title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Expected Number of Trials to get N Consecutive Heads
|
17 May, 2021
Given a number N. The task is to find the expected number of times a coin must be flipped to get N heads consecutively.Example:
Input: N = 2 Output: 6Input: N = 5 Output: 62
Approach: The key is to observe that if we see a tail between any consecutive N flip, it breaks the streak for continuous heads and we have to start over again for N consecutive head. Let the expected number of trial be X to get N consecutive heads. Below are the possible Cases:
Case 1: If, in the 1st trial, a tail occurs then it means that we have wasted one trial and we will have to do X more trial to get N consecutive head. The probability of this event is 1/2 and the total number of trial required to get N consecutive head is (X + count of the previous trial wasted).
Case 2: If, in the 2nd trial, a tail occurs then it means that we have wasted our all previous trial and we will have to do X more trial to get N consecutive head. The probability of this event is 1/4 and the total number of trials required to get N consecutive flips is (X + count of previous trial wasted).
Case 3:If, in the 3rd trial, a tail occurs then it means that we have wasted our all previous trial and we will have to do X more trial to get N. The probability of this event is 1/8 and the total number of trials required to get N consecutive flips is (X + count of the previous trial wasted). This will continue until we get N consecutive heads.
Case N: Similarly, if in the Nth trial, a tail occurs, then it means that we have wasted our all previous trial and we will have to do X more trial to get N. The probability of this event is 1/2N and the total number of trials required to get N consecutive flips is (X + count of the previous trial wasted).
From the above cases, the summation of all probability gives will gives the count of trials for N consecutive heads. Mathematically:
X = (1/2)*(X+1) + (1/4)*(X+2) + (1/8)*(X+3)+. . .+(1/2N)*(X+N) + (1/2N)*N
Solving the above equation for X. We have:
By opening the above expressions and arranging it we have:
X = X(1/2 + 1/4 + 1/8 + . . . . . . 1/2N)
+ (1/2 + 2/4 + 3/8 . . . . . . . + N/2N
+ N/2N)
The first part of the above equations form Geometric Progression and second part of the above equations forms an Arithmetico Geometric Sequence. Solving the above sequences separately we have: For Geometric Sequence:
Sum of GP series = 1/2 + 1/4 + 1/8 + . . . . . . 1/2N first term(a) is 1/2 common ratio(r) is 1/2 last term (nth term) is 1/2N which is also a * rN-1 Hence sum is given by: Sum of GP series = (1/2)*( (1 – (1/2)N)/(1 – 1/2) ) using formula : (a * (1 – rN)) / (1 – r) since r < 1 Sum of GP series = (1 – (1/2)N)
For Arithmetico Geometric Sequence:
Let S = Sum of Arithmetico Geometric Sequence:=> S = (1/2 + 2/4 + 3/8 + . . . . . . N/2N) .......(1)Multiplying By 2, we get => 2S = (1 + 2/2 + 3/4 + . . . . . . . + N/2N-1) .......(2)Subtracting the equation(1) from the equation(2), we get => S = (1/2 + 1/4 + 1/8 + . . . . . . 1/2N-1) – N/2N => S = sum of GP series – N/2N => S = (2 – (1/2)N-1)) – N/2N
Using the sum of the GP series and Arithmetico Geometric Sequence:
=> X = X*(1 – (1/2)N) + (2 – (1/2)N-1) – N/2N + N/2N => X = X*(1 – (1/2)N) + (2 – (1/2)N-1) => X*((1/2)N) = (2 – (1/2)N-1) => X = 2N+1 – 2
Now the above formula for X gives the number of trials requires getting N consecutive heads.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include "bits/stdc++.h"using namespace std; // Driver Codeint main(){ int N = 3; // Formula for number of trails for // N consecutive heads cout << pow(2, N + 1) - 2; return 0;}
// Java implementation of the above approachclass GFG{ // Driver Codepublic static void main(String[] args){ int N = 3; // Formula for number of trails for // N consecutive heads System.out.print(Math.pow(2, N + 1) - 2);}} // This code is contributed// by shivanisinghss2110
# Python3 implementation of the above approach # Driver codeif __name__ == '__main__': N = 3 # Formula for number of trails for # N consecutive heads print(pow(2, N + 1) - 2) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System;class GFG{ // Driver Codepublic static void Main(){ int N = 3; // Formula for number of trails for // N consecutive heads Console.Write(Math.Pow(2, N + 1) - 2);}} // This code is contributed// by Code_Mech
<script> // Javascript implementation of the above approach // Driver Code let N = 3; // Formula for number of trails for // N consecutive heads document.write(Math.pow(2, N + 1) - 2); </script>
14
Time Complexity: O(1)
mohit kumar 29
Arpit Agarwal 8
nidhi_biet
shivanisinghss2110
Code_Mech
code_hunt
Analysis
Geometric
Mathematical
Puzzles
Mathematical
Geometric
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Understanding Time Complexity with Simple Examples
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Time Complexity of building a heap
Time complexities of different data structures
Closest Pair of Points using Divide and Conquer algorithm
Program for distance between two points on earth
Find if two rectangles overlap
How to check if two given line segments intersect?
How to check if a given point lies inside or outside a polygon?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 182,
"s": 52,
"text": "Given a number N. The task is to find the expected number of times a coin must be flipped to get N heads consecutively.Example: "
},
{
"code": null,
"e": 230,
"s": 182,
"text": "Input: N = 2 Output: 6Input: N = 5 Output: 62 "
},
{
"code": null,
"e": 514,
"s": 232,
"text": "Approach: The key is to observe that if we see a tail between any consecutive N flip, it breaks the streak for continuous heads and we have to start over again for N consecutive head. Let the expected number of trial be X to get N consecutive heads. Below are the possible Cases: "
},
{
"code": null,
"e": 812,
"s": 514,
"text": "Case 1: If, in the 1st trial, a tail occurs then it means that we have wasted one trial and we will have to do X more trial to get N consecutive head. The probability of this event is 1/2 and the total number of trial required to get N consecutive head is (X + count of the previous trial wasted)."
},
{
"code": null,
"e": 1121,
"s": 812,
"text": "Case 2: If, in the 2nd trial, a tail occurs then it means that we have wasted our all previous trial and we will have to do X more trial to get N consecutive head. The probability of this event is 1/4 and the total number of trials required to get N consecutive flips is (X + count of previous trial wasted)."
},
{
"code": null,
"e": 1469,
"s": 1121,
"text": "Case 3:If, in the 3rd trial, a tail occurs then it means that we have wasted our all previous trial and we will have to do X more trial to get N. The probability of this event is 1/8 and the total number of trials required to get N consecutive flips is (X + count of the previous trial wasted). This will continue until we get N consecutive heads."
},
{
"code": null,
"e": 1779,
"s": 1469,
"text": "Case N: Similarly, if in the Nth trial, a tail occurs, then it means that we have wasted our all previous trial and we will have to do X more trial to get N. The probability of this event is 1/2N and the total number of trials required to get N consecutive flips is (X + count of the previous trial wasted). "
},
{
"code": null,
"e": 1914,
"s": 1779,
"text": "From the above cases, the summation of all probability gives will gives the count of trials for N consecutive heads. Mathematically: "
},
{
"code": null,
"e": 1990,
"s": 1914,
"text": "X = (1/2)*(X+1) + (1/4)*(X+2) + (1/8)*(X+3)+. . .+(1/2N)*(X+N) + (1/2N)*N "
},
{
"code": null,
"e": 2035,
"s": 1990,
"text": "Solving the above equation for X. We have: "
},
{
"code": null,
"e": 2194,
"s": 2035,
"text": "By opening the above expressions and arranging it we have:\nX = X(1/2 + 1/4 + 1/8 + . . . . . . 1/2N) \n + (1/2 + 2/4 + 3/8 . . . . . . . + N/2N \n + N/2N)"
},
{
"code": null,
"e": 2413,
"s": 2194,
"text": "The first part of the above equations form Geometric Progression and second part of the above equations forms an Arithmetico Geometric Sequence. Solving the above sequences separately we have: For Geometric Sequence: "
},
{
"code": null,
"e": 2725,
"s": 2413,
"text": "Sum of GP series = 1/2 + 1/4 + 1/8 + . . . . . . 1/2N first term(a) is 1/2 common ratio(r) is 1/2 last term (nth term) is 1/2N which is also a * rN-1 Hence sum is given by: Sum of GP series = (1/2)*( (1 – (1/2)N)/(1 – 1/2) ) using formula : (a * (1 – rN)) / (1 – r) since r < 1 Sum of GP series = (1 – (1/2)N) "
},
{
"code": null,
"e": 2763,
"s": 2725,
"text": "For Arithmetico Geometric Sequence: "
},
{
"code": null,
"e": 3120,
"s": 2763,
"text": "Let S = Sum of Arithmetico Geometric Sequence:=> S = (1/2 + 2/4 + 3/8 + . . . . . . N/2N) .......(1)Multiplying By 2, we get => 2S = (1 + 2/2 + 3/4 + . . . . . . . + N/2N-1) .......(2)Subtracting the equation(1) from the equation(2), we get => S = (1/2 + 1/4 + 1/8 + . . . . . . 1/2N-1) – N/2N => S = sum of GP series – N/2N => S = (2 – (1/2)N-1)) – N/2N "
},
{
"code": null,
"e": 3189,
"s": 3120,
"text": "Using the sum of the GP series and Arithmetico Geometric Sequence: "
},
{
"code": null,
"e": 3330,
"s": 3189,
"text": "=> X = X*(1 – (1/2)N) + (2 – (1/2)N-1) – N/2N + N/2N => X = X*(1 – (1/2)N) + (2 – (1/2)N-1) => X*((1/2)N) = (2 – (1/2)N-1) => X = 2N+1 – 2 "
},
{
"code": null,
"e": 3474,
"s": 3330,
"text": "Now the above formula for X gives the number of trials requires getting N consecutive heads.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3478,
"s": 3474,
"text": "C++"
},
{
"code": null,
"e": 3483,
"s": 3478,
"text": "Java"
},
{
"code": null,
"e": 3491,
"s": 3483,
"text": "Python3"
},
{
"code": null,
"e": 3494,
"s": 3491,
"text": "C#"
},
{
"code": null,
"e": 3505,
"s": 3494,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include \"bits/stdc++.h\"using namespace std; // Driver Codeint main(){ int N = 3; // Formula for number of trails for // N consecutive heads cout << pow(2, N + 1) - 2; return 0;}",
"e": 3743,
"s": 3505,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG{ // Driver Codepublic static void main(String[] args){ int N = 3; // Formula for number of trails for // N consecutive heads System.out.print(Math.pow(2, N + 1) - 2);}} // This code is contributed// by shivanisinghss2110",
"e": 4031,
"s": 3743,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Driver codeif __name__ == '__main__': N = 3 # Formula for number of trails for # N consecutive heads print(pow(2, N + 1) - 2) # This code is contributed by mohit kumar 29",
"e": 4269,
"s": 4031,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;class GFG{ // Driver Codepublic static void Main(){ int N = 3; // Formula for number of trails for // N consecutive heads Console.Write(Math.Pow(2, N + 1) - 2);}} // This code is contributed// by Code_Mech",
"e": 4543,
"s": 4269,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Driver Code let N = 3; // Formula for number of trails for // N consecutive heads document.write(Math.pow(2, N + 1) - 2); </script>",
"e": 4764,
"s": 4543,
"text": null
},
{
"code": null,
"e": 4767,
"s": 4764,
"text": "14"
},
{
"code": null,
"e": 4792,
"s": 4769,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 4807,
"s": 4792,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4823,
"s": 4807,
"text": "Arpit Agarwal 8"
},
{
"code": null,
"e": 4834,
"s": 4823,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4853,
"s": 4834,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 4863,
"s": 4853,
"text": "Code_Mech"
},
{
"code": null,
"e": 4873,
"s": 4863,
"text": "code_hunt"
},
{
"code": null,
"e": 4882,
"s": 4873,
"text": "Analysis"
},
{
"code": null,
"e": 4892,
"s": 4882,
"text": "Geometric"
},
{
"code": null,
"e": 4905,
"s": 4892,
"text": "Mathematical"
},
{
"code": null,
"e": 4913,
"s": 4905,
"text": "Puzzles"
},
{
"code": null,
"e": 4926,
"s": 4913,
"text": "Mathematical"
},
{
"code": null,
"e": 4936,
"s": 4926,
"text": "Geometric"
},
{
"code": null,
"e": 4944,
"s": 4936,
"text": "Puzzles"
},
{
"code": null,
"e": 5042,
"s": 4944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5079,
"s": 5042,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 5130,
"s": 5079,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 5197,
"s": 5130,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 5232,
"s": 5197,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 5279,
"s": 5232,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 5337,
"s": 5279,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 5386,
"s": 5337,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 5417,
"s": 5386,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 5468,
"s": 5417,
"text": "How to check if two given line segments intersect?"
}
] |
Explain subn() methods of “re” module in Python ?
|
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The re module in python refers to the module Regular Expressions (RE). It specifies a set of strings or patterns that matches it. Metacharacters are used to understand the analogy of RE.
subn()method is similar to sub() and also returns the new string along with the no. of replacements.
Syntax
re.subn (pattern, repl, string, count=0, flags=0)
Example
import re
print(re.subn('ov', '~*' , 'movie tickets booking in online'))
t = re.subn('ov', '~*' , 'movie tickets booking in online', flags = re.IGNORECASE)
print(t)
print(len(t))
print(t[0])
Here you can see that, subn() method It returns a tuple with count of total of all the replacements as well as the new string.
('m~*ie tickets booking in online', 1)
('m~*ie tickets booking in online', 1)
2
m~*ie tickets booking in online
|
[
{
"code": null,
"e": 1592,
"s": 1187,
"text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The re module in python refers to the module Regular Expressions (RE). It specifies a set of strings or patterns that matches it. Metacharacters are used to understand the analogy of RE. "
},
{
"code": null,
"e": 1693,
"s": 1592,
"text": "subn()method is similar to sub() and also returns the new string along with the no. of replacements."
},
{
"code": null,
"e": 1700,
"s": 1693,
"text": "Syntax"
},
{
"code": null,
"e": 1750,
"s": 1700,
"text": "re.subn (pattern, repl, string, count=0, flags=0)"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "Example"
},
{
"code": null,
"e": 1949,
"s": 1758,
"text": "import re\nprint(re.subn('ov', '~*' , 'movie tickets booking in online'))\nt = re.subn('ov', '~*' , 'movie tickets booking in online', flags = re.IGNORECASE)\nprint(t)\nprint(len(t))\nprint(t[0])"
},
{
"code": null,
"e": 2076,
"s": 1949,
"text": "Here you can see that, subn() method It returns a tuple with count of total of all the replacements as well as the new string."
},
{
"code": null,
"e": 2188,
"s": 2076,
"text": "('m~*ie tickets booking in online', 1)\n('m~*ie tickets booking in online', 1)\n2\nm~*ie tickets booking in online"
}
] |
time.Time.Before() Function in Golang With Examples
|
19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Before() function in Go language is used to check if the stated time instant t is before the stated u or not. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Before(u Time) bool
Here, “t” is the stated time and “u” is the time that is present as an argument in the Before() method.
Return Value: It returns true if “t” is present before “u” else it returns false.
Example 1:
// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t and u in UTC t := time.Date(2019, 0, 0, 0, 0, 0, 0, time.UTC) u := time.Date(2020, 0, 0, 0, 0, 0, 0, time.UTC) // Calling Before method res := t.Before(u) // Prints output fmt.Printf("%v", res)}
Output:
true
Example 2:
// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring t and u in UTC t := time.Date(2030, 0, 0, 0, 0, 0, 0, time.UTC) u := time.Date(2025, 0, 0, 0, 0, 0, 0, time.UTC) // Calling Before method res := t.Before(u) // Prints output fmt.Printf("%v", res)}
Output:
false
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Time Durations in Golang
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 377,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Before() function in Go language is used to check if the stated time instant t is before the stated u or not. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 385,
"s": 377,
"text": "Syntax:"
},
{
"code": null,
"e": 420,
"s": 385,
"text": "func (t Time) Before(u Time) bool\n"
},
{
"code": null,
"e": 524,
"s": 420,
"text": "Here, “t” is the stated time and “u” is the time that is present as an argument in the Before() method."
},
{
"code": null,
"e": 606,
"s": 524,
"text": "Return Value: It returns true if “t” is present before “u” else it returns false."
},
{
"code": null,
"e": 617,
"s": 606,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t and u in UTC t := time.Date(2019, 0, 0, 0, 0, 0, 0, time.UTC) u := time.Date(2020, 0, 0, 0, 0, 0, 0, time.UTC) // Calling Before method res := t.Before(u) // Prints output fmt.Printf(\"%v\", res)}",
"e": 1045,
"s": 617,
"text": null
},
{
"code": null,
"e": 1053,
"s": 1045,
"text": "Output:"
},
{
"code": null,
"e": 1059,
"s": 1053,
"text": "true\n"
},
{
"code": null,
"e": 1070,
"s": 1059,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// Time.Before() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring t and u in UTC t := time.Date(2030, 0, 0, 0, 0, 0, 0, time.UTC) u := time.Date(2025, 0, 0, 0, 0, 0, 0, time.UTC) // Calling Before method res := t.Before(u) // Prints output fmt.Printf(\"%v\", res)}",
"e": 1498,
"s": 1070,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1498,
"text": "Output:"
},
{
"code": null,
"e": 1513,
"s": 1506,
"text": "false\n"
},
{
"code": null,
"e": 1525,
"s": 1513,
"text": "GoLang-time"
},
{
"code": null,
"e": 1537,
"s": 1525,
"text": "Go Language"
},
{
"code": null,
"e": 1635,
"s": 1537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1664,
"s": 1635,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 1719,
"s": 1664,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 1740,
"s": 1719,
"text": "Structures in Golang"
},
{
"code": null,
"e": 1761,
"s": 1740,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 1786,
"s": 1761,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 1809,
"s": 1786,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 1827,
"s": 1809,
"text": "Strings in Golang"
},
{
"code": null,
"e": 1873,
"s": 1827,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 1886,
"s": 1873,
"text": "Go Variables"
}
] |
Implementing Yann LeCun’s LeNet-5 in PyTorch | by Eryk Lewinson | Towards Data Science
|
Recently, I watched the Data Science Pioneers movie by Dataiku, in which several data scientists talked about their jobs and how they apply data science in their daily jobs. In one of the talks, they mention how Yann LeCun’s Convolutional Neural Network architecture (also known as LeNet-5) was used by the American Post office to automatically identify handwritten zip code numbers. Another real-world application of the architecture was recognizing the numbers written on cheques by banking systems. It makes sense to point out that the LeNet-5 paper was published in 1998. That is one of the reasons why it is a good starting point to understand how CNNs work, before moving to more complex and modern architectures.
In this article, I briefly describe the architecture and show how to implement LeNet-5 in PyTorch. The article assumes a general understanding of the basics of Convolutional Neural Networks, including concepts such as convolutional layers, pooling layers, fully-connected layers, etc.
LeNet-5 is a 7 layer Convolutional Neural Network, trained on grayscale images of size 32 x 32 pixels.
To decode the image above, I present the naming convention used by the authors:
Cx — convolution layer,
Sx — subsampling (pooling) layer,
Fx — fully-connected layer,
x — index of the layer.
As LeNet-5 is relatively simple given modern standards, we can go over each of the layers separately to gain a good understanding of the architecture. However, before proceeding it also makes sense to remind the formula for calculating the output size of the convolutional layer.
The formula is presented below:
, where W is the input height/width (normally the images are squares, so there is no need to differentiate the two), F is the filter/kernel size, P is the padding, and S is the stride.
Having seen the architecture schema and the formula above, we can go over each layer of LeNet-5.
Layer 1 (C1): The first convolutional layer with 6 kernels of size 5×5 and the stride of 1. Given the input size (32×32×1), the output of this layer is of size 28×28×6.Layer 2 (S2): A subsampling/pooling layer with 6 kernels of size 2×2 and the stride of 2. The subsampling layer in the original architecture was a bit more complex than the traditionally used max/average pooling layers. I will quote [1]: “ The four inputs to a unit in S2 are added, then multiplied by a trainable coefficient, and added to a trainable bias. The result is passed through a sigmoidal function.”. As a result of non-overlapping receptive fields, the input to this layer is halved in size (14×14×6).Layer 3 (C3): The second convolutional layer with the same configuration as the first one, however, this time with 16 filters. The output of this layer is 10×10×16.Layer 4 (S4): The second pooling layer. The logic is identical to the previous one, but this time the layer has 16 filters. The output of this layer is of size 5×5×16.Layer 5 (C5): The last convolutional layer with 120 5×5 kernels. Given that the input to this layer is of size 5×5×16 and the kernels are of size 5×5, the output is 1×1×120. As a result, layers S4 and C5 are fully-connected. That is also why in some implementations of LeNet-5 actually use a fully-connected layer instead of the convolutional one as the 5th layer. The reason for keeping this layer as a convolutional one is the fact that if the input to the network is larger than the one used in [1] (the initial input, so 32×32 in this case), this layer will not be a fully-connected one, as the output of each kernel will not be 1×1.Layer 6 (F6): The first fully-connected layer, which takes the input of 120 units and returns 84 units. In the original paper, the authors used a custom activation function — a variant of the tanh activation function. For a thorough explanation, please refer to Appendix A in [1].Layer 7 (F7): The last dense layer, which outputs 10 units. In [1], the authors used Euclidean Radial Basis Function neurons as activation functions for this layer.
Layer 1 (C1): The first convolutional layer with 6 kernels of size 5×5 and the stride of 1. Given the input size (32×32×1), the output of this layer is of size 28×28×6.
Layer 2 (S2): A subsampling/pooling layer with 6 kernels of size 2×2 and the stride of 2. The subsampling layer in the original architecture was a bit more complex than the traditionally used max/average pooling layers. I will quote [1]: “ The four inputs to a unit in S2 are added, then multiplied by a trainable coefficient, and added to a trainable bias. The result is passed through a sigmoidal function.”. As a result of non-overlapping receptive fields, the input to this layer is halved in size (14×14×6).
Layer 3 (C3): The second convolutional layer with the same configuration as the first one, however, this time with 16 filters. The output of this layer is 10×10×16.
Layer 4 (S4): The second pooling layer. The logic is identical to the previous one, but this time the layer has 16 filters. The output of this layer is of size 5×5×16.
Layer 5 (C5): The last convolutional layer with 120 5×5 kernels. Given that the input to this layer is of size 5×5×16 and the kernels are of size 5×5, the output is 1×1×120. As a result, layers S4 and C5 are fully-connected. That is also why in some implementations of LeNet-5 actually use a fully-connected layer instead of the convolutional one as the 5th layer. The reason for keeping this layer as a convolutional one is the fact that if the input to the network is larger than the one used in [1] (the initial input, so 32×32 in this case), this layer will not be a fully-connected one, as the output of each kernel will not be 1×1.
Layer 6 (F6): The first fully-connected layer, which takes the input of 120 units and returns 84 units. In the original paper, the authors used a custom activation function — a variant of the tanh activation function. For a thorough explanation, please refer to Appendix A in [1].
Layer 7 (F7): The last dense layer, which outputs 10 units. In [1], the authors used Euclidean Radial Basis Function neurons as activation functions for this layer.
For more details on the reasoning behind the architecture and some choices (such as the non-standard activation functions), please refer to [1].
I will now show how to implement LeNet-5 (with some minor simplifications) in PyTorch. To keep the spirit of the original application of LeNet-5, we will train the network on the MNIST dataset. We start by importing all the required libraries.
Additionally, we check if the GPU is available and set the DEVICE variable accordingly. In the next step, we set up some parameters (such as the random seed, learning rate, batch size, number of epochs, etc.), which we will use later on while setting up the neural network.
As the next step, we define some helper functions used for training the neural network in PyTorch. As the general idea is very similar in most cases, you can slightly modify the functions for your needs and use them for training all kinds of networks. We start with the function responsible for the training part:
I will quickly describe what is happening in the train function. For each batch of observations we carry out the following steps:
Perform the forward pass — getting the predictions for the batch using the current weightsCalculate the value of the loss functionPerform the backward pass, in which the weights are adjusted based on the loss. This is the “learning” step.
Perform the forward pass — getting the predictions for the batch using the current weights
Calculate the value of the loss function
Perform the backward pass, in which the weights are adjusted based on the loss. This is the “learning” step.
Please note that for the training phase, the model is in the training mode (model.train()) and we also need to zero out the gradients for each batch. Additionally, we calculate the running loss within the training step.
Then, we define the function responsible for validation.
The validation function is very similar to the training one, with the difference being the lack of the actual learning step (the backward pass). Please note that we need to specify that we are using the model for evaluation only — model.eval(). We do not need to worry about the gradients, as in the next function you will see that we disable them for the validation step. Lastly, we combine them all together within the training loop:
In the training loop, for each epoch, we run both the train and validate functions, with the latter one running with torch.no_grad() in order not to update weights and save some computation time. Additionally to the loss function used for training, we calculate the accuracy of the model for both the training and validation steps using the custom get_accuracy function. The dataset we will be using is balanced, so there is no problem with using accuracy as the metric of choice. For brevity, I do not include all the helper functions here and you can find the definition of get_accuracy and plot_losses on GitHub.
Having defined the helper functions, it is time to prepare the data. Thanks to the popularity of the MNIST dataset (if you are not familiar with it, you can read some background here), it is readily available as one of the datasets within torchvision.
In the snippet above, we first defined a set of transforms to be applied to the source images. We first resize the images to 32×32 (the input size of LeNet-5) and then convert them to tensors. transforms.ToTensor() automatically scales the images to the [0, 1] range. Instead of resizing the images, we could have also applied some sort of padding to the images. In the simplest case, we would simply add 2 zeros on each side of the original image.
The second step is to define the datasets. For the training object, we specified download=True in order to download the dataset. While defining the datasets, we also indicate the previously defined transformations and whether the particular object will be used for training or not.
Lastly, we instantiated the DataLoaders by providing the dataset, the batch size, and the desire to shuffle the dataset in each epoch. For validation, this does not make a difference so we set it to False.
Below you can see a preview of 50 images coming from the training set.
Finally, it is the time to define the LeNet-5 architecture.
From the class definition above, you can see a few simplifications in comparison to the original network:
using the regular tanh activation function instead of the custom one described in [1],
using average pooling layers instead of the more complex equivalents used in the original architecture,
replacing the Euclidean Radial Basis Function activations in the output layer with the softmax function.
After defining the class, we need to instantiate the model (and send it to the correct device), the optimizer (ADAM in this case), and the loss function (Cross entropy). The last two are different than the method originally used in [1].
Having everything in place, we can train the network by running:
model, optimizer, _ = training_loop(model, criterion, optimizer, train_loader, valid_loader, N_EPOCHS, DEVICE)
What results in the following outputs:
The training loss plateaus, while the validation loss sometimes exhibits small bumps (increased values). Overall, I believe the performance can be described as quite satisfactory. The best results (on the validation set) were achieved in the 11th epoch.
To evaluate the predictions of our model, we can run the following code which displays a set of numbers coming from the validation set, together with the predicted label and the probability that the network assigns to that label (in other words, how confident the network is in the prediction).
From the image above we can see that the network is almost always sure about the label, with the only doubt visible in the digit 3 (in the second row, 3rd from right), when it is only 54% sure it is a 3. That is most likely due to the fact that the number indeed resembles an 8.
As the very last step, we run the following command to remove the downloaded dataset:
!rm -r mnist_data
In this article, I described the architecture of LeNet-5 and showed how to implement it and train it using the famous MNIST dataset. As this is one of the first CNN architectures, it is relatively straightforward and easy to understand, which makes it a good start for learning about Convolutional Neural Networks.
To further improve the performance of the network, it might be worthwhile to experiment with some data augmentation. To do so, we can apply transformations such as rotation or shearing (using torchvision.transforms) to the image, in order to create a more varied dataset. We should also pay attention that not all transformations might be applicable to the case of digit recognition. An example of such an incorrect transformation would be flipping the image to create a mirror reflection.
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
[1] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. Gradient-based learning applied to document recognition. Proceedings of the IEEE, November 1998. — available here
|
[
{
"code": null,
"e": 891,
"s": 171,
"text": "Recently, I watched the Data Science Pioneers movie by Dataiku, in which several data scientists talked about their jobs and how they apply data science in their daily jobs. In one of the talks, they mention how Yann LeCun’s Convolutional Neural Network architecture (also known as LeNet-5) was used by the American Post office to automatically identify handwritten zip code numbers. Another real-world application of the architecture was recognizing the numbers written on cheques by banking systems. It makes sense to point out that the LeNet-5 paper was published in 1998. That is one of the reasons why it is a good starting point to understand how CNNs work, before moving to more complex and modern architectures."
},
{
"code": null,
"e": 1176,
"s": 891,
"text": "In this article, I briefly describe the architecture and show how to implement LeNet-5 in PyTorch. The article assumes a general understanding of the basics of Convolutional Neural Networks, including concepts such as convolutional layers, pooling layers, fully-connected layers, etc."
},
{
"code": null,
"e": 1279,
"s": 1176,
"text": "LeNet-5 is a 7 layer Convolutional Neural Network, trained on grayscale images of size 32 x 32 pixels."
},
{
"code": null,
"e": 1359,
"s": 1279,
"text": "To decode the image above, I present the naming convention used by the authors:"
},
{
"code": null,
"e": 1383,
"s": 1359,
"text": "Cx — convolution layer,"
},
{
"code": null,
"e": 1417,
"s": 1383,
"text": "Sx — subsampling (pooling) layer,"
},
{
"code": null,
"e": 1445,
"s": 1417,
"text": "Fx — fully-connected layer,"
},
{
"code": null,
"e": 1469,
"s": 1445,
"text": "x — index of the layer."
},
{
"code": null,
"e": 1749,
"s": 1469,
"text": "As LeNet-5 is relatively simple given modern standards, we can go over each of the layers separately to gain a good understanding of the architecture. However, before proceeding it also makes sense to remind the formula for calculating the output size of the convolutional layer."
},
{
"code": null,
"e": 1781,
"s": 1749,
"text": "The formula is presented below:"
},
{
"code": null,
"e": 1966,
"s": 1781,
"text": ", where W is the input height/width (normally the images are squares, so there is no need to differentiate the two), F is the filter/kernel size, P is the padding, and S is the stride."
},
{
"code": null,
"e": 2063,
"s": 1966,
"text": "Having seen the architecture schema and the formula above, we can go over each layer of LeNet-5."
},
{
"code": null,
"e": 4156,
"s": 2063,
"text": "Layer 1 (C1): The first convolutional layer with 6 kernels of size 5×5 and the stride of 1. Given the input size (32×32×1), the output of this layer is of size 28×28×6.Layer 2 (S2): A subsampling/pooling layer with 6 kernels of size 2×2 and the stride of 2. The subsampling layer in the original architecture was a bit more complex than the traditionally used max/average pooling layers. I will quote [1]: “ The four inputs to a unit in S2 are added, then multiplied by a trainable coefficient, and added to a trainable bias. The result is passed through a sigmoidal function.”. As a result of non-overlapping receptive fields, the input to this layer is halved in size (14×14×6).Layer 3 (C3): The second convolutional layer with the same configuration as the first one, however, this time with 16 filters. The output of this layer is 10×10×16.Layer 4 (S4): The second pooling layer. The logic is identical to the previous one, but this time the layer has 16 filters. The output of this layer is of size 5×5×16.Layer 5 (C5): The last convolutional layer with 120 5×5 kernels. Given that the input to this layer is of size 5×5×16 and the kernels are of size 5×5, the output is 1×1×120. As a result, layers S4 and C5 are fully-connected. That is also why in some implementations of LeNet-5 actually use a fully-connected layer instead of the convolutional one as the 5th layer. The reason for keeping this layer as a convolutional one is the fact that if the input to the network is larger than the one used in [1] (the initial input, so 32×32 in this case), this layer will not be a fully-connected one, as the output of each kernel will not be 1×1.Layer 6 (F6): The first fully-connected layer, which takes the input of 120 units and returns 84 units. In the original paper, the authors used a custom activation function — a variant of the tanh activation function. For a thorough explanation, please refer to Appendix A in [1].Layer 7 (F7): The last dense layer, which outputs 10 units. In [1], the authors used Euclidean Radial Basis Function neurons as activation functions for this layer."
},
{
"code": null,
"e": 4325,
"s": 4156,
"text": "Layer 1 (C1): The first convolutional layer with 6 kernels of size 5×5 and the stride of 1. Given the input size (32×32×1), the output of this layer is of size 28×28×6."
},
{
"code": null,
"e": 4838,
"s": 4325,
"text": "Layer 2 (S2): A subsampling/pooling layer with 6 kernels of size 2×2 and the stride of 2. The subsampling layer in the original architecture was a bit more complex than the traditionally used max/average pooling layers. I will quote [1]: “ The four inputs to a unit in S2 are added, then multiplied by a trainable coefficient, and added to a trainable bias. The result is passed through a sigmoidal function.”. As a result of non-overlapping receptive fields, the input to this layer is halved in size (14×14×6)."
},
{
"code": null,
"e": 5003,
"s": 4838,
"text": "Layer 3 (C3): The second convolutional layer with the same configuration as the first one, however, this time with 16 filters. The output of this layer is 10×10×16."
},
{
"code": null,
"e": 5171,
"s": 5003,
"text": "Layer 4 (S4): The second pooling layer. The logic is identical to the previous one, but this time the layer has 16 filters. The output of this layer is of size 5×5×16."
},
{
"code": null,
"e": 5809,
"s": 5171,
"text": "Layer 5 (C5): The last convolutional layer with 120 5×5 kernels. Given that the input to this layer is of size 5×5×16 and the kernels are of size 5×5, the output is 1×1×120. As a result, layers S4 and C5 are fully-connected. That is also why in some implementations of LeNet-5 actually use a fully-connected layer instead of the convolutional one as the 5th layer. The reason for keeping this layer as a convolutional one is the fact that if the input to the network is larger than the one used in [1] (the initial input, so 32×32 in this case), this layer will not be a fully-connected one, as the output of each kernel will not be 1×1."
},
{
"code": null,
"e": 6090,
"s": 5809,
"text": "Layer 6 (F6): The first fully-connected layer, which takes the input of 120 units and returns 84 units. In the original paper, the authors used a custom activation function — a variant of the tanh activation function. For a thorough explanation, please refer to Appendix A in [1]."
},
{
"code": null,
"e": 6255,
"s": 6090,
"text": "Layer 7 (F7): The last dense layer, which outputs 10 units. In [1], the authors used Euclidean Radial Basis Function neurons as activation functions for this layer."
},
{
"code": null,
"e": 6400,
"s": 6255,
"text": "For more details on the reasoning behind the architecture and some choices (such as the non-standard activation functions), please refer to [1]."
},
{
"code": null,
"e": 6644,
"s": 6400,
"text": "I will now show how to implement LeNet-5 (with some minor simplifications) in PyTorch. To keep the spirit of the original application of LeNet-5, we will train the network on the MNIST dataset. We start by importing all the required libraries."
},
{
"code": null,
"e": 6918,
"s": 6644,
"text": "Additionally, we check if the GPU is available and set the DEVICE variable accordingly. In the next step, we set up some parameters (such as the random seed, learning rate, batch size, number of epochs, etc.), which we will use later on while setting up the neural network."
},
{
"code": null,
"e": 7232,
"s": 6918,
"text": "As the next step, we define some helper functions used for training the neural network in PyTorch. As the general idea is very similar in most cases, you can slightly modify the functions for your needs and use them for training all kinds of networks. We start with the function responsible for the training part:"
},
{
"code": null,
"e": 7362,
"s": 7232,
"text": "I will quickly describe what is happening in the train function. For each batch of observations we carry out the following steps:"
},
{
"code": null,
"e": 7601,
"s": 7362,
"text": "Perform the forward pass — getting the predictions for the batch using the current weightsCalculate the value of the loss functionPerform the backward pass, in which the weights are adjusted based on the loss. This is the “learning” step."
},
{
"code": null,
"e": 7692,
"s": 7601,
"text": "Perform the forward pass — getting the predictions for the batch using the current weights"
},
{
"code": null,
"e": 7733,
"s": 7692,
"text": "Calculate the value of the loss function"
},
{
"code": null,
"e": 7842,
"s": 7733,
"text": "Perform the backward pass, in which the weights are adjusted based on the loss. This is the “learning” step."
},
{
"code": null,
"e": 8062,
"s": 7842,
"text": "Please note that for the training phase, the model is in the training mode (model.train()) and we also need to zero out the gradients for each batch. Additionally, we calculate the running loss within the training step."
},
{
"code": null,
"e": 8119,
"s": 8062,
"text": "Then, we define the function responsible for validation."
},
{
"code": null,
"e": 8555,
"s": 8119,
"text": "The validation function is very similar to the training one, with the difference being the lack of the actual learning step (the backward pass). Please note that we need to specify that we are using the model for evaluation only — model.eval(). We do not need to worry about the gradients, as in the next function you will see that we disable them for the validation step. Lastly, we combine them all together within the training loop:"
},
{
"code": null,
"e": 9171,
"s": 8555,
"text": "In the training loop, for each epoch, we run both the train and validate functions, with the latter one running with torch.no_grad() in order not to update weights and save some computation time. Additionally to the loss function used for training, we calculate the accuracy of the model for both the training and validation steps using the custom get_accuracy function. The dataset we will be using is balanced, so there is no problem with using accuracy as the metric of choice. For brevity, I do not include all the helper functions here and you can find the definition of get_accuracy and plot_losses on GitHub."
},
{
"code": null,
"e": 9423,
"s": 9171,
"text": "Having defined the helper functions, it is time to prepare the data. Thanks to the popularity of the MNIST dataset (if you are not familiar with it, you can read some background here), it is readily available as one of the datasets within torchvision."
},
{
"code": null,
"e": 9872,
"s": 9423,
"text": "In the snippet above, we first defined a set of transforms to be applied to the source images. We first resize the images to 32×32 (the input size of LeNet-5) and then convert them to tensors. transforms.ToTensor() automatically scales the images to the [0, 1] range. Instead of resizing the images, we could have also applied some sort of padding to the images. In the simplest case, we would simply add 2 zeros on each side of the original image."
},
{
"code": null,
"e": 10154,
"s": 9872,
"text": "The second step is to define the datasets. For the training object, we specified download=True in order to download the dataset. While defining the datasets, we also indicate the previously defined transformations and whether the particular object will be used for training or not."
},
{
"code": null,
"e": 10360,
"s": 10154,
"text": "Lastly, we instantiated the DataLoaders by providing the dataset, the batch size, and the desire to shuffle the dataset in each epoch. For validation, this does not make a difference so we set it to False."
},
{
"code": null,
"e": 10431,
"s": 10360,
"text": "Below you can see a preview of 50 images coming from the training set."
},
{
"code": null,
"e": 10491,
"s": 10431,
"text": "Finally, it is the time to define the LeNet-5 architecture."
},
{
"code": null,
"e": 10597,
"s": 10491,
"text": "From the class definition above, you can see a few simplifications in comparison to the original network:"
},
{
"code": null,
"e": 10684,
"s": 10597,
"text": "using the regular tanh activation function instead of the custom one described in [1],"
},
{
"code": null,
"e": 10788,
"s": 10684,
"text": "using average pooling layers instead of the more complex equivalents used in the original architecture,"
},
{
"code": null,
"e": 10893,
"s": 10788,
"text": "replacing the Euclidean Radial Basis Function activations in the output layer with the softmax function."
},
{
"code": null,
"e": 11130,
"s": 10893,
"text": "After defining the class, we need to instantiate the model (and send it to the correct device), the optimizer (ADAM in this case), and the loss function (Cross entropy). The last two are different than the method originally used in [1]."
},
{
"code": null,
"e": 11195,
"s": 11130,
"text": "Having everything in place, we can train the network by running:"
},
{
"code": null,
"e": 11306,
"s": 11195,
"text": "model, optimizer, _ = training_loop(model, criterion, optimizer, train_loader, valid_loader, N_EPOCHS, DEVICE)"
},
{
"code": null,
"e": 11345,
"s": 11306,
"text": "What results in the following outputs:"
},
{
"code": null,
"e": 11599,
"s": 11345,
"text": "The training loss plateaus, while the validation loss sometimes exhibits small bumps (increased values). Overall, I believe the performance can be described as quite satisfactory. The best results (on the validation set) were achieved in the 11th epoch."
},
{
"code": null,
"e": 11894,
"s": 11599,
"text": "To evaluate the predictions of our model, we can run the following code which displays a set of numbers coming from the validation set, together with the predicted label and the probability that the network assigns to that label (in other words, how confident the network is in the prediction)."
},
{
"code": null,
"e": 12173,
"s": 11894,
"text": "From the image above we can see that the network is almost always sure about the label, with the only doubt visible in the digit 3 (in the second row, 3rd from right), when it is only 54% sure it is a 3. That is most likely due to the fact that the number indeed resembles an 8."
},
{
"code": null,
"e": 12259,
"s": 12173,
"text": "As the very last step, we run the following command to remove the downloaded dataset:"
},
{
"code": null,
"e": 12277,
"s": 12259,
"text": "!rm -r mnist_data"
},
{
"code": null,
"e": 12592,
"s": 12277,
"text": "In this article, I described the architecture of LeNet-5 and showed how to implement it and train it using the famous MNIST dataset. As this is one of the first CNN architectures, it is relatively straightforward and easy to understand, which makes it a good start for learning about Convolutional Neural Networks."
},
{
"code": null,
"e": 13082,
"s": 12592,
"text": "To further improve the performance of the network, it might be worthwhile to experiment with some data augmentation. To do so, we can apply transformations such as rotation or shearing (using torchvision.transforms) to the image, in order to create a more varied dataset. We should also pay attention that not all transformations might be applicable to the case of digit recognition. An example of such an incorrect transformation would be flipping the image to create a mirror reflection."
},
{
"code": null,
"e": 13244,
"s": 13082,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
}
] |
Maximum area of quadrilateral - GeeksforGeeks
|
29 Nov, 2021
Given four sides of quadrilateral a, b, c, d, find the maximum area of the quadrilateral possible from the given sides .Examples:
Input : 1 2 1 2
Output : 2.00
It is optimal to construct a rectangle for maximum area .
According to Bretschneider’s formula, the area of a general quadrilateral is given by Here a, b, c, d are the sides of a quadrilateral, s is the semiperimeter of a quadrilateral and angles are two opposite angles. So, this formula is maximized only when opposite angles sum to pi(180) then we can use a simplified form of Bretschneider’s formula to get the (maximum) area K. This formula is called as Brahmagupta’s formula . Below is the implementation of given approach
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find maximum are of a // quadrilateral#include <iostream>#include <math.h>using namespace std; double maxArea(double a, double b, double c, double d){ // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d));} // Driver codeint main(){ double a = 1, b = 2, c= 1, d = 2; cout <<maxArea(a, b, c, d); return 0;} // This code is contributed by shivanisinghss2110
// CPP program to find maximum are of a // quadrilateral#include <stdio.h>#include <math.h> double maxArea(double a, double b, double c, double d){ // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d));} // Driver codeint main(){ double a = 1, b = 2, c= 1, d = 2; printf("%.2f\n",maxArea(a, b, c, d)); return 0;}
// Java program to find maximum are of a // quadrilateralimport java.io.*; class GFG { static double maxArea(double a, double b, double c, double d) { // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code public static void main (String[] args) { double a = 1, b = 2, c= 1, d = 2; System.out.println(maxArea(a, b, c, d)); }} // This code is contributed by sunnysingh
# Python3 program to find maximum # area of a quadrilateralimport math def maxArea (a , b , c , d ): # Calculating the semi-perimeter # of the given quadrilateral semiperimeter = (a + b + c + d) / 2 # Applying Brahmagupta's formula to # get maximum area of quadrilateral return math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)) # Driver codea = 1b = 2c = 1d = 2print("%.2f"%maxArea(a, b, c, d)) # This code is contributed by "Sharad_Bhardwaj".
// C# program to find maximum are of a // quadrilateralusing System; class GFG { static double maxArea(double a, double b, double c, double d) { // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.Sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code public static void Main () { double a = 1, b = 2, c= 1, d = 2; Console.WriteLine(maxArea(a, b, c, d)); }} // This code is contributed by vt_m.
<?php// PHP program to find maximum are of a // quadrilateral function maxArea( $a, $b, $c, $d){ // Calculating the semi-perimeter // of the given quadrilateral $semiperimeter = ($a + $b + $c + $d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt(($semiperimeter - $a) * ($semiperimeter - $b) * ($semiperimeter - $c) * ($semiperimeter - $d));} // Driver code$a = 1; $b = 2; $c= 1; $d = 2;echo(maxArea($a, $b, $c, $d)); // This code is contributed by vt_m.?>
<script> // JavaScript program to find maximum are of a // quadrilateral function maxArea(a, b, c, d) { // Calculating the semi-perimeter // of the given quadrilateral let semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code let a = 1, b = 2, c= 1, d = 2; document.write(maxArea(a, b, c, d)); // This code is contributed by Surbhi Tyagi. </script>
Output:
2.00
vt_m
surbhityagi15
rajeev0719singh
shivanisinghss2110
area-volume-programs
Geometric
Technical Scripter
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Closest Pair of Points | O(nlogn) Implementation
Given n line segments, find if any two segments intersect
Convex Hull | Set 2 (Graham Scan)
Equation of circle when three points on the circle are given
Polygon Clipping | Sutherland–Hodgman Algorithm
Program for Point of Intersection of Two Lines
Haversine formula to find distance between two points on a sphere
|
[
{
"code": null,
"e": 24700,
"s": 24672,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 24832,
"s": 24700,
"text": "Given four sides of quadrilateral a, b, c, d, find the maximum area of the quadrilateral possible from the given sides .Examples: "
},
{
"code": null,
"e": 24920,
"s": 24832,
"text": "Input : 1 2 1 2\nOutput : 2.00\nIt is optimal to construct a rectangle for maximum area ."
},
{
"code": null,
"e": 25396,
"s": 24924,
"text": "According to Bretschneider’s formula, the area of a general quadrilateral is given by Here a, b, c, d are the sides of a quadrilateral, s is the semiperimeter of a quadrilateral and angles are two opposite angles. So, this formula is maximized only when opposite angles sum to pi(180) then we can use a simplified form of Bretschneider’s formula to get the (maximum) area K. This formula is called as Brahmagupta’s formula . Below is the implementation of given approach "
},
{
"code": null,
"e": 25400,
"s": 25396,
"text": "C++"
},
{
"code": null,
"e": 25402,
"s": 25400,
"text": "C"
},
{
"code": null,
"e": 25407,
"s": 25402,
"text": "Java"
},
{
"code": null,
"e": 25415,
"s": 25407,
"text": "Python3"
},
{
"code": null,
"e": 25418,
"s": 25415,
"text": "C#"
},
{
"code": null,
"e": 25422,
"s": 25418,
"text": "PHP"
},
{
"code": null,
"e": 25433,
"s": 25422,
"text": "Javascript"
},
{
"code": "// CPP program to find maximum are of a // quadrilateral#include <iostream>#include <math.h>using namespace std; double maxArea(double a, double b, double c, double d){ // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d));} // Driver codeint main(){ double a = 1, b = 2, c= 1, d = 2; cout <<maxArea(a, b, c, d); return 0;} // This code is contributed by shivanisinghss2110",
"e": 26131,
"s": 25433,
"text": null
},
{
"code": "// CPP program to find maximum are of a // quadrilateral#include <stdio.h>#include <math.h> double maxArea(double a, double b, double c, double d){ // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d));} // Driver codeint main(){ double a = 1, b = 2, c= 1, d = 2; printf(\"%.2f\\n\",maxArea(a, b, c, d)); return 0;}",
"e": 26768,
"s": 26131,
"text": null
},
{
"code": "// Java program to find maximum are of a // quadrilateralimport java.io.*; class GFG { static double maxArea(double a, double b, double c, double d) { // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code public static void main (String[] args) { double a = 1, b = 2, c= 1, d = 2; System.out.println(maxArea(a, b, c, d)); }} // This code is contributed by sunnysingh",
"e": 27578,
"s": 26768,
"text": null
},
{
"code": "# Python3 program to find maximum # area of a quadrilateralimport math def maxArea (a , b , c , d ): # Calculating the semi-perimeter # of the given quadrilateral semiperimeter = (a + b + c + d) / 2 # Applying Brahmagupta's formula to # get maximum area of quadrilateral return math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)) # Driver codea = 1b = 2c = 1d = 2print(\"%.2f\"%maxArea(a, b, c, d)) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 28156,
"s": 27578,
"text": null
},
{
"code": "// C# program to find maximum are of a // quadrilateralusing System; class GFG { static double maxArea(double a, double b, double c, double d) { // Calculating the semi-perimeter // of the given quadrilateral double semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.Sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code public static void Main () { double a = 1, b = 2, c= 1, d = 2; Console.WriteLine(maxArea(a, b, c, d)); }} // This code is contributed by vt_m.",
"e": 28966,
"s": 28156,
"text": null
},
{
"code": "<?php// PHP program to find maximum are of a // quadrilateral function maxArea( $a, $b, $c, $d){ // Calculating the semi-perimeter // of the given quadrilateral $semiperimeter = ($a + $b + $c + $d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return sqrt(($semiperimeter - $a) * ($semiperimeter - $b) * ($semiperimeter - $c) * ($semiperimeter - $d));} // Driver code$a = 1; $b = 2; $c= 1; $d = 2;echo(maxArea($a, $b, $c, $d)); // This code is contributed by vt_m.?>",
"e": 29543,
"s": 28966,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum are of a // quadrilateral function maxArea(a, b, c, d) { // Calculating the semi-perimeter // of the given quadrilateral let semiperimeter = (a + b + c + d) / 2; // Applying Brahmagupta's formula to // get maximum area of quadrilateral return Math.sqrt((semiperimeter - a) * (semiperimeter - b) * (semiperimeter - c) * (semiperimeter - d)); } // Driver code let a = 1, b = 2, c= 1, d = 2; document.write(maxArea(a, b, c, d)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 30163,
"s": 29543,
"text": null
},
{
"code": null,
"e": 30173,
"s": 30163,
"text": "Output: "
},
{
"code": null,
"e": 30178,
"s": 30173,
"text": "2.00"
},
{
"code": null,
"e": 30185,
"s": 30180,
"text": "vt_m"
},
{
"code": null,
"e": 30199,
"s": 30185,
"text": "surbhityagi15"
},
{
"code": null,
"e": 30215,
"s": 30199,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 30234,
"s": 30215,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 30255,
"s": 30234,
"text": "area-volume-programs"
},
{
"code": null,
"e": 30265,
"s": 30255,
"text": "Geometric"
},
{
"code": null,
"e": 30284,
"s": 30265,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30294,
"s": 30284,
"text": "Geometric"
},
{
"code": null,
"e": 30392,
"s": 30294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30401,
"s": 30392,
"text": "Comments"
},
{
"code": null,
"e": 30414,
"s": 30401,
"text": "Old Comments"
},
{
"code": null,
"e": 30463,
"s": 30414,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 30516,
"s": 30463,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 30567,
"s": 30516,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30616,
"s": 30567,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 30674,
"s": 30616,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 30708,
"s": 30674,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30769,
"s": 30708,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 30817,
"s": 30769,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 30864,
"s": 30817,
"text": "Program for Point of Intersection of Two Lines"
}
] |
How to run multiple test cases using TestNG Test Suite in Selenium?
|
We can run multiple test cases using TestNG test suite in Selenium webdriver. To execute test cases simultaneously, we have to enable parallel execution in TestNG.
A TestNG execution is driven by the TestNG xml file. To trigger parallel execution we have to use the attributes – parallel and thread-count. The attribute threadcount controls the number of threads to be triggered while executing the tests in a parallel mode. The values that can be set for parallel attributes are – tests, classes, instances and methods.
import org.testng.annotations.Test;
public class TestNG15 {
@Test
public void tC1() {
System.out.println("Test Case 1");
}
@Test
public void tC2() {
System.out.println("Test Case 2");
}
@Test
public void tC3() {
System.out.println("Test Case 3");
}
@Test
public void tC4() {
System.out.println("Test Case 4");
}
}
TestNG XML Implementation.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<!—parallel methods set for execution with 2 threads-->
<suite name="Test-Suite" parallel="methods" thread-count="2">
<test name="Tutorialspoint" >
<classes>
<class name="TestNG15" />
</classes>
</test>
</suite>
TestNG report in html format obtained from project folder test-output→index.html.
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "We can run multiple test cases using TestNG test suite in Selenium webdriver. To execute test cases simultaneously, we have to enable parallel execution in TestNG."
},
{
"code": null,
"e": 1583,
"s": 1226,
"text": "A TestNG execution is driven by the TestNG xml file. To trigger parallel execution we have to use the attributes – parallel and thread-count. The attribute threadcount controls the number of threads to be triggered while executing the tests in a parallel mode. The values that can be set for parallel attributes are – tests, classes, instances and methods."
},
{
"code": null,
"e": 1957,
"s": 1583,
"text": "import org.testng.annotations.Test;\npublic class TestNG15 {\n @Test\n public void tC1() {\n System.out.println(\"Test Case 1\");\n }\n @Test\n public void tC2() {\n System.out.println(\"Test Case 2\");\n }\n @Test\n public void tC3() {\n System.out.println(\"Test Case 3\");\n }\n @Test\n public void tC4() {\n System.out.println(\"Test Case 4\");\n }\n}"
},
{
"code": null,
"e": 1984,
"s": 1957,
"text": "TestNG XML Implementation."
},
{
"code": null,
"e": 2284,
"s": 1984,
"text": "<!DOCTYPE suite SYSTEM \"https://testng.org/testng-1.0.dtd\" >\n<!—parallel methods set for execution with 2 threads-->\n<suite name=\"Test-Suite\" parallel=\"methods\" thread-count=\"2\">\n <test name=\"Tutorialspoint\" >\n <classes>\n <class name=\"TestNG15\" />\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 2366,
"s": 2284,
"text": "TestNG report in html format obtained from project folder test-output→index.html."
}
] |
AtomicInteger set() method in Java with examples - GeeksforGeeks
|
29 Jan, 2019
The java.util.concurrent.atomic.AtomicInteger.set() is an inbuilt method in java that updates the previous value and sets it to a new value which is passed in the parameter.
Syntax:
public final void set(int newVal)
Parameters: The function accepts a single mandatory parameter newVal which is to be updated.
Return value: The function does not returns anything.
Program below demonstrates the function:
Program 1:
// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); System.out.println("Previous value: " + val); val.set(10); // Prints the updated value System.out.println("Current value: " + val); }}
Previous value: 0
Current value: 10
Program 2:
// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicInteger val = new AtomicInteger(18); System.out.println("Previous value: " + val); val.set(200); // Prints the updated value System.out.println("Current value: " + val); }}
Previous value: 18
Current value: 200
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#set–
Java - util package
Java-AtomicInteger
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Multithreading in Java
|
[
{
"code": null,
"e": 24500,
"s": 24472,
"text": "\n29 Jan, 2019"
},
{
"code": null,
"e": 24674,
"s": 24500,
"text": "The java.util.concurrent.atomic.AtomicInteger.set() is an inbuilt method in java that updates the previous value and sets it to a new value which is passed in the parameter."
},
{
"code": null,
"e": 24682,
"s": 24674,
"text": "Syntax:"
},
{
"code": null,
"e": 24717,
"s": 24682,
"text": "public final void set(int newVal)\n"
},
{
"code": null,
"e": 24810,
"s": 24717,
"text": "Parameters: The function accepts a single mandatory parameter newVal which is to be updated."
},
{
"code": null,
"e": 24864,
"s": 24810,
"text": "Return value: The function does not returns anything."
},
{
"code": null,
"e": 24905,
"s": 24864,
"text": "Program below demonstrates the function:"
},
{
"code": null,
"e": 24916,
"s": 24905,
"text": "Program 1:"
},
{
"code": "// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicInteger val = new AtomicInteger(0); System.out.println(\"Previous value: \" + val); val.set(10); // Prints the updated value System.out.println(\"Current value: \" + val); }}",
"e": 25406,
"s": 24916,
"text": null
},
{
"code": null,
"e": 25443,
"s": 25406,
"text": "Previous value: 0\nCurrent value: 10\n"
},
{
"code": null,
"e": 25454,
"s": 25443,
"text": "Program 2:"
},
{
"code": "// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicInteger; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicInteger val = new AtomicInteger(18); System.out.println(\"Previous value: \" + val); val.set(200); // Prints the updated value System.out.println(\"Current value: \" + val); }}",
"e": 25947,
"s": 25454,
"text": null
},
{
"code": null,
"e": 25986,
"s": 25947,
"text": "Previous value: 18\nCurrent value: 200\n"
},
{
"code": null,
"e": 26091,
"s": 25986,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#set–"
},
{
"code": null,
"e": 26111,
"s": 26091,
"text": "Java - util package"
},
{
"code": null,
"e": 26130,
"s": 26111,
"text": "Java-AtomicInteger"
},
{
"code": null,
"e": 26145,
"s": 26130,
"text": "Java-Functions"
},
{
"code": null,
"e": 26150,
"s": 26145,
"text": "Java"
},
{
"code": null,
"e": 26155,
"s": 26150,
"text": "Java"
},
{
"code": null,
"e": 26253,
"s": 26155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26262,
"s": 26253,
"text": "Comments"
},
{
"code": null,
"e": 26275,
"s": 26262,
"text": "Old Comments"
},
{
"code": null,
"e": 26305,
"s": 26275,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26337,
"s": 26305,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26388,
"s": 26337,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26407,
"s": 26388,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26425,
"s": 26407,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26456,
"s": 26425,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26488,
"s": 26456,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26507,
"s": 26488,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 26527,
"s": 26507,
"text": "Stack Class in Java"
}
] |
Exploratory Factor Analysis vs Principal Components: from concept to application | by Rafael Valdece Sousa Bastos | Towards Data Science
|
In data science, we often want to measure variables such as social-economic status (SES). Some variables have a lot of parameters (or items), for example, SES can be measured based on income, education, etc. Then, to proceed with the analysis, it is common to reduce the number of parameters to fewer components through Principal Components Analysis (PCA). However, we will see why some variables cannot be reduced by PCA and we will learn how to use Exploratory Factor Analysis in our favor.
Both of them are used to reduce the number of parameters to fewer variables. Also, both methods assume that the variance of a parameter is divided into specific variance, common variance, and error variance.
In PCA, when we retain a component, we take into account both specific variance and common variance. While in EFA we only take into account common variance. Seeing the next figure, we can think that A’s are specific variances, B is the common variance, and C’s are error variances. In PCA we use A’s + B while in EFA we only use B.
PCA is based on the formative model, where the variation in the component is based on the variation in item responses (i.e. level of income will affect the social-economic status). While EFA is based on the reflective model, where the variation of the items is based on the variation of a construct (i.e. a person's happiness will change their response to the items, not the contrary). We can see this representation with the following figure.
With that being said, the common application of EFA is to measure psychological variables. For example, if you want to measure a person’s level of happiness we will use only the common variance because the items of the instrument are trying to measure what they have in common (i.e. the level of happiness).
PCA has mostly three main steps.
Compute the covariance matrixCompute eigenvalues and eigenvectorsRotation of components
Compute the covariance matrix
Compute eigenvalues and eigenvectors
Rotation of components
While in EFA we have:
Verification of data adequacyComputation of covariance/correlation matrix (Factor Extraction)Selection of factors to retainRotation of factors
Verification of data adequacy
Computation of covariance/correlation matrix (Factor Extraction)
Selection of factors to retain
Rotation of factors
Since there are a lot of posts here on Towards Data Science regarding PCA, I will focus on EFA from now on. In the next section, I will describe each step from EFA.
We usually use two tests to measure if our data is adequate to proceed with EFA.
Bartlett’s test of sphericity
This test verifies the hypothesis that variables are not correlated in the population. Therefore, the null hypothesis is that the correlation matrix is equal to an identity matrix. If the correlation matrix is equal to an identity matrix, we cannot proceed with EFA, since there is no correlation between variables. The statistical analysis behind this test goes as follows:
χ2 =- [(n-1)-(2v+5)/6]ln|R|
Wheren is the sample sizev is the number of variables|R| is the determinant of the correlation matrix
In the literature, we can see that if the level of significance equals p < 0.05 that means we can proceed with EFA.
Kaiser-Meyer-Olkin (KMO)
Verify the proportion of variance of items that can be caused by factors. The test verifies if the inverse correlation matrix is close to a diagonal matrix, comparing the values of linear correlations with values of partial correlations.
Where:
rjk = correlation coefficient between Xj and Xk
pjk = correlation coefficient between Xj and Xk, controlling for other Xs.
Values under 0.5 are considered unacceptable, between 0.50 and 0.70 are mediocre, between 0.70 and 0.80 are good, above 0.80 are considered great and above 0.90 are excellent.
In EFA we have a lot of methods of extraction to choose from. If data are normally distributed, it is recommended to use maximum likelihood, since it enables a variety of goodness of fit indices, significance test of factor loadings, calculation of confidence intervals, etc. However, if the data doesn’t follow a normal distribution, it is recommended to use principal axis factoring.
There are a lot of methods we can use to select the number of items, I will focus mainly on three of them.
a) Kaiser criterion: it proposes if a factor’s eigenvalue is above 1.0, we should retain that factor. The logic behind it is: if a factor has an eigenvalue = 3.0, that means that the factor explains the same amount of variance as 3 items.
Watch out, this criterion is known to over and underestimate the number of factors. I would not recommend using it alone.
b) Scree plot: where we evaluate when there is a substantial decline in the magnitude of the eigenvalues. This method also has some limitations, because it can generate ambiguous results and are open to subjective interpretation.
c) Parallel analysis: the eigenvalue of the sample and eigenvalue of random data are calculated. The number of factors is selected when the number of eigenvalues of real data is bigger than from simulated data. This method usually works well.
Now we will see a tutorial for computing an EFA in R. We will be using the package psych to make our computations. Also, we will be using the Positive and Negative Affects Scale, which consists of items regarding negative and positive emotions.
We will read the dataset using the R function read.delim
Affects <- read.delim(“https://raw.githubusercontent.com/rafavsbastos/data/main/Afetos.dat")
The name we choose for our data frame was Affets. Using View(Affects) we will see our dataset:
To start manipulating data, we will need to download the psych package. Just run the following code.
install.packages(“psych”)
Ok. Now the package is on your computer. Now, we need to make it start working with library(psych) .
To see if it’s ok to do EFA with our data, we will first calculate Bartlett’s test of sphericity.
First, we calculate the correlation matrix:
correlation <- cor(Affects)
Then, we will calculate Bartlett’s test with cortest.bartlett(correlation, n=1033) , where the second argument is the sample size. We will have the following output:
The significance level was smaller than 0.05, which means we can proceed with EFA (if we assume values under 0.05 indicate the adequacy of our data).
Now we will compute KMO. Use the following code KMO(Affects) .
We can see that the overall Measure of Sample Adequacy (MSA) was 0.94, which means that it’s excellent. We can also see the MSA of each item below the overall MSA. Based on these results, we can proceed with EFA.
Using only one line of code, we will be able to extract the number of factors and select which factors we are going to retain.
fa.parallel(Affects,fm=”pa”, fa=”fa”, main = “Parallel Analysis Scree Plot”, n.iter=500)
Where:
the first argument is our data framefm is the extraction method; we are using principal axis factoring (“pa”)fa = “fa” ; if we write “fa” we will be doing an EFA. If we write “pc” we will be doing a PCA. Since we are using the reflective model, we will be doing an EFA.main = title of our image.n.iter = number of interactions we wish to do.
the first argument is our data frame
fm is the extraction method; we are using principal axis factoring (“pa”)
fa = “fa” ; if we write “fa” we will be doing an EFA. If we write “pc” we will be doing a PCA. Since we are using the reflective model, we will be doing an EFA.
main = title of our image.
n.iter = number of interactions we wish to do.
We will have the following output:
It tells us that we need to retain 3 factors based on Parallel Analysis. Another output from the same line of code is the next figure:
We can see our data eigenvalues (in blue) and the simulated data eigenvalues (in red). Look at the intersection between the red and blue eigenvalues and notice that the fourth eigenvalue of some random data explains more variance than the fourth eigenvalue from our data. However, if we consider the Kaiser criterion (black line crossing the figure), we will be extracting just two factors. Since we want to retain as few factors as possible, we will proceed with the analysis with only two factors.
Before we jump to the next section, I want to show you the difference between PCA and EFA when extracting the eigenvalues.
fa.parallel(Affects, fm = "pa", cor = "cor", fa= "both", main = "Parallel Analysis Scree Plot", n.iter=500)
In the figure above, PC represents principal components and FA represents factor analysis. If we use the Kaiser criterion in PCA, we will retain three factors, while if we use Parallel Analysis criterion, we will retain 2 factors. We can also notice that eigenvalues of PCA are higher than from the EFA, that’s because of that thing I said before, PCA takes into account common and specific variance, while EFA only takes common variance.
We can see which items explain more of the factor based on factor loadings, commonalities. Also, with the following code we can see explained variance and goodness of fit indices of our two-factor model:
fit <- fa(Affects, nfactors = 2, n.obs = 1033 , rotate = “oblimin”, residuals = TRUE, fm = “pa”)print(fit, sort = TRUE)
That prints out:
In the first table, we can see that Positive Affects Items (AP’s) load strongly on the first factor (PA1), while Negative Affects Items (AN’s) load strongly on the second factor (PA2). The commonality is represented by h2.
Bellow the first table, we have the proportion of explained variance for each factor. The factor of Positive Affects (PA1) explained 25% of the data variance, while the Negative Affects (PA2) explained 24%.
The goodness of fit indices is also calculated. Although they are widely used in Confirmatory Factor Analysis, their use in EFA is a bit of a mystery. There are few studies that evaluate the use of goodness of fit indices in EFA, therefore it may be difficult to interpret this part of the data.
To obtain a visual representation of the factor loadings, we will use the function fa.diagram(fit).
We can also see a geometric visualization of factors in their axis with plot(fit) .
In the graphic above, we want our Positive Affects items to be closer together while staying far from the cluster of Negative Affects items.
Given all steps so far, we can see that our measure presented a two-factor structure, which is the same as was theorized by previous authors. In addition, we found that items loaded in their given factors, and the factors explained a good portion of the variance.
I must highlight that, although we have statistical methods to select the number of factors to retain, only the researcher can choose which method will be the best one. That means the criterion to select the best method to retain factors is open to subjective interpretation. Also, I presented a statistical tool to analyze psychological data where the reflective model is more adequate.
Feel free to contact me by
Gmail: rafavsbastos@gmail.comWebsite for consulting and partnerships: rafavsbastos.wixsite.com/websiteLinkedIn: linkedin.com/in/rafael-valdece-sousa-bastos/Github: github.com/rafavsbastos
|
[
{
"code": null,
"e": 665,
"s": 172,
"text": "In data science, we often want to measure variables such as social-economic status (SES). Some variables have a lot of parameters (or items), for example, SES can be measured based on income, education, etc. Then, to proceed with the analysis, it is common to reduce the number of parameters to fewer components through Principal Components Analysis (PCA). However, we will see why some variables cannot be reduced by PCA and we will learn how to use Exploratory Factor Analysis in our favor."
},
{
"code": null,
"e": 873,
"s": 665,
"text": "Both of them are used to reduce the number of parameters to fewer variables. Also, both methods assume that the variance of a parameter is divided into specific variance, common variance, and error variance."
},
{
"code": null,
"e": 1205,
"s": 873,
"text": "In PCA, when we retain a component, we take into account both specific variance and common variance. While in EFA we only take into account common variance. Seeing the next figure, we can think that A’s are specific variances, B is the common variance, and C’s are error variances. In PCA we use A’s + B while in EFA we only use B."
},
{
"code": null,
"e": 1649,
"s": 1205,
"text": "PCA is based on the formative model, where the variation in the component is based on the variation in item responses (i.e. level of income will affect the social-economic status). While EFA is based on the reflective model, where the variation of the items is based on the variation of a construct (i.e. a person's happiness will change their response to the items, not the contrary). We can see this representation with the following figure."
},
{
"code": null,
"e": 1957,
"s": 1649,
"text": "With that being said, the common application of EFA is to measure psychological variables. For example, if you want to measure a person’s level of happiness we will use only the common variance because the items of the instrument are trying to measure what they have in common (i.e. the level of happiness)."
},
{
"code": null,
"e": 1990,
"s": 1957,
"text": "PCA has mostly three main steps."
},
{
"code": null,
"e": 2078,
"s": 1990,
"text": "Compute the covariance matrixCompute eigenvalues and eigenvectorsRotation of components"
},
{
"code": null,
"e": 2108,
"s": 2078,
"text": "Compute the covariance matrix"
},
{
"code": null,
"e": 2145,
"s": 2108,
"text": "Compute eigenvalues and eigenvectors"
},
{
"code": null,
"e": 2168,
"s": 2145,
"text": "Rotation of components"
},
{
"code": null,
"e": 2190,
"s": 2168,
"text": "While in EFA we have:"
},
{
"code": null,
"e": 2333,
"s": 2190,
"text": "Verification of data adequacyComputation of covariance/correlation matrix (Factor Extraction)Selection of factors to retainRotation of factors"
},
{
"code": null,
"e": 2363,
"s": 2333,
"text": "Verification of data adequacy"
},
{
"code": null,
"e": 2428,
"s": 2363,
"text": "Computation of covariance/correlation matrix (Factor Extraction)"
},
{
"code": null,
"e": 2459,
"s": 2428,
"text": "Selection of factors to retain"
},
{
"code": null,
"e": 2479,
"s": 2459,
"text": "Rotation of factors"
},
{
"code": null,
"e": 2644,
"s": 2479,
"text": "Since there are a lot of posts here on Towards Data Science regarding PCA, I will focus on EFA from now on. In the next section, I will describe each step from EFA."
},
{
"code": null,
"e": 2725,
"s": 2644,
"text": "We usually use two tests to measure if our data is adequate to proceed with EFA."
},
{
"code": null,
"e": 2755,
"s": 2725,
"text": "Bartlett’s test of sphericity"
},
{
"code": null,
"e": 3130,
"s": 2755,
"text": "This test verifies the hypothesis that variables are not correlated in the population. Therefore, the null hypothesis is that the correlation matrix is equal to an identity matrix. If the correlation matrix is equal to an identity matrix, we cannot proceed with EFA, since there is no correlation between variables. The statistical analysis behind this test goes as follows:"
},
{
"code": null,
"e": 3158,
"s": 3130,
"text": "χ2 =- [(n-1)-(2v+5)/6]ln|R|"
},
{
"code": null,
"e": 3260,
"s": 3158,
"text": "Wheren is the sample sizev is the number of variables|R| is the determinant of the correlation matrix"
},
{
"code": null,
"e": 3376,
"s": 3260,
"text": "In the literature, we can see that if the level of significance equals p < 0.05 that means we can proceed with EFA."
},
{
"code": null,
"e": 3401,
"s": 3376,
"text": "Kaiser-Meyer-Olkin (KMO)"
},
{
"code": null,
"e": 3639,
"s": 3401,
"text": "Verify the proportion of variance of items that can be caused by factors. The test verifies if the inverse correlation matrix is close to a diagonal matrix, comparing the values of linear correlations with values of partial correlations."
},
{
"code": null,
"e": 3646,
"s": 3639,
"text": "Where:"
},
{
"code": null,
"e": 3694,
"s": 3646,
"text": "rjk = correlation coefficient between Xj and Xk"
},
{
"code": null,
"e": 3769,
"s": 3694,
"text": "pjk = correlation coefficient between Xj and Xk, controlling for other Xs."
},
{
"code": null,
"e": 3945,
"s": 3769,
"text": "Values under 0.5 are considered unacceptable, between 0.50 and 0.70 are mediocre, between 0.70 and 0.80 are good, above 0.80 are considered great and above 0.90 are excellent."
},
{
"code": null,
"e": 4331,
"s": 3945,
"text": "In EFA we have a lot of methods of extraction to choose from. If data are normally distributed, it is recommended to use maximum likelihood, since it enables a variety of goodness of fit indices, significance test of factor loadings, calculation of confidence intervals, etc. However, if the data doesn’t follow a normal distribution, it is recommended to use principal axis factoring."
},
{
"code": null,
"e": 4438,
"s": 4331,
"text": "There are a lot of methods we can use to select the number of items, I will focus mainly on three of them."
},
{
"code": null,
"e": 4677,
"s": 4438,
"text": "a) Kaiser criterion: it proposes if a factor’s eigenvalue is above 1.0, we should retain that factor. The logic behind it is: if a factor has an eigenvalue = 3.0, that means that the factor explains the same amount of variance as 3 items."
},
{
"code": null,
"e": 4799,
"s": 4677,
"text": "Watch out, this criterion is known to over and underestimate the number of factors. I would not recommend using it alone."
},
{
"code": null,
"e": 5029,
"s": 4799,
"text": "b) Scree plot: where we evaluate when there is a substantial decline in the magnitude of the eigenvalues. This method also has some limitations, because it can generate ambiguous results and are open to subjective interpretation."
},
{
"code": null,
"e": 5272,
"s": 5029,
"text": "c) Parallel analysis: the eigenvalue of the sample and eigenvalue of random data are calculated. The number of factors is selected when the number of eigenvalues of real data is bigger than from simulated data. This method usually works well."
},
{
"code": null,
"e": 5517,
"s": 5272,
"text": "Now we will see a tutorial for computing an EFA in R. We will be using the package psych to make our computations. Also, we will be using the Positive and Negative Affects Scale, which consists of items regarding negative and positive emotions."
},
{
"code": null,
"e": 5574,
"s": 5517,
"text": "We will read the dataset using the R function read.delim"
},
{
"code": null,
"e": 5667,
"s": 5574,
"text": "Affects <- read.delim(“https://raw.githubusercontent.com/rafavsbastos/data/main/Afetos.dat\")"
},
{
"code": null,
"e": 5762,
"s": 5667,
"text": "The name we choose for our data frame was Affets. Using View(Affects) we will see our dataset:"
},
{
"code": null,
"e": 5863,
"s": 5762,
"text": "To start manipulating data, we will need to download the psych package. Just run the following code."
},
{
"code": null,
"e": 5889,
"s": 5863,
"text": "install.packages(“psych”)"
},
{
"code": null,
"e": 5990,
"s": 5889,
"text": "Ok. Now the package is on your computer. Now, we need to make it start working with library(psych) ."
},
{
"code": null,
"e": 6088,
"s": 5990,
"text": "To see if it’s ok to do EFA with our data, we will first calculate Bartlett’s test of sphericity."
},
{
"code": null,
"e": 6132,
"s": 6088,
"text": "First, we calculate the correlation matrix:"
},
{
"code": null,
"e": 6160,
"s": 6132,
"text": "correlation <- cor(Affects)"
},
{
"code": null,
"e": 6326,
"s": 6160,
"text": "Then, we will calculate Bartlett’s test with cortest.bartlett(correlation, n=1033) , where the second argument is the sample size. We will have the following output:"
},
{
"code": null,
"e": 6476,
"s": 6326,
"text": "The significance level was smaller than 0.05, which means we can proceed with EFA (if we assume values under 0.05 indicate the adequacy of our data)."
},
{
"code": null,
"e": 6539,
"s": 6476,
"text": "Now we will compute KMO. Use the following code KMO(Affects) ."
},
{
"code": null,
"e": 6752,
"s": 6539,
"text": "We can see that the overall Measure of Sample Adequacy (MSA) was 0.94, which means that it’s excellent. We can also see the MSA of each item below the overall MSA. Based on these results, we can proceed with EFA."
},
{
"code": null,
"e": 6879,
"s": 6752,
"text": "Using only one line of code, we will be able to extract the number of factors and select which factors we are going to retain."
},
{
"code": null,
"e": 6969,
"s": 6879,
"text": "fa.parallel(Affects,fm=”pa”, fa=”fa”, main = “Parallel Analysis Scree Plot”, n.iter=500)"
},
{
"code": null,
"e": 6976,
"s": 6969,
"text": "Where:"
},
{
"code": null,
"e": 7318,
"s": 6976,
"text": "the first argument is our data framefm is the extraction method; we are using principal axis factoring (“pa”)fa = “fa” ; if we write “fa” we will be doing an EFA. If we write “pc” we will be doing a PCA. Since we are using the reflective model, we will be doing an EFA.main = title of our image.n.iter = number of interactions we wish to do."
},
{
"code": null,
"e": 7355,
"s": 7318,
"text": "the first argument is our data frame"
},
{
"code": null,
"e": 7429,
"s": 7355,
"text": "fm is the extraction method; we are using principal axis factoring (“pa”)"
},
{
"code": null,
"e": 7590,
"s": 7429,
"text": "fa = “fa” ; if we write “fa” we will be doing an EFA. If we write “pc” we will be doing a PCA. Since we are using the reflective model, we will be doing an EFA."
},
{
"code": null,
"e": 7617,
"s": 7590,
"text": "main = title of our image."
},
{
"code": null,
"e": 7664,
"s": 7617,
"text": "n.iter = number of interactions we wish to do."
},
{
"code": null,
"e": 7699,
"s": 7664,
"text": "We will have the following output:"
},
{
"code": null,
"e": 7834,
"s": 7699,
"text": "It tells us that we need to retain 3 factors based on Parallel Analysis. Another output from the same line of code is the next figure:"
},
{
"code": null,
"e": 8334,
"s": 7834,
"text": "We can see our data eigenvalues (in blue) and the simulated data eigenvalues (in red). Look at the intersection between the red and blue eigenvalues and notice that the fourth eigenvalue of some random data explains more variance than the fourth eigenvalue from our data. However, if we consider the Kaiser criterion (black line crossing the figure), we will be extracting just two factors. Since we want to retain as few factors as possible, we will proceed with the analysis with only two factors."
},
{
"code": null,
"e": 8457,
"s": 8334,
"text": "Before we jump to the next section, I want to show you the difference between PCA and EFA when extracting the eigenvalues."
},
{
"code": null,
"e": 8565,
"s": 8457,
"text": "fa.parallel(Affects, fm = \"pa\", cor = \"cor\", fa= \"both\", main = \"Parallel Analysis Scree Plot\", n.iter=500)"
},
{
"code": null,
"e": 9004,
"s": 8565,
"text": "In the figure above, PC represents principal components and FA represents factor analysis. If we use the Kaiser criterion in PCA, we will retain three factors, while if we use Parallel Analysis criterion, we will retain 2 factors. We can also notice that eigenvalues of PCA are higher than from the EFA, that’s because of that thing I said before, PCA takes into account common and specific variance, while EFA only takes common variance."
},
{
"code": null,
"e": 9208,
"s": 9004,
"text": "We can see which items explain more of the factor based on factor loadings, commonalities. Also, with the following code we can see explained variance and goodness of fit indices of our two-factor model:"
},
{
"code": null,
"e": 9328,
"s": 9208,
"text": "fit <- fa(Affects, nfactors = 2, n.obs = 1033 , rotate = “oblimin”, residuals = TRUE, fm = “pa”)print(fit, sort = TRUE)"
},
{
"code": null,
"e": 9345,
"s": 9328,
"text": "That prints out:"
},
{
"code": null,
"e": 9568,
"s": 9345,
"text": "In the first table, we can see that Positive Affects Items (AP’s) load strongly on the first factor (PA1), while Negative Affects Items (AN’s) load strongly on the second factor (PA2). The commonality is represented by h2."
},
{
"code": null,
"e": 9775,
"s": 9568,
"text": "Bellow the first table, we have the proportion of explained variance for each factor. The factor of Positive Affects (PA1) explained 25% of the data variance, while the Negative Affects (PA2) explained 24%."
},
{
"code": null,
"e": 10071,
"s": 9775,
"text": "The goodness of fit indices is also calculated. Although they are widely used in Confirmatory Factor Analysis, their use in EFA is a bit of a mystery. There are few studies that evaluate the use of goodness of fit indices in EFA, therefore it may be difficult to interpret this part of the data."
},
{
"code": null,
"e": 10171,
"s": 10071,
"text": "To obtain a visual representation of the factor loadings, we will use the function fa.diagram(fit)."
},
{
"code": null,
"e": 10255,
"s": 10171,
"text": "We can also see a geometric visualization of factors in their axis with plot(fit) ."
},
{
"code": null,
"e": 10396,
"s": 10255,
"text": "In the graphic above, we want our Positive Affects items to be closer together while staying far from the cluster of Negative Affects items."
},
{
"code": null,
"e": 10660,
"s": 10396,
"text": "Given all steps so far, we can see that our measure presented a two-factor structure, which is the same as was theorized by previous authors. In addition, we found that items loaded in their given factors, and the factors explained a good portion of the variance."
},
{
"code": null,
"e": 11048,
"s": 10660,
"text": "I must highlight that, although we have statistical methods to select the number of factors to retain, only the researcher can choose which method will be the best one. That means the criterion to select the best method to retain factors is open to subjective interpretation. Also, I presented a statistical tool to analyze psychological data where the reflective model is more adequate."
},
{
"code": null,
"e": 11075,
"s": 11048,
"text": "Feel free to contact me by"
}
] |
How to Run MySQL and phpMyAdmin Using Docker | by Mahbub Zaman | Towards Data Science
|
Managing a MySQL server using the command-line interface can be difficult for many people. It becomes a lot easier when we can work with a graphical interface. The database administration tool phpMyAdmin solves that problem. We can use this tool over a web interface. It supports MySQL and MariaDB with a wide variety of operations, such as import data, export data, execution of SQL statements, and many more.
We will use Docker for our setup because running and managing phpMyAdmin on a different machine can be nerve-wracking for environment management. Docker solves this problem by using its containerization technology, which uses Docker images. Previously, I’ve discussed how to run MySQL using Docker. You can read the following post, where I’ve covered some basic concepts and commands of MySQL and Docker.
towardsdatascience.com
From this post, you’ll learn how to connect phpMyAdmin to a MySQL server using Docker. This method will save you time and effort since you don’t have to install or configure phpMyAdmin and MySQL.
There are two ways we can connect phpMyAdmin with MySQL using Docker. In the first method, we will use a single Docker compose file. For the second one, I’ll show you how to connect to an already running MySQL Docker container. First, you will need to install Docker. I’ll use macOS for both methods.
In this method, we will use a Docker compose file. We need to put docker-compose.yml inside a folder. The folder name used in this setup is phpMyAdmin. Let’s break down the individual ingredients of the docker-compose.yml file.
version: '3.1'services: db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test_db ports: - "3308:3306" phpmyadmin: image: phpmyadmin/phpmyadmin:latest restart: always environment: PMA_HOST: db PMA_USER: root PMA_PASSWORD: root ports: - "8080:80"
First, we are using a version tag to define the Compose file format, which is 3.1. There are other file formats — 1, 2, 2.x, and 3.x. Get more information on Compose file formats from Docker’s documentation here.
We follow our version tag by the services hash. Inside this, we have to define the services we want to use for our application. For our application, we have two services, db, and phpmyadmin.
To make our setup process quick and easy, we are using the pre-built official image of MySQL and phpMyAdmin for the image tag.
When we use always for the restart tag, the container always restarts. It can save time. For example, you don’t have to start the container every time you reboot your machine manually. It restarts the container when either the Docker daemon restarts or the container itself is manually restarted.
We have defined the environment variables under the environment tag, which we will use for database and phpMyAdmin authentication.
Finally, the ports tag is used to define both host and container ports. For the db service, it maps the port 3308 on the host to port 3306 on the MySQL container. For the phpmyadmin service, it maps the port 8080 on the host to port 80 on the phpMyAdmin container.
Now run the following command from the same directory where the docker-compose.yml file is located. The command docker compose up starts and runs your entire app. If you encounter the following error, that means you’re already running a Docker container on port 3308. To fix the problem, you just have to change to a different port, or you can stop the other container.
Bind for 0.0.0.0:3308 failed: port is already allocated
Now choose any web browser and go to the following address.
http://localhost:8080
Voila! you should see the web page like the one below on your browser.
As you can see, there is a warning message at the bottom. Let’s fix that now.
You are all set to manage your database!
In this method, you will learn how to connect a phpMyAdmin docker container to a MySQL container that is already running. It is helpful when you don’t have a phpMyAdmin service in your docker-compose file.
First, we need to list all the current Docker networks using the following command.
docker network ls
Now you should see phpmyadmin_default from the list. Our goal here is to find the application network that we have created using the docker-compose file in method one. Since we didn’t specify a network name in the docker-compose file for our application, Docker will give the network name based on the name of the directory with _default at the end. In this case, phpmyadmin_default. If you’re interested in Docker networks, check here.
Well done, you have successfully identified the network! Finally, we can run a stand-alone phpMyAdmin Docker container, which is connected to our desired network.
docker run --name stand-alone-phpmyadmin --network phpmyadmin_default -p 8081:80 phpmyadmin/phpmyadmin:latest
The docker run command is used to run a container from an image. Here we are using phpmyadmin/phpmyadmin:latest image.
The --name flag (optional) is used to give the container a specific name. If you don’t want to provide one, Docker will randomly assign a name.
The —-network flag is used to connect to a Docker network.
The -p flag is already discussed in this post.
Now choose any web browser and go to the following address. Use root as a username and password to log in.
http://localhost:8081/index.php
This method is helpful when you want to connect multiple Docker containers.
Database management can be a daunting task when we use a command-line interface. The web-based tool phpMyAdmin takes care of that problem, and Docker makes the entire process smoother. I use this setup to experiment with MySQL queries, which saves a lot of time. By using Docker, I don’t have to worry about MySQL and phpMyAdmin setup. I hope this will help you to get started with MySQL, phpMyAdmin, and Docker.
|
[
{
"code": null,
"e": 582,
"s": 171,
"text": "Managing a MySQL server using the command-line interface can be difficult for many people. It becomes a lot easier when we can work with a graphical interface. The database administration tool phpMyAdmin solves that problem. We can use this tool over a web interface. It supports MySQL and MariaDB with a wide variety of operations, such as import data, export data, execution of SQL statements, and many more."
},
{
"code": null,
"e": 987,
"s": 582,
"text": "We will use Docker for our setup because running and managing phpMyAdmin on a different machine can be nerve-wracking for environment management. Docker solves this problem by using its containerization technology, which uses Docker images. Previously, I’ve discussed how to run MySQL using Docker. You can read the following post, where I’ve covered some basic concepts and commands of MySQL and Docker."
},
{
"code": null,
"e": 1010,
"s": 987,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1206,
"s": 1010,
"text": "From this post, you’ll learn how to connect phpMyAdmin to a MySQL server using Docker. This method will save you time and effort since you don’t have to install or configure phpMyAdmin and MySQL."
},
{
"code": null,
"e": 1507,
"s": 1206,
"text": "There are two ways we can connect phpMyAdmin with MySQL using Docker. In the first method, we will use a single Docker compose file. For the second one, I’ll show you how to connect to an already running MySQL Docker container. First, you will need to install Docker. I’ll use macOS for both methods."
},
{
"code": null,
"e": 1735,
"s": 1507,
"text": "In this method, we will use a Docker compose file. We need to put docker-compose.yml inside a folder. The folder name used in this setup is phpMyAdmin. Let’s break down the individual ingredients of the docker-compose.yml file."
},
{
"code": null,
"e": 2080,
"s": 1735,
"text": "version: '3.1'services: db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test_db ports: - \"3308:3306\" phpmyadmin: image: phpmyadmin/phpmyadmin:latest restart: always environment: PMA_HOST: db PMA_USER: root PMA_PASSWORD: root ports: - \"8080:80\""
},
{
"code": null,
"e": 2293,
"s": 2080,
"text": "First, we are using a version tag to define the Compose file format, which is 3.1. There are other file formats — 1, 2, 2.x, and 3.x. Get more information on Compose file formats from Docker’s documentation here."
},
{
"code": null,
"e": 2484,
"s": 2293,
"text": "We follow our version tag by the services hash. Inside this, we have to define the services we want to use for our application. For our application, we have two services, db, and phpmyadmin."
},
{
"code": null,
"e": 2611,
"s": 2484,
"text": "To make our setup process quick and easy, we are using the pre-built official image of MySQL and phpMyAdmin for the image tag."
},
{
"code": null,
"e": 2908,
"s": 2611,
"text": "When we use always for the restart tag, the container always restarts. It can save time. For example, you don’t have to start the container every time you reboot your machine manually. It restarts the container when either the Docker daemon restarts or the container itself is manually restarted."
},
{
"code": null,
"e": 3039,
"s": 2908,
"text": "We have defined the environment variables under the environment tag, which we will use for database and phpMyAdmin authentication."
},
{
"code": null,
"e": 3304,
"s": 3039,
"text": "Finally, the ports tag is used to define both host and container ports. For the db service, it maps the port 3308 on the host to port 3306 on the MySQL container. For the phpmyadmin service, it maps the port 8080 on the host to port 80 on the phpMyAdmin container."
},
{
"code": null,
"e": 3674,
"s": 3304,
"text": "Now run the following command from the same directory where the docker-compose.yml file is located. The command docker compose up starts and runs your entire app. If you encounter the following error, that means you’re already running a Docker container on port 3308. To fix the problem, you just have to change to a different port, or you can stop the other container."
},
{
"code": null,
"e": 3730,
"s": 3674,
"text": "Bind for 0.0.0.0:3308 failed: port is already allocated"
},
{
"code": null,
"e": 3790,
"s": 3730,
"text": "Now choose any web browser and go to the following address."
},
{
"code": null,
"e": 3812,
"s": 3790,
"text": "http://localhost:8080"
},
{
"code": null,
"e": 3883,
"s": 3812,
"text": "Voila! you should see the web page like the one below on your browser."
},
{
"code": null,
"e": 3961,
"s": 3883,
"text": "As you can see, there is a warning message at the bottom. Let’s fix that now."
},
{
"code": null,
"e": 4002,
"s": 3961,
"text": "You are all set to manage your database!"
},
{
"code": null,
"e": 4208,
"s": 4002,
"text": "In this method, you will learn how to connect a phpMyAdmin docker container to a MySQL container that is already running. It is helpful when you don’t have a phpMyAdmin service in your docker-compose file."
},
{
"code": null,
"e": 4292,
"s": 4208,
"text": "First, we need to list all the current Docker networks using the following command."
},
{
"code": null,
"e": 4310,
"s": 4292,
"text": "docker network ls"
},
{
"code": null,
"e": 4747,
"s": 4310,
"text": "Now you should see phpmyadmin_default from the list. Our goal here is to find the application network that we have created using the docker-compose file in method one. Since we didn’t specify a network name in the docker-compose file for our application, Docker will give the network name based on the name of the directory with _default at the end. In this case, phpmyadmin_default. If you’re interested in Docker networks, check here."
},
{
"code": null,
"e": 4910,
"s": 4747,
"text": "Well done, you have successfully identified the network! Finally, we can run a stand-alone phpMyAdmin Docker container, which is connected to our desired network."
},
{
"code": null,
"e": 5020,
"s": 4910,
"text": "docker run --name stand-alone-phpmyadmin --network phpmyadmin_default -p 8081:80 phpmyadmin/phpmyadmin:latest"
},
{
"code": null,
"e": 5139,
"s": 5020,
"text": "The docker run command is used to run a container from an image. Here we are using phpmyadmin/phpmyadmin:latest image."
},
{
"code": null,
"e": 5283,
"s": 5139,
"text": "The --name flag (optional) is used to give the container a specific name. If you don’t want to provide one, Docker will randomly assign a name."
},
{
"code": null,
"e": 5342,
"s": 5283,
"text": "The —-network flag is used to connect to a Docker network."
},
{
"code": null,
"e": 5389,
"s": 5342,
"text": "The -p flag is already discussed in this post."
},
{
"code": null,
"e": 5496,
"s": 5389,
"text": "Now choose any web browser and go to the following address. Use root as a username and password to log in."
},
{
"code": null,
"e": 5528,
"s": 5496,
"text": "http://localhost:8081/index.php"
},
{
"code": null,
"e": 5604,
"s": 5528,
"text": "This method is helpful when you want to connect multiple Docker containers."
}
] |
Creating and Deploying using AWS CLI
|
AWS CLI is a command line tool which helps to work with AWS services. We can use it to create, update, delete, invoke aws lambda function. In this chapter, you will discuss about installation and usage of AWS CLI in detail.
This section will guide you through the installation of AWS CLI on various operating systems. Follow the steps given and observe corresponding screenshots wherever attached.
Check your Windows configuration and choose one of the following links for installing AWS CLI MSI −
For Windows 64 bit − AWS CLI MSI install for windows (64bit)
For Windows 64 bit − AWS CLI MSI install for windows (64bit)
For Windows 32 bit − AWS CLI MSI install for windows (32)
For Windows 32 bit − AWS CLI MSI install for windows (32)
Once you choose corresponding link and click it, you can find a Window as shown here −
Next, set the Environment path in windows as shown in the screenshots below −
Once done, you can use the following command on the command prompt, to see if aws cli is installed −
aws --version
It displays the details of aws-cli version as shown in the following screenshot −
For installing on Linux and Mac, you need Python 2.6.3 or higher verison of it. Then, use following commands for further installation processes −
$ curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
$ unzip awscli-bundle.zip
$ sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
Now, we need to configure AWS settings. You can use the following command for this purpose −
aws configure
For this purpose, it requires details such as −
AWS Access Key ID
AWS Secret Access Key
Default region name
Default output from format
You can obtain these details from your aws console. Go to you Account name at top right corner as shown −
Now, click My Security Credentials and select users from left side. Add user with details as asked.
Add the user and to get the access key and secret key. To see the new access key, choose Show. Your credentials will look like as shown below −
Access key ID − AOSAIOSFOCDD7Example
Secret access key − aJuirCVtnROUN/K7MDENG/bPxRfiCYExampleKEY
The following table will give command references available to work with aws cli.
Now, let us discuss these commands one by one in detail.
This api will create a new lambda function. The code needs to be given in zip format. If the function to be created already exists, the api will fail. Note that the function name is case-sensitive.
The list of commands that you can use with create-function is given here −
create-function
--function-name <value>
--runtime <value>
--role <value>
--handler <value>
[--code <value>]
[--description <value>]
[--timeout <value>]
[--memory-size <value>]
[--environment <value>]
[--kms-key-arn <value>]
[--tags <value>]
[--zip-file <value>]
[--cli-input-json <value>]
Various options that you can use with the functions above are as follows −
--function-name (string) − This takes the name of the function. The name can be 64-bit characters.
--runtime(string) − Here you need to specify the runtime environment ie the language selection. The details of the runtime are as given below −
--role(string) − This will be the name of the lambda policy ie the role to be given to the lambda function for accessing other services. It will have the permission as per the role specified.
--handler (string) − This is the name of the handler where the lambda code execution will start.
For nodejs, handler name is the module name that we export.
For java, it is package.classname :: handler or package.classname
For python, handler is nameofthefile.
--code (structure) −AWS Lambda code
--description (string) − description for the AWS Lambda function
--timeout (integer) − timeout will have the time at which the lambda function has to terminate execution. The default is 3s.
--memory-size (integer) − This is the memory given to the aws lambda function. AWS will allocate the amount of CPU and memory allocation based on the memory given.
--environment (structure) − its a object with environment details required in the aws lambda function.
e.g : Variables = {Name1 = string, Name2 = string}
--kms-key-arn (string) − this is amazon resource name (ARN) used to encrypt the environment variables. If not provided it will take the default settings to encrypt.
--zip-file (blob) − path of the zip file which has the details of the code.
--cli-input-json (string) : Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values.
Now, let us create a simple AWS Lambda function using runtime as nodejsand add some console.logs to be printed.
Consider a sample code for understanding the same −
exports.handler = async (event) => {
console.log("Using aws cli");
return 'Hello from Lambda from aws cli!'
};
Now, zip the file and store it as awscli.zip.
For the role, let us use the arn from the existing role we have created. To get the ARN, you will have to follow the steps as shown here. Observe the respective screenshots wherever attached −
Go to IAM and select the role you want from Roles. The ARN details for the role are displayed as shown below. Use Role ARN with create-function in aws cli.
Observe here that the role arn is : arn:aws:iam::625297745038:role/lambdaapipolicy
The command with values for create-function is as follows −
aws lambda create-function
--function-name "awslambdausingcli"
--runtime "nodejs8.10"
--role "arn:aws:iam::625297745038:role/lambdaapipolicy"
--handler "awscli.handler"
--timeout 5
--memory-size 256
--zip-file "fileb://awscli.zip"
Now, if you run the command in aws cli, you can find an output as shown below −
In AWS console, the Lambda function is displayed as shown below −
The details of the functions are as shown here −
The details of the configuration are as given below −
You can test the function and check the output as shown −
The corresponding Log output is shown here −
This api gives the list of functions created so far in AWS Lambda.
The following are the commands asscociated with this API −
list-functions
[--master-region <value>]
[--function-version <value>]
[--max-items <value>]
[--cli-input-json <value>]
The following are various options you can use under this list-functions api −
--master-region(string) − optional. The region from which the functions needs to be displayed.
--function-version(string) − optional. This will give the function version.
--max-items(integer) − optional. This will give the items as the per the value specified.
--cli-input-json(string) − optional. Will perform operation based on the json file provided.
The command with values list-functions is as follows −
aws lambda list-functions --max-items 3
The command displays details as follows −
This api will give details of the functions and also a url link which has zip file uploaded using create-function. The url with zip details will be valid only for 10 mins.
The following are the commands associated with this api −
get-function
--function-name <value>
[--qualifier <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
--function-name − Name of the AWS Lambda function. You can also specify Amazon Resource Name of the function.
--qualifier(string) − Optional. Function version can be used to get the details of the function.
The command with values to get-function are −
aws lambda get-function --function-name awslambdausingcli
The command display details are as follows −
It gives the url which has the zip code uploaded. In the above case the url is −
https://prod-04-2014-
tasks.s3.amazonaws.com/snapshots/625297745038/awslambdausingcli-97048f8d-4a08
-4ed9-99d9-acb00d2063d2?versionId=d04HKvPu9S2zz8pzjbW6Rmf5o5fxnc_r&X-Amz-Security
-Token=FQoDYXdzEKT%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDCpTmGvtwKToPBiWcyK3A96UcJEnwvYDhMbbxu
%2Bg2gffK2ocfnlEeiCHak8QqqE1RFpbKrdks9NzxP9gNbagL4M9RValxJ1a9PUY%2FOdAekscRHOiX00MVAxUlI8
2pKryhdOwLJWSj0uRzqvOxCcBwJenHrSNPeG6lMa2ZDo0qZFEUDONSaTg4nuSnJK1f6t3pMAKu4vF9wPvf92G%2BU
60rUxwleggigISmD9l1IlZse3%2BVF1JlNuN%2F5d85v0y2Q%2F%2BO515CybcZpn91sHPYG8JMJ00LsrkQ2Ww4VU
9Zz5c5QYH4JYPj0CyEgSz9b%2FMceMPpOoPUAMjctb%2FEwQqcShZeqAr9%2Fcd2ZI%2BXl2%2Bs4ri0ucgPvQQvs
eGIIiZbX3GqdwR2jb1nylrAEIfiuFMoSWfcFYoYtuL0MZnjGR9jy2GNkp6MB%2BlHHr7%2BnuFRUzU26rgDYmdE1w
Rb3%2B21Jm49WGDa9opRLvUxFaux57Or70haib2FuKzN6Gf3Vzzk5KPdWsYUpaLyf%2B1ovEytOZhB1JEXuCs%2FG
IlOXS88yxT%2BpOKmyxweiezpGgI%2FAkSAQTbSRsYQKIOFyIJNHzplwrJKhy28vy60numIBIo9Zqq2AU%3D
&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180527T112426Z&X-Amz-
SignedHeaders=host&X-Amz-Expires=600&X-Amz-
Credential=ASIAICSQHLSBWFP37U4Q%2F20180527%2Fus-
east-1%2Fs3%2Faws4_request&X-Amz-Signature=
8b97e7d6d7da13313068e027894d2c875be5e50a0c5a62550f55307985bdc1aa
This will give the configuration details of the AWS Lambda function.
The following are the commands used along with this api −
get-function-configuration
--function-name <value>
[--qualifier <value>]
The following are the options used with
--function-name (string) − name of the aws lambda function. You can also specify Amazon Resource Name of the function.
--qualifier(string) − Optional.Function version can be used to get the details of the function.
The command with values to get-function are −
aws lambda get-function-configuration --function-name awslambdausingcli
The command displays details as follows −
This api gives the accounts settings.
The command that you can use with this api are −
get-account-settings
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
You can use the following options with this api −
--cli-input-json(string) − Performs the service based on the json string provided.
--generate-cli-skeleton(string) − It prints json output without sending the API request.
You can use the following command for get-account-settings −
aws lambda get-account-settings
You can see the following output when you execute the command given above −
This api helps to update the configuration details for AWS Lambda function created. You can change the memory, timeout, handler, role, runtime, description etc.
The following are the commands involved in the update-function-configuration api −
update-function-configuration
--function-name <value>
[--role <value>]
[--handler <value>]
[--description <value>]
[--timeout <value>]
[--memory-size <value>]
[--environment <value>]
[--runtime <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
The following are the options involved in update-function-configuration api −
--function-name − name of the aws lambda function
--role (string) − optional. The ARN of role is needed to be updated.
--handler (string) − optional. The handler details of aws lambda function.
--description(string) − optional. Description for the function.
--timeout(integer) − optional. Time required so that aws lambda function can terminate.
--memory-size(integer) − optional. This is the memory given to the aws lambda function. AWS will allocate the amount of CPU and memory allocation based on the memory given.
--environment (structure) − optional. It is an object with environment details required in the aws lambda function.
e.g: Variables = {Name1 = string, Name2 = string}
--runtime(string) − Here you need to specify the runtime environment ie the language selection.
The details of the runtime are shown in the table given below −
--cli-input-json (string) − optional. This will perform the operation on the api as specified in the json string provided.
--generate-cli-skeleton (string) − optional. This will output the JSON skeleton of all details without executing the api. The output can be used as a input to --cli-input-json.
Now, let us chage the memory and timeout of AWS Lambda function that we have created earlier. Follow the Steps given below and observe the corresponding screenshots attached for this purpose −
The memory and timeout before the change occurred is as follows −
Now, with update-function-configuration, let us change the memory and timeout to 320MB and timeout to 10s. For this purpose, use the following command with values −
aws lambda update-function-configuration --function-name “awslambdusingcli”
--timeout 10 --memory-size 320
Then you can see the following output as the display −
The display in AWS console after using update-function-configuration is as follows −
This api will update the code for an existing AWS Lambda function.
update-function-code
--function-name <value>
[--zip-file <value>]
[--s3-bucket <value>]
[--s3-key <value>]
[--s3-object-version <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
The following are the options involved with the update-function-code api −
--function-name(string) − name of aws lambda function
--zip-file (blob) − optional. Path of the zip file which has the code to be updated.
--s3-bucket(string) − optional. S3 bucket name which has the zip file with code uploaded.
--s3-key(string) − optional. AWS s3 object key name which has to be uploaded.
--s3-object-version (string) − optional. AWS s3 object version.
--cli-input-json (string) − optional. This will perform the operation on the api as specified in the json string provided.
--generate-cli-skeleton (string) − optional. This will output the JSON skeleton of all details without executing the api. The output can be used as a input to --cli-input-json.
The updated code is as shown below −
exports.handler = async (event, context) => {
console.log("Using aws cli");
console.log()
return 'Hello from Lambda from aws cli!'
};
You can use the following command with values for this purpose −
aws lambda update-function-code --function-name "awslambdausingcli"
--zip-file "fileb://awscli.zip"
The corresponding output is as shown here −
The display from AWS console is as shown here −
The corresponding log output is as shown below −
The delete aws cli api will delete the function given.
The command details for the same are given here −
delete-function
--function-name <value>
[--qualifier <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
The options included in this api are as given below −
--function-name(string) − this will take the lambda function name or the arn of the aws lambda function.
--qualifier (string) − This is optional. Here you can specify the version of aws lambda that needs to be deleted.
-- cli-input-json(string) − Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values.
--generate-cli-skeleton(string) − it prints json skeleton to standard output without sending the API request.
aws lambda delete-function --function-name "lambdatestcli"
Now, observe that the function will not be seen in AWS Lambda function list −
35 Lectures
7.5 hours
Mr. Pradeep Kshetrapal
30 Lectures
3.5 hours
Priyanka Choudhary
44 Lectures
7.5 hours
Eduonix Learning Solutions
51 Lectures
6 hours
Manuj Aggarwal
41 Lectures
5 hours
AR Shankar
14 Lectures
1 hours
Zach Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2630,
"s": 2406,
"text": "AWS CLI is a command line tool which helps to work with AWS services. We can use it to create, update, delete, invoke aws lambda function. In this chapter, you will discuss about installation and usage of AWS CLI in detail."
},
{
"code": null,
"e": 2804,
"s": 2630,
"text": "This section will guide you through the installation of AWS CLI on various operating systems. Follow the steps given and observe corresponding screenshots wherever attached."
},
{
"code": null,
"e": 2904,
"s": 2804,
"text": "Check your Windows configuration and choose one of the following links for installing AWS CLI MSI −"
},
{
"code": null,
"e": 2965,
"s": 2904,
"text": "For Windows 64 bit − AWS CLI MSI install for windows (64bit)"
},
{
"code": null,
"e": 3026,
"s": 2965,
"text": "For Windows 64 bit − AWS CLI MSI install for windows (64bit)"
},
{
"code": null,
"e": 3084,
"s": 3026,
"text": "For Windows 32 bit − AWS CLI MSI install for windows (32)"
},
{
"code": null,
"e": 3142,
"s": 3084,
"text": "For Windows 32 bit − AWS CLI MSI install for windows (32)"
},
{
"code": null,
"e": 3229,
"s": 3142,
"text": "Once you choose corresponding link and click it, you can find a Window as shown here −"
},
{
"code": null,
"e": 3307,
"s": 3229,
"text": "Next, set the Environment path in windows as shown in the screenshots below −"
},
{
"code": null,
"e": 3408,
"s": 3307,
"text": "Once done, you can use the following command on the command prompt, to see if aws cli is installed −"
},
{
"code": null,
"e": 3423,
"s": 3408,
"text": "aws --version\n"
},
{
"code": null,
"e": 3505,
"s": 3423,
"text": "It displays the details of aws-cli version as shown in the following screenshot −"
},
{
"code": null,
"e": 3651,
"s": 3505,
"text": "For installing on Linux and Mac, you need Python 2.6.3 or higher verison of it. Then, use following commands for further installation processes −"
},
{
"code": null,
"e": 3832,
"s": 3651,
"text": "$ curl \"https://s3.amazonaws.com/aws-cli/awscli-bundle.zip\" -o \"awscli-bundle.zip\"\n$ unzip awscli-bundle.zip\n$ sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws\n"
},
{
"code": null,
"e": 3925,
"s": 3832,
"text": "Now, we need to configure AWS settings. You can use the following command for this purpose −"
},
{
"code": null,
"e": 3940,
"s": 3925,
"text": "aws configure\n"
},
{
"code": null,
"e": 3988,
"s": 3940,
"text": "For this purpose, it requires details such as −"
},
{
"code": null,
"e": 4006,
"s": 3988,
"text": "AWS Access Key ID"
},
{
"code": null,
"e": 4028,
"s": 4006,
"text": "AWS Secret Access Key"
},
{
"code": null,
"e": 4048,
"s": 4028,
"text": "Default region name"
},
{
"code": null,
"e": 4075,
"s": 4048,
"text": "Default output from format"
},
{
"code": null,
"e": 4181,
"s": 4075,
"text": "You can obtain these details from your aws console. Go to you Account name at top right corner as shown −"
},
{
"code": null,
"e": 4281,
"s": 4181,
"text": "Now, click My Security Credentials and select users from left side. Add user with details as asked."
},
{
"code": null,
"e": 4425,
"s": 4281,
"text": "Add the user and to get the access key and secret key. To see the new access key, choose Show. Your credentials will look like as shown below −"
},
{
"code": null,
"e": 4462,
"s": 4425,
"text": "Access key ID − AOSAIOSFOCDD7Example"
},
{
"code": null,
"e": 4523,
"s": 4462,
"text": "Secret access key − aJuirCVtnROUN/K7MDENG/bPxRfiCYExampleKEY"
},
{
"code": null,
"e": 4604,
"s": 4523,
"text": "The following table will give command references available to work with aws cli."
},
{
"code": null,
"e": 4661,
"s": 4604,
"text": "Now, let us discuss these commands one by one in detail."
},
{
"code": null,
"e": 4859,
"s": 4661,
"text": "This api will create a new lambda function. The code needs to be given in zip format. If the function to be created already exists, the api will fail. Note that the function name is case-sensitive."
},
{
"code": null,
"e": 4934,
"s": 4859,
"text": "The list of commands that you can use with create-function is given here −"
},
{
"code": null,
"e": 5233,
"s": 4934,
"text": "create-function \n--function-name <value>\n--runtime <value>\n--role <value>\n--handler <value>\n[--code <value>] \n[--description <value>] \n[--timeout <value>] \n[--memory-size <value>] \n[--environment <value>] \n[--kms-key-arn <value>] \n[--tags <value>] \n[--zip-file <value>] \n[--cli-input-json <value>]\n"
},
{
"code": null,
"e": 5308,
"s": 5233,
"text": "Various options that you can use with the functions above are as follows −"
},
{
"code": null,
"e": 5407,
"s": 5308,
"text": "--function-name (string) − This takes the name of the function. The name can be 64-bit characters."
},
{
"code": null,
"e": 5551,
"s": 5407,
"text": "--runtime(string) − Here you need to specify the runtime environment ie the language selection. The details of the runtime are as given below −"
},
{
"code": null,
"e": 5743,
"s": 5551,
"text": "--role(string) − This will be the name of the lambda policy ie the role to be given to the lambda function for accessing other services. It will have the permission as per the role specified."
},
{
"code": null,
"e": 5840,
"s": 5743,
"text": "--handler (string) − This is the name of the handler where the lambda code execution will start."
},
{
"code": null,
"e": 5900,
"s": 5840,
"text": "For nodejs, handler name is the module name that we export."
},
{
"code": null,
"e": 5966,
"s": 5900,
"text": "For java, it is package.classname :: handler or package.classname"
},
{
"code": null,
"e": 6004,
"s": 5966,
"text": "For python, handler is nameofthefile."
},
{
"code": null,
"e": 6040,
"s": 6004,
"text": "--code (structure) −AWS Lambda code"
},
{
"code": null,
"e": 6105,
"s": 6040,
"text": "--description (string) − description for the AWS Lambda function"
},
{
"code": null,
"e": 6231,
"s": 6105,
"text": "--timeout (integer) − timeout will have the time at which the lambda function has to terminate execution. The default is 3s."
},
{
"code": null,
"e": 6395,
"s": 6231,
"text": "--memory-size (integer) − This is the memory given to the aws lambda function. AWS will allocate the amount of CPU and memory allocation based on the memory given."
},
{
"code": null,
"e": 6498,
"s": 6395,
"text": "--environment (structure) − its a object with environment details required in the aws lambda function."
},
{
"code": null,
"e": 6550,
"s": 6498,
"text": "e.g : Variables = {Name1 = string, Name2 = string}\n"
},
{
"code": null,
"e": 6715,
"s": 6550,
"text": "--kms-key-arn (string) − this is amazon resource name (ARN) used to encrypt the environment variables. If not provided it will take the default settings to encrypt."
},
{
"code": null,
"e": 6791,
"s": 6715,
"text": "--zip-file (blob) − path of the zip file which has the details of the code."
},
{
"code": null,
"e": 7061,
"s": 6791,
"text": "--cli-input-json (string) : Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values."
},
{
"code": null,
"e": 7173,
"s": 7061,
"text": "Now, let us create a simple AWS Lambda function using runtime as nodejsand add some console.logs to be printed."
},
{
"code": null,
"e": 7225,
"s": 7173,
"text": "Consider a sample code for understanding the same −"
},
{
"code": null,
"e": 7342,
"s": 7225,
"text": "exports.handler = async (event) => {\n console.log(\"Using aws cli\");\n return 'Hello from Lambda from aws cli!'\n};"
},
{
"code": null,
"e": 7388,
"s": 7342,
"text": "Now, zip the file and store it as awscli.zip."
},
{
"code": null,
"e": 7581,
"s": 7388,
"text": "For the role, let us use the arn from the existing role we have created. To get the ARN, you will have to follow the steps as shown here. Observe the respective screenshots wherever attached −"
},
{
"code": null,
"e": 7737,
"s": 7581,
"text": "Go to IAM and select the role you want from Roles. The ARN details for the role are displayed as shown below. Use Role ARN with create-function in aws cli."
},
{
"code": null,
"e": 7820,
"s": 7737,
"text": "Observe here that the role arn is : arn:aws:iam::625297745038:role/lambdaapipolicy"
},
{
"code": null,
"e": 7880,
"s": 7820,
"text": "The command with values for create-function is as follows −"
},
{
"code": null,
"e": 8119,
"s": 7880,
"text": "aws lambda create-function \n--function-name \"awslambdausingcli\" \n--runtime \"nodejs8.10\" \n--role \"arn:aws:iam::625297745038:role/lambdaapipolicy\" \n--handler \"awscli.handler\" \n--timeout 5 \n--memory-size 256 \n--zip-file \"fileb://awscli.zip\"\n"
},
{
"code": null,
"e": 8199,
"s": 8119,
"text": "Now, if you run the command in aws cli, you can find an output as shown below −"
},
{
"code": null,
"e": 8265,
"s": 8199,
"text": "In AWS console, the Lambda function is displayed as shown below −"
},
{
"code": null,
"e": 8314,
"s": 8265,
"text": "The details of the functions are as shown here −"
},
{
"code": null,
"e": 8368,
"s": 8314,
"text": "The details of the configuration are as given below −"
},
{
"code": null,
"e": 8426,
"s": 8368,
"text": "You can test the function and check the output as shown −"
},
{
"code": null,
"e": 8471,
"s": 8426,
"text": "The corresponding Log output is shown here −"
},
{
"code": null,
"e": 8538,
"s": 8471,
"text": "This api gives the list of functions created so far in AWS Lambda."
},
{
"code": null,
"e": 8597,
"s": 8538,
"text": "The following are the commands asscociated with this API −"
},
{
"code": null,
"e": 8717,
"s": 8597,
"text": "list-functions\n[--master-region <value>]\n[--function-version <value>]\n[--max-items <value>]\n[--cli-input-json <value>]\n"
},
{
"code": null,
"e": 8795,
"s": 8717,
"text": "The following are various options you can use under this list-functions api −"
},
{
"code": null,
"e": 8890,
"s": 8795,
"text": "--master-region(string) − optional. The region from which the functions needs to be displayed."
},
{
"code": null,
"e": 8966,
"s": 8890,
"text": "--function-version(string) − optional. This will give the function version."
},
{
"code": null,
"e": 9056,
"s": 8966,
"text": "--max-items(integer) − optional. This will give the items as the per the value specified."
},
{
"code": null,
"e": 9149,
"s": 9056,
"text": "--cli-input-json(string) − optional. Will perform operation based on the json file provided."
},
{
"code": null,
"e": 9204,
"s": 9149,
"text": "The command with values list-functions is as follows −"
},
{
"code": null,
"e": 9245,
"s": 9204,
"text": "aws lambda list-functions --max-items 3\n"
},
{
"code": null,
"e": 9287,
"s": 9245,
"text": "The command displays details as follows −"
},
{
"code": null,
"e": 9459,
"s": 9287,
"text": "This api will give details of the functions and also a url link which has zip file uploaded using create-function. The url with zip details will be valid only for 10 mins."
},
{
"code": null,
"e": 9517,
"s": 9459,
"text": "The following are the commands associated with this api −"
},
{
"code": null,
"e": 9638,
"s": 9517,
"text": "get-function\n--function-name <value>\n[--qualifier <value>]\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 9748,
"s": 9638,
"text": "--function-name − Name of the AWS Lambda function. You can also specify Amazon Resource Name of the function."
},
{
"code": null,
"e": 9845,
"s": 9748,
"text": "--qualifier(string) − Optional. Function version can be used to get the details of the function."
},
{
"code": null,
"e": 9891,
"s": 9845,
"text": "The command with values to get-function are −"
},
{
"code": null,
"e": 9950,
"s": 9891,
"text": "aws lambda get-function --function-name awslambdausingcli\n"
},
{
"code": null,
"e": 9995,
"s": 9950,
"text": "The command display details are as follows −"
},
{
"code": null,
"e": 10076,
"s": 9995,
"text": "It gives the url which has the zip code uploaded. In the above case the url is −"
},
{
"code": null,
"e": 11245,
"s": 10076,
"text": "https://prod-04-2014-\ntasks.s3.amazonaws.com/snapshots/625297745038/awslambdausingcli-97048f8d-4a08\n-4ed9-99d9-acb00d2063d2?versionId=d04HKvPu9S2zz8pzjbW6Rmf5o5fxnc_r&X-Amz-Security\n-Token=FQoDYXdzEKT%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDCpTmGvtwKToPBiWcyK3A96UcJEnwvYDhMbbxu\n%2Bg2gffK2ocfnlEeiCHak8QqqE1RFpbKrdks9NzxP9gNbagL4M9RValxJ1a9PUY%2FOdAekscRHOiX00MVAxUlI8\n2pKryhdOwLJWSj0uRzqvOxCcBwJenHrSNPeG6lMa2ZDo0qZFEUDONSaTg4nuSnJK1f6t3pMAKu4vF9wPvf92G%2BU\n60rUxwleggigISmD9l1IlZse3%2BVF1JlNuN%2F5d85v0y2Q%2F%2BO515CybcZpn91sHPYG8JMJ00LsrkQ2Ww4VU\n9Zz5c5QYH4JYPj0CyEgSz9b%2FMceMPpOoPUAMjctb%2FEwQqcShZeqAr9%2Fcd2ZI%2BXl2%2Bs4ri0ucgPvQQvs\neGIIiZbX3GqdwR2jb1nylrAEIfiuFMoSWfcFYoYtuL0MZnjGR9jy2GNkp6MB%2BlHHr7%2BnuFRUzU26rgDYmdE1w\nRb3%2B21Jm49WGDa9opRLvUxFaux57Or70haib2FuKzN6Gf3Vzzk5KPdWsYUpaLyf%2B1ovEytOZhB1JEXuCs%2FG\nIlOXS88yxT%2BpOKmyxweiezpGgI%2FAkSAQTbSRsYQKIOFyIJNHzplwrJKhy28vy60numIBIo9Zqq2AU%3D\n&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180527T112426Z&X-Amz-\nSignedHeaders=host&X-Amz-Expires=600&X-Amz-\nCredential=ASIAICSQHLSBWFP37U4Q%2F20180527%2Fus-\neast-1%2Fs3%2Faws4_request&X-Amz-Signature=\n8b97e7d6d7da13313068e027894d2c875be5e50a0c5a62550f55307985bdc1aa\n"
},
{
"code": null,
"e": 11314,
"s": 11245,
"text": "This will give the configuration details of the AWS Lambda function."
},
{
"code": null,
"e": 11372,
"s": 11314,
"text": "The following are the commands used along with this api −"
},
{
"code": null,
"e": 11446,
"s": 11372,
"text": "get-function-configuration\n--function-name <value>\n[--qualifier <value>]\n"
},
{
"code": null,
"e": 11486,
"s": 11446,
"text": "The following are the options used with"
},
{
"code": null,
"e": 11605,
"s": 11486,
"text": "--function-name (string) − name of the aws lambda function. You can also specify Amazon Resource Name of the function."
},
{
"code": null,
"e": 11702,
"s": 11605,
"text": "--qualifier(string) − Optional.Function version can be used to get the details of the function.\n"
},
{
"code": null,
"e": 11748,
"s": 11702,
"text": "The command with values to get-function are −"
},
{
"code": null,
"e": 11821,
"s": 11748,
"text": "aws lambda get-function-configuration --function-name awslambdausingcli\n"
},
{
"code": null,
"e": 11863,
"s": 11821,
"text": "The command displays details as follows −"
},
{
"code": null,
"e": 11901,
"s": 11863,
"text": "This api gives the accounts settings."
},
{
"code": null,
"e": 11950,
"s": 11901,
"text": "The command that you can use with this api are −"
},
{
"code": null,
"e": 12033,
"s": 11950,
"text": "get-account-settings\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 12083,
"s": 12033,
"text": "You can use the following options with this api −"
},
{
"code": null,
"e": 12166,
"s": 12083,
"text": "--cli-input-json(string) − Performs the service based on the json string provided."
},
{
"code": null,
"e": 12255,
"s": 12166,
"text": "--generate-cli-skeleton(string) − It prints json output without sending the API request."
},
{
"code": null,
"e": 12316,
"s": 12255,
"text": "You can use the following command for get-account-settings −"
},
{
"code": null,
"e": 12349,
"s": 12316,
"text": "aws lambda get-account-settings\n"
},
{
"code": null,
"e": 12425,
"s": 12349,
"text": "You can see the following output when you execute the command given above −"
},
{
"code": null,
"e": 12586,
"s": 12425,
"text": "This api helps to update the configuration details for AWS Lambda function created. You can change the memory, timeout, handler, role, runtime, description etc."
},
{
"code": null,
"e": 12669,
"s": 12586,
"text": "The following are the commands involved in the update-function-configuration api −"
},
{
"code": null,
"e": 12934,
"s": 12669,
"text": "update-function-configuration\n--function-name <value>\n[--role <value>]\n[--handler <value>]\n[--description <value>]\n[--timeout <value>]\n[--memory-size <value>]\n[--environment <value>]\n[--runtime <value>]\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 13012,
"s": 12934,
"text": "The following are the options involved in update-function-configuration api −"
},
{
"code": null,
"e": 13062,
"s": 13012,
"text": "--function-name − name of the aws lambda function"
},
{
"code": null,
"e": 13131,
"s": 13062,
"text": "--role (string) − optional. The ARN of role is needed to be updated."
},
{
"code": null,
"e": 13206,
"s": 13131,
"text": "--handler (string) − optional. The handler details of aws lambda function."
},
{
"code": null,
"e": 13270,
"s": 13206,
"text": "--description(string) − optional. Description for the function."
},
{
"code": null,
"e": 13358,
"s": 13270,
"text": "--timeout(integer) − optional. Time required so that aws lambda function can terminate."
},
{
"code": null,
"e": 13531,
"s": 13358,
"text": "--memory-size(integer) − optional. This is the memory given to the aws lambda function. AWS will allocate the amount of CPU and memory allocation based on the memory given."
},
{
"code": null,
"e": 13647,
"s": 13531,
"text": "--environment (structure) − optional. It is an object with environment details required in the aws lambda function."
},
{
"code": null,
"e": 13698,
"s": 13647,
"text": "e.g: Variables = {Name1 = string, Name2 = string}\n"
},
{
"code": null,
"e": 13794,
"s": 13698,
"text": "--runtime(string) − Here you need to specify the runtime environment ie the language selection."
},
{
"code": null,
"e": 13858,
"s": 13794,
"text": "The details of the runtime are shown in the table given below −"
},
{
"code": null,
"e": 13981,
"s": 13858,
"text": "--cli-input-json (string) − optional. This will perform the operation on the api as specified in the json string provided."
},
{
"code": null,
"e": 14158,
"s": 13981,
"text": "--generate-cli-skeleton (string) − optional. This will output the JSON skeleton of all details without executing the api. The output can be used as a input to --cli-input-json."
},
{
"code": null,
"e": 14351,
"s": 14158,
"text": "Now, let us chage the memory and timeout of AWS Lambda function that we have created earlier. Follow the Steps given below and observe the corresponding screenshots attached for this purpose −"
},
{
"code": null,
"e": 14417,
"s": 14351,
"text": "The memory and timeout before the change occurred is as follows −"
},
{
"code": null,
"e": 14582,
"s": 14417,
"text": "Now, with update-function-configuration, let us change the memory and timeout to 320MB and timeout to 10s. For this purpose, use the following command with values −"
},
{
"code": null,
"e": 14691,
"s": 14582,
"text": "aws lambda update-function-configuration --function-name “awslambdusingcli” \n--timeout 10 --memory-size 320\n"
},
{
"code": null,
"e": 14746,
"s": 14691,
"text": "Then you can see the following output as the display −"
},
{
"code": null,
"e": 14831,
"s": 14746,
"text": "The display in AWS console after using update-function-configuration is as follows −"
},
{
"code": null,
"e": 14898,
"s": 14831,
"text": "This api will update the code for an existing AWS Lambda function."
},
{
"code": null,
"e": 15097,
"s": 14898,
"text": "update-function-code\n--function-name <value>\n[--zip-file <value>]\n[--s3-bucket <value>]\n[--s3-key <value>]\n[--s3-object-version <value>]\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 15172,
"s": 15097,
"text": "The following are the options involved with the update-function-code api −"
},
{
"code": null,
"e": 15226,
"s": 15172,
"text": "--function-name(string) − name of aws lambda function"
},
{
"code": null,
"e": 15311,
"s": 15226,
"text": "--zip-file (blob) − optional. Path of the zip file which has the code to be updated."
},
{
"code": null,
"e": 15401,
"s": 15311,
"text": "--s3-bucket(string) − optional. S3 bucket name which has the zip file with code uploaded."
},
{
"code": null,
"e": 15479,
"s": 15401,
"text": "--s3-key(string) − optional. AWS s3 object key name which has to be uploaded."
},
{
"code": null,
"e": 15543,
"s": 15479,
"text": "--s3-object-version (string) − optional. AWS s3 object version."
},
{
"code": null,
"e": 15666,
"s": 15543,
"text": "--cli-input-json (string) − optional. This will perform the operation on the api as specified in the json string provided."
},
{
"code": null,
"e": 15843,
"s": 15666,
"text": "--generate-cli-skeleton (string) − optional. This will output the JSON skeleton of all details without executing the api. The output can be used as a input to --cli-input-json."
},
{
"code": null,
"e": 15880,
"s": 15843,
"text": "The updated code is as shown below −"
},
{
"code": null,
"e": 16023,
"s": 15880,
"text": "exports.handler = async (event, context) => {\n console.log(\"Using aws cli\");\n console.log()\n return 'Hello from Lambda from aws cli!'\n};"
},
{
"code": null,
"e": 16088,
"s": 16023,
"text": "You can use the following command with values for this purpose −"
},
{
"code": null,
"e": 16190,
"s": 16088,
"text": "aws lambda update-function-code --function-name \"awslambdausingcli\" \n--zip-file \"fileb://awscli.zip\"\n"
},
{
"code": null,
"e": 16234,
"s": 16190,
"text": "The corresponding output is as shown here −"
},
{
"code": null,
"e": 16282,
"s": 16234,
"text": "The display from AWS console is as shown here −"
},
{
"code": null,
"e": 16331,
"s": 16282,
"text": "The corresponding log output is as shown below −"
},
{
"code": null,
"e": 16386,
"s": 16331,
"text": "The delete aws cli api will delete the function given."
},
{
"code": null,
"e": 16436,
"s": 16386,
"text": "The command details for the same are given here −"
},
{
"code": null,
"e": 16560,
"s": 16436,
"text": "delete-function\n--function-name <value>\n[--qualifier <value>]\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 16614,
"s": 16560,
"text": "The options included in this api are as given below −"
},
{
"code": null,
"e": 16719,
"s": 16614,
"text": "--function-name(string) − this will take the lambda function name or the arn of the aws lambda function."
},
{
"code": null,
"e": 16833,
"s": 16719,
"text": "--qualifier (string) − This is optional. Here you can specify the version of aws lambda that needs to be deleted."
},
{
"code": null,
"e": 17103,
"s": 16833,
"text": "-- cli-input-json(string) − Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values."
},
{
"code": null,
"e": 17213,
"s": 17103,
"text": "--generate-cli-skeleton(string) − it prints json skeleton to standard output without sending the API request."
},
{
"code": null,
"e": 17273,
"s": 17213,
"text": "aws lambda delete-function --function-name \"lambdatestcli\"\n"
},
{
"code": null,
"e": 17351,
"s": 17273,
"text": "Now, observe that the function will not be seen in AWS Lambda function list −"
},
{
"code": null,
"e": 17386,
"s": 17351,
"text": "\n 35 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 17410,
"s": 17386,
"text": " Mr. Pradeep Kshetrapal"
},
{
"code": null,
"e": 17445,
"s": 17410,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 17465,
"s": 17445,
"text": " Priyanka Choudhary"
},
{
"code": null,
"e": 17500,
"s": 17465,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 17528,
"s": 17500,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 17561,
"s": 17528,
"text": "\n 51 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 17577,
"s": 17561,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 17610,
"s": 17577,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 17622,
"s": 17610,
"text": " AR Shankar"
},
{
"code": null,
"e": 17655,
"s": 17622,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17668,
"s": 17655,
"text": " Zach Miller"
},
{
"code": null,
"e": 17675,
"s": 17668,
"text": " Print"
},
{
"code": null,
"e": 17686,
"s": 17675,
"text": " Add Notes"
}
] |
Java Inheritance (Subclass and Superclass)
|
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends
keyword.
In the example below, the Car class
(subclass) inherits the attributes and methods from the Vehicle class
(superclass):
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Try it Yourself »
Did you notice the protected modifier in Vehicle?
We set the brand attribute in Vehicle to a protected access
modifier. If it was set to private, the Car class would not be able to access
it.
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks.
If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
The output will be something like this:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 141,
"s": 0,
"text": "In Java, it is possible to inherit attributes and methods from one class to another. We group the \"inheritance concept\" into two categories:"
},
{
"code": null,
"e": 203,
"s": 141,
"text": "subclass (child) - the class that inherits from another class"
},
{
"code": null,
"e": 256,
"s": 203,
"text": "superclass (parent) - the class being inherited from"
},
{
"code": null,
"e": 307,
"s": 256,
"text": "To inherit from a class, use the extends \nkeyword."
},
{
"code": null,
"e": 429,
"s": 307,
"text": "In the example below, the Car class \n(subclass) inherits the attributes and methods from the Vehicle class \n(superclass):"
},
{
"code": null,
"e": 1090,
"s": 429,
"text": "class Vehicle {\n protected String brand = \"Ford\"; // Vehicle attribute\n public void honk() { // Vehicle method\n System.out.println(\"Tuut, tuut!\");\n }\n}\n\nclass Car extends Vehicle {\n private String modelName = \"Mustang\"; // Car attribute\n public static void main(String[] args) {\n\n // Create a myCar object\n Car myCar = new Car();\n\n // Call the honk() method (from the Vehicle class) on the myCar object\n myCar.honk();\n\n // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class\n System.out.println(myCar.brand + \" \" + myCar.modelName);\n }\n}\n \n"
},
{
"code": null,
"e": 1110,
"s": 1090,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1160,
"s": 1110,
"text": "Did you notice the protected modifier in Vehicle?"
},
{
"code": null,
"e": 1304,
"s": 1160,
"text": "We set the brand attribute in Vehicle to a protected access \nmodifier. If it was set to private, the Car class would not be able to access \nit."
},
{
"code": null,
"e": 1420,
"s": 1304,
"text": "- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class."
},
{
"code": null,
"e": 1534,
"s": 1420,
"text": "Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks."
},
{
"code": null,
"e": 1614,
"s": 1534,
"text": "If you don't want other classes to inherit from a class, use the final keyword:"
},
{
"code": null,
"e": 1679,
"s": 1614,
"text": "If you try to access a final class, Java will generate an error:"
},
{
"code": null,
"e": 1747,
"s": 1679,
"text": "final class Vehicle {\n ...\n}\n\nclass Car extends Vehicle {\n ...\n}\n"
},
{
"code": null,
"e": 1787,
"s": 1747,
"text": "The output will be something like this:"
},
{
"code": null,
"e": 1820,
"s": 1787,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1862,
"s": 1820,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1969,
"s": 1862,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1988,
"s": 1969,
"text": "help@w3schools.com"
}
] |
How to create pivot table with sum for data stored in R data frame?
|
To create pivot table with sum for data stored in R data frame, we can follow the below steps −
First of all, create a data frame with two categorical and one numerical column.
First of all, create a data frame with two categorical and one numerical column.
Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame.
Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame.
Let’s create a data frame as shown below −
Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
Group Gender Score
1 B Male 69
2 B Male 66
3 D Male 34
4 D Male 25
5 E Male 51
6 B Male 38
7 E Male 48
8 A Female 29
9 D Male 10
10 C Female 96
11 E Female 8
12 D Male 39
13 E Female 94
14 D Female 61
15 A Female 70
16 B Male 90
17 B Female 100
18 B Female 27
19 A Female 33
20 A Female 98
21 A Male 32
22 B Female 78
23 E Male 86
24 D Male 74
25 A Female 99
Create pivot table
Using dcast function from reshape2 package to create pivot table for the data stored in data frame df −
Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
library(reshape2)
dcast(data=df,formula=Group~Gender,fun.aggregate=sum,value.var="Score")
Group Female Male
1 A 152 181
2 B 177 117
3 C 83 66
4 D 137 51
5 E 196 149
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "To create pivot table with sum for data stored in R data frame, we can follow the below steps −"
},
{
"code": null,
"e": 1239,
"s": 1158,
"text": "First of all, create a data frame with two categorical and one numerical column."
},
{
"code": null,
"e": 1320,
"s": 1239,
"text": "First of all, create a data frame with two categorical and one numerical column."
},
{
"code": null,
"e": 1424,
"s": 1320,
"text": "Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame."
},
{
"code": null,
"e": 1528,
"s": 1424,
"text": "Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame."
},
{
"code": null,
"e": 1571,
"s": 1528,
"text": "Let’s create a data frame as shown below −"
},
{
"code": null,
"e": 1728,
"s": 1571,
"text": "Group<-sample(LETTERS[1:5],25,replace=TRUE)\nGender<-sample(c(\"Male\",\"Female\"),25,replace=TRUE)\nScore<-sample(1:100,25)\ndf<-data.frame(Group,Gender,Score)\ndf"
},
{
"code": null,
"e": 1847,
"s": 1728,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2292,
"s": 1847,
"text": " Group Gender Score\n1 B Male 69\n2 B Male 66\n3 D Male 34\n4 D Male 25\n5 E Male 51\n6 B Male 38\n7 E Male 48\n8 A Female 29\n9 D Male 10\n10 C Female 96\n11 E Female 8\n12 D Male 39\n13 E Female 94\n14 D Female 61\n15 A Female 70\n16 B Male 90\n17 B Female 100\n18 B Female 27\n19 A Female 33\n20 A Female 98\n21 A Male 32\n22 B Female 78\n23 E Male 86\n24 D Male 74\n25 A Female 99"
},
{
"code": null,
"e": 2311,
"s": 2292,
"text": "Create pivot table"
},
{
"code": null,
"e": 2415,
"s": 2311,
"text": "Using dcast function from reshape2 package to create pivot table for the data stored in data frame df −"
},
{
"code": null,
"e": 2659,
"s": 2415,
"text": "Group<-sample(LETTERS[1:5],25,replace=TRUE)\nGender<-sample(c(\"Male\",\"Female\"),25,replace=TRUE)\nScore<-sample(1:100,25)\ndf<-data.frame(Group,Gender,Score)\nlibrary(reshape2)\ndcast(data=df,formula=Group~Gender,fun.aggregate=sum,value.var=\"Score\")"
},
{
"code": null,
"e": 2780,
"s": 2659,
"text": " Group Female Male\n1 A 152 181\n2 B 177 117\n3 C 83 66\n4 D 137 51\n5 E 196 149"
}
] |
Mutex lock for Linux Thread Synchronization - GeeksforGeeks
|
20 Nov, 2019
Prerequisite : Multithreading in C
Thread synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as a critical section. Processes’ access to critical section is controlled by using synchronization techniques. When one thread starts executing the critical section (a serialized segment of the program) the other thread should wait until the first thread finishes. If proper synchronization techniques are not applied, it may cause a race condition where the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads.
Thread Synchronization ProblemsAn example code to study synchronization problems :
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter; void* trythis(void* arg){ unsigned long i = 0; counter += 1; printf("\n Job %d has started\n", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf("\n Job %d has finished\n", counter); return NULL;} int main(void){ int i = 0; int error; while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf("\nThread can't be created : [%s]", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); return 0;}
How to compile above program?To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program.
gfg@ubuntu:~/$ gcc filename.c -lpthread
In this example, two threads(jobs) are created and in the start function of these threads, a counter is maintained to get the logs about job number which is started and when it is completed.
Output :
Job 1 has started
Job 2 has started
Job 2 has finished
Job 2 has finished
Problem: From the last two logs, one can see that the log ‘Job 2 has finished’ is repeated twice while no log for ‘Job 1 has finished’ is seen.
Why it has occurred ?On observing closely and visualizing the execution of the code, we can see that :
The log ‘Job 2 has started’ is printed just after ‘Job 1 has Started’ so it can easily be concluded that while thread 1 was processing the scheduler scheduled the thread 2.
If we take the above assumption true then the value of the ‘counter’ variable got incremented again before job 1 got finished.
So, when Job 1 actually got finished, then the wrong value of counter produced the log ‘Job 2 has finished’ followed by the ‘Job 2 has finished’ for the actual job 2 or vice versa as it is dependent on scheduler.
So we see that its not the repetitive log but the wrong value of the ‘counter’ variable that is the problem.
The actual problem was the usage of the variable ‘counter’ by a second thread when the first thread was using or about to use it.
In other words, we can say that lack of synchronization between the threads while using the shared resource ‘counter’ caused the problems or in one word we can say that this problem happened due to ‘Synchronization problem’ between two threads.How to solve it ?The most popular way of achieving thread synchronization is by using Mutexes.MutexA Mutex is a lock that we set before using a shared resource and release after using it.When the lock is set, no other thread can access the locked region of code.So we see that even if thread 2 is scheduled while thread 1 was not done accessing the shared resource and the code is locked by thread 1 using mutexes then thread 2 cannot even access that region of code.So this ensures synchronized access of shared resources in the code.Working of a mutexSuppose one thread has locked a region of code using mutex and is executing that piece of code.Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.Mutex lock will only be released by the thread who locked it.So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.Hence, this system ensures synchronization among the threads while working on shared resources.A mutex is initialized and then a lock is achieved by calling the following two functions : The first function initializes a mutex and through second function any critical region in the code can be locked.int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1.The mutex can be unlocked and destroyed by calling following two functions :The first function releases the lock and the second function destroys the lock so that it cannot be used anywhere in future.int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1.An example to show how mutexes are used for thread synchronization#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter;pthread_mutex_t lock; void* trythis(void* arg){ pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf("\n Job %d has started\n", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf("\n Job %d has finished\n", counter); pthread_mutex_unlock(&lock); return NULL;} int main(void){ int i = 0; int error; if (pthread_mutex_init(&lock, NULL) != 0) { printf("\n mutex init has failed\n"); return 1; } while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf("\nThread can't be created :[%s]", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); pthread_mutex_destroy(&lock); return 0;}In the above code:A mutex is initialized in the beginning of the main function.The same mutex is locked in the ‘trythis()’ function while using the shared resource ‘counter’.At the end of the function ‘trythis()’ the same mutex is unlocked.At the end of the main function when both the threads are done, the mutex is destroyed.Output :Job 1 started
Job 1 finished
Job 2 started
Job 2 finished
So this time the start and finish logs of both the jobs are present. So thread synchronization took place by the use of Mutex.References :Synchronization (computer science)Lock (computer science)This article is contributed by Kishlay Verma. 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.My Personal Notes
arrow_drop_upSave
How to solve it ?
The most popular way of achieving thread synchronization is by using Mutexes.
A Mutex is a lock that we set before using a shared resource and release after using it.
When the lock is set, no other thread can access the locked region of code.
So we see that even if thread 2 is scheduled while thread 1 was not done accessing the shared resource and the code is locked by thread 1 using mutexes then thread 2 cannot even access that region of code.
So this ensures synchronized access of shared resources in the code.
Working of a mutex
Suppose one thread has locked a region of code using mutex and is executing that piece of code.Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.Mutex lock will only be released by the thread who locked it.So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.
Suppose one thread has locked a region of code using mutex and is executing that piece of code.
Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.
Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.
Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.
Mutex lock will only be released by the thread who locked it.
So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.
Hence, this system ensures synchronization among the threads while working on shared resources.
A mutex is initialized and then a lock is achieved by calling the following two functions : The first function initializes a mutex and through second function any critical region in the code can be locked.
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1.
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.
Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.
int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1.
Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1.
The mutex can be unlocked and destroyed by calling following two functions :The first function releases the lock and the second function destroys the lock so that it cannot be used anywhere in future.
int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1.
int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1
Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1
int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1.
Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1.
An example to show how mutexes are used for thread synchronization
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter;pthread_mutex_t lock; void* trythis(void* arg){ pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf("\n Job %d has started\n", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf("\n Job %d has finished\n", counter); pthread_mutex_unlock(&lock); return NULL;} int main(void){ int i = 0; int error; if (pthread_mutex_init(&lock, NULL) != 0) { printf("\n mutex init has failed\n"); return 1; } while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf("\nThread can't be created :[%s]", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); pthread_mutex_destroy(&lock); return 0;}
In the above code:
A mutex is initialized in the beginning of the main function.
The same mutex is locked in the ‘trythis()’ function while using the shared resource ‘counter’.
At the end of the function ‘trythis()’ the same mutex is unlocked.
At the end of the main function when both the threads are done, the mutex is destroyed.
Output :
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished
So this time the start and finish logs of both the jobs are present. So thread synchronization took place by the use of Mutex.
References :Synchronization (computer science)Lock (computer science)
This article is contributed by Kishlay Verma. 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.
shashibhusan
adenprior
Linux-Unix
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Banker's Algorithm in Operating System
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1
|
[
{
"code": null,
"e": 24051,
"s": 24023,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 24086,
"s": 24051,
"text": "Prerequisite : Multithreading in C"
},
{
"code": null,
"e": 24750,
"s": 24086,
"text": "Thread synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as a critical section. Processes’ access to critical section is controlled by using synchronization techniques. When one thread starts executing the critical section (a serialized segment of the program) the other thread should wait until the first thread finishes. If proper synchronization techniques are not applied, it may cause a race condition where the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads."
},
{
"code": null,
"e": 24833,
"s": 24750,
"text": "Thread Synchronization ProblemsAn example code to study synchronization problems :"
},
{
"code": "#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter; void* trythis(void* arg){ unsigned long i = 0; counter += 1; printf(\"\\n Job %d has started\\n\", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf(\"\\n Job %d has finished\\n\", counter); return NULL;} int main(void){ int i = 0; int error; while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf(\"\\nThread can't be created : [%s]\", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); return 0;}",
"e": 25513,
"s": 24833,
"text": null
},
{
"code": null,
"e": 25688,
"s": 25513,
"text": "How to compile above program?To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program."
},
{
"code": null,
"e": 25729,
"s": 25688,
"text": "gfg@ubuntu:~/$ gcc filename.c -lpthread\n"
},
{
"code": null,
"e": 25920,
"s": 25729,
"text": "In this example, two threads(jobs) are created and in the start function of these threads, a counter is maintained to get the logs about job number which is started and when it is completed."
},
{
"code": null,
"e": 25929,
"s": 25920,
"text": "Output :"
},
{
"code": null,
"e": 26004,
"s": 25929,
"text": "Job 1 has started\nJob 2 has started\nJob 2 has finished\nJob 2 has finished\n"
},
{
"code": null,
"e": 26148,
"s": 26004,
"text": "Problem: From the last two logs, one can see that the log ‘Job 2 has finished’ is repeated twice while no log for ‘Job 1 has finished’ is seen."
},
{
"code": null,
"e": 26251,
"s": 26148,
"text": "Why it has occurred ?On observing closely and visualizing the execution of the code, we can see that :"
},
{
"code": null,
"e": 26424,
"s": 26251,
"text": "The log ‘Job 2 has started’ is printed just after ‘Job 1 has Started’ so it can easily be concluded that while thread 1 was processing the scheduler scheduled the thread 2."
},
{
"code": null,
"e": 26551,
"s": 26424,
"text": "If we take the above assumption true then the value of the ‘counter’ variable got incremented again before job 1 got finished."
},
{
"code": null,
"e": 26764,
"s": 26551,
"text": "So, when Job 1 actually got finished, then the wrong value of counter produced the log ‘Job 2 has finished’ followed by the ‘Job 2 has finished’ for the actual job 2 or vice versa as it is dependent on scheduler."
},
{
"code": null,
"e": 26873,
"s": 26764,
"text": "So we see that its not the repetitive log but the wrong value of the ‘counter’ variable that is the problem."
},
{
"code": null,
"e": 27003,
"s": 26873,
"text": "The actual problem was the usage of the variable ‘counter’ by a second thread when the first thread was using or about to use it."
},
{
"code": null,
"e": 33505,
"s": 27003,
"text": "In other words, we can say that lack of synchronization between the threads while using the shared resource ‘counter’ caused the problems or in one word we can say that this problem happened due to ‘Synchronization problem’ between two threads.How to solve it ?The most popular way of achieving thread synchronization is by using Mutexes.MutexA Mutex is a lock that we set before using a shared resource and release after using it.When the lock is set, no other thread can access the locked region of code.So we see that even if thread 2 is scheduled while thread 1 was not done accessing the shared resource and the code is locked by thread 1 using mutexes then thread 2 cannot even access that region of code.So this ensures synchronized access of shared resources in the code.Working of a mutexSuppose one thread has locked a region of code using mutex and is executing that piece of code.Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.Mutex lock will only be released by the thread who locked it.So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.Hence, this system ensures synchronization among the threads while working on shared resources.A mutex is initialized and then a lock is achieved by calling the following two functions : The first function initializes a mutex and through second function any critical region in the code can be locked.int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1.The mutex can be unlocked and destroyed by calling following two functions :The first function releases the lock and the second function destroys the lock so that it cannot be used anywhere in future.int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1.An example to show how mutexes are used for thread synchronization#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter;pthread_mutex_t lock; void* trythis(void* arg){ pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf(\"\\n Job %d has started\\n\", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf(\"\\n Job %d has finished\\n\", counter); pthread_mutex_unlock(&lock); return NULL;} int main(void){ int i = 0; int error; if (pthread_mutex_init(&lock, NULL) != 0) { printf(\"\\n mutex init has failed\\n\"); return 1; } while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf(\"\\nThread can't be created :[%s]\", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); pthread_mutex_destroy(&lock); return 0;}In the above code:A mutex is initialized in the beginning of the main function.The same mutex is locked in the ‘trythis()’ function while using the shared resource ‘counter’.At the end of the function ‘trythis()’ the same mutex is unlocked.At the end of the main function when both the threads are done, the mutex is destroyed.Output :Job 1 started\nJob 1 finished\nJob 2 started\nJob 2 finished\nSo this time the start and finish logs of both the jobs are present. So thread synchronization took place by the use of Mutex.References :Synchronization (computer science)Lock (computer science)This article is contributed by Kishlay Verma. 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.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 33523,
"s": 33505,
"text": "How to solve it ?"
},
{
"code": null,
"e": 33601,
"s": 33523,
"text": "The most popular way of achieving thread synchronization is by using Mutexes."
},
{
"code": null,
"e": 33690,
"s": 33601,
"text": "A Mutex is a lock that we set before using a shared resource and release after using it."
},
{
"code": null,
"e": 33766,
"s": 33690,
"text": "When the lock is set, no other thread can access the locked region of code."
},
{
"code": null,
"e": 33972,
"s": 33766,
"text": "So we see that even if thread 2 is scheduled while thread 1 was not done accessing the shared resource and the code is locked by thread 1 using mutexes then thread 2 cannot even access that region of code."
},
{
"code": null,
"e": 34041,
"s": 33972,
"text": "So this ensures synchronized access of shared resources in the code."
},
{
"code": null,
"e": 34060,
"s": 34041,
"text": "Working of a mutex"
},
{
"code": null,
"e": 34836,
"s": 34060,
"text": "Suppose one thread has locked a region of code using mutex and is executing that piece of code.Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.Mutex lock will only be released by the thread who locked it.So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it."
},
{
"code": null,
"e": 34932,
"s": 34836,
"text": "Suppose one thread has locked a region of code using mutex and is executing that piece of code."
},
{
"code": null,
"e": 35066,
"s": 34932,
"text": "Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked."
},
{
"code": null,
"e": 35240,
"s": 35066,
"text": "Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep."
},
{
"code": null,
"e": 35394,
"s": 35240,
"text": "Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released."
},
{
"code": null,
"e": 35456,
"s": 35394,
"text": "Mutex lock will only be released by the thread who locked it."
},
{
"code": null,
"e": 35617,
"s": 35456,
"text": "So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it."
},
{
"code": null,
"e": 35713,
"s": 35617,
"text": "Hence, this system ensures synchronization among the threads while working on shared resources."
},
{
"code": null,
"e": 35919,
"s": 35713,
"text": "A mutex is initialized and then a lock is achieved by calling the following two functions : The first function initializes a mutex and through second function any critical region in the code can be locked."
},
{
"code": null,
"e": 37083,
"s": 35919,
"text": "int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1.int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1."
},
{
"code": null,
"e": 37495,
"s": 37083,
"text": "int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1."
},
{
"code": null,
"e": 37666,
"s": 37495,
"text": "Returned valueIf successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.If unsuccessful, pthread_mutex_init() returns -1."
},
{
"code": null,
"e": 38419,
"s": 37666,
"text": "int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1."
},
{
"code": null,
"e": 38529,
"s": 38419,
"text": "Returned valueIf successful, pthread_mutex_lock() returns 0.If unsuccessful, pthread_mutex_lock() returns -1."
},
{
"code": null,
"e": 38730,
"s": 38529,
"text": "The mutex can be unlocked and destroyed by calling following two functions :The first function releases the lock and the second function destroys the lock so that it cannot be used anywhere in future."
},
{
"code": null,
"e": 39890,
"s": 38730,
"text": "int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1."
},
{
"code": null,
"e": 40701,
"s": 39890,
"text": "int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1"
},
{
"code": null,
"e": 40814,
"s": 40701,
"text": "Returned valueIf successful, pthread_mutex_unlock() returns 0.If unsuccessful, pthread_mutex_unlock() returns -1"
},
{
"code": null,
"e": 41164,
"s": 40814,
"text": "int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1."
},
{
"code": null,
"e": 41280,
"s": 41164,
"text": "Returned valueIf successful, pthread_mutex_destroy() returns 0.If unsuccessful, pthread_mutex_destroy() returns -1."
},
{
"code": null,
"e": 41347,
"s": 41280,
"text": "An example to show how mutexes are used for thread synchronization"
},
{
"code": "#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> pthread_t tid[2];int counter;pthread_mutex_t lock; void* trythis(void* arg){ pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf(\"\\n Job %d has started\\n\", counter); for (i = 0; i < (0xFFFFFFFF); i++) ; printf(\"\\n Job %d has finished\\n\", counter); pthread_mutex_unlock(&lock); return NULL;} int main(void){ int i = 0; int error; if (pthread_mutex_init(&lock, NULL) != 0) { printf(\"\\n mutex init has failed\\n\"); return 1; } while (i < 2) { error = pthread_create(&(tid[i]), NULL, &trythis, NULL); if (error != 0) printf(\"\\nThread can't be created :[%s]\", strerror(error)); i++; } pthread_join(tid[0], NULL); pthread_join(tid[1], NULL); pthread_mutex_destroy(&lock); return 0;}",
"e": 42342,
"s": 41347,
"text": null
},
{
"code": null,
"e": 42361,
"s": 42342,
"text": "In the above code:"
},
{
"code": null,
"e": 42423,
"s": 42361,
"text": "A mutex is initialized in the beginning of the main function."
},
{
"code": null,
"e": 42519,
"s": 42423,
"text": "The same mutex is locked in the ‘trythis()’ function while using the shared resource ‘counter’."
},
{
"code": null,
"e": 42586,
"s": 42519,
"text": "At the end of the function ‘trythis()’ the same mutex is unlocked."
},
{
"code": null,
"e": 42674,
"s": 42586,
"text": "At the end of the main function when both the threads are done, the mutex is destroyed."
},
{
"code": null,
"e": 42683,
"s": 42674,
"text": "Output :"
},
{
"code": null,
"e": 42742,
"s": 42683,
"text": "Job 1 started\nJob 1 finished\nJob 2 started\nJob 2 finished\n"
},
{
"code": null,
"e": 42869,
"s": 42742,
"text": "So this time the start and finish logs of both the jobs are present. So thread synchronization took place by the use of Mutex."
},
{
"code": null,
"e": 42939,
"s": 42869,
"text": "References :Synchronization (computer science)Lock (computer science)"
},
{
"code": null,
"e": 43240,
"s": 42939,
"text": "This article is contributed by Kishlay Verma. 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."
},
{
"code": null,
"e": 43365,
"s": 43240,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43378,
"s": 43365,
"text": "shashibhusan"
},
{
"code": null,
"e": 43388,
"s": 43378,
"text": "adenprior"
},
{
"code": null,
"e": 43399,
"s": 43388,
"text": "Linux-Unix"
},
{
"code": null,
"e": 43417,
"s": 43399,
"text": "Operating Systems"
},
{
"code": null,
"e": 43435,
"s": 43417,
"text": "Operating Systems"
},
{
"code": null,
"e": 43533,
"s": 43435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43542,
"s": 43533,
"text": "Comments"
},
{
"code": null,
"e": 43555,
"s": 43542,
"text": "Old Comments"
},
{
"code": null,
"e": 43590,
"s": 43555,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 43626,
"s": 43590,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 43664,
"s": 43626,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 43700,
"s": 43664,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 43738,
"s": 43700,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 43777,
"s": 43738,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 43804,
"s": 43777,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 43853,
"s": 43804,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 43893,
"s": 43853,
"text": "Program for FCFS CPU Scheduling | Set 1"
}
] |
Angular PrimeNG Card Component - GeeksforGeeks
|
11 Sep, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Card Component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code.
Card Component: A card is used to display flexible and extensible content containers.
Properties:
header: It specifies the title of the card. It is of string data type & the default value is null.
subheader: It specifies the secondary title of the card. It is of string data type & the default value is null.
style: It is used to set the inline style of the component. It is of string data type & the default value is null.
styleClass: It is used to set the style class of the component. It is of string data type & the default value is null.
Styling:
p-card: It is the container element.
p-card-reader: It is the title element.
p-card-subheader: It is the subtitle element.
p-card-content: It is the content of the card.
p-card-footer: It is the footer of the card.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that illustrates how to use the Card component.
app.component.html
<h2>GeeksforGeeks</h2><p-card header="Angular PrimeNG Card component"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.</p> </p-card>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { CardModule } from "primeng/card"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, CardModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will know how to use the subheader property in the Card component.
app.component.html
<p-card header='GeeksforGeeks' subheader="Angular PrimeNG Card component"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.</p> </p-card>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { CardModule } from 'primeng/card'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, CardModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/card
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n11 Sep, 2021"
},
{
"code": null,
"e": 25496,
"s": 25109,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Card Component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. "
},
{
"code": null,
"e": 25582,
"s": 25496,
"text": "Card Component: A card is used to display flexible and extensible content containers."
},
{
"code": null,
"e": 25594,
"s": 25582,
"text": "Properties:"
},
{
"code": null,
"e": 25693,
"s": 25594,
"text": "header: It specifies the title of the card. It is of string data type & the default value is null."
},
{
"code": null,
"e": 25805,
"s": 25693,
"text": "subheader: It specifies the secondary title of the card. It is of string data type & the default value is null."
},
{
"code": null,
"e": 25920,
"s": 25805,
"text": "style: It is used to set the inline style of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 26039,
"s": 25920,
"text": "styleClass: It is used to set the style class of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 26048,
"s": 26039,
"text": "Styling:"
},
{
"code": null,
"e": 26085,
"s": 26048,
"text": "p-card: It is the container element."
},
{
"code": null,
"e": 26125,
"s": 26085,
"text": "p-card-reader: It is the title element."
},
{
"code": null,
"e": 26171,
"s": 26125,
"text": "p-card-subheader: It is the subtitle element."
},
{
"code": null,
"e": 26218,
"s": 26171,
"text": "p-card-content: It is the content of the card."
},
{
"code": null,
"e": 26263,
"s": 26218,
"text": "p-card-footer: It is the footer of the card."
},
{
"code": null,
"e": 26317,
"s": 26265,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 26384,
"s": 26317,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 26399,
"s": 26384,
"text": "ng new appname"
},
{
"code": null,
"e": 26496,
"s": 26399,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 26507,
"s": 26496,
"text": "cd appname"
},
{
"code": null,
"e": 26556,
"s": 26507,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 26613,
"s": 26556,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 26665,
"s": 26613,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 26751,
"s": 26665,
"text": "Example 1: This is the basic example that illustrates how to use the Card component. "
},
{
"code": null,
"e": 26770,
"s": 26751,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><p-card header=\"Angular PrimeNG Card component\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.</p> </p-card>",
"e": 27044,
"s": 26770,
"text": null
},
{
"code": null,
"e": 27061,
"s": 27044,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}",
"e": 27244,
"s": 27061,
"text": null
},
{
"code": null,
"e": 27258,
"s": 27244,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { CardModule } from \"primeng/card\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, CardModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 27721,
"s": 27258,
"text": null
},
{
"code": null,
"e": 27731,
"s": 27723,
"text": "Output:"
},
{
"code": null,
"e": 27829,
"s": 27731,
"text": "Example 2: In this example, we will know how to use the subheader property in the Card component."
},
{
"code": null,
"e": 27848,
"s": 27829,
"text": "app.component.html"
},
{
"code": "<p-card header='GeeksforGeeks' subheader=\"Angular PrimeNG Card component\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.</p> </p-card>",
"e": 28133,
"s": 27848,
"text": null
},
{
"code": null,
"e": 28150,
"s": 28133,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}",
"e": 28333,
"s": 28150,
"text": null
},
{
"code": null,
"e": 28347,
"s": 28333,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { CardModule } from 'primeng/card'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, CardModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 28809,
"s": 28347,
"text": null
},
{
"code": null,
"e": 28817,
"s": 28809,
"text": "Output:"
},
{
"code": null,
"e": 28875,
"s": 28817,
"text": "Reference: https://primefaces.org/primeng/showcase/#/card"
},
{
"code": null,
"e": 28891,
"s": 28875,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 28901,
"s": 28891,
"text": "AngularJS"
},
{
"code": null,
"e": 28918,
"s": 28901,
"text": "Web Technologies"
},
{
"code": null,
"e": 29016,
"s": 28918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29060,
"s": 29016,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 29084,
"s": 29060,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29119,
"s": 29084,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29172,
"s": 29119,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29221,
"s": 29172,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 29263,
"s": 29221,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29296,
"s": 29263,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29339,
"s": 29296,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29389,
"s": 29339,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How do inline variables work in C++/C++17?
|
In C++, we can use the inline keyword for functions. In C++ 17 version, the inline variable concept has come.
The inline variable is allowed to be defined in multiple translation units. It also follows the one definition rule. If this is defined more than one time, the compiler merges them all into a single object in final program.
In C++ (before C++17 version), we cannot initialize the value of static variables directly in the class. We have to define them outside of the class.
#include<iostream>
using namespace std;
class MyClass {
public:
MyClass() {
++num;
}
~MyClass() {
--num;
}
static int num;
};
int MyClass::num = 10;
int main() {
cout<<"The static value is: " << MyClass::num;
}
The static value is: 10
In C++17, we can initialize the static variables inside the class using inline variables.
#include<iostream>
using namespace std;
class MyClass {
public:
MyClass() {
++num;
}
~MyClass() {
--num;
}
inline static int num = 10;
};
int main() {
cout<<"The static value is: " << MyClass::num;
}
The static value is: 10
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "In C++, we can use the inline keyword for functions. In C++ 17 version, the inline variable concept has come."
},
{
"code": null,
"e": 1396,
"s": 1172,
"text": "The inline variable is allowed to be defined in multiple translation units. It also follows the one definition rule. If this is defined more than one time, the compiler merges them all into a single object in final program."
},
{
"code": null,
"e": 1546,
"s": 1396,
"text": "In C++ (before C++17 version), we cannot initialize the value of static variables directly in the class. We have to define them outside of the class."
},
{
"code": null,
"e": 1811,
"s": 1546,
"text": "#include<iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n ++num;\n }\n ~MyClass() {\n --num;\n }\n static int num;\n};\nint MyClass::num = 10;\nint main() {\n cout<<\"The static value is: \" << MyClass::num;\n}"
},
{
"code": null,
"e": 1925,
"s": 1811,
"text": "The static value is: 10\nIn C++17, we can initialize the static variables inside the class using inline variables."
},
{
"code": null,
"e": 2179,
"s": 1925,
"text": "#include<iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n ++num;\n }\n ~MyClass() {\n --num;\n }\n inline static int num = 10;\n};\nint main() {\n cout<<\"The static value is: \" << MyClass::num;\n}"
},
{
"code": null,
"e": 2203,
"s": 2179,
"text": "The static value is: 10"
}
] |
C Language | Set 3 - GeeksforGeeks
|
09 Apr, 2018
Following questions have been asked in GATE CS exam.
1.Assume the following C variable declaration
int *A [10], B[10][10];
Of the following expressionsI A[2]II A[2][3]III B[1]IV B[2][3]which will not give compile-time errors if used as left hand sides of assignment statements in a C program (GATE CS 2003)?a) I, II, and IV onlyb) II, III, and IV onlyc) II and IV onlyd) IV only
Answer (a)See below program
int main(){ int *A[10], B[10][10]; int C[] = {12, 11, 13, 14}; /* No problem with below statement as A[2] is a pointer and we are assigning a value to pointer */ A[2] = C; /* No problem with below statement also as array style indexing can be done with pointers*/ A[2][3] = 15; /* Simple assignment to an element of a 2D array*/ B[2][3] = 15; printf("%d %d", A[2][0], A[2][3]); getchar();}
2. Consider the following declaration of a ‘two-dimensional array in C:
char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of a[40][50] is (GATE CS 2002)a) 4040b) 4050c) 5040d) 5050
Answer(b)
Address of a[40][50] =
Base address + 40*100*element_size + 50*element_size
0 + 4000*1 + 50*1
4050
3. The C language is. (GATE CS 2002)a) A context free languageb) A context sensitive languagec) A regular languaged) Parsable fully only by a Turing machine
Answer (b)C and C++ are context-sensitive languages.
There are several reasons:
To parse C and C++, you start by using a very powerful preprocessor. These preprocessors are inevitably written by hand (they are not based on a theoretic foundation like regular expressions or context-free grammars).The grammar is ambiguous: it has LR conflicts, such as the if-then-else conflict. Parsers typically resolve this using context (an “else” matches the closest “if”).C and C++ lexers require lexical feedback to differentiate between typedef names and identifiers. That is, the context-sensitive lexer needs help from the “context-free” parser to distinguish between an identifier “foo” and a typedef name “foo”. In this snippet,int foo;
typedef int foo;
foo x;the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive.
To parse C and C++, you start by using a very powerful preprocessor. These preprocessors are inevitably written by hand (they are not based on a theoretic foundation like regular expressions or context-free grammars).
The grammar is ambiguous: it has LR conflicts, such as the if-then-else conflict. Parsers typically resolve this using context (an “else” matches the closest “if”).
C and C++ lexers require lexical feedback to differentiate between typedef names and identifiers. That is, the context-sensitive lexer needs help from the “context-free” parser to distinguish between an identifier “foo” and a typedef name “foo”. In this snippet,int foo;
typedef int foo;
foo x;the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive.
int foo;
typedef int foo;
foo x;
the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive.
Ref: C and C++ are not context free
4 The most appropriate matching for the following pairs (GATE CS 2000)
X: m=malloc(5); m= NULL; 1: using dangling pointers
Y: free(n); n->value=5; 2: using uninitialized pointers
Z: char *p; *p = ’a’; 3. lost memory is:
(a) X—1 Y—3 Z-2(b) X—2 Y—1 Z-3(C) X—3 Y—2 Z-1(d) X—3 Y—1 Z-2
Answer (d)X -> A pointer is assigned to NULL without freeing memory so a clear example of memory leakY -> Trying to retrieve value after freeing it so dangling pointer.Z -> Using uninitialized pointers
5. Consider the following C-program:
void foo(int n, int sum){ int k = 0, j = 0; if (n == 0) return; k = n % 10; j = n / 10; sum = sum + k; foo (j, sum); printf ("%d,", k);} int main (){ int a = 2048, sum = 0; foo (a, sum); printf ("%d\n", sum); getchar();}
What does the above program print? (GATE CS 2005)(a) 8, 4, 0, 2, 14(b) 8, 4, 0, 2, 0(C) 2, 0, 4, 8, 14(d) 2, 0, 4, 8, 0
Answer (d)sum has no use in foo(), it is there just to confuse. Function foo() just prints all digits of a number. In main, there is one more printf statement after foo(), so one more 0 is printed after all digits of n.
Please write comments if you find any of the above answers/explanations incorrect or you want to add some more information about questions.
GATE-CS-2000
GATE-CS-2002
GATE-CS-2003
GATE-CS-2005
GATE-CS-C-Language
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Introduction of Operating System - Set 1
Types of Network Topology
Inter Process Communication (IPC)
Data Structures and Algorithms | Set 21
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
|
[
{
"code": null,
"e": 23569,
"s": 23541,
"text": "\n09 Apr, 2018"
},
{
"code": null,
"e": 23622,
"s": 23569,
"text": "Following questions have been asked in GATE CS exam."
},
{
"code": null,
"e": 23668,
"s": 23622,
"text": "1.Assume the following C variable declaration"
},
{
"code": null,
"e": 23695,
"s": 23668,
"text": " int *A [10], B[10][10]; "
},
{
"code": null,
"e": 23951,
"s": 23695,
"text": "Of the following expressionsI A[2]II A[2][3]III B[1]IV B[2][3]which will not give compile-time errors if used as left hand sides of assignment statements in a C program (GATE CS 2003)?a) I, II, and IV onlyb) II, III, and IV onlyc) II and IV onlyd) IV only"
},
{
"code": null,
"e": 23979,
"s": 23951,
"text": "Answer (a)See below program"
},
{
"code": "int main(){ int *A[10], B[10][10]; int C[] = {12, 11, 13, 14}; /* No problem with below statement as A[2] is a pointer and we are assigning a value to pointer */ A[2] = C; /* No problem with below statement also as array style indexing can be done with pointers*/ A[2][3] = 15; /* Simple assignment to an element of a 2D array*/ B[2][3] = 15; printf(\"%d %d\", A[2][0], A[2][3]); getchar();} ",
"e": 24407,
"s": 23979,
"text": null
},
{
"code": null,
"e": 24479,
"s": 24407,
"text": "2. Consider the following declaration of a ‘two-dimensional array in C:"
},
{
"code": null,
"e": 24499,
"s": 24479,
"text": " char a[100][100]; "
},
{
"code": null,
"e": 24681,
"s": 24499,
"text": "Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of a[40][50] is (GATE CS 2002)a) 4040b) 4050c) 5040d) 5050"
},
{
"code": null,
"e": 24691,
"s": 24681,
"text": "Answer(b)"
},
{
"code": null,
"e": 24807,
"s": 24691,
"text": "Address of a[40][50] = \n Base address + 40*100*element_size + 50*element_size\n 0 + 4000*1 + 50*1\n 4050\n"
},
{
"code": null,
"e": 24964,
"s": 24807,
"text": "3. The C language is. (GATE CS 2002)a) A context free languageb) A context sensitive languagec) A regular languaged) Parsable fully only by a Turing machine"
},
{
"code": null,
"e": 25017,
"s": 24964,
"text": "Answer (b)C and C++ are context-sensitive languages."
},
{
"code": null,
"e": 25044,
"s": 25017,
"text": "There are several reasons:"
},
{
"code": null,
"e": 26133,
"s": 25044,
"text": "To parse C and C++, you start by using a very powerful preprocessor. These preprocessors are inevitably written by hand (they are not based on a theoretic foundation like regular expressions or context-free grammars).The grammar is ambiguous: it has LR conflicts, such as the if-then-else conflict. Parsers typically resolve this using context (an “else” matches the closest “if”).C and C++ lexers require lexical feedback to differentiate between typedef names and identifiers. That is, the context-sensitive lexer needs help from the “context-free” parser to distinguish between an identifier “foo” and a typedef name “foo”. In this snippet,int foo;\ntypedef int foo;\nfoo x;the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive."
},
{
"code": null,
"e": 26351,
"s": 26133,
"text": "To parse C and C++, you start by using a very powerful preprocessor. These preprocessors are inevitably written by hand (they are not based on a theoretic foundation like regular expressions or context-free grammars)."
},
{
"code": null,
"e": 26516,
"s": 26351,
"text": "The grammar is ambiguous: it has LR conflicts, such as the if-then-else conflict. Parsers typically resolve this using context (an “else” matches the closest “if”)."
},
{
"code": null,
"e": 27224,
"s": 26516,
"text": "C and C++ lexers require lexical feedback to differentiate between typedef names and identifiers. That is, the context-sensitive lexer needs help from the “context-free” parser to distinguish between an identifier “foo” and a typedef name “foo”. In this snippet,int foo;\ntypedef int foo;\nfoo x;the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive."
},
{
"code": null,
"e": 27257,
"s": 27224,
"text": "int foo;\ntypedef int foo;\nfoo x;"
},
{
"code": null,
"e": 27671,
"s": 27257,
"text": "the first “foo” is an identifier while the second and third are typedef names. You need to parse typedef declarations to figure this out (and since types have nested parentheses, this is definitely at least as hard as parsing a context-free language).This means that the parser and lexer are mutually recursive, so it doesn’t make sense to say that the parser is context free while the lexer is context sensitive."
},
{
"code": null,
"e": 27707,
"s": 27671,
"text": "Ref: C and C++ are not context free"
},
{
"code": null,
"e": 27778,
"s": 27707,
"text": "4 The most appropriate matching for the following pairs (GATE CS 2000)"
},
{
"code": null,
"e": 27953,
"s": 27778,
"text": "X: m=malloc(5); m= NULL; 1: using dangling pointers\nY: free(n); n->value=5; 2: using uninitialized pointers\nZ: char *p; *p = ’a’; 3. lost memory is:\n"
},
{
"code": null,
"e": 28014,
"s": 27953,
"text": "(a) X—1 Y—3 Z-2(b) X—2 Y—1 Z-3(C) X—3 Y—2 Z-1(d) X—3 Y—1 Z-2"
},
{
"code": null,
"e": 28216,
"s": 28014,
"text": "Answer (d)X -> A pointer is assigned to NULL without freeing memory so a clear example of memory leakY -> Trying to retrieve value after freeing it so dangling pointer.Z -> Using uninitialized pointers"
},
{
"code": null,
"e": 28253,
"s": 28216,
"text": "5. Consider the following C-program:"
},
{
"code": "void foo(int n, int sum){ int k = 0, j = 0; if (n == 0) return; k = n % 10; j = n / 10; sum = sum + k; foo (j, sum); printf (\"%d,\", k);} int main (){ int a = 2048, sum = 0; foo (a, sum); printf (\"%d\\n\", sum); getchar();}",
"e": 28493,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28613,
"s": 28493,
"text": "What does the above program print? (GATE CS 2005)(a) 8, 4, 0, 2, 14(b) 8, 4, 0, 2, 0(C) 2, 0, 4, 8, 14(d) 2, 0, 4, 8, 0"
},
{
"code": null,
"e": 28833,
"s": 28613,
"text": "Answer (d)sum has no use in foo(), it is there just to confuse. Function foo() just prints all digits of a number. In main, there is one more printf statement after foo(), so one more 0 is printed after all digits of n."
},
{
"code": null,
"e": 28973,
"s": 28833,
"text": "Please write comments if you find any of the above answers/explanations incorrect or you want to add some more information about questions."
},
{
"code": null,
"e": 28986,
"s": 28973,
"text": "GATE-CS-2000"
},
{
"code": null,
"e": 28999,
"s": 28986,
"text": "GATE-CS-2002"
},
{
"code": null,
"e": 29012,
"s": 28999,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 29025,
"s": 29012,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 29044,
"s": 29025,
"text": "GATE-CS-C-Language"
},
{
"code": null,
"e": 29052,
"s": 29044,
"text": "GATE CS"
},
{
"code": null,
"e": 29056,
"s": 29052,
"text": "MCQ"
},
{
"code": null,
"e": 29154,
"s": 29056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29163,
"s": 29154,
"text": "Comments"
},
{
"code": null,
"e": 29176,
"s": 29163,
"text": "Old Comments"
},
{
"code": null,
"e": 29208,
"s": 29176,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 29247,
"s": 29208,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 29288,
"s": 29247,
"text": "Introduction of Operating System - Set 1"
},
{
"code": null,
"e": 29314,
"s": 29288,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 29348,
"s": 29314,
"text": "Inter Process Communication (IPC)"
},
{
"code": null,
"e": 29388,
"s": 29348,
"text": "Data Structures and Algorithms | Set 21"
},
{
"code": null,
"e": 29435,
"s": 29388,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 29461,
"s": 29435,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 29487,
"s": 29461,
"text": "Computer Networks | Set 1"
}
] |
Count the number of objects using Static member function in C++
|
Here we will see how to count number of objects are created from a specific class using some static member functions. The static members are class properties, not the object properties. For a single class there will be only one instance for static members. No new members are created for each objects.
In this problem we are using one static counter variable to keep track the number of objects, then static member will be there to display the count
value.
When a new object is created, so the constructor will be called. Inside the constructor, the count value is increased. Thus we can get the output.
#include <iostream>
using namespace std;
class My_Class{
private:
static int count;
public:
My_Class() { //in constructor increase the count value
cout << "Calling Constructor" << endl;
count++;
} static int objCount() {
return count;
}
};
int My_Class::count;
main() {
My_Class my_obj1, my_obj2, my_obj3;
int cnt;
cnt = My_Class::objCount();
cout << "Number of objects:" << cnt;
}
Calling Constructor
Calling Constructor
Calling Constructor
Number of objects:3
|
[
{
"code": null,
"e": 1364,
"s": 1062,
"text": "Here we will see how to count number of objects are created from a specific class using some static member functions. The static members are class properties, not the object properties. For a single class there will be only one instance for static members. No new members are created for each objects."
},
{
"code": null,
"e": 1519,
"s": 1364,
"text": "In this problem we are using one static counter variable to keep track the number of objects, then static member will be there to display the count\nvalue."
},
{
"code": null,
"e": 1666,
"s": 1519,
"text": "When a new object is created, so the constructor will be called. Inside the constructor, the count value is increased. Thus we can get the output."
},
{
"code": null,
"e": 2120,
"s": 1666,
"text": "#include <iostream>\nusing namespace std;\nclass My_Class{\n private:\n static int count;\n public:\n My_Class() { //in constructor increase the count value\n cout << \"Calling Constructor\" << endl;\n count++;\n } static int objCount() {\n return count;\n }\n };\nint My_Class::count;\nmain() {\n My_Class my_obj1, my_obj2, my_obj3;\n int cnt;\n cnt = My_Class::objCount();\n cout << \"Number of objects:\" << cnt;\n}"
},
{
"code": null,
"e": 2200,
"s": 2120,
"text": "Calling Constructor\nCalling Constructor\nCalling Constructor\nNumber of objects:3"
}
] |
Data Classes in Python | Set 3 (dataclass fields) - GeeksforGeeks
|
12 Apr, 2019
Prerequisite: Data Classes in Python Set 1 | Set 2
In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function.
field() function –
dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
The MISSING value is a sentinel object used to detect if the default and default_factory parameters are provided. This sentinel is used because None is a valid value for default. No code should directly use the MISSING value.
default: This parameter specifies the default value for the attribute, if no value is provided during object creation. Similar to the parameters in a function, fields with a default value must come after any fields without a default.There is also an alternative way to provide a default value – just like you do to a normal variable using = operator. (Line #9 in below code)
from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str author: str language: str = field(default ='Python3') upvotes: int = 0 # A DataClass objectarticle = GfgArticle("DataClass", "vibhu4agarwal")print(article)
Output:
GfgArticle(title='DataClass', author='vibhu4agarwal', language='Python3', upvotes=0)
default_factory : If provided, it must be a zero-argument callable that will be called when a default value is needed for this field.The return value of the callable will be set as the default value for the attribute in object creation.You either provide a callable to the default factory OR you provide a default value to the attribute. It is an error to specify both default and default_factory.
from dataclasses import dataclass, fieldfrom random import choice def get_default_language(): languages = ['Python3', 'Java', "CPP"] return choice(languages) @dataclassclass GfgArticle: title: str author: str language: str = field(default_factory = get_default_language) upvotes: int = 0 # A DataClass objectarticle = GfgArticle("DataClass", "vibhu4agarwal")print(article)
The above code puts one of the Python3, Java or CPP as default value for language while DataClass object creation.
The init, repr and hash parameters are similar to that in the dataclass function as discussed in previous article. compare parameter can be related to order as that in dataclass function. The difference is being in their ability to be applicable only to a particular attribute, not to all the attributes in the DataClass under the decorator.
init : If true (the default), this field is included as a parameter to the generated __init__() method. A way to set default value should be provided when init is set to False.
repr : If true (the default), this field is included in the string returned by the generated __repr__() method.
compare : If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.).
from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str = field(compare = False) author: str = field(repr = False) language: str = field(default ='Python3') upvotes: int = field(init = False, default = 0) # DataClass objects# Note the difference in their title valuearticle1 = GfgArticle("DataClass", "vibhu4agarwal")article2 = GfgArticle("Python Packaging", "vibhu4agarwal") print(article1)print(article1.author)print(article1 == article2)
Output:
GfgArticle(title='DataClass', language='Python3', upvotes=0)
vibhu4agarwal
True
hash : This can be a bool or None. If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare: this would normally be the expected behavior.A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged.
metadata : This is usually a dictionary, the key-value pair indicating various information and it’s data.This particular attribute does not really seem to be in use most of the times but it’s important if your DataClass is actually being in used somewhere during development and the attribute’s data is used or accessed by third-parties when their tool or software is integrated in the project.In the script, it’s value can be accessed by querying __dataclass_fields__ variable of the object.
from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str = field(compare = False) author: str = field(metadata ={'data': 'Profile Handle'}) language: str = field(default ='Python3') upvotes: int = field(init = False, default = 0) # A DataClass objectarticle = GfgArticle("DataClass", "vibhu4agarwal")print(article)print(article.__dataclass_fields__['author'].metadata)
Output:
GfgArticle(title='DataClass', author='vibhu4agarwal', language='Python3', upvotes=0)
{'data': 'Profile Handle'}
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()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23801,
"s": 23773,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 23852,
"s": 23801,
"text": "Prerequisite: Data Classes in Python Set 1 | Set 2"
},
{
"code": null,
"e": 24014,
"s": 23852,
"text": "In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function."
},
{
"code": null,
"e": 24033,
"s": 24014,
"text": "field() function –"
},
{
"code": null,
"e": 24158,
"s": 24033,
"text": "dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)"
},
{
"code": null,
"e": 24384,
"s": 24158,
"text": "The MISSING value is a sentinel object used to detect if the default and default_factory parameters are provided. This sentinel is used because None is a valid value for default. No code should directly use the MISSING value."
},
{
"code": null,
"e": 24759,
"s": 24384,
"text": "default: This parameter specifies the default value for the attribute, if no value is provided during object creation. Similar to the parameters in a function, fields with a default value must come after any fields without a default.There is also an alternative way to provide a default value – just like you do to a normal variable using = operator. (Line #9 in below code)"
},
{
"code": "from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str author: str language: str = field(default ='Python3') upvotes: int = 0 # A DataClass objectarticle = GfgArticle(\"DataClass\", \"vibhu4agarwal\")print(article)",
"e": 25011,
"s": 24759,
"text": null
},
{
"code": null,
"e": 25019,
"s": 25011,
"text": "Output:"
},
{
"code": null,
"e": 25105,
"s": 25019,
"text": "GfgArticle(title='DataClass', author='vibhu4agarwal', language='Python3', upvotes=0)\n"
},
{
"code": null,
"e": 25503,
"s": 25105,
"text": "default_factory : If provided, it must be a zero-argument callable that will be called when a default value is needed for this field.The return value of the callable will be set as the default value for the attribute in object creation.You either provide a callable to the default factory OR you provide a default value to the attribute. It is an error to specify both default and default_factory."
},
{
"code": "from dataclasses import dataclass, fieldfrom random import choice def get_default_language(): languages = ['Python3', 'Java', \"CPP\"] return choice(languages) @dataclassclass GfgArticle: title: str author: str language: str = field(default_factory = get_default_language) upvotes: int = 0 # A DataClass objectarticle = GfgArticle(\"DataClass\", \"vibhu4agarwal\")print(article)",
"e": 25899,
"s": 25503,
"text": null
},
{
"code": null,
"e": 26014,
"s": 25899,
"text": "The above code puts one of the Python3, Java or CPP as default value for language while DataClass object creation."
},
{
"code": null,
"e": 26356,
"s": 26014,
"text": "The init, repr and hash parameters are similar to that in the dataclass function as discussed in previous article. compare parameter can be related to order as that in dataclass function. The difference is being in their ability to be applicable only to a particular attribute, not to all the attributes in the DataClass under the decorator."
},
{
"code": null,
"e": 26533,
"s": 26356,
"text": "init : If true (the default), this field is included as a parameter to the generated __init__() method. A way to set default value should be provided when init is set to False."
},
{
"code": null,
"e": 26645,
"s": 26533,
"text": "repr : If true (the default), this field is included in the string returned by the generated __repr__() method."
},
{
"code": null,
"e": 26780,
"s": 26645,
"text": "compare : If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(), et al.)."
},
{
"code": "from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str = field(compare = False) author: str = field(repr = False) language: str = field(default ='Python3') upvotes: int = field(init = False, default = 0) # DataClass objects# Note the difference in their title valuearticle1 = GfgArticle(\"DataClass\", \"vibhu4agarwal\")article2 = GfgArticle(\"Python Packaging\", \"vibhu4agarwal\") print(article1)print(article1.author)print(article1 == article2)",
"e": 27262,
"s": 26780,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27262,
"text": "Output:"
},
{
"code": null,
"e": 27351,
"s": 27270,
"text": "GfgArticle(title='DataClass', language='Python3', upvotes=0)\nvibhu4agarwal\nTrue\n"
},
{
"code": null,
"e": 27682,
"s": 27351,
"text": "hash : This can be a bool or None. If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare: this would normally be the expected behavior.A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged."
},
{
"code": null,
"e": 28175,
"s": 27682,
"text": "metadata : This is usually a dictionary, the key-value pair indicating various information and it’s data.This particular attribute does not really seem to be in use most of the times but it’s important if your DataClass is actually being in used somewhere during development and the attribute’s data is used or accessed by third-parties when their tool or software is integrated in the project.In the script, it’s value can be accessed by querying __dataclass_fields__ variable of the object."
},
{
"code": "from dataclasses import dataclass, field @dataclassclass GfgArticle: title: str = field(compare = False) author: str = field(metadata ={'data': 'Profile Handle'}) language: str = field(default ='Python3') upvotes: int = field(init = False, default = 0) # A DataClass objectarticle = GfgArticle(\"DataClass\", \"vibhu4agarwal\")print(article)print(article.__dataclass_fields__['author'].metadata)",
"e": 28583,
"s": 28175,
"text": null
},
{
"code": null,
"e": 28591,
"s": 28583,
"text": "Output:"
},
{
"code": null,
"e": 28704,
"s": 28591,
"text": "GfgArticle(title='DataClass', author='vibhu4agarwal', language='Python3', upvotes=0)\n{'data': 'Profile Handle'}\n"
},
{
"code": null,
"e": 28711,
"s": 28704,
"text": "Python"
},
{
"code": null,
"e": 28809,
"s": 28711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28818,
"s": 28809,
"text": "Comments"
},
{
"code": null,
"e": 28831,
"s": 28818,
"text": "Old Comments"
},
{
"code": null,
"e": 28849,
"s": 28831,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28884,
"s": 28849,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28906,
"s": 28884,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28938,
"s": 28906,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28968,
"s": 28938,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29010,
"s": 28968,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29036,
"s": 29010,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29079,
"s": 29036,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29123,
"s": 29079,
"text": "Reading and Writing to text files in Python"
}
] |
Python SQLite - Join
|
When you have divided the data in two tables you can fetch combined records from these two tables using Joins.
Assume we have created a table with name CRICKETERS using the following query −
sqlite> CREATE TABLE CRICKETERS (
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Age int,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255)
);
sqlite>
Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table.
sqlite> CREATE TABLE ODIStats (
First_Name VARCHAR(255),
Matches INT,
Runs INT,
AVG FLOAT,
Centuries INT,
HalfCenturies INT
);
sqlite>
Following statement retrieves data combining the values in these two tables −
sqlite> SELECT
Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,
OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies
from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;
First_Name Last_Name Country Matches Runs Centuries HalfCenturies
---------- ---------- ------- ---------- ------------- ---------- ----------
Shikhar Dhawan Indi 133 5518 17 27
Jonathan Trott Sout 68 2819 4 22
Kumara Sangakkara Sril 404 14234 25 93
Virat Kohli Indi 239 11520 43 54
Rohit Sharma Indi 218 8686 24 42
sqlite>
Following SQLite example, demonstrates the JOIN clause using python −
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving data
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''
#Executing the query
cursor.execute(sql)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'),
('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'Raja@mymail.com', 'Vishakhapatnam'),
('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com', 'Pune'),
('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3316,
"s": 3205,
"text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins."
},
{
"code": null,
"e": 3396,
"s": 3316,
"text": "Assume we have created a table with name CRICKETERS using the following query −"
},
{
"code": null,
"e": 3565,
"s": 3396,
"text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>\n"
},
{
"code": null,
"e": 3681,
"s": 3565,
"text": "Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table."
},
{
"code": null,
"e": 3834,
"s": 3681,
"text": "sqlite> CREATE TABLE ODIStats (\n First_Name VARCHAR(255),\n Matches INT,\n Runs INT,\n AVG FLOAT,\n Centuries INT,\n HalfCenturies INT\n);\nsqlite>"
},
{
"code": null,
"e": 3912,
"s": 3834,
"text": "Following statement retrieves data combining the values in these two tables −"
},
{
"code": null,
"e": 4693,
"s": 3912,
"text": "sqlite> SELECT\n Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,\n OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies\n from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;\nFirst_Name Last_Name Country Matches Runs Centuries HalfCenturies\n---------- ---------- ------- ---------- ------------- ---------- ----------\nShikhar Dhawan Indi 133 5518 17 27\nJonathan Trott Sout 68 2819 4 22\nKumara Sangakkara Sril 404 14234 25 93\nVirat Kohli Indi 239 11520 43 54\nRohit Sharma Indi 218 8686 24 42\nsqlite>\n"
},
{
"code": null,
"e": 4763,
"s": 4693,
"text": "Following SQLite example, demonstrates the JOIN clause using python −"
},
{
"code": null,
"e": 5217,
"s": 4763,
"text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving data\nsql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 5567,
"s": 5217,
"text": "[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'Raja@mymail.com', 'Vishakhapatnam'), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com', 'Pune'), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]\n"
},
{
"code": null,
"e": 5604,
"s": 5567,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5620,
"s": 5604,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5653,
"s": 5620,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5672,
"s": 5653,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5707,
"s": 5672,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5729,
"s": 5707,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5763,
"s": 5729,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5791,
"s": 5763,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5826,
"s": 5791,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5840,
"s": 5826,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5873,
"s": 5840,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5890,
"s": 5873,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5897,
"s": 5890,
"text": " Print"
},
{
"code": null,
"e": 5908,
"s": 5897,
"text": " Add Notes"
}
] |
Grant all privileges of a database to a MySQL user?
|
First, create a user and password using CREATE command. The syntax is as follows.
CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';
The syntax to give all privileges of the specific database to the user is as follows.
GRANT ALL PRIVILEGES ON yourDatabaseName . * TO 'yourUserName'@'localhost';
Now you can implement the above syntaxes to create a user and grant all privileges. The query is as follows to create a user.
mysql> create user 'Adam Smith'@'localhost' IDENTIFIED BY 'Adam123456';
Query OK, 0 rows affected (0.29 sec)
Now, grant all privileges to the user. The query is as follows.
mysql> GRANT ALL PRIVILEGES ON test . * TO 'Adam Smith'@'localhost';
Query OK, 0 rows affected (0.19 sec)
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "First, create a user and password using CREATE command. The syntax is as follows."
},
{
"code": null,
"e": 1213,
"s": 1144,
"text": "CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';"
},
{
"code": null,
"e": 1299,
"s": 1213,
"text": "The syntax to give all privileges of the specific database to the user is as follows."
},
{
"code": null,
"e": 1375,
"s": 1299,
"text": "GRANT ALL PRIVILEGES ON yourDatabaseName . * TO 'yourUserName'@'localhost';"
},
{
"code": null,
"e": 1501,
"s": 1375,
"text": "Now you can implement the above syntaxes to create a user and grant all privileges. The query is as follows to create a user."
},
{
"code": null,
"e": 1610,
"s": 1501,
"text": "mysql> create user 'Adam Smith'@'localhost' IDENTIFIED BY 'Adam123456';\nQuery OK, 0 rows affected (0.29 sec)"
},
{
"code": null,
"e": 1674,
"s": 1610,
"text": "Now, grant all privileges to the user. The query is as follows."
},
{
"code": null,
"e": 1780,
"s": 1674,
"text": "mysql> GRANT ALL PRIVILEGES ON test . * TO 'Adam Smith'@'localhost';\nQuery OK, 0 rows affected (0.19 sec)"
}
] |
How can I use a script to create users in MongoDB?
|
You can use createUser() method for this. Following is the syntax −
db.createUser(
{
user: "yourUserName",
pwd: "yourPassword",
roles: [ { role: "read", db: "yourDatabaseName" } ]
}
);
Let us create a user in MongoDB. Here, we are using database ‘test’ −
> db.createUser(
... {
... user: "David",
... pwd: "David123456",
... roles: [ { role: "read", db: "test" } ]
... }
... );
This will produce the following output −
Successfully added user: {
"user" : "David",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "You can use createUser() method for this. Following is the syntax −"
},
{
"code": null,
"e": 1271,
"s": 1130,
"text": "db.createUser(\n {\n user: \"yourUserName\",\n pwd: \"yourPassword\",\n roles: [ { role: \"read\", db: \"yourDatabaseName\" } ]\n }\n);"
},
{
"code": null,
"e": 1341,
"s": 1271,
"text": "Let us create a user in MongoDB. Here, we are using database ‘test’ −"
},
{
"code": null,
"e": 1488,
"s": 1341,
"text": "> db.createUser(\n... {\n... user: \"David\",\n... pwd: \"David123456\",\n... roles: [ { role: \"read\", db: \"test\" } ]\n... }\n... );"
},
{
"code": null,
"e": 1529,
"s": 1488,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1664,
"s": 1529,
"text": "Successfully added user: {\n \"user\" : \"David\",\n \"roles\" : [\n {\n \"role\" : \"read\",\n \"db\" : \"test\"\n }\n ]\n}"
}
] |
How to find a matching substring using regular expression in C#?
|
Our string is −
string str = " My make ";
Use the following regular expression to find the substring “make”
@"\bmake\b"
Here is the complete code −
Live Demo
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
public class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach(Match m in mc) {
Console.WriteLine("Found:" + m);
}
}
public static void Main(string[] args) {
string str = "My make";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bmake\b");
}
}
}
Matching words start with 'm' and ends with 'e':
The Expression: \bmake\b
Found:make
|
[
{
"code": null,
"e": 1078,
"s": 1062,
"text": "Our string is −"
},
{
"code": null,
"e": 1105,
"s": 1078,
"text": "string str = \" My make \";\n"
},
{
"code": null,
"e": 1171,
"s": 1105,
"text": "Use the following regular expression to find the substring “make”"
},
{
"code": null,
"e": 1184,
"s": 1171,
"text": "@\"\\bmake\\b\"\n"
},
{
"code": null,
"e": 1212,
"s": 1184,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1223,
"s": 1212,
"text": " Live Demo"
},
{
"code": null,
"e": 1821,
"s": 1223,
"text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace RegExApplication {\n public class Program {\n private static void showMatch(string text, string expr) {\n Console.WriteLine(\"The Expression: \" + expr);\n MatchCollection mc = Regex.Matches(text, expr);\n\n foreach(Match m in mc) {\n Console.WriteLine(\"Found:\" + m);\n }\n }\n\n public static void Main(string[] args) {\n string str = \"My make\";\n\n Console.WriteLine(\"Matching words start with 'm' and ends with 'e':\");\n showMatch(str, @\"\\bmake\\b\");\n }\n }\n}"
},
{
"code": null,
"e": 1907,
"s": 1821,
"text": "Matching words start with 'm' and ends with 'e':\nThe Expression: \\bmake\\b\nFound:make\n"
}
] |
How to call a method after a delay in Android Kotlin?
|
This example demonstrates how to call a method after a delay in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16sp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@color/colorPrimaryDark"
android:textSize="48sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textViewTitle"
android:layout_centerInParent="true"
android:text="Wait for the Toast to display."
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
private val string = "Delay by 5 seconds"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
val handler = Handler()
handler.postDelayed({ testToast() }, 5000)
}
private fun testToast() {
Toast.makeText(this, "This method is called after a delay!", Toast.LENGTH_SHORT).show()
textView.text = string
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "This example demonstrates how to call a method after a delay in Android Kotlin."
},
{
"code": null,
"e": 1270,
"s": 1142,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1335,
"s": 1270,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2706,
"s": 1335,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16sp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textViewTitle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/textViewTitle\"\n android:layout_centerInParent=\"true\"\n android:text=\"Wait for the Toast to display.\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2761,
"s": 2706,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3498,
"s": 2761,
"text": "import android.os.Bundle\nimport android.os.Handler\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n private val string = \"Delay by 5 seconds\"\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n val handler = Handler()\n handler.postDelayed({ testToast() }, 5000)\n }\n private fun testToast() {\n Toast.makeText(this, \"This method is called after a delay!\", Toast.LENGTH_SHORT).show()\n textView.text = string\n }\n}"
},
{
"code": null,
"e": 3553,
"s": 3498,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4226,
"s": 3553,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4576,
"s": 4226,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Pytube | Python library to download youtube videos - GeeksforGeeks
|
08 Dec, 2021
YouTube is very popular video sharing website. Downloading a video from YouTube is a tough job. Downloading the Downloader and get the video using that or go to any other website which fetches the video and saves on your computer. Using Python, this task is very easy. Few lines of code will download the video from YouTube for you. For this, there a python library named as ‘pytube’. pytube is a lightweight, dependency-free Python library which is used for downloading videos from the web.pytube is not the native library. You need to install it before using it. Installation is easy when you have pip. In the Terminal or Command Prompt, type the following command to install pytube.
pip install pytube
In case you don’t have pip, install it as an external library.
Downloading a single video
pytube library makes the video downloading very easy. Create the object of the YouTube module by passing the link as the parameter. Then, get the appropriate extension and resolution of the video. You can set the name of the file as your convenience, in another case original name will be kept. After that, download the file using the download function which has one parameter which is the location where to download the file.
Python3
# importing the module from pytube import YouTube # where to save SAVE_PATH = "E:/" #to_do # link of the video to be downloaded link="https://www.youtube.com/watch?v=xWOoBJUqlbI" try: # object creation using YouTube # which was imported in the beginning yt = YouTube(link) except: print("Connection Error") #to handle exception # filters out all the files with "mp4" extension mp4files = yt.filter('mp4') #to set the name of the fileyt.set_filename('GeeksforGeeks Video') # get the video with the extension and# resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print("Some Error!") print('Task Completed!')
Downloading a file takes some time as a very large amount of data is being downloaded from the web. Depending on the speed of the connection, time taken to execute the program varies. In case you wish to download the number of files, go with the next case.
Downloading multiple videos
The basic task of downloading the multiple videos is same as downloading a single video. We can use a for loop for downloading the video.
Python3
from pytube import YouTube #where to save SAVE_PATH = "E:/" #to_do #link of the video to be downloaded link=["https://www.youtube.com/watch?v=xWOoBJUqlbI", "https://www.youtube.com/watch?v=xWOoBJUqlbI" ] for i in link: try: # object creation using YouTube # which was imported in the beginning yt = YouTube(i) except: #to handle exception print("Connection Error") #filters out all the files with "mp4" extension mp4files = yt.filter('mp4') # get the video with the extension and # resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print("Some Error!") print('Task Completed!')
In this, we have used a for loop for downloading multiple files as shown. One can use file handling for keeping the all the links in a file which needs to be downloaded.
Download multiple videos using File Handling
Using file handling, we can open the file which has the group of links in it. Traversing every link of a text file and applying the very basic video downloading program is done here. Here, we have a text file named as “links_file.txt” which has all the links which need to be downloaded.
Python3
from pytube import YouTube # where to save SAVE_PATH = "E:/" #to_do # link of the video to be downloaded # opening the file link=open('links_file.txt','r') for i in link: try: # object creation using YouTube # which was imported in the beginning yt = YouTube(i) except: #to handle exception print("Connection Error") #filters out all the files with "mp4" extension mp4files = yt.filter('mp4') # get the video with the extension and # resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print("Some Error!") print('Task Completed!')
Important Points:
Make sure you are connected to the internet to download the videos. Otherwise it will raise an error.Don’t use the set_filename() function in any loop. In this case, only one video will be downloaded.You can modify the names everytime using another array of names.Connection Interruption in between will also raise an error and video will not be downloaded in that case.
Make sure you are connected to the internet to download the videos. Otherwise it will raise an error.
Don’t use the set_filename() function in any loop. In this case, only one video will be downloaded.
You can modify the names everytime using another array of names.
Connection Interruption in between will also raise an error and video will not be downloaded in that case.
This article is contributed by Rishabh Bansal. 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.
varshagumber28
simmytarika5
GBlog
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
6 Best IDE's For Python in 2022
A Freshers Guide To Programming
Supervised and Unsupervised learning
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": 24751,
"s": 24723,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25437,
"s": 24751,
"text": "YouTube is very popular video sharing website. Downloading a video from YouTube is a tough job. Downloading the Downloader and get the video using that or go to any other website which fetches the video and saves on your computer. Using Python, this task is very easy. Few lines of code will download the video from YouTube for you. For this, there a python library named as ‘pytube’. pytube is a lightweight, dependency-free Python library which is used for downloading videos from the web.pytube is not the native library. You need to install it before using it. Installation is easy when you have pip. In the Terminal or Command Prompt, type the following command to install pytube."
},
{
"code": null,
"e": 25457,
"s": 25437,
"text": "pip install pytube\n"
},
{
"code": null,
"e": 25520,
"s": 25457,
"text": "In case you don’t have pip, install it as an external library."
},
{
"code": null,
"e": 25547,
"s": 25520,
"text": "Downloading a single video"
},
{
"code": null,
"e": 25974,
"s": 25547,
"text": "pytube library makes the video downloading very easy. Create the object of the YouTube module by passing the link as the parameter. Then, get the appropriate extension and resolution of the video. You can set the name of the file as your convenience, in another case original name will be kept. After that, download the file using the download function which has one parameter which is the location where to download the file."
},
{
"code": null,
"e": 25982,
"s": 25974,
"text": "Python3"
},
{
"code": "# importing the module from pytube import YouTube # where to save SAVE_PATH = \"E:/\" #to_do # link of the video to be downloaded link=\"https://www.youtube.com/watch?v=xWOoBJUqlbI\" try: # object creation using YouTube # which was imported in the beginning yt = YouTube(link) except: print(\"Connection Error\") #to handle exception # filters out all the files with \"mp4\" extension mp4files = yt.filter('mp4') #to set the name of the fileyt.set_filename('GeeksforGeeks Video') # get the video with the extension and# resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print(\"Some Error!\") print('Task Completed!') ",
"e": 26750,
"s": 25982,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26750,
"text": "Downloading a file takes some time as a very large amount of data is being downloaded from the web. Depending on the speed of the connection, time taken to execute the program varies. In case you wish to download the number of files, go with the next case."
},
{
"code": null,
"e": 27035,
"s": 27007,
"text": "Downloading multiple videos"
},
{
"code": null,
"e": 27173,
"s": 27035,
"text": "The basic task of downloading the multiple videos is same as downloading a single video. We can use a for loop for downloading the video."
},
{
"code": null,
"e": 27181,
"s": 27173,
"text": "Python3"
},
{
"code": "from pytube import YouTube #where to save SAVE_PATH = \"E:/\" #to_do #link of the video to be downloaded link=[\"https://www.youtube.com/watch?v=xWOoBJUqlbI\", \"https://www.youtube.com/watch?v=xWOoBJUqlbI\" ] for i in link: try: # object creation using YouTube # which was imported in the beginning yt = YouTube(i) except: #to handle exception print(\"Connection Error\") #filters out all the files with \"mp4\" extension mp4files = yt.filter('mp4') # get the video with the extension and # resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print(\"Some Error!\") print('Task Completed!') ",
"e": 28018,
"s": 27181,
"text": null
},
{
"code": null,
"e": 28188,
"s": 28018,
"text": "In this, we have used a for loop for downloading multiple files as shown. One can use file handling for keeping the all the links in a file which needs to be downloaded."
},
{
"code": null,
"e": 28233,
"s": 28188,
"text": "Download multiple videos using File Handling"
},
{
"code": null,
"e": 28521,
"s": 28233,
"text": "Using file handling, we can open the file which has the group of links in it. Traversing every link of a text file and applying the very basic video downloading program is done here. Here, we have a text file named as “links_file.txt” which has all the links which need to be downloaded."
},
{
"code": null,
"e": 28529,
"s": 28521,
"text": "Python3"
},
{
"code": "from pytube import YouTube # where to save SAVE_PATH = \"E:/\" #to_do # link of the video to be downloaded # opening the file link=open('links_file.txt','r') for i in link: try: # object creation using YouTube # which was imported in the beginning yt = YouTube(i) except: #to handle exception print(\"Connection Error\") #filters out all the files with \"mp4\" extension mp4files = yt.filter('mp4') # get the video with the extension and # resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: # downloading the video d_video.download(SAVE_PATH) except: print(\"Some Error!\") print('Task Completed!') ",
"e": 29326,
"s": 28529,
"text": null
},
{
"code": null,
"e": 29344,
"s": 29326,
"text": "Important Points:"
},
{
"code": null,
"e": 29715,
"s": 29344,
"text": "Make sure you are connected to the internet to download the videos. Otherwise it will raise an error.Don’t use the set_filename() function in any loop. In this case, only one video will be downloaded.You can modify the names everytime using another array of names.Connection Interruption in between will also raise an error and video will not be downloaded in that case."
},
{
"code": null,
"e": 29817,
"s": 29715,
"text": "Make sure you are connected to the internet to download the videos. Otherwise it will raise an error."
},
{
"code": null,
"e": 29917,
"s": 29817,
"text": "Don’t use the set_filename() function in any loop. In this case, only one video will be downloaded."
},
{
"code": null,
"e": 29982,
"s": 29917,
"text": "You can modify the names everytime using another array of names."
},
{
"code": null,
"e": 30089,
"s": 29982,
"text": "Connection Interruption in between will also raise an error and video will not be downloaded in that case."
},
{
"code": null,
"e": 30391,
"s": 30089,
"text": "This article is contributed by Rishabh Bansal. 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."
},
{
"code": null,
"e": 30516,
"s": 30391,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30531,
"s": 30516,
"text": "varshagumber28"
},
{
"code": null,
"e": 30544,
"s": 30531,
"text": "simmytarika5"
},
{
"code": null,
"e": 30550,
"s": 30544,
"text": "GBlog"
},
{
"code": null,
"e": 30557,
"s": 30550,
"text": "Python"
},
{
"code": null,
"e": 30574,
"s": 30557,
"text": "Web Technologies"
},
{
"code": null,
"e": 30672,
"s": 30574,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30681,
"s": 30672,
"text": "Comments"
},
{
"code": null,
"e": 30694,
"s": 30681,
"text": "Old Comments"
},
{
"code": null,
"e": 30750,
"s": 30694,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 30775,
"s": 30750,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30807,
"s": 30775,
"text": "6 Best IDE's For Python in 2022"
},
{
"code": null,
"e": 30839,
"s": 30807,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 30876,
"s": 30839,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 30904,
"s": 30876,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30954,
"s": 30904,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30976,
"s": 30954,
"text": "Python map() function"
}
] |
How to call a parent method from child class in JavaScript? - GeeksforGeeks
|
05 Jun, 2020
A property in programming known as inheritance, by virtue of which a class can derive the methods and properties of other class analogous to parent-child relationship in living beings. A child inherits its characteristics from its parents but it doesn’t work the other around. Also, similar to the parent-child relationship of living beings, a child can have its own properties too in addition to inherited ones. In the programming context, the class that derives from other classes is known as derived or sub or child class. Whereas, the class from which characteristic is derived is known as the base or super or parent class.
The concept of inheritance, sub, and superclass is same in all programming languages the only difference being their implementation. The objective here is to call a function defined in parent class with the help of child class. To obtain this result following methods listed can be used.
Direct calling method: Since a derived class has access to all characteristics of its base class, using child class’s object to refer to parent class’s function makes perfect sense.
javascript
<!DOCTYPE html><html> <head> <title>Calling parrent from child class</title> </head> <body> <script type="text/javascript"> class Parent { func1() { alert("inside func1() of class parent"); } func2() { alert("inside func2() of class parent"); } } class Child extends Parent { func3() { alert("inside func3() of class Child"); } } // Declaring objects // Parent's object let p1 = new Parent(); // Child's object let c1 = new Child(); // Calling func()1 using parent's object p1.func1(); // Calling func1() using child's object c1.func1(); </script> </body></html>
Output: Two times will pop out that alert one time by using the parent’s object and other time by using the child’s object.
Using super Method: The super keyword is used in JS to call functions and constructors from parent class. Where ever super is mentioned in the child class the compiler looks for the specified function in its parent’s class. This is mostly used when functions are overloaded and a certain requirement asks for parent’s version of the function. It is also used to overload constructors
javascript
<!DOCTYPE html><html> <head> <title>Calling parrent from child class</title> </head> <body> <script type="text/javascript"> class Parent { func1() { alert("inside func1() of class parent"); } func2() { alert("inside func2() of class parent"); } } class Child extends Parent { // Overloaded function func1() { alert("inside func1() of class Child "); alert("calling func1() of parent class"); // Calling for parent's version of func1() super.func1(); } } let c1 = new Child(); // Call to func1() of child class // There the func1() will call func1() // From aprent using super c1.func1(); </script> </body></html>
Output:
Calling method & Constructor: In this program we call method and constructor from child class.
javascript
<!DOCTYPE html><html> <head> <title> Call method and constructor from child class </title> </head> <body> <script type="text/javascript"> class Parent { constructor(name) { this.name = name; } display() { alert("name: " + this.name); } } class Child extends Parent { constructor(name, num) { // Calling parent's constructor super(name); this.num = num; } display() { // Calling display() from parent super.display(); alert("num: " + this.num); } } let p1 = new Parent("a"); let c1 = new Child("b", 1); p1.display(); c1.display(); </script> </body></html>
Output:
HTML-Misc
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 24364,
"s": 24336,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24995,
"s": 24364,
"text": "A property in programming known as inheritance, by virtue of which a class can derive the methods and properties of other class analogous to parent-child relationship in living beings. A child inherits its characteristics from its parents but it doesn’t work the other around. Also, similar to the parent-child relationship of living beings, a child can have its own properties too in addition to inherited ones. In the programming context, the class that derives from other classes is known as derived or sub or child class. Whereas, the class from which characteristic is derived is known as the base or super or parent class. "
},
{
"code": null,
"e": 25283,
"s": 24995,
"text": "The concept of inheritance, sub, and superclass is same in all programming languages the only difference being their implementation. The objective here is to call a function defined in parent class with the help of child class. To obtain this result following methods listed can be used."
},
{
"code": null,
"e": 25465,
"s": 25283,
"text": "Direct calling method: Since a derived class has access to all characteristics of its base class, using child class’s object to refer to parent class’s function makes perfect sense."
},
{
"code": null,
"e": 25476,
"s": 25465,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Calling parrent from child class</title> </head> <body> <script type=\"text/javascript\"> class Parent { func1() { alert(\"inside func1() of class parent\"); } func2() { alert(\"inside func2() of class parent\"); } } class Child extends Parent { func3() { alert(\"inside func3() of class Child\"); } } // Declaring objects // Parent's object let p1 = new Parent(); // Child's object let c1 = new Child(); // Calling func()1 using parent's object p1.func1(); // Calling func1() using child's object c1.func1(); </script> </body></html>",
"e": 26374,
"s": 25476,
"text": null
},
{
"code": null,
"e": 26498,
"s": 26374,
"text": "Output: Two times will pop out that alert one time by using the parent’s object and other time by using the child’s object."
},
{
"code": null,
"e": 26884,
"s": 26500,
"text": "Using super Method: The super keyword is used in JS to call functions and constructors from parent class. Where ever super is mentioned in the child class the compiler looks for the specified function in its parent’s class. This is mostly used when functions are overloaded and a certain requirement asks for parent’s version of the function. It is also used to overload constructors"
},
{
"code": null,
"e": 26895,
"s": 26884,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Calling parrent from child class</title> </head> <body> <script type=\"text/javascript\"> class Parent { func1() { alert(\"inside func1() of class parent\"); } func2() { alert(\"inside func2() of class parent\"); } } class Child extends Parent { // Overloaded function func1() { alert(\"inside func1() of class Child \"); alert(\"calling func1() of parent class\"); // Calling for parent's version of func1() super.func1(); } } let c1 = new Child(); // Call to func1() of child class // There the func1() will call func1() // From aprent using super c1.func1(); </script> </body></html>",
"e": 27872,
"s": 26895,
"text": null
},
{
"code": null,
"e": 27881,
"s": 27872,
"text": "Output: "
},
{
"code": null,
"e": 27976,
"s": 27881,
"text": "Calling method & Constructor: In this program we call method and constructor from child class."
},
{
"code": null,
"e": 27987,
"s": 27976,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Call method and constructor from child class </title> </head> <body> <script type=\"text/javascript\"> class Parent { constructor(name) { this.name = name; } display() { alert(\"name: \" + this.name); } } class Child extends Parent { constructor(name, num) { // Calling parent's constructor super(name); this.num = num; } display() { // Calling display() from parent super.display(); alert(\"num: \" + this.num); } } let p1 = new Parent(\"a\"); let c1 = new Child(\"b\", 1); p1.display(); c1.display(); </script> </body></html>",
"e": 28964,
"s": 27987,
"text": null
},
{
"code": null,
"e": 28973,
"s": 28964,
"text": "Output: "
},
{
"code": null,
"e": 28983,
"s": 28973,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28999,
"s": 28983,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29006,
"s": 28999,
"text": "Picked"
},
{
"code": null,
"e": 29017,
"s": 29006,
"text": "JavaScript"
},
{
"code": null,
"e": 29034,
"s": 29017,
"text": "Web Technologies"
},
{
"code": null,
"e": 29061,
"s": 29034,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29159,
"s": 29061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29204,
"s": 29159,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29265,
"s": 29204,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29337,
"s": 29265,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29389,
"s": 29337,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29435,
"s": 29389,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29477,
"s": 29435,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29510,
"s": 29477,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29553,
"s": 29510,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29603,
"s": 29553,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Common error in Group By - GeeksforGeeks
|
19 Jun, 2019
Prerequisite: SQL | GROUP BY
Error:Column ‘col’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Examples:
Input:
select empId, empName, empAmount from emp group by empId, empName
Output: Error
Explanation:empAmount is not in group by list and is neither an aggregate function, the query will give above error. For empId and empName there are multiple empAmount, Database engine could not choose one empAmount.
Input:
select empId, sum(empAmount) as debit from emp group by empId
Output:
empId | debit
1 | 300
2 | 400
GROUP BY:From the above examples it is clear that we can have only those columns which are there in the group by or arguments of an aggregate function in the select clause. but that’s not completely true.
“The 1999 and 2003 versions of the SQL standard require that the columns appearing in the SELECT list are functionally dependent upon the groups defined by the GROUP BY clause. In other words, if we know that a column contains only one value for any given combination of values in the columns appearing in the GROUP BY clause, we may reference the column in the SELECT list even if it does not appear in an aggregate expression”–By Roland Bouman
In layman terms:
If columns in group by has a column which is either the primary key or unique key then the combination will only have one value for other columns.
But grouping by a unique column does not make sense but it will become useful when other tables are involved.
A Few Exceptions:MySQL lets you SELECT anything in a query with group by. It will select in random order and whatever is first will return you.
Example:
Input:
select empId, empName, empAmount from emp group by empId, empName
The above query will not give any error. It will pick random empAmount from the list and pair it with the empID and empName.
The correct behavior can be enabled by adding a flag (i.e., ONLY_FULL_GROUP_BY) or by using MySQL v5.7.5 or higher. In that case, the query would raise the above error.
DBMS-SQL
SQL-basics
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?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Delete Duplicate Rows
SQL Query to Convert VARCHAR to INT
SQL - SELECT from Multiple Tables with MS SQL Server
How to Select Data Between Two Dates and Times in SQL Server?
|
[
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 24323,
"s": 24294,
"text": "Prerequisite: SQL | GROUP BY"
},
{
"code": null,
"e": 24456,
"s": 24323,
"text": "Error:Column ‘col’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
},
{
"code": null,
"e": 24466,
"s": 24456,
"text": "Examples:"
},
{
"code": null,
"e": 24556,
"s": 24466,
"text": "Input: \nselect empId, empName, empAmount from emp group by empId, empName\n\nOutput: Error "
},
{
"code": null,
"e": 24773,
"s": 24556,
"text": "Explanation:empAmount is not in group by list and is neither an aggregate function, the query will give above error. For empId and empName there are multiple empAmount, Database engine could not choose one empAmount."
},
{
"code": null,
"e": 24891,
"s": 24773,
"text": "Input: \nselect empId, sum(empAmount) as debit from emp group by empId\n\nOutput:\nempId | debit\n1 | 300\n2 | 400 "
},
{
"code": null,
"e": 25096,
"s": 24891,
"text": "GROUP BY:From the above examples it is clear that we can have only those columns which are there in the group by or arguments of an aggregate function in the select clause. but that’s not completely true."
},
{
"code": null,
"e": 25542,
"s": 25096,
"text": "“The 1999 and 2003 versions of the SQL standard require that the columns appearing in the SELECT list are functionally dependent upon the groups defined by the GROUP BY clause. In other words, if we know that a column contains only one value for any given combination of values in the columns appearing in the GROUP BY clause, we may reference the column in the SELECT list even if it does not appear in an aggregate expression”–By Roland Bouman"
},
{
"code": null,
"e": 25559,
"s": 25542,
"text": "In layman terms:"
},
{
"code": null,
"e": 25706,
"s": 25559,
"text": "If columns in group by has a column which is either the primary key or unique key then the combination will only have one value for other columns."
},
{
"code": null,
"e": 25816,
"s": 25706,
"text": "But grouping by a unique column does not make sense but it will become useful when other tables are involved."
},
{
"code": null,
"e": 25960,
"s": 25816,
"text": "A Few Exceptions:MySQL lets you SELECT anything in a query with group by. It will select in random order and whatever is first will return you."
},
{
"code": null,
"e": 25969,
"s": 25960,
"text": "Example:"
},
{
"code": null,
"e": 26043,
"s": 25969,
"text": "Input:\nselect empId, empName, empAmount from emp group by empId, empName "
},
{
"code": null,
"e": 26168,
"s": 26043,
"text": "The above query will not give any error. It will pick random empAmount from the list and pair it with the empID and empName."
},
{
"code": null,
"e": 26337,
"s": 26168,
"text": "The correct behavior can be enabled by adding a flag (i.e., ONLY_FULL_GROUP_BY) or by using MySQL v5.7.5 or higher. In that case, the query would raise the above error."
},
{
"code": null,
"e": 26346,
"s": 26337,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26357,
"s": 26346,
"text": "SQL-basics"
},
{
"code": null,
"e": 26361,
"s": 26357,
"text": "SQL"
},
{
"code": null,
"e": 26365,
"s": 26361,
"text": "SQL"
},
{
"code": null,
"e": 26463,
"s": 26365,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26529,
"s": 26463,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26561,
"s": 26529,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26639,
"s": 26561,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26656,
"s": 26639,
"text": "SQL using Python"
},
{
"code": null,
"e": 26671,
"s": 26656,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26737,
"s": 26671,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26772,
"s": 26737,
"text": "SQL Query to Delete Duplicate Rows"
},
{
"code": null,
"e": 26808,
"s": 26772,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26861,
"s": 26808,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
Python Inner Functions - GeeksforGeeks
|
25 Nov, 2019
In Python, functions are treated as first class objects. First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, ...
Note: To know more about first class objects click here.
A function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. To know more about encapsulation click here.
Example:
# Python program to illustrate # nested functions def outerFunction(text): text = text def innerFunction(): print(text) innerFunction() if __name__ == '__main__': outerFunction('Hey !')
Output:
Hey!
In the above example, innerFunction() has been defined inside outerFunction(), making it an inner function. To call innerFunction(), we must first call outerFunction(). The outerFunction() will then go ahead and call innerFunction() as it has been defined inside it.
It is important that outer function has to be called, so that the inner function can execute. To demonstrate this consider the below example:Example:
# Python program to illustrate # nested functions def outerFunction(text): text = text def innerFunction(): print(text) innerFunction()
Output:
This code will return nothing when executed.
The location where we can find a variable and also access it if required is called the scope of a variable.It is known how to access a global variable inside a function, but, what about accessing the variable of an outer function? Let’s see an example:
# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): print(s) f2() # Driver's codef1()
Output:
I love GeeksforGeeks
In the above example, it can be seen that it is similar to accessing the global variable from a function. Now let’s suppose you want to change the variable of the outer function.
# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): s = 'Me too' print(s) f2() print(s) # Driver's codef1()
Output:
Me too
I love GeeksforGeeks
It can be seen the value of the variable of the outer function is not changed. However, the value of the variable of the outer function can be changed. There are different ways to change the value of the variable of the outer function.
Using an iterable –# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = ['I love GeeksforGeeks'] def f2(): s[0] = 'Me too' print(s) f2() print(s) # Driver's codef1()Output:['Me too']
['Me too']
# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = ['I love GeeksforGeeks'] def f2(): s[0] = 'Me too' print(s) f2() print(s) # Driver's codef1()
Output:
['Me too']
['Me too']
Using nonlocal keyword –# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): nonlocal s s = 'Me too' print(s) f2() print(s) # Driver's codef1()Output:Me too
Me too
# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): nonlocal s s = 'Me too' print(s) f2() print(s) # Driver's codef1()
Output:
Me too
Me too
Value can also be changed as shown in the below example.# Python program to # demonstrate accessing of# variables of nested functions def f1(): f1.s = 'I love GeeksforGeeks' def f2(): f1.s = 'Me too' print(f1.s) f2() print(f1.s) # Driver's codef1()Output:Me too
Me too
# Python program to # demonstrate accessing of# variables of nested functions def f1(): f1.s = 'I love GeeksforGeeks' def f2(): f1.s = 'Me too' print(f1.s) f2() print(f1.s) # Driver's codef1()
Output:
Me too
Me too
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.filter_none.
# Python program to illustrate # closures def outerFunction(text): text = text def innerFunction(): print(text) return innerFunction # Note we are returning function WITHOUT parenthesis if __name__ == '__main__': myFunction = outerFunction('Hey !') myFunction()
Output:
Hey!
As observed from above code, closures help to invoke function outside their scope.
The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope.
# Python program to illustrate # closures import logging logging.basicConfig(filename ='example.log', level = logging.INFO) def logger(func): def log_func(*args): logging.info( 'Running "{}" with arguments {}'.format(func.__name__, args)) print(func(*args)) # Necessary for closure to work (returning WITHOUT parenthesis) return log_func def add(x, y): return x + y def sub(x, y): return x-y add_logger = logger(add) sub_logger = logger(sub) add_logger(3, 3) add_logger(4, 5) sub_logger(10, 5) sub_logger(20, 10)
Output:
6
9
5
10
Python-Functions
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
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 24649,
"s": 24268,
"text": "In Python, functions are treated as first class objects. First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions."
},
{
"code": null,
"e": 24686,
"s": 24649,
"text": "Properties of first class functions:"
},
{
"code": null,
"e": 24732,
"s": 24686,
"text": "A function is an instance of the Object type."
},
{
"code": null,
"e": 24774,
"s": 24732,
"text": "You can store the function in a variable."
},
{
"code": null,
"e": 24836,
"s": 24774,
"text": "You can pass the function as a parameter to another function."
},
{
"code": null,
"e": 24881,
"s": 24836,
"text": "You can return the function from a function."
},
{
"code": null,
"e": 24951,
"s": 24881,
"text": "You can store them in data structures such as hash tables, lists, ..."
},
{
"code": null,
"e": 25008,
"s": 24951,
"text": "Note: To know more about first class objects click here."
},
{
"code": null,
"e": 25370,
"s": 25008,
"text": "A function which is defined inside another function is known as inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation. To know more about encapsulation click here."
},
{
"code": null,
"e": 25379,
"s": 25370,
"text": "Example:"
},
{
"code": "# Python program to illustrate # nested functions def outerFunction(text): text = text def innerFunction(): print(text) innerFunction() if __name__ == '__main__': outerFunction('Hey !') ",
"e": 25602,
"s": 25379,
"text": null
},
{
"code": null,
"e": 25610,
"s": 25602,
"text": "Output:"
},
{
"code": null,
"e": 25616,
"s": 25610,
"text": "Hey!\n"
},
{
"code": null,
"e": 25883,
"s": 25616,
"text": "In the above example, innerFunction() has been defined inside outerFunction(), making it an inner function. To call innerFunction(), we must first call outerFunction(). The outerFunction() will then go ahead and call innerFunction() as it has been defined inside it."
},
{
"code": null,
"e": 26033,
"s": 25883,
"text": "It is important that outer function has to be called, so that the inner function can execute. To demonstrate this consider the below example:Example:"
},
{
"code": "# Python program to illustrate # nested functions def outerFunction(text): text = text def innerFunction(): print(text) innerFunction() ",
"e": 26198,
"s": 26033,
"text": null
},
{
"code": null,
"e": 26206,
"s": 26198,
"text": "Output:"
},
{
"code": null,
"e": 26252,
"s": 26206,
"text": "This code will return nothing when executed.\n"
},
{
"code": null,
"e": 26505,
"s": 26252,
"text": "The location where we can find a variable and also access it if required is called the scope of a variable.It is known how to access a global variable inside a function, but, what about accessing the variable of an outer function? Let’s see an example:"
},
{
"code": "# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): print(s) f2() # Driver's codef1()",
"e": 26698,
"s": 26505,
"text": null
},
{
"code": null,
"e": 26706,
"s": 26698,
"text": "Output:"
},
{
"code": null,
"e": 26728,
"s": 26706,
"text": "I love GeeksforGeeks\n"
},
{
"code": null,
"e": 26907,
"s": 26728,
"text": "In the above example, it can be seen that it is similar to accessing the global variable from a function. Now let’s suppose you want to change the variable of the outer function."
},
{
"code": "# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): s = 'Me too' print(s) f2() print(s) # Driver's codef1()",
"e": 27132,
"s": 26907,
"text": null
},
{
"code": null,
"e": 27140,
"s": 27132,
"text": "Output:"
},
{
"code": null,
"e": 27169,
"s": 27140,
"text": "Me too\nI love GeeksforGeeks\n"
},
{
"code": null,
"e": 27405,
"s": 27169,
"text": "It can be seen the value of the variable of the outer function is not changed. However, the value of the variable of the outer function can be changed. There are different ways to change the value of the variable of the outer function."
},
{
"code": null,
"e": 27683,
"s": 27405,
"text": "Using an iterable –# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = ['I love GeeksforGeeks'] def f2(): s[0] = 'Me too' print(s) f2() print(s) # Driver's codef1()Output:['Me too']\n['Me too']\n"
},
{
"code": "# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = ['I love GeeksforGeeks'] def f2(): s[0] = 'Me too' print(s) f2() print(s) # Driver's codef1()",
"e": 27913,
"s": 27683,
"text": null
},
{
"code": null,
"e": 27921,
"s": 27913,
"text": "Output:"
},
{
"code": null,
"e": 27944,
"s": 27921,
"text": "['Me too']\n['Me too']\n"
},
{
"code": null,
"e": 28232,
"s": 27944,
"text": "Using nonlocal keyword –# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): nonlocal s s = 'Me too' print(s) f2() print(s) # Driver's codef1()Output:Me too\nMe too\n"
},
{
"code": "# Python program to # demonstrate accessing of# variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): nonlocal s s = 'Me too' print(s) f2() print(s) # Driver's codef1()",
"e": 28475,
"s": 28232,
"text": null
},
{
"code": null,
"e": 28483,
"s": 28475,
"text": "Output:"
},
{
"code": null,
"e": 28498,
"s": 28483,
"text": "Me too\nMe too\n"
},
{
"code": null,
"e": 28812,
"s": 28498,
"text": "Value can also be changed as shown in the below example.# Python program to # demonstrate accessing of# variables of nested functions def f1(): f1.s = 'I love GeeksforGeeks' def f2(): f1.s = 'Me too' print(f1.s) f2() print(f1.s) # Driver's codef1()Output:Me too\nMe too\n"
},
{
"code": "# Python program to # demonstrate accessing of# variables of nested functions def f1(): f1.s = 'I love GeeksforGeeks' def f2(): f1.s = 'Me too' print(f1.s) f2() print(f1.s) # Driver's codef1()",
"e": 29049,
"s": 28812,
"text": null
},
{
"code": null,
"e": 29057,
"s": 29049,
"text": "Output:"
},
{
"code": null,
"e": 29072,
"s": 29057,
"text": "Me too\nMe too\n"
},
{
"code": null,
"e": 29185,
"s": 29072,
"text": "A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory."
},
{
"code": null,
"e": 29465,
"s": 29185,
"text": "It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created."
},
{
"code": null,
"e": 29681,
"s": 29465,
"text": "A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.filter_none."
},
{
"code": "# Python program to illustrate # closures def outerFunction(text): text = text def innerFunction(): print(text) return innerFunction # Note we are returning function WITHOUT parenthesis if __name__ == '__main__': myFunction = outerFunction('Hey !') myFunction() ",
"e": 29984,
"s": 29681,
"text": null
},
{
"code": null,
"e": 29992,
"s": 29984,
"text": "Output:"
},
{
"code": null,
"e": 29998,
"s": 29992,
"text": "Hey!\n"
},
{
"code": null,
"e": 30081,
"s": 29998,
"text": "As observed from above code, closures help to invoke function outside their scope."
},
{
"code": null,
"e": 30253,
"s": 30081,
"text": "The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope."
},
{
"code": "# Python program to illustrate # closures import logging logging.basicConfig(filename ='example.log', level = logging.INFO) def logger(func): def log_func(*args): logging.info( 'Running \"{}\" with arguments {}'.format(func.__name__, args)) print(func(*args)) # Necessary for closure to work (returning WITHOUT parenthesis) return log_func def add(x, y): return x + y def sub(x, y): return x-y add_logger = logger(add) sub_logger = logger(sub) add_logger(3, 3) add_logger(4, 5) sub_logger(10, 5) sub_logger(20, 10) ",
"e": 30857,
"s": 30253,
"text": null
},
{
"code": null,
"e": 30865,
"s": 30857,
"text": "Output:"
},
{
"code": null,
"e": 30875,
"s": 30865,
"text": "6\n9\n5\n10\n"
},
{
"code": null,
"e": 30892,
"s": 30875,
"text": "Python-Functions"
},
{
"code": null,
"e": 30899,
"s": 30892,
"text": "Python"
},
{
"code": null,
"e": 30997,
"s": 30899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31006,
"s": 30997,
"text": "Comments"
},
{
"code": null,
"e": 31019,
"s": 31006,
"text": "Old Comments"
},
{
"code": null,
"e": 31037,
"s": 31019,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31072,
"s": 31037,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31104,
"s": 31072,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31126,
"s": 31104,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31156,
"s": 31126,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31198,
"s": 31156,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31224,
"s": 31198,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31267,
"s": 31224,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31304,
"s": 31267,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Fun with the Binomial Distribution | by Tony Yiu | Towards Data Science
|
Everyone knows and loves the normal distribution. It is used in a huge variety of applications such as investment modeling, A/B testing, and manufacturing process improvement (six sigma).
But people are less familiar with the binomial distribution. That’s a shame because the binomial distribution is really useful. Have you ever been asked something like:
“Given 10 flips of a fair coin, what is the probability of getting 6 heads?”
Probability (especially back of the napkin probability calculations) is not my favorite thing in the world. So when I first learned about the binomial distribution, I thought, “Yes, I never have to worry about coin flip probability questions again!”
That’s because the results of coin flips follow the binomial distribution. I should emphasize that the law of large numbers applies here. To be technically correct, I should say that if were to repeatedly perform the same set of experiments (flipping the coin 10 times) over and over, the number of heads that we observe across all those sets would follow the binomial distribution.
Don’t worry, I will illustrate this in detail shortly.
First let’s start with the slightly more technical definition — the binomial distribution is the probability distribution of a sequence of experiments where each experiment produces a binary outcome and where each of the outcomes is independent of all the others.
A single coin flip is an example of an experiment with a binary outcome. Coin flips meet the other binomial distribution requirement as well — the outcome of each individual coin flip is independent of all the others. Just to be clear, the outcomes of the experiment don’t need to be equally likely as they are with flips of a fair coin — the following things also meet the prerequisites of the binomial distribution:
An unfair coin (e.g. one with an 80% probability of coming up heads).
Randomly picking people on the street to answer a yes or no question.
Attempting to convince visitors of a website to buy a product — the yes or no outcome is whether they purchased or not.
One thing that may trouble newcomers to probability and statistics is the idea of a probability distribution. We tend to think deterministically such as “I flipped a coin 10 times and produced 6 heads”. So the outcome is 6 — where is the distribution then?
The probability distribution derives from variance. If both you and I flipped 10 coins, it’s pretty likely that we would get different results (you might get 5 heads and I get 7). This variance, a.k.a. uncertainty around the outcome, produces a probability distribution, which basically tells us what outcomes are relatively more likely (such as 5 heads) and which outcomes are relatively less likely (such as 10 heads).
We can produce such a probability distribution through simulation, such as in the image below:
Before we go into some Python code that would run this simulation and produce a binomial distribution, let’s first get some definitions out of the way. When you see binomial distributions and the experiments that underlie them described in textbooks, the descriptions always include the following key parameters:
n: the number of times we perform our experiment. In our coin example, n is equal to 10 (each experiment is 1 flip of the coin).p: the probability of success. For a fair coin, it would be 50%.k: the target number of successes. Earlier we mentioned that we were looking for 6 successes.
n: the number of times we perform our experiment. In our coin example, n is equal to 10 (each experiment is 1 flip of the coin).
p: the probability of success. For a fair coin, it would be 50%.
k: the target number of successes. Earlier we mentioned that we were looking for 6 successes.
Let’s go through some python code that runs the simulation we described above. The code below (also available on my Github here) does the following:
Generate a random number between 0 and 1. If that number is 0.5 or more, then count it as heads, otherwise tails. Do this n times using a Python list comprehension. This happens within the function run_binom via the variables tosses.Repeat this a specified number of times (the amount of trials is specified by the input variable trials). We will perform 1,000 trials.
Generate a random number between 0 and 1. If that number is 0.5 or more, then count it as heads, otherwise tails. Do this n times using a Python list comprehension. This happens within the function run_binom via the variables tosses.
Repeat this a specified number of times (the amount of trials is specified by the input variable trials). We will perform 1,000 trials.
# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns# Input variables# Number of trialstrials = 1000# Number of independent experiments in each trialn = 10# Probability of success for each experimentp = 0.5# Function that runs our coin toss trials# heads is a list of the number of successes from each trial of n experimentsdef run_binom(trials, n, p): heads = [] for i in range(trials): tosses = [np.random.random() for i in range(n)] heads.append(len([i for i in tosses if i>=0.50])) return heads# Run the functionheads = run_binom(trials, n, p)# Plot the results as a histogramfig, ax = plt.subplots(figsize=(14,7))ax = sns.distplot(heads, bins=11, label='simulation results')ax.set_xlabel("Number of Heads",fontsize=16)ax.set_ylabel("Frequency",fontsize=16)
So that’s the code. So what happens when we repeat our 10 coin toss trial 1,000 times? We get the histogram plotted below:
Let’s modify the plotting section of our previous code so that our plot also shows the actual binomial distribution (using the stats.binom function from the scipy library):
# Plot the actual binomial distribution as a sanity checkfrom scipy.stats import binomx = range(0,11)ax.plot(x, binom.pmf(x, n, p), 'ro', label='actual binomial distribution')ax.vlines(x, 0, binom.pmf(x, n, p), colors='r', lw=5, alpha=0.5)plt.legend()plt.show()
The following plot shows our original simulated distribution in blue and the actual binomial distribution in red. The takeaway is that the binomial distribution is a pretty good approximation of what we would have observed if we had actually repeated our 10 coin tosses 1,000 times — so instead of wasting tons of time tossing coins and recording the results, we can just use the binomial distribution!
And if we wanted to simulate the result of a single sequence of n experiments (recall that n=10 for our example but really it could be any positive integer), we could generate that using a binomially distributed random variable like so:
np.random.binomial(n, p)
Finally, let’s answer our original question (probability of getting 6 heads with 10 coin flips) by running 10,000 simulations of our 10 coin flips:
# Probability of getting 6 headsruns = 10000prob_6 = sum([1 for i in np.random.binomial(n, p, size=runs) if i==6])/runsprint('The probability of 6 heads is: ' + str(prob_6))
We find the probability to be around 20% (we can also see that in our earlier histogram via the height of the red vertical line above 6 on the x axis).
Cool, but what if we want to analyze things beyond coin flips? Let’s run through a stylized real world use case for the binomial distribution. Imagine that we are data scientists tasked with improving the ROI (Return on Investment) of our company’s call center, where employees attempt to cold call potential customers and get them to purchase our product.
You look at some historical data and find the following:
The typical call center employee completes on average 50 calls per day.
The probability of a conversion (purchase) for each call is 4%.
The average revenue to your company for each conversion is $20.
The call center you are analyzing has 100 employees.
Each employee is paid $200 per day of work.
We can think of each employee as a binomially distributed random variable with the following parameters:
n = 50
p = 4%
The following code simulates our call center:
# Call Center Simulation# Number of employees to simulateemployees = 100# Cost per employeewage = 200# Number of independent calls per employeen = 50# Probability of success for each callp = 0.04# Revenue per callrevenue = 100# Binomial random variables of call center employeesconversions = np.random.binomial(n, p, size=employees)# Print some key metrics of our call centerprint('Average Conversions per Employee: ' + str(round(np.mean(conversions), 2)))print('Standard Deviation of Conversions per Employee: ' + str(round(np.std(conversions), 2)))print('Total Conversions: ' + str(np.sum(conversions)))print('Total Revenues: ' + str(np.sum(conversions)*revenue))print('Total Expense: ' + str(employees*wage))print('Total Profits: ' + str(np.sum(conversions)*revenue - employees*wage))
If you run the code, you get outputs like the following (it changes from run to run because conversions is an array of binomially distributed random variables) key metrics for your call center:
Average Conversions per Employee: 2.13
Standard Deviation of Conversions per Employee: 1.48
Total Conversions: 213
Total Revenues: $21,300
Total Expenses: $20,000
Total Profits: $1,300
Profits are pretty slim compared to expenses. But these are results for just one randomly generated day. Let’s look at the profit of our call center over 1,000 simulations and see how the daily profit varies:
Wow, there is a very high chance of loss given the current operating metrics of our call center (nearly half the simulated profits are negative). What should we do then?
Recalling that each employee’s results follows a binomial distribution, we realize that we can do one or more of the following to improve things:
Make more cold calls (increase n).
Convert at a higher percentage (increase p).
Pay our employees less (we won’t do this because we are nice).
Eventually, we develop a lead generation tool that allows our call center employees to identify people that are more likely to purchase our product. This results in shorter phone calls (less sweet talking required) and an uptick in our conversion probability, ultimately producing these revisions to our parameters:
n = 55
p = 5%
Let’s run the following lines of code that simulates 1,000 potential days of our new and improved call center to see how these changes impact the statistical distribution of our future daily profit.
# Call Center Simulation (Higher Conversion Rate)# Number of employees to simulateemployees = 100# Cost per employeewage = 200# Number of independent calls per employeen = 55# Probability of success for each callp = 0.05# Revenue per callrevenue = 100# Binomial random variables of call center employeesconversions_up = np.random.binomial(n, p, size=employees)# Simulate 1,000 days for our call center# Number of days to simulatesims = 1000sim_conversions_up = [np.sum(np.random.binomial(n, p, size=employees)) for i in range(sims)]sim_profits_up = np.array(sim_conversions_up)*revenue - employees*wage# Plot and save the results as a histogramfig, ax = plt.subplots(figsize=(14,7))ax = sns.distplot(sim_profits, bins=20, label='original call center simulation results')ax = sns.distplot(sim_profits_up, bins=20, label='improved call center simulation results', color='red')ax.set_xlabel("Profits",fontsize=16)ax.set_ylabel("Frequency",fontsize=16)plt.legend()
The above code also plots the distribution of our improved results (red) against our old ones (blue). We don’t need to run an A/B test (though we really should) to see that our lead generation tool has significantly improved the operation and profitability of our call center.
We successfully recognized that the profit produced by each employee follows a binomial distribution — so if we could increase both the n (number of cold calls made per day) and p (probability of conversion for each call) parameters, we could generate higher profits.
I should end by making the following points:
Probability distributions are models that approximate reality. If we can identify a distribution that closely models the the outcome we care about then that’s really powerful — like we saw above, with just a few parameters (n and p), we could model the profits produced by hundreds of people.
However, it is also important to be cognizant of where and how the model fails to match the reality of our situation — this way we know in what situations our model is likely to underperform.
Cheers!
More Data Science and Analytics Related Posts By Me:
Understanding PCA
Understanding Random Forest
Understanding Neural Nets
Understanding A/B Testing
Visualizing Stocks with Tableau
The Curse of Dimensionality
|
[
{
"code": null,
"e": 360,
"s": 172,
"text": "Everyone knows and loves the normal distribution. It is used in a huge variety of applications such as investment modeling, A/B testing, and manufacturing process improvement (six sigma)."
},
{
"code": null,
"e": 529,
"s": 360,
"text": "But people are less familiar with the binomial distribution. That’s a shame because the binomial distribution is really useful. Have you ever been asked something like:"
},
{
"code": null,
"e": 606,
"s": 529,
"text": "“Given 10 flips of a fair coin, what is the probability of getting 6 heads?”"
},
{
"code": null,
"e": 856,
"s": 606,
"text": "Probability (especially back of the napkin probability calculations) is not my favorite thing in the world. So when I first learned about the binomial distribution, I thought, “Yes, I never have to worry about coin flip probability questions again!”"
},
{
"code": null,
"e": 1239,
"s": 856,
"text": "That’s because the results of coin flips follow the binomial distribution. I should emphasize that the law of large numbers applies here. To be technically correct, I should say that if were to repeatedly perform the same set of experiments (flipping the coin 10 times) over and over, the number of heads that we observe across all those sets would follow the binomial distribution."
},
{
"code": null,
"e": 1294,
"s": 1239,
"text": "Don’t worry, I will illustrate this in detail shortly."
},
{
"code": null,
"e": 1558,
"s": 1294,
"text": "First let’s start with the slightly more technical definition — the binomial distribution is the probability distribution of a sequence of experiments where each experiment produces a binary outcome and where each of the outcomes is independent of all the others."
},
{
"code": null,
"e": 1976,
"s": 1558,
"text": "A single coin flip is an example of an experiment with a binary outcome. Coin flips meet the other binomial distribution requirement as well — the outcome of each individual coin flip is independent of all the others. Just to be clear, the outcomes of the experiment don’t need to be equally likely as they are with flips of a fair coin — the following things also meet the prerequisites of the binomial distribution:"
},
{
"code": null,
"e": 2046,
"s": 1976,
"text": "An unfair coin (e.g. one with an 80% probability of coming up heads)."
},
{
"code": null,
"e": 2116,
"s": 2046,
"text": "Randomly picking people on the street to answer a yes or no question."
},
{
"code": null,
"e": 2236,
"s": 2116,
"text": "Attempting to convince visitors of a website to buy a product — the yes or no outcome is whether they purchased or not."
},
{
"code": null,
"e": 2493,
"s": 2236,
"text": "One thing that may trouble newcomers to probability and statistics is the idea of a probability distribution. We tend to think deterministically such as “I flipped a coin 10 times and produced 6 heads”. So the outcome is 6 — where is the distribution then?"
},
{
"code": null,
"e": 2914,
"s": 2493,
"text": "The probability distribution derives from variance. If both you and I flipped 10 coins, it’s pretty likely that we would get different results (you might get 5 heads and I get 7). This variance, a.k.a. uncertainty around the outcome, produces a probability distribution, which basically tells us what outcomes are relatively more likely (such as 5 heads) and which outcomes are relatively less likely (such as 10 heads)."
},
{
"code": null,
"e": 3009,
"s": 2914,
"text": "We can produce such a probability distribution through simulation, such as in the image below:"
},
{
"code": null,
"e": 3322,
"s": 3009,
"text": "Before we go into some Python code that would run this simulation and produce a binomial distribution, let’s first get some definitions out of the way. When you see binomial distributions and the experiments that underlie them described in textbooks, the descriptions always include the following key parameters:"
},
{
"code": null,
"e": 3608,
"s": 3322,
"text": "n: the number of times we perform our experiment. In our coin example, n is equal to 10 (each experiment is 1 flip of the coin).p: the probability of success. For a fair coin, it would be 50%.k: the target number of successes. Earlier we mentioned that we were looking for 6 successes."
},
{
"code": null,
"e": 3737,
"s": 3608,
"text": "n: the number of times we perform our experiment. In our coin example, n is equal to 10 (each experiment is 1 flip of the coin)."
},
{
"code": null,
"e": 3802,
"s": 3737,
"text": "p: the probability of success. For a fair coin, it would be 50%."
},
{
"code": null,
"e": 3896,
"s": 3802,
"text": "k: the target number of successes. Earlier we mentioned that we were looking for 6 successes."
},
{
"code": null,
"e": 4045,
"s": 3896,
"text": "Let’s go through some python code that runs the simulation we described above. The code below (also available on my Github here) does the following:"
},
{
"code": null,
"e": 4414,
"s": 4045,
"text": "Generate a random number between 0 and 1. If that number is 0.5 or more, then count it as heads, otherwise tails. Do this n times using a Python list comprehension. This happens within the function run_binom via the variables tosses.Repeat this a specified number of times (the amount of trials is specified by the input variable trials). We will perform 1,000 trials."
},
{
"code": null,
"e": 4648,
"s": 4414,
"text": "Generate a random number between 0 and 1. If that number is 0.5 or more, then count it as heads, otherwise tails. Do this n times using a Python list comprehension. This happens within the function run_binom via the variables tosses."
},
{
"code": null,
"e": 4784,
"s": 4648,
"text": "Repeat this a specified number of times (the amount of trials is specified by the input variable trials). We will perform 1,000 trials."
},
{
"code": null,
"e": 5605,
"s": 4784,
"text": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns# Input variables# Number of trialstrials = 1000# Number of independent experiments in each trialn = 10# Probability of success for each experimentp = 0.5# Function that runs our coin toss trials# heads is a list of the number of successes from each trial of n experimentsdef run_binom(trials, n, p): heads = [] for i in range(trials): tosses = [np.random.random() for i in range(n)] heads.append(len([i for i in tosses if i>=0.50])) return heads# Run the functionheads = run_binom(trials, n, p)# Plot the results as a histogramfig, ax = plt.subplots(figsize=(14,7))ax = sns.distplot(heads, bins=11, label='simulation results')ax.set_xlabel(\"Number of Heads\",fontsize=16)ax.set_ylabel(\"Frequency\",fontsize=16)"
},
{
"code": null,
"e": 5728,
"s": 5605,
"text": "So that’s the code. So what happens when we repeat our 10 coin toss trial 1,000 times? We get the histogram plotted below:"
},
{
"code": null,
"e": 5901,
"s": 5728,
"text": "Let’s modify the plotting section of our previous code so that our plot also shows the actual binomial distribution (using the stats.binom function from the scipy library):"
},
{
"code": null,
"e": 6163,
"s": 5901,
"text": "# Plot the actual binomial distribution as a sanity checkfrom scipy.stats import binomx = range(0,11)ax.plot(x, binom.pmf(x, n, p), 'ro', label='actual binomial distribution')ax.vlines(x, 0, binom.pmf(x, n, p), colors='r', lw=5, alpha=0.5)plt.legend()plt.show()"
},
{
"code": null,
"e": 6566,
"s": 6163,
"text": "The following plot shows our original simulated distribution in blue and the actual binomial distribution in red. The takeaway is that the binomial distribution is a pretty good approximation of what we would have observed if we had actually repeated our 10 coin tosses 1,000 times — so instead of wasting tons of time tossing coins and recording the results, we can just use the binomial distribution!"
},
{
"code": null,
"e": 6803,
"s": 6566,
"text": "And if we wanted to simulate the result of a single sequence of n experiments (recall that n=10 for our example but really it could be any positive integer), we could generate that using a binomially distributed random variable like so:"
},
{
"code": null,
"e": 6828,
"s": 6803,
"text": "np.random.binomial(n, p)"
},
{
"code": null,
"e": 6976,
"s": 6828,
"text": "Finally, let’s answer our original question (probability of getting 6 heads with 10 coin flips) by running 10,000 simulations of our 10 coin flips:"
},
{
"code": null,
"e": 7150,
"s": 6976,
"text": "# Probability of getting 6 headsruns = 10000prob_6 = sum([1 for i in np.random.binomial(n, p, size=runs) if i==6])/runsprint('The probability of 6 heads is: ' + str(prob_6))"
},
{
"code": null,
"e": 7302,
"s": 7150,
"text": "We find the probability to be around 20% (we can also see that in our earlier histogram via the height of the red vertical line above 6 on the x axis)."
},
{
"code": null,
"e": 7659,
"s": 7302,
"text": "Cool, but what if we want to analyze things beyond coin flips? Let’s run through a stylized real world use case for the binomial distribution. Imagine that we are data scientists tasked with improving the ROI (Return on Investment) of our company’s call center, where employees attempt to cold call potential customers and get them to purchase our product."
},
{
"code": null,
"e": 7716,
"s": 7659,
"text": "You look at some historical data and find the following:"
},
{
"code": null,
"e": 7788,
"s": 7716,
"text": "The typical call center employee completes on average 50 calls per day."
},
{
"code": null,
"e": 7852,
"s": 7788,
"text": "The probability of a conversion (purchase) for each call is 4%."
},
{
"code": null,
"e": 7916,
"s": 7852,
"text": "The average revenue to your company for each conversion is $20."
},
{
"code": null,
"e": 7969,
"s": 7916,
"text": "The call center you are analyzing has 100 employees."
},
{
"code": null,
"e": 8013,
"s": 7969,
"text": "Each employee is paid $200 per day of work."
},
{
"code": null,
"e": 8118,
"s": 8013,
"text": "We can think of each employee as a binomially distributed random variable with the following parameters:"
},
{
"code": null,
"e": 8125,
"s": 8118,
"text": "n = 50"
},
{
"code": null,
"e": 8132,
"s": 8125,
"text": "p = 4%"
},
{
"code": null,
"e": 8178,
"s": 8132,
"text": "The following code simulates our call center:"
},
{
"code": null,
"e": 8966,
"s": 8178,
"text": "# Call Center Simulation# Number of employees to simulateemployees = 100# Cost per employeewage = 200# Number of independent calls per employeen = 50# Probability of success for each callp = 0.04# Revenue per callrevenue = 100# Binomial random variables of call center employeesconversions = np.random.binomial(n, p, size=employees)# Print some key metrics of our call centerprint('Average Conversions per Employee: ' + str(round(np.mean(conversions), 2)))print('Standard Deviation of Conversions per Employee: ' + str(round(np.std(conversions), 2)))print('Total Conversions: ' + str(np.sum(conversions)))print('Total Revenues: ' + str(np.sum(conversions)*revenue))print('Total Expense: ' + str(employees*wage))print('Total Profits: ' + str(np.sum(conversions)*revenue - employees*wage))"
},
{
"code": null,
"e": 9160,
"s": 8966,
"text": "If you run the code, you get outputs like the following (it changes from run to run because conversions is an array of binomially distributed random variables) key metrics for your call center:"
},
{
"code": null,
"e": 9199,
"s": 9160,
"text": "Average Conversions per Employee: 2.13"
},
{
"code": null,
"e": 9252,
"s": 9199,
"text": "Standard Deviation of Conversions per Employee: 1.48"
},
{
"code": null,
"e": 9275,
"s": 9252,
"text": "Total Conversions: 213"
},
{
"code": null,
"e": 9299,
"s": 9275,
"text": "Total Revenues: $21,300"
},
{
"code": null,
"e": 9323,
"s": 9299,
"text": "Total Expenses: $20,000"
},
{
"code": null,
"e": 9345,
"s": 9323,
"text": "Total Profits: $1,300"
},
{
"code": null,
"e": 9554,
"s": 9345,
"text": "Profits are pretty slim compared to expenses. But these are results for just one randomly generated day. Let’s look at the profit of our call center over 1,000 simulations and see how the daily profit varies:"
},
{
"code": null,
"e": 9724,
"s": 9554,
"text": "Wow, there is a very high chance of loss given the current operating metrics of our call center (nearly half the simulated profits are negative). What should we do then?"
},
{
"code": null,
"e": 9870,
"s": 9724,
"text": "Recalling that each employee’s results follows a binomial distribution, we realize that we can do one or more of the following to improve things:"
},
{
"code": null,
"e": 9905,
"s": 9870,
"text": "Make more cold calls (increase n)."
},
{
"code": null,
"e": 9950,
"s": 9905,
"text": "Convert at a higher percentage (increase p)."
},
{
"code": null,
"e": 10013,
"s": 9950,
"text": "Pay our employees less (we won’t do this because we are nice)."
},
{
"code": null,
"e": 10329,
"s": 10013,
"text": "Eventually, we develop a lead generation tool that allows our call center employees to identify people that are more likely to purchase our product. This results in shorter phone calls (less sweet talking required) and an uptick in our conversion probability, ultimately producing these revisions to our parameters:"
},
{
"code": null,
"e": 10336,
"s": 10329,
"text": "n = 55"
},
{
"code": null,
"e": 10343,
"s": 10336,
"text": "p = 5%"
},
{
"code": null,
"e": 10542,
"s": 10343,
"text": "Let’s run the following lines of code that simulates 1,000 potential days of our new and improved call center to see how these changes impact the statistical distribution of our future daily profit."
},
{
"code": null,
"e": 11503,
"s": 10542,
"text": "# Call Center Simulation (Higher Conversion Rate)# Number of employees to simulateemployees = 100# Cost per employeewage = 200# Number of independent calls per employeen = 55# Probability of success for each callp = 0.05# Revenue per callrevenue = 100# Binomial random variables of call center employeesconversions_up = np.random.binomial(n, p, size=employees)# Simulate 1,000 days for our call center# Number of days to simulatesims = 1000sim_conversions_up = [np.sum(np.random.binomial(n, p, size=employees)) for i in range(sims)]sim_profits_up = np.array(sim_conversions_up)*revenue - employees*wage# Plot and save the results as a histogramfig, ax = plt.subplots(figsize=(14,7))ax = sns.distplot(sim_profits, bins=20, label='original call center simulation results')ax = sns.distplot(sim_profits_up, bins=20, label='improved call center simulation results', color='red')ax.set_xlabel(\"Profits\",fontsize=16)ax.set_ylabel(\"Frequency\",fontsize=16)plt.legend()"
},
{
"code": null,
"e": 11780,
"s": 11503,
"text": "The above code also plots the distribution of our improved results (red) against our old ones (blue). We don’t need to run an A/B test (though we really should) to see that our lead generation tool has significantly improved the operation and profitability of our call center."
},
{
"code": null,
"e": 12048,
"s": 11780,
"text": "We successfully recognized that the profit produced by each employee follows a binomial distribution — so if we could increase both the n (number of cold calls made per day) and p (probability of conversion for each call) parameters, we could generate higher profits."
},
{
"code": null,
"e": 12093,
"s": 12048,
"text": "I should end by making the following points:"
},
{
"code": null,
"e": 12386,
"s": 12093,
"text": "Probability distributions are models that approximate reality. If we can identify a distribution that closely models the the outcome we care about then that’s really powerful — like we saw above, with just a few parameters (n and p), we could model the profits produced by hundreds of people."
},
{
"code": null,
"e": 12578,
"s": 12386,
"text": "However, it is also important to be cognizant of where and how the model fails to match the reality of our situation — this way we know in what situations our model is likely to underperform."
},
{
"code": null,
"e": 12586,
"s": 12578,
"text": "Cheers!"
},
{
"code": null,
"e": 12639,
"s": 12586,
"text": "More Data Science and Analytics Related Posts By Me:"
},
{
"code": null,
"e": 12657,
"s": 12639,
"text": "Understanding PCA"
},
{
"code": null,
"e": 12685,
"s": 12657,
"text": "Understanding Random Forest"
},
{
"code": null,
"e": 12711,
"s": 12685,
"text": "Understanding Neural Nets"
},
{
"code": null,
"e": 12737,
"s": 12711,
"text": "Understanding A/B Testing"
},
{
"code": null,
"e": 12769,
"s": 12737,
"text": "Visualizing Stocks with Tableau"
}
] |
Program to find Smallest and Largest Word in a String in C++
|
In this problem, we are given string str. Our task is to create a program to
find Smallest and Largest Word in a String in C++.
Problem Description − Here, we have a string we need to find the word whose length is maximum and minimum out of all words in the string. The word is separated using white spaces or null(\0) characters.
Let’s take an example to understand the problem
str = “Learn Programming at TutorialsPoint”
smallest word = at
largest word = Tutorialspoint
To find the smallest and largest word, we will find the length of each word
by using two indexes, one for the start of the word and one for the ending
which is marked using the ‘ ’ (space character) or ‘\0’ character. Then using
the start and end index, we will find the maxLength and minlength. And
update the smallestWord and largestWord based on the current word’s
length.
Program to illustrate the working of our solution
Live Demo
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string str){
int StrLength = str.length();
int startIndex = 0, endIndex = 0;
int minLength = StrLength, maxLength = 0, currentLength;
string smallest, largest;
while (endIndex <= StrLength){
if (str[endIndex] != '\0' && str[endIndex] != ' ')
endIndex++;
else{
currentLength = endIndex - startIndex;
if (currentLength < minLength){
smallest = str.substr(startIndex, currentLength);
minLength = currentLength;
}
if (currentLength > maxLength){
largest = str.substr(startIndex, currentLength);
maxLength = currentLength;
}
endIndex++;
startIndex = endIndex;
}
}
cout<<"Smallest Word from the string is "<<smallest<<"\n";
cout<<"Smallest Word from the string is "<<largest;
}
int main() {
string a = "Learn Programming at TutorialsPoint";
minMaxLengthWords(a);
}
Smallest Word from the string is at
Smallest Word from the string is TutorialsPoint
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "In this problem, we are given string str. Our task is to create a program to\nfind Smallest and Largest Word in a String in C++."
},
{
"code": null,
"e": 1393,
"s": 1190,
"text": "Problem Description − Here, we have a string we need to find the word whose length is maximum and minimum out of all words in the string. The word is separated using white spaces or null(\\0) characters."
},
{
"code": null,
"e": 1441,
"s": 1393,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1485,
"s": 1441,
"text": "str = “Learn Programming at TutorialsPoint”"
},
{
"code": null,
"e": 1534,
"s": 1485,
"text": "smallest word = at\nlargest word = Tutorialspoint"
},
{
"code": null,
"e": 1910,
"s": 1534,
"text": "To find the smallest and largest word, we will find the length of each word\nby using two indexes, one for the start of the word and one for the ending\nwhich is marked using the ‘ ’ (space character) or ‘\\0’ character. Then using\nthe start and end index, we will find the maxLength and minlength. And\nupdate the smallestWord and largestWord based on the current word’s\nlength."
},
{
"code": null,
"e": 1960,
"s": 1910,
"text": "Program to illustrate the working of our solution"
},
{
"code": null,
"e": 1971,
"s": 1960,
"text": " Live Demo"
},
{
"code": null,
"e": 2979,
"s": 1971,
"text": "#include<iostream>\n#include<cstring>\nusing namespace std;\nvoid minMaxLengthWords(string str){\n int StrLength = str.length();\n int startIndex = 0, endIndex = 0;\n int minLength = StrLength, maxLength = 0, currentLength;\n string smallest, largest;\n while (endIndex <= StrLength){\n if (str[endIndex] != '\\0' && str[endIndex] != ' ')\n endIndex++;\n else{\n currentLength = endIndex - startIndex;\n if (currentLength < minLength){\n smallest = str.substr(startIndex, currentLength);\n minLength = currentLength;\n }\n if (currentLength > maxLength){\n largest = str.substr(startIndex, currentLength);\n maxLength = currentLength;\n }\n endIndex++;\n startIndex = endIndex;\n }\n }\n cout<<\"Smallest Word from the string is \"<<smallest<<\"\\n\";\n cout<<\"Smallest Word from the string is \"<<largest;\n}\nint main() {\n string a = \"Learn Programming at TutorialsPoint\";\n minMaxLengthWords(a);\n}"
},
{
"code": null,
"e": 3063,
"s": 2979,
"text": "Smallest Word from the string is at\nSmallest Word from the string is TutorialsPoint"
}
] |
8 different ways to Add Two Numbers in C/C++ - GeeksforGeeks
|
29 May, 2021
Given two numbers A and B, the task is to find the sum of the given two numbers.Examples:
Input: A = 5, B = 6 Output: sum = 11Input: A = 4, B = 11 Output: sum = 15
Method 1 – using Addition Operator: Here simply use the addition operator between two numbers and print the sum of the number.
sum = A + B
Below is the implementation of the above approach:
C++
// C++ program to add two number// using addition operator#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return A + B;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << "sum = " << addTwoNumber(A, B); return 0;}
sum = 15
Method 2 – using Subtraction Operator: Here simply use the subtraction operator between two numbers, two times so that minus-minus multiply and produce + operator and return the sum of the number.
sum = A – (-B)
Below is the implementation of the above approach:
C++
// C++ program to add two number// using subtraction operator#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return A - (-B);} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << "sum = " << addTwoNumber(A, B); return 0;}
sum = 15
Method 3 – using increment/decrement operator: Here use increment/decrement operator while one number decrement to zero and in another number increment by one when the first number decrement by one, return the second number.
while(B > 0) { A++; B–; }
Below is the implementation of the above approach:
C++
// C++ program to add two number using// increment/decrement operator#include <iostream>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // When A is positive while (A > 0) { A--; B++; } // When A is negative while (A < 0) { A++; B--; } // Return sum of A and B return B;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << "sum = " << addTwoNumber(A, B); return 0;}
sum = 15
Method 4 – using printf() method: Here “%*s” specifier print value of a variable, the value of variable times, and printf return how many character print on the screen.
printf(“%*s%*s”, A, “”, B, “”);
Below is the implementation of the above approach:
C++
// C++ program to add two number// using printf method#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return printf("%*s%*s", A, "", B, "");} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf("sum = %d", addTwoNumber(A, B)); return 0;}
sum = 15
Method 5 – using Half Adder method: A sum of two bits can be obtained by performing Bitwise XOR(^) of the two bits. Carry bit can be obtained by performing Bitwise AND(&) of two bits. Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at the same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
Sum = A & B; Carry = x ^ y
Below is the implementation of the above approach:
C++
// C++ program to add two number// using half adder method#include <iostream>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Iterate till there is no carry while (B != 0) { // Carry now contains common // set bits of A and B int carry = A & B; // Sum of bits of A and B // where at least one of the // bits is not set A = A ^ B; // Carry is shifted by one so // that adding it to A gives // the required sum B = carry << 1; } return A;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf("sum = %d", addTwoNumber(A, B)); return 0;}
sum = 15
Method 6 – using exponential and logarithm: The idea is to find the exponential of the given two numbers and print the logarithmic of the result.
printf(“%g\n”, log(exp(A) * exp(B)));
Below is the implementation of the above approach:
C++
// C++ program to add two number// using log and exponential#include <bits/stdc++.h>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return log(exp(A) * exp(B));} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf("sum = %d", addTwoNumber(A, B)); return 0;}
sum = 15
Method 7 – using Recursion:
Get the numbers A and B whose sum is to be calculated.Base Case: If A is greater than 0, then return B.
Get the numbers A and B whose sum is to be calculated.
Base Case: If A is greater than 0, then return B.
if(A > 0) {
return B;
}
3. Recursive Call: Update A to (A&B)<<1 and B to A ^ B and recursively call for the updated value.
recursive_function((A & B) << 1, A ^ B);
Below is the implementation of the above approach:
C++
// C++ program to add two number// using Recursion#include <iostream> // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Base Case if (!A) return B; // Recursive Call else return addTwoNumber((A & B) << 1, A ^ B);} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf("sum = %d", addTwoNumber(A, B)); return 0;}
sum = 15
Method 8 – using this pointer
Taking two numbers x and y from the user and the task is to find the sum of the given two numbers using this pointer.
Example:
input:
Enter Two Number: 5
4
output:
Sum is: 9
This can be done by accessing the data member of an object by using this pointer and performing an addition operation between them.
C++
// CPP program for above approach#include <iostream>using namespace std; class A{ int a, b, sum; public: A(int x, int y) { a = x; b = y; } // Using this pointer to // access variable void calcSum() { sum = this->a + this->b; } void showSum() { cout << "Sum is: " << sum << endl; }}; // Driver Codeint main(){ int x, y; cout << "Enter Two Numbers: "; x = 4, y = 5; A a(x, y); a.calcSum(); a.showSum(); return 0;}
Enter Two Numbers: Sum is: 9
aroraprajjwal
Code_Mech
C Programs
C++ Programs
Mathematical
Recursion
School Programming
Mathematical
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
C++ Program for QuickSort
C++ program for hashing with chaining
Sorting a Map by value in C++ STL
cin in C++
delete keyword in C++
|
[
{
"code": null,
"e": 24642,
"s": 24614,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 24733,
"s": 24642,
"text": "Given two numbers A and B, the task is to find the sum of the given two numbers.Examples: "
},
{
"code": null,
"e": 24809,
"s": 24733,
"text": "Input: A = 5, B = 6 Output: sum = 11Input: A = 4, B = 11 Output: sum = 15 "
},
{
"code": null,
"e": 24937,
"s": 24809,
"text": "Method 1 – using Addition Operator: Here simply use the addition operator between two numbers and print the sum of the number. "
},
{
"code": null,
"e": 24950,
"s": 24937,
"text": "sum = A + B "
},
{
"code": null,
"e": 25002,
"s": 24950,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25006,
"s": 25002,
"text": "C++"
},
{
"code": "// C++ program to add two number// using addition operator#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return A + B;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << \"sum = \" << addTwoNumber(A, B); return 0;}",
"e": 25371,
"s": 25006,
"text": null
},
{
"code": null,
"e": 25380,
"s": 25371,
"text": "sum = 15"
},
{
"code": null,
"e": 25579,
"s": 25380,
"text": "Method 2 – using Subtraction Operator: Here simply use the subtraction operator between two numbers, two times so that minus-minus multiply and produce + operator and return the sum of the number. "
},
{
"code": null,
"e": 25596,
"s": 25579,
"text": "sum = A – (-B) "
},
{
"code": null,
"e": 25648,
"s": 25596,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25652,
"s": 25648,
"text": "C++"
},
{
"code": "// C++ program to add two number// using subtraction operator#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return A - (-B);} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << \"sum = \" << addTwoNumber(A, B); return 0;}",
"e": 26023,
"s": 25652,
"text": null
},
{
"code": null,
"e": 26032,
"s": 26023,
"text": "sum = 15"
},
{
"code": null,
"e": 26258,
"s": 26032,
"text": "Method 3 – using increment/decrement operator: Here use increment/decrement operator while one number decrement to zero and in another number increment by one when the first number decrement by one, return the second number. "
},
{
"code": null,
"e": 26286,
"s": 26258,
"text": "while(B > 0) { A++; B–; } "
},
{
"code": null,
"e": 26338,
"s": 26286,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26342,
"s": 26338,
"text": "C++"
},
{
"code": "// C++ program to add two number using// increment/decrement operator#include <iostream>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // When A is positive while (A > 0) { A--; B++; } // When A is negative while (A < 0) { A++; B--; } // Return sum of A and B return B;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call cout << \"sum = \" << addTwoNumber(A, B); return 0;}",
"e": 26863,
"s": 26342,
"text": null
},
{
"code": null,
"e": 26872,
"s": 26863,
"text": "sum = 15"
},
{
"code": null,
"e": 27041,
"s": 26872,
"text": "Method 4 – using printf() method: Here “%*s” specifier print value of a variable, the value of variable times, and printf return how many character print on the screen."
},
{
"code": null,
"e": 27074,
"s": 27041,
"text": "printf(“%*s%*s”, A, “”, B, “”); "
},
{
"code": null,
"e": 27126,
"s": 27074,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27130,
"s": 27126,
"text": "C++"
},
{
"code": "// C++ program to add two number// using printf method#include <iostream>using namespace std;// Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return printf(\"%*s%*s\", A, \"\", B, \"\");} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf(\"sum = %d\", addTwoNumber(A, B)); return 0;}",
"e": 27516,
"s": 27130,
"text": null
},
{
"code": null,
"e": 27540,
"s": 27516,
"text": " sum = 15"
},
{
"code": null,
"e": 28125,
"s": 27540,
"text": "Method 5 – using Half Adder method: A sum of two bits can be obtained by performing Bitwise XOR(^) of the two bits. Carry bit can be obtained by performing Bitwise AND(&) of two bits. Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at the same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. "
},
{
"code": null,
"e": 28153,
"s": 28125,
"text": "Sum = A & B; Carry = x ^ y "
},
{
"code": null,
"e": 28205,
"s": 28153,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28209,
"s": 28205,
"text": "C++"
},
{
"code": "// C++ program to add two number// using half adder method#include <iostream>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Iterate till there is no carry while (B != 0) { // Carry now contains common // set bits of A and B int carry = A & B; // Sum of bits of A and B // where at least one of the // bits is not set A = A ^ B; // Carry is shifted by one so // that adding it to A gives // the required sum B = carry << 1; } return A;} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf(\"sum = %d\", addTwoNumber(A, B)); return 0;}",
"e": 28938,
"s": 28209,
"text": null
},
{
"code": null,
"e": 28947,
"s": 28938,
"text": "sum = 15"
},
{
"code": null,
"e": 29093,
"s": 28947,
"text": "Method 6 – using exponential and logarithm: The idea is to find the exponential of the given two numbers and print the logarithmic of the result."
},
{
"code": null,
"e": 29132,
"s": 29093,
"text": "printf(“%g\\n”, log(exp(A) * exp(B))); "
},
{
"code": null,
"e": 29184,
"s": 29132,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 29188,
"s": 29184,
"text": "C++"
},
{
"code": "// C++ program to add two number// using log and exponential#include <bits/stdc++.h>using namespace std; // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Return sum of A and B return log(exp(A) * exp(B));} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf(\"sum = %d\", addTwoNumber(A, B)); return 0;}",
"e": 29576,
"s": 29188,
"text": null
},
{
"code": null,
"e": 29585,
"s": 29576,
"text": "sum = 15"
},
{
"code": null,
"e": 29614,
"s": 29585,
"text": "Method 7 – using Recursion: "
},
{
"code": null,
"e": 29718,
"s": 29614,
"text": "Get the numbers A and B whose sum is to be calculated.Base Case: If A is greater than 0, then return B."
},
{
"code": null,
"e": 29773,
"s": 29718,
"text": "Get the numbers A and B whose sum is to be calculated."
},
{
"code": null,
"e": 29823,
"s": 29773,
"text": "Base Case: If A is greater than 0, then return B."
},
{
"code": null,
"e": 29850,
"s": 29823,
"text": "if(A > 0) {\n return B;\n}"
},
{
"code": null,
"e": 29956,
"s": 29850,
"text": " 3. Recursive Call: Update A to (A&B)<<1 and B to A ^ B and recursively call for the updated value. "
},
{
"code": null,
"e": 29997,
"s": 29956,
"text": "recursive_function((A & B) << 1, A ^ B);"
},
{
"code": null,
"e": 30048,
"s": 29997,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30052,
"s": 30048,
"text": "C++"
},
{
"code": "// C++ program to add two number// using Recursion#include <iostream> // Function to return sum// of two numberint addTwoNumber(int A, int B){ // Base Case if (!A) return B; // Recursive Call else return addTwoNumber((A & B) << 1, A ^ B);} // Driver Codeint main(){ // Given two number int A = 4, B = 11; // Function call printf(\"sum = %d\", addTwoNumber(A, B)); return 0;}",
"e": 30468,
"s": 30052,
"text": null
},
{
"code": null,
"e": 30477,
"s": 30468,
"text": "sum = 15"
},
{
"code": null,
"e": 30508,
"s": 30477,
"text": "Method 8 – using this pointer"
},
{
"code": null,
"e": 30626,
"s": 30508,
"text": "Taking two numbers x and y from the user and the task is to find the sum of the given two numbers using this pointer."
},
{
"code": null,
"e": 30635,
"s": 30626,
"text": "Example:"
},
{
"code": null,
"e": 30642,
"s": 30635,
"text": "input:"
},
{
"code": null,
"e": 30662,
"s": 30642,
"text": "Enter Two Number: 5"
},
{
"code": null,
"e": 30664,
"s": 30662,
"text": "4"
},
{
"code": null,
"e": 30672,
"s": 30664,
"text": "output:"
},
{
"code": null,
"e": 30682,
"s": 30672,
"text": "Sum is: 9"
},
{
"code": null,
"e": 30814,
"s": 30682,
"text": "This can be done by accessing the data member of an object by using this pointer and performing an addition operation between them."
},
{
"code": null,
"e": 30818,
"s": 30814,
"text": "C++"
},
{
"code": "// CPP program for above approach#include <iostream>using namespace std; class A{ int a, b, sum; public: A(int x, int y) { a = x; b = y; } // Using this pointer to // access variable void calcSum() { sum = this->a + this->b; } void showSum() { cout << \"Sum is: \" << sum << endl; }}; // Driver Codeint main(){ int x, y; cout << \"Enter Two Numbers: \"; x = 4, y = 5; A a(x, y); a.calcSum(); a.showSum(); return 0;}",
"e": 31317,
"s": 30818,
"text": null
},
{
"code": null,
"e": 31346,
"s": 31317,
"text": "Enter Two Numbers: Sum is: 9"
},
{
"code": null,
"e": 31360,
"s": 31346,
"text": "aroraprajjwal"
},
{
"code": null,
"e": 31370,
"s": 31360,
"text": "Code_Mech"
},
{
"code": null,
"e": 31381,
"s": 31370,
"text": "C Programs"
},
{
"code": null,
"e": 31394,
"s": 31381,
"text": "C++ Programs"
},
{
"code": null,
"e": 31407,
"s": 31394,
"text": "Mathematical"
},
{
"code": null,
"e": 31417,
"s": 31407,
"text": "Recursion"
},
{
"code": null,
"e": 31436,
"s": 31417,
"text": "School Programming"
},
{
"code": null,
"e": 31449,
"s": 31436,
"text": "Mathematical"
},
{
"code": null,
"e": 31459,
"s": 31449,
"text": "Recursion"
},
{
"code": null,
"e": 31557,
"s": 31459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31566,
"s": 31557,
"text": "Comments"
},
{
"code": null,
"e": 31579,
"s": 31566,
"text": "Old Comments"
},
{
"code": null,
"e": 31620,
"s": 31579,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 31651,
"s": 31620,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 31692,
"s": 31651,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 31726,
"s": 31692,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 31779,
"s": 31726,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 31805,
"s": 31779,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 31843,
"s": 31805,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 31877,
"s": 31843,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 31888,
"s": 31877,
"text": "cin in C++"
}
] |
\bigcap - Tex Command
|
\bigcap - Used to draw bigcap symbol.
{ \bigcap }
\bigcap command is used to draw bigcap symbol.
\bigcap
⋂
\bigcap
⋂
\bigcap
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8024,
"s": 7986,
"text": "\\bigcap - Used to draw bigcap symbol."
},
{
"code": null,
"e": 8036,
"s": 8024,
"text": "{ \\bigcap }"
},
{
"code": null,
"e": 8083,
"s": 8036,
"text": "\\bigcap command is used to draw bigcap symbol."
},
{
"code": null,
"e": 8098,
"s": 8083,
"text": "\n\\bigcap\n\n⋂\n\n\n"
},
{
"code": null,
"e": 8111,
"s": 8098,
"text": "\\bigcap\n\n⋂\n\n"
},
{
"code": null,
"e": 8119,
"s": 8111,
"text": "\\bigcap"
},
{
"code": null,
"e": 8151,
"s": 8119,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8164,
"s": 8151,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8197,
"s": 8164,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8210,
"s": 8197,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8242,
"s": 8210,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8278,
"s": 8242,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8313,
"s": 8278,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8330,
"s": 8313,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8363,
"s": 8330,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8377,
"s": 8363,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8409,
"s": 8377,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8424,
"s": 8409,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8431,
"s": 8424,
"text": " Print"
},
{
"code": null,
"e": 8442,
"s": 8431,
"text": " Add Notes"
}
] |
Detecting Sounds with Deep Learning | by Hyeongchan Kim | Towards Data Science
|
Created together with Dmytro Karabash, Maxim Korotkov, Tony Chen.
Have you ever woken up without understanding what it was, but knowing for sure that some sound isn’t right?
Sound identification is one of our instincts that kept human beings safe. Sounds play a significant role in our life, Starting from recognizing a predator nearby to being inspired by music, to groups of human voices, to the cry of a bird. Inevitably, developing audio classifiers is a crucial task in our lives.
Ordinarily, it is essential to classify the sounds’ source and is already widely used for various purposes. In music, there’s a classifier for the genre of music. Recently similar systems began to be used to classify birdcalls, historically done by Ornithologists. Their goal is to categorize birds, considering it is challenging to discover birdcalls from the fields or noisy surroundings.
Recently, Deep Learning (DL) has grown one of the popular technologies to solve multiple tasks in our lives due to its accuracy and the improvement of computational devices like CPU (Central Processing Unit), GPU (Graphics Processing Unit). The below chart shows how influential the deep learning market is and its expected size from the aspects of the software, hardware, and services.
In this post, We will take the task of reading an audio file with zero to few birdcalls. Moreover, using deep learning to identify which bird it is, based on the Cornell Birdcall Identification Challenge, where we acquired a silver medal (top 2%).
We can find that countless articles about processing audio data into a spectrogram, along with explained how to load sound data, including making it to a spectrogram format and why it is critical. Here’s an example of a spectrogram of birdcall of Alder Flycatcher and a photo of such a bird, just in case you are curious.
The speed of data processing is one of the keys to employing a deep learning model. Conversely, the increment of computation power, the computation cost of audio processing is still expensive on a CPU. Nevertheless, if we choose a better computation resource to process the data like a GPU, it can boost the speed of about ten to one hundred times faster! We will show how to process spectrogram fast by utilizing a library called torchlibrosa that enables us to process spectrogram on a GPU.
torchlibrosa is a Python library that has some audio processing functions implemented in PyTorch that can utilize GPU resources. PyTorch enables running this spectrogram algorithm on a GPU. Here’s an example of extracting spectrogram features using torchlibrosa.
from torchlibrosa.stft import Spectrogramspectrogram_extractor = Spectrogram( win_length=1024, hop_length=320).cuda()
We can load audio data via the librosa library, one of the popular Python audio processing libraries.
import librosa# get raw audio dataexample, _ = librosa.load('example.wav', sr=32000, mono=True)
raw_audio = torch.Tensor(example).unsqueeze(0).cuda()spectrogram = spectrogram_extractor(raw_audio)
We can process audio data on the GPU by adopting the torchlibrosa library. You may wonder how much faster on the GPU than the CPU. Here’s the speed of processing the benchmark between the devices. We just picked audio from the data obtained from the Cornell Birdcall Identification Kaggle Challenge, which is publicly available, and compared how long it takes on CPU and GPU. We tested on the Colab to reproduce the performance, and it is about x15 faster on GPU than CPU to process log-mel spectrogram from about 5 minutes audio.
Accordingly, Deep Learning has shown brilliant performance in the audio domain. It can catch numerous patterns of target classes correctly in the time-series data. The more important point is the environment and data matter in birdcalls. The environments like fields or the middle of the mountains make batches of noises interfering with the birdcalls. Several birds can exist in long recorded audio. Consequently, we need to build a noise-robust, multi-label audio classifier.
We will present a deep learning architecture used by our team (Dragonsong) in Cornell Birdcall Identification Kaggle Challenge.
We built a novel audio classifier architecture that effectively catches time-series features by utilizing CNN, RNN, and Attention modules. Here is our brief plot of architecture used at the challenge.
We process raw audio with a log-mel spectrogram as an input of our architecture, and it passes through the ResNeSt50 backbone, which is one of the image classification architectures. Afterward, we take the features, which contain both spatial and temporal information, to the RoI (Region of Interest) pooling and bi-GRU layers. In the layers, it catches the time-wise information while reducing the feature dimension because we thought extracting temporal features is pivotal to classify numbers of birdcalls in long audio. Ultimately, we pass the data into the attention module to score by each time step to find out which time-step the birds exist.
Not only building deep learning architecture to represent the data but also how to train the model is vital (a.k.a training recipe). To classify audios that contain various birdcalls with a noisy background, we mix bunches of birdcalls into audio and noises like white noise. Also, regarding many variations of birdcalls, we augment pitch and mask some audio frames by using SpecAugment.
Here is a short example (a mixed version of Alder Flycatcher and American Avocet) of what we applied augmentations.
Have you ever woken up without understanding what it was, but knowing for sure that some sound isn’t right? With great algorithms, machines will be able to identify what it was and help you sleep better. Stay tuned!
Originally published at YourDataBlog.
|
[
{
"code": null,
"e": 238,
"s": 172,
"text": "Created together with Dmytro Karabash, Maxim Korotkov, Tony Chen."
},
{
"code": null,
"e": 346,
"s": 238,
"text": "Have you ever woken up without understanding what it was, but knowing for sure that some sound isn’t right?"
},
{
"code": null,
"e": 658,
"s": 346,
"text": "Sound identification is one of our instincts that kept human beings safe. Sounds play a significant role in our life, Starting from recognizing a predator nearby to being inspired by music, to groups of human voices, to the cry of a bird. Inevitably, developing audio classifiers is a crucial task in our lives."
},
{
"code": null,
"e": 1049,
"s": 658,
"text": "Ordinarily, it is essential to classify the sounds’ source and is already widely used for various purposes. In music, there’s a classifier for the genre of music. Recently similar systems began to be used to classify birdcalls, historically done by Ornithologists. Their goal is to categorize birds, considering it is challenging to discover birdcalls from the fields or noisy surroundings."
},
{
"code": null,
"e": 1436,
"s": 1049,
"text": "Recently, Deep Learning (DL) has grown one of the popular technologies to solve multiple tasks in our lives due to its accuracy and the improvement of computational devices like CPU (Central Processing Unit), GPU (Graphics Processing Unit). The below chart shows how influential the deep learning market is and its expected size from the aspects of the software, hardware, and services."
},
{
"code": null,
"e": 1684,
"s": 1436,
"text": "In this post, We will take the task of reading an audio file with zero to few birdcalls. Moreover, using deep learning to identify which bird it is, based on the Cornell Birdcall Identification Challenge, where we acquired a silver medal (top 2%)."
},
{
"code": null,
"e": 2006,
"s": 1684,
"text": "We can find that countless articles about processing audio data into a spectrogram, along with explained how to load sound data, including making it to a spectrogram format and why it is critical. Here’s an example of a spectrogram of birdcall of Alder Flycatcher and a photo of such a bird, just in case you are curious."
},
{
"code": null,
"e": 2499,
"s": 2006,
"text": "The speed of data processing is one of the keys to employing a deep learning model. Conversely, the increment of computation power, the computation cost of audio processing is still expensive on a CPU. Nevertheless, if we choose a better computation resource to process the data like a GPU, it can boost the speed of about ten to one hundred times faster! We will show how to process spectrogram fast by utilizing a library called torchlibrosa that enables us to process spectrogram on a GPU."
},
{
"code": null,
"e": 2762,
"s": 2499,
"text": "torchlibrosa is a Python library that has some audio processing functions implemented in PyTorch that can utilize GPU resources. PyTorch enables running this spectrogram algorithm on a GPU. Here’s an example of extracting spectrogram features using torchlibrosa."
},
{
"code": null,
"e": 2887,
"s": 2762,
"text": "from torchlibrosa.stft import Spectrogramspectrogram_extractor = Spectrogram( win_length=1024, hop_length=320).cuda()"
},
{
"code": null,
"e": 2989,
"s": 2887,
"text": "We can load audio data via the librosa library, one of the popular Python audio processing libraries."
},
{
"code": null,
"e": 3085,
"s": 2989,
"text": "import librosa# get raw audio dataexample, _ = librosa.load('example.wav', sr=32000, mono=True)"
},
{
"code": null,
"e": 3185,
"s": 3085,
"text": "raw_audio = torch.Tensor(example).unsqueeze(0).cuda()spectrogram = spectrogram_extractor(raw_audio)"
},
{
"code": null,
"e": 3716,
"s": 3185,
"text": "We can process audio data on the GPU by adopting the torchlibrosa library. You may wonder how much faster on the GPU than the CPU. Here’s the speed of processing the benchmark between the devices. We just picked audio from the data obtained from the Cornell Birdcall Identification Kaggle Challenge, which is publicly available, and compared how long it takes on CPU and GPU. We tested on the Colab to reproduce the performance, and it is about x15 faster on GPU than CPU to process log-mel spectrogram from about 5 minutes audio."
},
{
"code": null,
"e": 4194,
"s": 3716,
"text": "Accordingly, Deep Learning has shown brilliant performance in the audio domain. It can catch numerous patterns of target classes correctly in the time-series data. The more important point is the environment and data matter in birdcalls. The environments like fields or the middle of the mountains make batches of noises interfering with the birdcalls. Several birds can exist in long recorded audio. Consequently, we need to build a noise-robust, multi-label audio classifier."
},
{
"code": null,
"e": 4322,
"s": 4194,
"text": "We will present a deep learning architecture used by our team (Dragonsong) in Cornell Birdcall Identification Kaggle Challenge."
},
{
"code": null,
"e": 4523,
"s": 4322,
"text": "We built a novel audio classifier architecture that effectively catches time-series features by utilizing CNN, RNN, and Attention modules. Here is our brief plot of architecture used at the challenge."
},
{
"code": null,
"e": 5174,
"s": 4523,
"text": "We process raw audio with a log-mel spectrogram as an input of our architecture, and it passes through the ResNeSt50 backbone, which is one of the image classification architectures. Afterward, we take the features, which contain both spatial and temporal information, to the RoI (Region of Interest) pooling and bi-GRU layers. In the layers, it catches the time-wise information while reducing the feature dimension because we thought extracting temporal features is pivotal to classify numbers of birdcalls in long audio. Ultimately, we pass the data into the attention module to score by each time step to find out which time-step the birds exist."
},
{
"code": null,
"e": 5562,
"s": 5174,
"text": "Not only building deep learning architecture to represent the data but also how to train the model is vital (a.k.a training recipe). To classify audios that contain various birdcalls with a noisy background, we mix bunches of birdcalls into audio and noises like white noise. Also, regarding many variations of birdcalls, we augment pitch and mask some audio frames by using SpecAugment."
},
{
"code": null,
"e": 5678,
"s": 5562,
"text": "Here is a short example (a mixed version of Alder Flycatcher and American Avocet) of what we applied augmentations."
},
{
"code": null,
"e": 5894,
"s": 5678,
"text": "Have you ever woken up without understanding what it was, but knowing for sure that some sound isn’t right? With great algorithms, machines will be able to identify what it was and help you sleep better. Stay tuned!"
}
] |
Mapping 2019–20 Australian bushfires | by Miguel Pinto | Towards Data Science
|
The extreme extent of 2019–20 Australian bushfires made headlines around the world at the beginning of 2020. Extreme events like these are expected to become more frequent in a warming climate. Monitoring the extent of the fires is very important to assess the damage and for a wide range of applications ranging from forest management to fire carbon emission and air pollution. Daily satellite images with resolution up to about 500m per pixel allow monitoring the burned regions. It is however not a simple task as clouds and smoke are often present in the images. As an image-based problem, monitoring the daily progression of burned areas is a well-suited task for the computer vision domain.
In this story, I show how to use BA-Net model (of which I’m one of the authors) to map the fires in Australia, and how you can do the same for virtually anywhere on Earth, with the open-source code and pre-trained models provided in this Github repository as a Python package named banet.
If you are only interested in the results you can jump straight to the “Visualizing the results” section, after the 5 steps.
The Region class in banet.geo should be used as follows, where the bbox argument receives a list with the left, bottom, right and top boundaries of the region. The pixel_size should be kept as 0.01o (about 1 km) to be close to the resolution of the satellite data that will be used here.
r = Region(name='Australia', bbox=[146, -39, 154, -26], pixel_size=0.01)r.export('data/regions/R_Australia.json')
VIIRS Active Fires is a product that provides near-real-time estimations of the radiative power of fires that are active during the satellite passage. These polar orbit satellites view most of the points on Earth twice a day. The data can be downloaded from this page: following “Create New Request”; selecting the region; selecting “VIIRS S-NPP”; selecting the time-range starting one month before and ending one month after the study period (or at least 15 days). As for the file format, it should be selected CSV. After submitting the request it should be processed shortly. Data can then be downloaded and saved as “hotspots{name}.csv”, using the “name” defined in Step 1.
Plotting all the active fire events results in the figure above where colours represent the day of burning starting the count at Jan 1st, 2019.
The following bash code makes use of the banet command-line utility to download the data from Nasa Earth Data.
#!/bin/bash -l region="Australia"tstart="2019-08-01 00:00:00"tend="2020-02-17 23:59:59"path_save="/data/Australia/rawdata"regions_path="/data/regions"banet_viirs750_download $region "$tstart" "$tend" $path_save $regions_path
The region variable needs to be set to the name defined in Step 1 and the regions_path to the respective directory where the JSON file was saved.
For this step, another utility function is provided in banet package. The procedure consists on reading the raw data (in HDF format) as downloaded in Step 3, and saving a MAT file for each day with:
Red, near-infrared (NIR) and middle infrared (MIR) reflectances;
Gridded active fire data.
#!/bin/bash -lregion="Australia"viirs_path="/data/Australia/rawdata"save_path="/data/Australia/dataset"fires_path="/data/ActiveFires"regions_path="/data/regions"banet_create_dataset $region $viirs_path $fires_path $save_path $regions_path
Notice that fires_path should be set to the directory in which the CSV file obtained in Step 2 was saved.
Once again, banet package provides a utility command line function to process this step. This procedure consists in loading 64-day sequences and cropping the large images into 128x128 tiles, feed each to the model and merge back the tiles to get the results for the entire image.
#!/bin/bash -lregion="Australia"tstart="2019-08-01 00:00:00"tend="2020-02-17 23:59:59"input_path="/data/Australia/dataset"output_path="/data/Australia/output"regions_path="/data/regions"banet_predict_times $region "$tstart" "$tend" $input_path $output_path $regions_path
Notice that the input_path should correspond to the save_path of Step 4 — the directory where the dataset is stored.
After following the 5 steps above, results will be saved in the output_path. The figure below shows the confidence level (left) and the day of burning given by the model (right). Hereafter, only pixels with a confidence level of at least 0.5 are considered.
Notice that the progression of dates of burning is usually smooth, contrasting to other existing products as discussed in this story or in the BA-Net academic paper. The improvement in the date of burning allows for a more accurate representation of daily burned area as shown in the figure below.
Notice the extreme values of burned area at the end of 2019 and the beginning of 2020 — the period where the fires in Australia made headlines across the globe.
The total burned area represented in the bar plot is 6 688 147 ha. For comparison, the number mentioned in Wikipedia for New South Wales, Victoria and Australian Capital Territory all together is 6 956 688 ha. These numbers cannot be directly compared since here we include small fires in south Queensland and only consider part of Victoria state. Nevertheless, it is a close match.
At this scale, some overestimation of the burned area is likely as there are often smaller non-burned patches inside the burned regions. To better identify these regions, higher resolution images like Sentinel-2 (10-meter pixel size) would be needed. These images are, however, only available every 5 days, not allowing to map the daily progression of fires.
Deep learning applications with remote sensing data started flourishing over the very recent years. I believe this trend will continue for the foreseeable future. Burned areas mapping is one of the topics where I expect significant advances over the next few years. The sheer volume of spatio-temporal data constantly retrieved from several satellites makes this problem challenging. Deep learning — powered by GPUs and TPUs — opens ground for a vast sea of new possibilities yet to be explored.
towardsdatascience.com
Thanks for reading! Have a great day!
|
[
{
"code": null,
"e": 869,
"s": 172,
"text": "The extreme extent of 2019–20 Australian bushfires made headlines around the world at the beginning of 2020. Extreme events like these are expected to become more frequent in a warming climate. Monitoring the extent of the fires is very important to assess the damage and for a wide range of applications ranging from forest management to fire carbon emission and air pollution. Daily satellite images with resolution up to about 500m per pixel allow monitoring the burned regions. It is however not a simple task as clouds and smoke are often present in the images. As an image-based problem, monitoring the daily progression of burned areas is a well-suited task for the computer vision domain."
},
{
"code": null,
"e": 1158,
"s": 869,
"text": "In this story, I show how to use BA-Net model (of which I’m one of the authors) to map the fires in Australia, and how you can do the same for virtually anywhere on Earth, with the open-source code and pre-trained models provided in this Github repository as a Python package named banet."
},
{
"code": null,
"e": 1283,
"s": 1158,
"text": "If you are only interested in the results you can jump straight to the “Visualizing the results” section, after the 5 steps."
},
{
"code": null,
"e": 1571,
"s": 1283,
"text": "The Region class in banet.geo should be used as follows, where the bbox argument receives a list with the left, bottom, right and top boundaries of the region. The pixel_size should be kept as 0.01o (about 1 km) to be close to the resolution of the satellite data that will be used here."
},
{
"code": null,
"e": 1685,
"s": 1571,
"text": "r = Region(name='Australia', bbox=[146, -39, 154, -26], pixel_size=0.01)r.export('data/regions/R_Australia.json')"
},
{
"code": null,
"e": 2362,
"s": 1685,
"text": "VIIRS Active Fires is a product that provides near-real-time estimations of the radiative power of fires that are active during the satellite passage. These polar orbit satellites view most of the points on Earth twice a day. The data can be downloaded from this page: following “Create New Request”; selecting the region; selecting “VIIRS S-NPP”; selecting the time-range starting one month before and ending one month after the study period (or at least 15 days). As for the file format, it should be selected CSV. After submitting the request it should be processed shortly. Data can then be downloaded and saved as “hotspots{name}.csv”, using the “name” defined in Step 1."
},
{
"code": null,
"e": 2506,
"s": 2362,
"text": "Plotting all the active fire events results in the figure above where colours represent the day of burning starting the count at Jan 1st, 2019."
},
{
"code": null,
"e": 2617,
"s": 2506,
"text": "The following bash code makes use of the banet command-line utility to download the data from Nasa Earth Data."
},
{
"code": null,
"e": 2842,
"s": 2617,
"text": "#!/bin/bash -l region=\"Australia\"tstart=\"2019-08-01 00:00:00\"tend=\"2020-02-17 23:59:59\"path_save=\"/data/Australia/rawdata\"regions_path=\"/data/regions\"banet_viirs750_download $region \"$tstart\" \"$tend\" $path_save $regions_path"
},
{
"code": null,
"e": 2988,
"s": 2842,
"text": "The region variable needs to be set to the name defined in Step 1 and the regions_path to the respective directory where the JSON file was saved."
},
{
"code": null,
"e": 3187,
"s": 2988,
"text": "For this step, another utility function is provided in banet package. The procedure consists on reading the raw data (in HDF format) as downloaded in Step 3, and saving a MAT file for each day with:"
},
{
"code": null,
"e": 3252,
"s": 3187,
"text": "Red, near-infrared (NIR) and middle infrared (MIR) reflectances;"
},
{
"code": null,
"e": 3278,
"s": 3252,
"text": "Gridded active fire data."
},
{
"code": null,
"e": 3517,
"s": 3278,
"text": "#!/bin/bash -lregion=\"Australia\"viirs_path=\"/data/Australia/rawdata\"save_path=\"/data/Australia/dataset\"fires_path=\"/data/ActiveFires\"regions_path=\"/data/regions\"banet_create_dataset $region $viirs_path $fires_path $save_path $regions_path"
},
{
"code": null,
"e": 3623,
"s": 3517,
"text": "Notice that fires_path should be set to the directory in which the CSV file obtained in Step 2 was saved."
},
{
"code": null,
"e": 3903,
"s": 3623,
"text": "Once again, banet package provides a utility command line function to process this step. This procedure consists in loading 64-day sequences and cropping the large images into 128x128 tiles, feed each to the model and merge back the tiles to get the results for the entire image."
},
{
"code": null,
"e": 4174,
"s": 3903,
"text": "#!/bin/bash -lregion=\"Australia\"tstart=\"2019-08-01 00:00:00\"tend=\"2020-02-17 23:59:59\"input_path=\"/data/Australia/dataset\"output_path=\"/data/Australia/output\"regions_path=\"/data/regions\"banet_predict_times $region \"$tstart\" \"$tend\" $input_path $output_path $regions_path"
},
{
"code": null,
"e": 4291,
"s": 4174,
"text": "Notice that the input_path should correspond to the save_path of Step 4 — the directory where the dataset is stored."
},
{
"code": null,
"e": 4549,
"s": 4291,
"text": "After following the 5 steps above, results will be saved in the output_path. The figure below shows the confidence level (left) and the day of burning given by the model (right). Hereafter, only pixels with a confidence level of at least 0.5 are considered."
},
{
"code": null,
"e": 4847,
"s": 4549,
"text": "Notice that the progression of dates of burning is usually smooth, contrasting to other existing products as discussed in this story or in the BA-Net academic paper. The improvement in the date of burning allows for a more accurate representation of daily burned area as shown in the figure below."
},
{
"code": null,
"e": 5008,
"s": 4847,
"text": "Notice the extreme values of burned area at the end of 2019 and the beginning of 2020 — the period where the fires in Australia made headlines across the globe."
},
{
"code": null,
"e": 5391,
"s": 5008,
"text": "The total burned area represented in the bar plot is 6 688 147 ha. For comparison, the number mentioned in Wikipedia for New South Wales, Victoria and Australian Capital Territory all together is 6 956 688 ha. These numbers cannot be directly compared since here we include small fires in south Queensland and only consider part of Victoria state. Nevertheless, it is a close match."
},
{
"code": null,
"e": 5750,
"s": 5391,
"text": "At this scale, some overestimation of the burned area is likely as there are often smaller non-burned patches inside the burned regions. To better identify these regions, higher resolution images like Sentinel-2 (10-meter pixel size) would be needed. These images are, however, only available every 5 days, not allowing to map the daily progression of fires."
},
{
"code": null,
"e": 6246,
"s": 5750,
"text": "Deep learning applications with remote sensing data started flourishing over the very recent years. I believe this trend will continue for the foreseeable future. Burned areas mapping is one of the topics where I expect significant advances over the next few years. The sheer volume of spatio-temporal data constantly retrieved from several satellites makes this problem challenging. Deep learning — powered by GPUs and TPUs — opens ground for a vast sea of new possibilities yet to be explored."
},
{
"code": null,
"e": 6269,
"s": 6246,
"text": "towardsdatascience.com"
}
] |
Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes
|
09 Mar, 2021
The in-built File.length() method in java can be used to get file size in java. The length() function is a part of the File class in Java. This function returns the length of the file whose path was specified. If the file does not exist or some error happens then it returns 0.
Parameters: This method does not accept any parameter.
Syntax:
long len = file.length()
In the same way, exists() function is also a part of the File class in Java. This function determines whether the file or directory denoted by the abstract filename exists or not. The function returns true if the file whose path is given exists and if not then it returns false
Syntax:
file.exists()
Parameters: This method also does not accept any parameter.
Returns: True or False
This example shows how to get a file’s size in bytes by using file.exists() and file.length() method of File class.
Java
// Simple Java Program find the size of the fileimport java.io.File;public class GFG { public static void main(String[] args) { // create file object enter the path of // the file for which size is to be found File file = new File("/home/user/GFG.txt"); if (file.exists()) { double bytes = file.length(); double kilobytes = (bytes / 1024); // converting file size to bytes to kb double megabytes = (kilobytes / 1024); // converting file size tolb to mb double gigabytes = (megabytes / 1024); System.out.println("bytes : " + bytes); System.out.println("kilobytes : " + kilobytes); System.out.println("megabytes : " + megabytes); } else { System.out.println("File does not exists!"); } }}
bytes : 17,07,91,615
kilobytes : 1,66,788.686
megabytes : 162.8795766
Note: If you want file size in Gigabytes then again you have to divide mb value by 1024 and so on.
But Nowadays we can directly use File.size(path) after Java 7. In this we do not have to create file object we can directly find the size of the file.
Java-Files
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Factory method design pattern in Java
Implementing a Linked List in Java using Class
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "The in-built File.length() method in java can be used to get file size in java. The length() function is a part of the File class in Java. This function returns the length of the file whose path was specified. If the file does not exist or some error happens then it returns 0."
},
{
"code": null,
"e": 361,
"s": 306,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 369,
"s": 361,
"text": "Syntax:"
},
{
"code": null,
"e": 394,
"s": 369,
"text": "long len = file.length()"
},
{
"code": null,
"e": 672,
"s": 394,
"text": "In the same way, exists() function is also a part of the File class in Java. This function determines whether the file or directory denoted by the abstract filename exists or not. The function returns true if the file whose path is given exists and if not then it returns false"
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Syntax:"
},
{
"code": null,
"e": 694,
"s": 680,
"text": "file.exists()"
},
{
"code": null,
"e": 754,
"s": 694,
"text": "Parameters: This method also does not accept any parameter."
},
{
"code": null,
"e": 777,
"s": 754,
"text": "Returns: True or False"
},
{
"code": null,
"e": 893,
"s": 777,
"text": "This example shows how to get a file’s size in bytes by using file.exists() and file.length() method of File class."
},
{
"code": null,
"e": 898,
"s": 893,
"text": "Java"
},
{
"code": "// Simple Java Program find the size of the fileimport java.io.File;public class GFG { public static void main(String[] args) { // create file object enter the path of // the file for which size is to be found File file = new File(\"/home/user/GFG.txt\"); if (file.exists()) { double bytes = file.length(); double kilobytes = (bytes / 1024); // converting file size to bytes to kb double megabytes = (kilobytes / 1024); // converting file size tolb to mb double gigabytes = (megabytes / 1024); System.out.println(\"bytes : \" + bytes); System.out.println(\"kilobytes : \" + kilobytes); System.out.println(\"megabytes : \" + megabytes); } else { System.out.println(\"File does not exists!\"); } }}",
"e": 1760,
"s": 898,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1760,
"text": "bytes : 17,07,91,615\nkilobytes : 1,66,788.686\nmegabytes : 162.8795766"
},
{
"code": null,
"e": 1929,
"s": 1830,
"text": "Note: If you want file size in Gigabytes then again you have to divide mb value by 1024 and so on."
},
{
"code": null,
"e": 2080,
"s": 1929,
"text": "But Nowadays we can directly use File.size(path) after Java 7. In this we do not have to create file object we can directly find the size of the file."
},
{
"code": null,
"e": 2091,
"s": 2080,
"text": "Java-Files"
},
{
"code": null,
"e": 2098,
"s": 2091,
"text": "Picked"
},
{
"code": null,
"e": 2103,
"s": 2098,
"text": "Java"
},
{
"code": null,
"e": 2117,
"s": 2103,
"text": "Java Programs"
},
{
"code": null,
"e": 2122,
"s": 2117,
"text": "Java"
},
{
"code": null,
"e": 2220,
"s": 2122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2235,
"s": 2220,
"text": "Stream In Java"
},
{
"code": null,
"e": 2256,
"s": 2235,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2277,
"s": 2256,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2296,
"s": 2277,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2313,
"s": 2296,
"text": "Generics in Java"
},
{
"code": null,
"e": 2339,
"s": 2313,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2373,
"s": 2339,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 2411,
"s": 2373,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 2458,
"s": 2411,
"text": "Implementing a Linked List in Java using Class"
}
] |
Tesseract OCR with Java with Examples
|
06 Dec, 2021
In this article, we will learn how to work with Tesseract OCR in Java using the Tesseract API.
What is Tesseract OCR?Tesseract OCR is an optical character reading engine developed by HP laboratories in 1985 and open sourced in 2005. Since 2006 it is developed by Google. Tesseract has Unicode (UTF-8) support and can recognize more than 100 languages “out of the box” and thus can be used for building different language scanning software also. Latest Tesseract version is Tesseract 4. It adds a new neural net (LSTM) based OCR engine which is focused on line recognition but also still supports the legacy Tesseract OCR engine which works by recognizing character patterns.
How OCR works?
Generally OCR works as follows:
Pre-process image data, for example: convert to gray scale, smooth, de-skew, filter.Detect lines, words and characters.Produce ranked list of candidate characters based on trained data set. (here the setDataPath() method is used for setting path of trainer data)Post process recognized characters, choose best characters based on confidence from previous step and language data. Language data includes dictionary, grammar rules, etc.
Pre-process image data, for example: convert to gray scale, smooth, de-skew, filter.
Detect lines, words and characters.
Produce ranked list of candidate characters based on trained data set. (here the setDataPath() method is used for setting path of trainer data)
Post process recognized characters, choose best characters based on confidence from previous step and language data. Language data includes dictionary, grammar rules, etc.
Advantages
The advantages of OCR are numerous, but namely:
it increases the efficiency and effectiveness of office work
The ability to instantly search through content is immensely useful, especially in an office setting that has to deal with high volume scanning or high document inflow.
OCR is quick ensuring the document’s content remains intact while saving time as well.
Workflow is increased since employees no longer have to waste time on manual labour and can work quicker and more efficiently.
Disadvantages
The OCR is limited to language recognition.
There is lot of effort that is required to make trainer data of different languages and implement that.
One also need to do extra work on image processing as it is the most essential part that really matters when it comes to the performance of OCR.
After doing such a great amount of work, no OCR can offer an accuracy of 100% and even after OCR we have to determine the unrecognized character by neighbouring methods of machine learning or manually correct it.
How to use Tesseract OCR
The first step is to download the Tess4J API from the linkExtract the Files from the downloaded fileOpen your IDE and make a new projectLink the jar file with your project. Refer this link .Please migrate via this path “..\Tess4J-3.4.8-src\Tess4J\dist”.
The first step is to download the Tess4J API from the link
Extract the Files from the downloaded file
Open your IDE and make a new project
Link the jar file with your project. Refer this link .
Please migrate via this path “..\Tess4J-3.4.8-src\Tess4J\dist”.
Now you are done with your linking jar in your project and ready to use tesseract engine.
Performing OCR on clear images
Now that you have linked the jar file, we can get started with our coding part. The following code reads an image file and perform OCR and display text on the console.
Java
import java.io.File; import net.sourceforge.tess4j.Tesseract;import net.sourceforge.tess4j.TesseractException; public class Test { public static void main(String[] args) { Tesseract tesseract = new Tesseract(); try { tesseract.setDatapath("D:/Tess4J/tessdata"); // the path of your tess data folder // inside the extracted file String text = tesseract.doOCR(new File("image.jpg")); // path of your image file System.out.print(text); } catch (TesseractException e) { e.printStackTrace(); } }
Input:
Output:
05221859
Working:
Performing OCR on unclear images
Note that the image selected above is actually very clear and grayscaled but this doesn’t happen in most of the cases. In most of the cases, we get a noisy image and thus a very nosy output. To deal with it we need to perform some processing on the image called Image processing.
Tesseract works best when there is a very clean segmentation of the foreground text from the background. In practice, it can be extremely challenging to guarantee good segmentation. There are a variety of reasons you might not get good quality output from Tesseract if the image has noise on the background. Noise removal from image comes in the part of image processing. For this, we need to know that in what way an image should be processed.
You can refer this article for a detail understanding of how can you improve the accuracy. To implement the same in JAVA, we will make a small intelligence-based model which will scan the RGB content of the image and then convert it into the grayscaled content and also we will perform some zooming effect on the image too.
The below example is a sample code on how the image can be grayscaled based on its RGB content. So if images are very dark then they become brighter and clearer and if in case the images are whitish then they are scaled to little dark contrast so that text is visible.
Java
import java.awt.Graphics2D;import net.sourceforge.tess4j.*;import java.awt.Image;import java.awt.image.*;import java.io.*; import javax.imageio.ImageIO; public class ScanedImage { public static void processImg(BufferedImage ipimage, float scaleFactor, float offset) throws IOException, TesseractException { // Making an empty image buffer // to store image later // ipimage is an image buffer // of input image BufferedImage opimage = new BufferedImage(1050, 1024, ipimage.getType()); // creating a 2D platform // on the buffer image // for drawing the new image Graphics2D graphic = opimage.createGraphics(); // drawing new image starting from 0 0 // of size 1050 x 1024 (zoomed images) // null is the ImageObserver class object graphic.drawImage(ipimage, 0, 0, 1050, 1024, null); graphic.dispose(); // rescale OP object // for gray scaling images RescaleOp rescale = new RescaleOp(scaleFactor, offset, null); // performing scaling // and writing on a .png file BufferedImage fopimage = rescale.filter(opimage, null); ImageIO .write(fopimage, "jpg", new File("D:\\Tess4J\\Testing and learning\\output.png")); // Instantiating the Tesseract class // which is used to perform OCR Tesseract it = new Tesseract(); it.setDatapath("D:\\Program Files\\Workspace\\Tess4J"); // doing OCR on the image // and storing result in string str String str = it.doOCR(fopimage); System.out.println(str); } public static void main(String args[]) throws Exception { File f = new File( "D:\\Tess4J\\Testing and learning\\Final Learning Results\\input.jpg"); BufferedImage ipimage = ImageIO.read(f); // getting RGB content of the whole image file double d = ipimage .getRGB(ipimage.getTileWidth() / 2, ipimage.getTileHeight() / 2); // comparing the values // and setting new scaling values // that are later on used by RescaleOP if (d >= -1.4211511E7 && d < -7254228) { processImg(ipimage, 3f, -10f); } else if (d >= -7254228 && d < -2171170) { processImg(ipimage, 1.455f, -47f); } else if (d >= -2171170 && d < -1907998) { processImg(ipimage, 1.35f, -10f); } else if (d >= -1907998 && d < -257) { processImg(ipimage, 1.19f, 0.5f); } else if (d >= -257 && d < -1) { processImg(ipimage, 1f, 0.5f); } else if (d >= -1 && d < 2) { processImg(ipimage, 1f, 0.35f); } }}
Input:
input.png
Output:
output.png
Working:
adnanirshad158
Image-Processing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "In this article, we will learn how to work with Tesseract OCR in Java using the Tesseract API."
},
{
"code": null,
"e": 703,
"s": 123,
"text": "What is Tesseract OCR?Tesseract OCR is an optical character reading engine developed by HP laboratories in 1985 and open sourced in 2005. Since 2006 it is developed by Google. Tesseract has Unicode (UTF-8) support and can recognize more than 100 languages “out of the box” and thus can be used for building different language scanning software also. Latest Tesseract version is Tesseract 4. It adds a new neural net (LSTM) based OCR engine which is focused on line recognition but also still supports the legacy Tesseract OCR engine which works by recognizing character patterns."
},
{
"code": null,
"e": 718,
"s": 703,
"text": "How OCR works?"
},
{
"code": null,
"e": 750,
"s": 718,
"text": "Generally OCR works as follows:"
},
{
"code": null,
"e": 1184,
"s": 750,
"text": "Pre-process image data, for example: convert to gray scale, smooth, de-skew, filter.Detect lines, words and characters.Produce ranked list of candidate characters based on trained data set. (here the setDataPath() method is used for setting path of trainer data)Post process recognized characters, choose best characters based on confidence from previous step and language data. Language data includes dictionary, grammar rules, etc."
},
{
"code": null,
"e": 1269,
"s": 1184,
"text": "Pre-process image data, for example: convert to gray scale, smooth, de-skew, filter."
},
{
"code": null,
"e": 1305,
"s": 1269,
"text": "Detect lines, words and characters."
},
{
"code": null,
"e": 1449,
"s": 1305,
"text": "Produce ranked list of candidate characters based on trained data set. (here the setDataPath() method is used for setting path of trainer data)"
},
{
"code": null,
"e": 1621,
"s": 1449,
"text": "Post process recognized characters, choose best characters based on confidence from previous step and language data. Language data includes dictionary, grammar rules, etc."
},
{
"code": null,
"e": 1632,
"s": 1621,
"text": "Advantages"
},
{
"code": null,
"e": 1680,
"s": 1632,
"text": "The advantages of OCR are numerous, but namely:"
},
{
"code": null,
"e": 1741,
"s": 1680,
"text": "it increases the efficiency and effectiveness of office work"
},
{
"code": null,
"e": 1910,
"s": 1741,
"text": "The ability to instantly search through content is immensely useful, especially in an office setting that has to deal with high volume scanning or high document inflow."
},
{
"code": null,
"e": 1997,
"s": 1910,
"text": "OCR is quick ensuring the document’s content remains intact while saving time as well."
},
{
"code": null,
"e": 2124,
"s": 1997,
"text": "Workflow is increased since employees no longer have to waste time on manual labour and can work quicker and more efficiently."
},
{
"code": null,
"e": 2138,
"s": 2124,
"text": "Disadvantages"
},
{
"code": null,
"e": 2182,
"s": 2138,
"text": "The OCR is limited to language recognition."
},
{
"code": null,
"e": 2286,
"s": 2182,
"text": "There is lot of effort that is required to make trainer data of different languages and implement that."
},
{
"code": null,
"e": 2431,
"s": 2286,
"text": "One also need to do extra work on image processing as it is the most essential part that really matters when it comes to the performance of OCR."
},
{
"code": null,
"e": 2644,
"s": 2431,
"text": "After doing such a great amount of work, no OCR can offer an accuracy of 100% and even after OCR we have to determine the unrecognized character by neighbouring methods of machine learning or manually correct it."
},
{
"code": null,
"e": 2669,
"s": 2644,
"text": "How to use Tesseract OCR"
},
{
"code": null,
"e": 2923,
"s": 2669,
"text": "The first step is to download the Tess4J API from the linkExtract the Files from the downloaded fileOpen your IDE and make a new projectLink the jar file with your project. Refer this link .Please migrate via this path “..\\Tess4J-3.4.8-src\\Tess4J\\dist”."
},
{
"code": null,
"e": 2982,
"s": 2923,
"text": "The first step is to download the Tess4J API from the link"
},
{
"code": null,
"e": 3025,
"s": 2982,
"text": "Extract the Files from the downloaded file"
},
{
"code": null,
"e": 3062,
"s": 3025,
"text": "Open your IDE and make a new project"
},
{
"code": null,
"e": 3117,
"s": 3062,
"text": "Link the jar file with your project. Refer this link ."
},
{
"code": null,
"e": 3181,
"s": 3117,
"text": "Please migrate via this path “..\\Tess4J-3.4.8-src\\Tess4J\\dist”."
},
{
"code": null,
"e": 3271,
"s": 3181,
"text": "Now you are done with your linking jar in your project and ready to use tesseract engine."
},
{
"code": null,
"e": 3302,
"s": 3271,
"text": "Performing OCR on clear images"
},
{
"code": null,
"e": 3470,
"s": 3302,
"text": "Now that you have linked the jar file, we can get started with our coding part. The following code reads an image file and perform OCR and display text on the console."
},
{
"code": null,
"e": 3475,
"s": 3470,
"text": "Java"
},
{
"code": "import java.io.File; import net.sourceforge.tess4j.Tesseract;import net.sourceforge.tess4j.TesseractException; public class Test { public static void main(String[] args) { Tesseract tesseract = new Tesseract(); try { tesseract.setDatapath(\"D:/Tess4J/tessdata\"); // the path of your tess data folder // inside the extracted file String text = tesseract.doOCR(new File(\"image.jpg\")); // path of your image file System.out.print(text); } catch (TesseractException e) { e.printStackTrace(); } }",
"e": 4110,
"s": 3475,
"text": null
},
{
"code": null,
"e": 4117,
"s": 4110,
"text": "Input:"
},
{
"code": null,
"e": 4125,
"s": 4117,
"text": "Output:"
},
{
"code": null,
"e": 4134,
"s": 4125,
"text": "05221859"
},
{
"code": null,
"e": 4143,
"s": 4134,
"text": "Working:"
},
{
"code": null,
"e": 4176,
"s": 4143,
"text": "Performing OCR on unclear images"
},
{
"code": null,
"e": 4456,
"s": 4176,
"text": "Note that the image selected above is actually very clear and grayscaled but this doesn’t happen in most of the cases. In most of the cases, we get a noisy image and thus a very nosy output. To deal with it we need to perform some processing on the image called Image processing."
},
{
"code": null,
"e": 4901,
"s": 4456,
"text": "Tesseract works best when there is a very clean segmentation of the foreground text from the background. In practice, it can be extremely challenging to guarantee good segmentation. There are a variety of reasons you might not get good quality output from Tesseract if the image has noise on the background. Noise removal from image comes in the part of image processing. For this, we need to know that in what way an image should be processed."
},
{
"code": null,
"e": 5225,
"s": 4901,
"text": "You can refer this article for a detail understanding of how can you improve the accuracy. To implement the same in JAVA, we will make a small intelligence-based model which will scan the RGB content of the image and then convert it into the grayscaled content and also we will perform some zooming effect on the image too."
},
{
"code": null,
"e": 5494,
"s": 5225,
"text": "The below example is a sample code on how the image can be grayscaled based on its RGB content. So if images are very dark then they become brighter and clearer and if in case the images are whitish then they are scaled to little dark contrast so that text is visible."
},
{
"code": null,
"e": 5499,
"s": 5494,
"text": "Java"
},
{
"code": "import java.awt.Graphics2D;import net.sourceforge.tess4j.*;import java.awt.Image;import java.awt.image.*;import java.io.*; import javax.imageio.ImageIO; public class ScanedImage { public static void processImg(BufferedImage ipimage, float scaleFactor, float offset) throws IOException, TesseractException { // Making an empty image buffer // to store image later // ipimage is an image buffer // of input image BufferedImage opimage = new BufferedImage(1050, 1024, ipimage.getType()); // creating a 2D platform // on the buffer image // for drawing the new image Graphics2D graphic = opimage.createGraphics(); // drawing new image starting from 0 0 // of size 1050 x 1024 (zoomed images) // null is the ImageObserver class object graphic.drawImage(ipimage, 0, 0, 1050, 1024, null); graphic.dispose(); // rescale OP object // for gray scaling images RescaleOp rescale = new RescaleOp(scaleFactor, offset, null); // performing scaling // and writing on a .png file BufferedImage fopimage = rescale.filter(opimage, null); ImageIO .write(fopimage, \"jpg\", new File(\"D:\\\\Tess4J\\\\Testing and learning\\\\output.png\")); // Instantiating the Tesseract class // which is used to perform OCR Tesseract it = new Tesseract(); it.setDatapath(\"D:\\\\Program Files\\\\Workspace\\\\Tess4J\"); // doing OCR on the image // and storing result in string str String str = it.doOCR(fopimage); System.out.println(str); } public static void main(String args[]) throws Exception { File f = new File( \"D:\\\\Tess4J\\\\Testing and learning\\\\Final Learning Results\\\\input.jpg\"); BufferedImage ipimage = ImageIO.read(f); // getting RGB content of the whole image file double d = ipimage .getRGB(ipimage.getTileWidth() / 2, ipimage.getTileHeight() / 2); // comparing the values // and setting new scaling values // that are later on used by RescaleOP if (d >= -1.4211511E7 && d < -7254228) { processImg(ipimage, 3f, -10f); } else if (d >= -7254228 && d < -2171170) { processImg(ipimage, 1.455f, -47f); } else if (d >= -2171170 && d < -1907998) { processImg(ipimage, 1.35f, -10f); } else if (d >= -1907998 && d < -257) { processImg(ipimage, 1.19f, 0.5f); } else if (d >= -257 && d < -1) { processImg(ipimage, 1f, 0.5f); } else if (d >= -1 && d < 2) { processImg(ipimage, 1f, 0.35f); } }}",
"e": 8484,
"s": 5499,
"text": null
},
{
"code": null,
"e": 8491,
"s": 8484,
"text": "Input:"
},
{
"code": null,
"e": 8501,
"s": 8491,
"text": "input.png"
},
{
"code": null,
"e": 8509,
"s": 8501,
"text": "Output:"
},
{
"code": null,
"e": 8520,
"s": 8509,
"text": "output.png"
},
{
"code": null,
"e": 8529,
"s": 8520,
"text": "Working:"
},
{
"code": null,
"e": 8544,
"s": 8529,
"text": "adnanirshad158"
},
{
"code": null,
"e": 8561,
"s": 8544,
"text": "Image-Processing"
},
{
"code": null,
"e": 8566,
"s": 8561,
"text": "Java"
},
{
"code": null,
"e": 8571,
"s": 8566,
"text": "Java"
}
] |
Uniform-Cost Search (Dijkstra for large Graphs)
|
25 Aug, 2021
Uniform-Cost Search is a variant of Dijikstra’s algorithm. Here, instead of inserting all vertices into a priority queue, we insert only source, then one by one insert when needed. In every step, we check if the item is already in priority queue (using visited array). If yes, we perform decrease key, else we insert it. This variant of Dijkstra is useful for infinite graphs and those graph which are too large to represent in the memory. Uniform-Cost Search is mainly used in Artificial Intelligence.
Examples:
Input :
Output :
Minimum cost from S to G is =3
Uniform-Cost Search is similar to Dijikstra’s algorithm . In this algorithm from the starting state we will visit the adjacent states and will choose the least costly state then we will choose the next least costly state from the all un-visited and adjacent states of the visited states, in this way we will try to reach the goal state (note we wont continue the path through a goal state ), even if we reach the goal state we will continue searching for other possible paths( if there are multiple goals) . We will keep a priority queue which will give the least costliest next state from all the adjacent states of visited states.
C++
Python3
C#
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // graphvector<vector<int> > graph; // map to store cost of edgesmap<pair<int, int>, int> cost; // returns the minimum cost in a vector( if// there are multiple goal states)vector<int> uniform_cost_search(vector<int> goal, int start){ // minimum cost upto // goal state from starting // state vector<int> answer; // create a priority queue priority_queue<pair<int, int> > queue; // set the answer vector to max value for (int i = 0; i < goal.size(); i++) answer.push_back(INT_MAX); // insert the starting index queue.push(make_pair(0, start)); // map to store visited node map<int, int> visited; // count int count = 0; // while the queue is not empty while (queue.size() > 0) { // get the top element of the // priority queue pair<int, int> p = queue.top(); // pop the element queue.pop(); // get the original value p.first *= -1; // check if the element is part of // the goal list if (find(goal.begin(), goal.end(), p.second) != goal.end()) { // get the position int index = find(goal.begin(), goal.end(), p.second) - goal.begin(); // if a new goal is reached if (answer[index] == INT_MAX) count++; // if the cost is less if (answer[index] > p.first) answer[index] = p.first; // pop the element queue.pop(); // if all goals are reached if (count == goal.size()) return answer; } // check for the non visited nodes // which are adjacent to present node if (visited[p.second] == 0) for (int i = 0; i < graph[p.second].size(); i++) { // value is multiplied by -1 so that // least priority is at the top queue.push(make_pair((p.first + cost[make_pair(p.second, graph[p.second][i])]) * -1, graph[p.second][i])); } // mark as visited visited[p.second] = 1; } return answer;} // main functionint main(){ // create the graph graph.resize(7); // add edge graph[0].push_back(1); graph[0].push_back(3); graph[3].push_back(1); graph[3].push_back(6); graph[3].push_back(4); graph[1].push_back(6); graph[4].push_back(2); graph[4].push_back(5); graph[2].push_back(1); graph[5].push_back(2); graph[5].push_back(6); graph[6].push_back(4); // add the cost cost[make_pair(0, 1)] = 2; cost[make_pair(0, 3)] = 5; cost[make_pair(1, 6)] = 1; cost[make_pair(3, 1)] = 5; cost[make_pair(3, 6)] = 6; cost[make_pair(3, 4)] = 2; cost[make_pair(2, 1)] = 4; cost[make_pair(4, 2)] = 4; cost[make_pair(4, 5)] = 3; cost[make_pair(5, 2)] = 6; cost[make_pair(5, 6)] = 3; cost[make_pair(6, 4)] = 7; // goal state vector<int> goal; // set the goal // there can be multiple goal states goal.push_back(6); // get the answer vector<int> answer = uniform_cost_search(goal, 0); // print the answer cout << "Minimum cost from 0 to 6 is = " << answer[0] << endl; return 0;}
# Python3 implementation of above approach # returns the minimum cost in a vector( if# there are multiple goal states)def uniform_cost_search(goal, start): # minimum cost upto # goal state from starting global graph,cost answer = [] # create a priority queue queue = [] # set the answer vector to max value for i in range(len(goal)): answer.append(10**8) # insert the starting index queue.append([0, start]) # map to store visited node visited = {} # count count = 0 # while the queue is not empty while (len(queue) > 0): # get the top element of the queue = sorted(queue) p = queue[-1] # pop the element del queue[-1] # get the original value p[0] *= -1 # check if the element is part of # the goal list if (p[1] in goal): # get the position index = goal.index(p[1]) # if a new goal is reached if (answer[index] == 10**8): count += 1 # if the cost is less if (answer[index] > p[0]): answer[index] = p[0] # pop the element del queue[-1] queue = sorted(queue) if (count == len(goal)): return answer # check for the non visited nodes # which are adjacent to present node if (p[1] not in visited): for i in range(len(graph[p[1]])): # value is multiplied by -1 so that # least priority is at the top queue.append( [(p[0] + cost[(p[1], graph[p[1]][i])])* -1, graph[p[1]][i]]) # mark as visited visited[p[1]] = 1 return answer # main functionif __name__ == '__main__': # create the graph graph,cost = [[] for i in range(8)],{} # add edge graph[0].append(1) graph[0].append(3) graph[3].append(1) graph[3].append(6) graph[3].append(4) graph[1].append(6) graph[4].append(2) graph[4].append(5) graph[2].append(1) graph[5].append(2) graph[5].append(6) graph[6].append(4) # add the cost cost[(0, 1)] = 2 cost[(0, 3)] = 5 cost[(1, 6)] = 1 cost[(3, 1)] = 5 cost[(3, 6)] = 6 cost[(3, 4)] = 2 cost[(2, 1)] = 4 cost[(4, 2)] = 4 cost[(4, 5)] = 3 cost[(5, 2)] = 6 cost[(5, 6)] = 3 cost[(6, 4)] = 7 # goal state goal = [] # set the goal # there can be multiple goal states goal.append(6) # get the answer answer = uniform_cost_search(goal, 0) # print the answer print("Minimum cost from 0 to 6 is = ",answer[0]) # This code is contributed by mohit kumar 29
// C# implementation of above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // graphstatic List<List<int>> graph=new List<List<int>>(); // map to store cost of edgesstatic Dictionary<Tuple<int,int>,int> cost= new Dictionary<Tuple<int,int>,int>(); // returns the minimum cost in a vector( if// there are multiple goal states)static List<int> uniform_cost_search(List<int> goal, int start){ // minimum cost upto // goal state from starting // state List<int> answer=new List<int>(); // create a priority queue List<Tuple<int, int> > queue = new List<Tuple<int, int> >(); // set the answer vector to max value for (int i = 0; i < goal.Count; i++) answer.Add(int.MaxValue); // insert the starting index queue.Add(new Tuple<int,int>(0, start)); // map to store visited node Dictionary<int, int> visited=new Dictionary<int,int>(); // count int count = 0; // while the queue is not empty while (queue.Count > 0) { // get the top element of the // priority queue Tuple<int, int> q = queue[0]; Tuple<int, int> p = new Tuple<int,int>(-q.Item1,q.Item2); // pop the element queue.RemoveAt(0); // check if the element is part of // the goal list if (goal.Contains(p.Item2)) { // get the position int index = goal.IndexOf(p.Item2); // if a new goal is reached if (answer[index] == int.MaxValue) count++; // if the cost is less if (answer[index] > p.Item1) answer[index] = p.Item1; // pop the element queue.RemoveAt(0); // if all goals are reached if (count == goal.Count) return answer; } // check for the non visited nodes // which are adjacent to present node if (!visited.ContainsKey(p.Item2)) for (int i = 0; i < graph[p.Item2].Count; i++) { // value is multiplied by -1 so that // least priority is at the top queue.Add(new Tuple<int,int>((p.Item1 + (cost.ContainsKey(new Tuple<int,int>(p.Item2, graph[p.Item2][i])) ? cost[new Tuple<int,int>(p.Item2, graph[p.Item2][i])] : 0))*-1, graph[p.Item2][i])); } // mark as visited visited[p.Item2] = 1; } return answer;} // main functionpublic static void Main(params string []args){ // create the graph graph=new List<List<int>>(); for(int i=0;i<7;i++) { graph.Add(new List<int>()); } // add edge graph[0].Add(1); graph[0].Add(3); graph[3].Add(1); graph[3].Add(6); graph[3].Add(4); graph[1].Add(6); graph[4].Add(2); graph[4].Add(5); graph[2].Add(1); graph[5].Add(2); graph[5].Add(6); graph[6].Add(4); // add the cost cost[new Tuple<int,int>(0, 1)] = 2; cost[new Tuple<int,int>(0, 3)] = 5; cost[new Tuple<int,int>(1, 6)] = 1; cost[new Tuple<int,int>(3, 1)] = 5; cost[new Tuple<int,int>(3, 6)] = 6; cost[new Tuple<int,int>(3, 4)] = 2; cost[new Tuple<int,int>(2, 1)] = 4; cost[new Tuple<int,int>(4, 2)] = 4; cost[new Tuple<int,int>(4, 5)] = 3; cost[new Tuple<int,int>(5, 2)] = 6; cost[new Tuple<int,int>(5, 6)] = 3; cost[new Tuple<int,int>(6, 4)] = 7; // goal state List<int> goal=new List<int>(); // set the goal // there can be multiple goal states goal.Add(6); // get the answer List<int> answer = uniform_cost_search(goal, 0); // print the answer Console.Write("Minimum cost from 0 to 6 is = " + answer[0]); }} // This code is contributed by rutvik_56.
Minimum cost from 0 to 6 is = 3
Complexity: O( m ^ (1+floor(l/e))) where, m is the maximum number of neighbors a node has l is the length of the shortest path to the goal state e is the least cost of an edge
mohit kumar 29
rutvik_56
Kirti_Mangal
anikaseth98
Artificial Intelligence
Dijkstra
Shortest Path
Algorithms
Graph
Heap
Graph
Shortest Path
Heap
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 557,
"s": 54,
"text": "Uniform-Cost Search is a variant of Dijikstra’s algorithm. Here, instead of inserting all vertices into a priority queue, we insert only source, then one by one insert when needed. In every step, we check if the item is already in priority queue (using visited array). If yes, we perform decrease key, else we insert it. This variant of Dijkstra is useful for infinite graphs and those graph which are too large to represent in the memory. Uniform-Cost Search is mainly used in Artificial Intelligence."
},
{
"code": null,
"e": 568,
"s": 557,
"text": "Examples: "
},
{
"code": null,
"e": 576,
"s": 568,
"text": "Input :"
},
{
"code": null,
"e": 616,
"s": 576,
"text": "Output :\nMinimum cost from S to G is =3"
},
{
"code": null,
"e": 1249,
"s": 616,
"text": "Uniform-Cost Search is similar to Dijikstra’s algorithm . In this algorithm from the starting state we will visit the adjacent states and will choose the least costly state then we will choose the next least costly state from the all un-visited and adjacent states of the visited states, in this way we will try to reach the goal state (note we wont continue the path through a goal state ), even if we reach the goal state we will continue searching for other possible paths( if there are multiple goals) . We will keep a priority queue which will give the least costliest next state from all the adjacent states of visited states."
},
{
"code": null,
"e": 1253,
"s": 1249,
"text": "C++"
},
{
"code": null,
"e": 1261,
"s": 1253,
"text": "Python3"
},
{
"code": null,
"e": 1264,
"s": 1261,
"text": "C#"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // graphvector<vector<int> > graph; // map to store cost of edgesmap<pair<int, int>, int> cost; // returns the minimum cost in a vector( if// there are multiple goal states)vector<int> uniform_cost_search(vector<int> goal, int start){ // minimum cost upto // goal state from starting // state vector<int> answer; // create a priority queue priority_queue<pair<int, int> > queue; // set the answer vector to max value for (int i = 0; i < goal.size(); i++) answer.push_back(INT_MAX); // insert the starting index queue.push(make_pair(0, start)); // map to store visited node map<int, int> visited; // count int count = 0; // while the queue is not empty while (queue.size() > 0) { // get the top element of the // priority queue pair<int, int> p = queue.top(); // pop the element queue.pop(); // get the original value p.first *= -1; // check if the element is part of // the goal list if (find(goal.begin(), goal.end(), p.second) != goal.end()) { // get the position int index = find(goal.begin(), goal.end(), p.second) - goal.begin(); // if a new goal is reached if (answer[index] == INT_MAX) count++; // if the cost is less if (answer[index] > p.first) answer[index] = p.first; // pop the element queue.pop(); // if all goals are reached if (count == goal.size()) return answer; } // check for the non visited nodes // which are adjacent to present node if (visited[p.second] == 0) for (int i = 0; i < graph[p.second].size(); i++) { // value is multiplied by -1 so that // least priority is at the top queue.push(make_pair((p.first + cost[make_pair(p.second, graph[p.second][i])]) * -1, graph[p.second][i])); } // mark as visited visited[p.second] = 1; } return answer;} // main functionint main(){ // create the graph graph.resize(7); // add edge graph[0].push_back(1); graph[0].push_back(3); graph[3].push_back(1); graph[3].push_back(6); graph[3].push_back(4); graph[1].push_back(6); graph[4].push_back(2); graph[4].push_back(5); graph[2].push_back(1); graph[5].push_back(2); graph[5].push_back(6); graph[6].push_back(4); // add the cost cost[make_pair(0, 1)] = 2; cost[make_pair(0, 3)] = 5; cost[make_pair(1, 6)] = 1; cost[make_pair(3, 1)] = 5; cost[make_pair(3, 6)] = 6; cost[make_pair(3, 4)] = 2; cost[make_pair(2, 1)] = 4; cost[make_pair(4, 2)] = 4; cost[make_pair(4, 5)] = 3; cost[make_pair(5, 2)] = 6; cost[make_pair(5, 6)] = 3; cost[make_pair(6, 4)] = 7; // goal state vector<int> goal; // set the goal // there can be multiple goal states goal.push_back(6); // get the answer vector<int> answer = uniform_cost_search(goal, 0); // print the answer cout << \"Minimum cost from 0 to 6 is = \" << answer[0] << endl; return 0;}",
"e": 4585,
"s": 1264,
"text": null
},
{
"code": "# Python3 implementation of above approach # returns the minimum cost in a vector( if# there are multiple goal states)def uniform_cost_search(goal, start): # minimum cost upto # goal state from starting global graph,cost answer = [] # create a priority queue queue = [] # set the answer vector to max value for i in range(len(goal)): answer.append(10**8) # insert the starting index queue.append([0, start]) # map to store visited node visited = {} # count count = 0 # while the queue is not empty while (len(queue) > 0): # get the top element of the queue = sorted(queue) p = queue[-1] # pop the element del queue[-1] # get the original value p[0] *= -1 # check if the element is part of # the goal list if (p[1] in goal): # get the position index = goal.index(p[1]) # if a new goal is reached if (answer[index] == 10**8): count += 1 # if the cost is less if (answer[index] > p[0]): answer[index] = p[0] # pop the element del queue[-1] queue = sorted(queue) if (count == len(goal)): return answer # check for the non visited nodes # which are adjacent to present node if (p[1] not in visited): for i in range(len(graph[p[1]])): # value is multiplied by -1 so that # least priority is at the top queue.append( [(p[0] + cost[(p[1], graph[p[1]][i])])* -1, graph[p[1]][i]]) # mark as visited visited[p[1]] = 1 return answer # main functionif __name__ == '__main__': # create the graph graph,cost = [[] for i in range(8)],{} # add edge graph[0].append(1) graph[0].append(3) graph[3].append(1) graph[3].append(6) graph[3].append(4) graph[1].append(6) graph[4].append(2) graph[4].append(5) graph[2].append(1) graph[5].append(2) graph[5].append(6) graph[6].append(4) # add the cost cost[(0, 1)] = 2 cost[(0, 3)] = 5 cost[(1, 6)] = 1 cost[(3, 1)] = 5 cost[(3, 6)] = 6 cost[(3, 4)] = 2 cost[(2, 1)] = 4 cost[(4, 2)] = 4 cost[(4, 5)] = 3 cost[(5, 2)] = 6 cost[(5, 6)] = 3 cost[(6, 4)] = 7 # goal state goal = [] # set the goal # there can be multiple goal states goal.append(6) # get the answer answer = uniform_cost_search(goal, 0) # print the answer print(\"Minimum cost from 0 to 6 is = \",answer[0]) # This code is contributed by mohit kumar 29",
"e": 7243,
"s": 4585,
"text": null
},
{
"code": "// C# implementation of above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // graphstatic List<List<int>> graph=new List<List<int>>(); // map to store cost of edgesstatic Dictionary<Tuple<int,int>,int> cost= new Dictionary<Tuple<int,int>,int>(); // returns the minimum cost in a vector( if// there are multiple goal states)static List<int> uniform_cost_search(List<int> goal, int start){ // minimum cost upto // goal state from starting // state List<int> answer=new List<int>(); // create a priority queue List<Tuple<int, int> > queue = new List<Tuple<int, int> >(); // set the answer vector to max value for (int i = 0; i < goal.Count; i++) answer.Add(int.MaxValue); // insert the starting index queue.Add(new Tuple<int,int>(0, start)); // map to store visited node Dictionary<int, int> visited=new Dictionary<int,int>(); // count int count = 0; // while the queue is not empty while (queue.Count > 0) { // get the top element of the // priority queue Tuple<int, int> q = queue[0]; Tuple<int, int> p = new Tuple<int,int>(-q.Item1,q.Item2); // pop the element queue.RemoveAt(0); // check if the element is part of // the goal list if (goal.Contains(p.Item2)) { // get the position int index = goal.IndexOf(p.Item2); // if a new goal is reached if (answer[index] == int.MaxValue) count++; // if the cost is less if (answer[index] > p.Item1) answer[index] = p.Item1; // pop the element queue.RemoveAt(0); // if all goals are reached if (count == goal.Count) return answer; } // check for the non visited nodes // which are adjacent to present node if (!visited.ContainsKey(p.Item2)) for (int i = 0; i < graph[p.Item2].Count; i++) { // value is multiplied by -1 so that // least priority is at the top queue.Add(new Tuple<int,int>((p.Item1 + (cost.ContainsKey(new Tuple<int,int>(p.Item2, graph[p.Item2][i])) ? cost[new Tuple<int,int>(p.Item2, graph[p.Item2][i])] : 0))*-1, graph[p.Item2][i])); } // mark as visited visited[p.Item2] = 1; } return answer;} // main functionpublic static void Main(params string []args){ // create the graph graph=new List<List<int>>(); for(int i=0;i<7;i++) { graph.Add(new List<int>()); } // add edge graph[0].Add(1); graph[0].Add(3); graph[3].Add(1); graph[3].Add(6); graph[3].Add(4); graph[1].Add(6); graph[4].Add(2); graph[4].Add(5); graph[2].Add(1); graph[5].Add(2); graph[5].Add(6); graph[6].Add(4); // add the cost cost[new Tuple<int,int>(0, 1)] = 2; cost[new Tuple<int,int>(0, 3)] = 5; cost[new Tuple<int,int>(1, 6)] = 1; cost[new Tuple<int,int>(3, 1)] = 5; cost[new Tuple<int,int>(3, 6)] = 6; cost[new Tuple<int,int>(3, 4)] = 2; cost[new Tuple<int,int>(2, 1)] = 4; cost[new Tuple<int,int>(4, 2)] = 4; cost[new Tuple<int,int>(4, 5)] = 3; cost[new Tuple<int,int>(5, 2)] = 6; cost[new Tuple<int,int>(5, 6)] = 3; cost[new Tuple<int,int>(6, 4)] = 7; // goal state List<int> goal=new List<int>(); // set the goal // there can be multiple goal states goal.Add(6); // get the answer List<int> answer = uniform_cost_search(goal, 0); // print the answer Console.Write(\"Minimum cost from 0 to 6 is = \" + answer[0]); }} // This code is contributed by rutvik_56.",
"e": 10932,
"s": 7243,
"text": null
},
{
"code": null,
"e": 10964,
"s": 10932,
"text": "Minimum cost from 0 to 6 is = 3"
},
{
"code": null,
"e": 11143,
"s": 10966,
"text": "Complexity: O( m ^ (1+floor(l/e))) where, m is the maximum number of neighbors a node has l is the length of the shortest path to the goal state e is the least cost of an edge "
},
{
"code": null,
"e": 11158,
"s": 11143,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11168,
"s": 11158,
"text": "rutvik_56"
},
{
"code": null,
"e": 11181,
"s": 11168,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 11193,
"s": 11181,
"text": "anikaseth98"
},
{
"code": null,
"e": 11217,
"s": 11193,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 11226,
"s": 11217,
"text": "Dijkstra"
},
{
"code": null,
"e": 11240,
"s": 11226,
"text": "Shortest Path"
},
{
"code": null,
"e": 11251,
"s": 11240,
"text": "Algorithms"
},
{
"code": null,
"e": 11257,
"s": 11251,
"text": "Graph"
},
{
"code": null,
"e": 11262,
"s": 11257,
"text": "Heap"
},
{
"code": null,
"e": 11268,
"s": 11262,
"text": "Graph"
},
{
"code": null,
"e": 11282,
"s": 11268,
"text": "Shortest Path"
},
{
"code": null,
"e": 11287,
"s": 11282,
"text": "Heap"
},
{
"code": null,
"e": 11298,
"s": 11287,
"text": "Algorithms"
}
] |
Tuple Relational Calculus (TRC) in DBMS
|
30 Nov, 2021
Tuple Relational Calculus is a non-procedural query language unlike relational algebra. Tuple Calculus provides only the description of the query but it does not provide the methods to solve it. Thus, it explains what to do but not how to do. In Tuple Calculus, a query is expressed as
{t| P(t)}
where t = resulting tuples, P(t) = known as Predicate and these are the conditions that are used to fetch t
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.
P(t) may have various conditions logically combined with OR (∨), AND (∧), NOT(¬). It also uses quantifiers: ∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t) is true. ∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r.
Example: Table-1: Customer
Table-2: Branch
Table-3: Account
Table-4: Loan
Table-5: Borrower
Table-6: Depositor
Queries-1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount.
{t| t ∈ loan ∧ t[amount]>=10000}
Resulting relation:
In the above query, t[amount] is known as tuple variable.
Queries-2: Find the loan number for each loan of an amount greater or equal to 10000.
{t| ∃ s ∈ loan(t[loan number] = s[loan number]
∧ s[amount]>=10000)}
Resulting relation:
Queries-3: Find the names of all customers who have a loan and an account at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
Resulting relation:
Queries-4: Find the names of all customers having a loan at the “ABC” branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))}
Resulting relation:
Nityananda Gohain
VijaykumarSakhare
simmytarika5
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 339,
"s": 52,
"text": "Tuple Relational Calculus is a non-procedural query language unlike relational algebra. Tuple Calculus provides only the description of the query but it does not provide the methods to solve it. Thus, it explains what to do but not how to do. In Tuple Calculus, a query is expressed as "
},
{
"code": null,
"e": 349,
"s": 339,
"text": "{t| P(t)}"
},
{
"code": null,
"e": 458,
"s": 349,
"text": "where t = resulting tuples, P(t) = known as Predicate and these are the conditions that are used to fetch t "
},
{
"code": null,
"e": 539,
"s": 458,
"text": "Thus, it generates set of all tuples t, such that Predicate P(t) is true for t. "
},
{
"code": null,
"e": 803,
"s": 539,
"text": "P(t) may have various conditions logically combined with OR (∨), AND (∧), NOT(¬). It also uses quantifiers: ∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t) is true. ∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r. "
},
{
"code": null,
"e": 831,
"s": 803,
"text": "Example: Table-1: Customer "
},
{
"code": null,
"e": 848,
"s": 831,
"text": "Table-2: Branch "
},
{
"code": null,
"e": 866,
"s": 848,
"text": "Table-3: Account "
},
{
"code": null,
"e": 881,
"s": 866,
"text": "Table-4: Loan "
},
{
"code": null,
"e": 900,
"s": 881,
"text": "Table-5: Borrower "
},
{
"code": null,
"e": 920,
"s": 900,
"text": "Table-6: Depositor "
},
{
"code": null,
"e": 1021,
"s": 920,
"text": "Queries-1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount. "
},
{
"code": null,
"e": 1055,
"s": 1021,
"text": "{t| t ∈ loan ∧ t[amount]>=10000}"
},
{
"code": null,
"e": 1076,
"s": 1055,
"text": "Resulting relation: "
},
{
"code": null,
"e": 1135,
"s": 1076,
"text": "In the above query, t[amount] is known as tuple variable. "
},
{
"code": null,
"e": 1223,
"s": 1135,
"text": "Queries-2: Find the loan number for each loan of an amount greater or equal to 10000. "
},
{
"code": null,
"e": 1312,
"s": 1223,
"text": "{t| ∃ s ∈ loan(t[loan number] = s[loan number] \n ∧ s[amount]>=10000)}"
},
{
"code": null,
"e": 1333,
"s": 1312,
"text": "Resulting relation: "
},
{
"code": null,
"e": 1422,
"s": 1333,
"text": "Queries-3: Find the names of all customers who have a loan and an account at the bank. "
},
{
"code": null,
"e": 1546,
"s": 1422,
"text": "{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name]) \n ∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}"
},
{
"code": null,
"e": 1567,
"s": 1546,
"text": "Resulting relation: "
},
{
"code": null,
"e": 1647,
"s": 1567,
"text": "Queries-4: Find the names of all customers having a loan at the “ABC” branch. "
},
{
"code": null,
"e": 1782,
"s": 1647,
"text": "{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name] \n ∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))}"
},
{
"code": null,
"e": 1803,
"s": 1782,
"text": "Resulting relation: "
},
{
"code": null,
"e": 1821,
"s": 1803,
"text": "Nityananda Gohain"
},
{
"code": null,
"e": 1839,
"s": 1821,
"text": "VijaykumarSakhare"
},
{
"code": null,
"e": 1852,
"s": 1839,
"text": "simmytarika5"
},
{
"code": null,
"e": 1857,
"s": 1852,
"text": "DBMS"
},
{
"code": null,
"e": 1865,
"s": 1857,
"text": "GATE CS"
},
{
"code": null,
"e": 1870,
"s": 1865,
"text": "DBMS"
},
{
"code": null,
"e": 1968,
"s": 1870,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2015,
"s": 1968,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 2033,
"s": 2015,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 2074,
"s": 2033,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 2085,
"s": 2074,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2138,
"s": 2085,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2158,
"s": 2138,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 2185,
"s": 2158,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 2198,
"s": 2185,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 2247,
"s": 2198,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Optparse module in Python
|
17 Feb, 2022
Optparse module makes easy to write command-line tools. It allows argument parsing in the python program.
optparse make it easy to handle the command-line argument.
It comes default with python.
It allows dynamic data input to change the output
Code: Creating an OptionParser object.
Python3
import optparseparser = optparse.OptionParser()
Defining options:
It should be added one at a time using the add_option(). Each Option instance represents a set of synonymous command-line option string.
Way to create an Option instance are:
OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)
To define an option with only a short option string:
parser.add_option("-f", attr=value, ....)
And to define an option with only a long option string:
parser.add_option("--foo", attr=value, ....)
Standard Option Actions:
“store”: store this option’s argument (default).
“store_const”: store a constant value.
“store_true”: store True.
“store_false”: store False.
“append”: append this option’s argument to a list.
“append_const”: append a constant value to a list.
Standard Option Attributes:
Option.action: (default: “store”)
Option.type: (default: “string”)
Option.dest: (default: derived from option strings)
Option.default: The value to use for this option’s destination if the option is not seen on the command line.
Here’s an example of using optparse module in a simple script:
Python3
# import OptionParser class# from optparse module.from optparse import OptionParser # create a OptionParser# class objectparser = OptionParser() # ass optionsparser.add_option("-f", "--file", dest = "filename", help = "write report to FILE", metavar = "FILE")parser.add_option("-q", "--quiet", action = "store_false", dest = "verbose", default = True, help = "don't print status messages to stdout") (options, args) = parser.parse_args()
With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:
<yourscript> --file=outfile -q
Code: Writing python script for print table of n.
Python3
# import optparse moduleimport optparse # define a function for# table of ndef table(n, dest_cheak): for i in range(1,11): tab = i*n if dest_cheak: print(tab) return tab # define a function for# adding optionsdef Main(): # create OptionParser object parser = optparse.OptionParser() # add options parser.add_option('-n', dest = 'num', type = 'int', help = 'specify the n''th table number to output') parser.add_option('-o', dest = 'out', type = 'string', help = 'specify an output file (Optional)') parser.add_option("-a", "--all", action = "store_true", dest = "print", default = False, help = "print all numbers up to N") (options, args) = parser.parse_args() if (options.num == None): print (parser.usage) exit(0) else: number = options.num # function calling result = table(number, options.print) print ("The " + str(number)+ "th table is " + str(result)) if (options.out != None): # open a file in append mode f = open(options.out,"a") # write in the file f.write(str(result) + '\n') # Driver codeif __name__ == '__main__': # function calling Main()
Output:
python file_name.py -n 4
python file_name.py -n 4 -o
file.txt created
python file_name.py -n 4 -a
For knowing more about this module click here.
varshagumber28
simmytarika5
python-modules
Python
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
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 160,
"s": 54,
"text": "Optparse module makes easy to write command-line tools. It allows argument parsing in the python program."
},
{
"code": null,
"e": 219,
"s": 160,
"text": "optparse make it easy to handle the command-line argument."
},
{
"code": null,
"e": 249,
"s": 219,
"text": "It comes default with python."
},
{
"code": null,
"e": 300,
"s": 249,
"text": "It allows dynamic data input to change the output "
},
{
"code": null,
"e": 339,
"s": 300,
"text": "Code: Creating an OptionParser object."
},
{
"code": null,
"e": 347,
"s": 339,
"text": "Python3"
},
{
"code": "import optparseparser = optparse.OptionParser()",
"e": 395,
"s": 347,
"text": null
},
{
"code": null,
"e": 416,
"s": 398,
"text": "Defining options:"
},
{
"code": null,
"e": 555,
"s": 418,
"text": "It should be added one at a time using the add_option(). Each Option instance represents a set of synonymous command-line option string."
},
{
"code": null,
"e": 595,
"s": 557,
"text": "Way to create an Option instance are:"
},
{
"code": null,
"e": 636,
"s": 597,
"text": " OptionParser.add_option(option)"
},
{
"code": null,
"e": 694,
"s": 636,
"text": " OptionParser.add_option(*opt_str, attr=value, ...)"
},
{
"code": null,
"e": 750,
"s": 696,
"text": " To define an option with only a short option string:"
},
{
"code": null,
"e": 795,
"s": 752,
"text": " parser.add_option(\"-f\", attr=value, ....)"
},
{
"code": null,
"e": 853,
"s": 797,
"text": "And to define an option with only a long option string:"
},
{
"code": null,
"e": 900,
"s": 855,
"text": "parser.add_option(\"--foo\", attr=value, ....)"
},
{
"code": null,
"e": 928,
"s": 902,
"text": "Standard Option Actions: "
},
{
"code": null,
"e": 979,
"s": 930,
"text": "“store”: store this option’s argument (default)."
},
{
"code": null,
"e": 1018,
"s": 979,
"text": "“store_const”: store a constant value."
},
{
"code": null,
"e": 1044,
"s": 1018,
"text": "“store_true”: store True."
},
{
"code": null,
"e": 1072,
"s": 1044,
"text": "“store_false”: store False."
},
{
"code": null,
"e": 1123,
"s": 1072,
"text": "“append”: append this option’s argument to a list."
},
{
"code": null,
"e": 1174,
"s": 1123,
"text": "“append_const”: append a constant value to a list."
},
{
"code": null,
"e": 1204,
"s": 1176,
"text": "Standard Option Attributes:"
},
{
"code": null,
"e": 1240,
"s": 1206,
"text": "Option.action: (default: “store”)"
},
{
"code": null,
"e": 1273,
"s": 1240,
"text": "Option.type: (default: “string”)"
},
{
"code": null,
"e": 1325,
"s": 1273,
"text": "Option.dest: (default: derived from option strings)"
},
{
"code": null,
"e": 1435,
"s": 1325,
"text": "Option.default: The value to use for this option’s destination if the option is not seen on the command line."
},
{
"code": null,
"e": 1500,
"s": 1437,
"text": "Here’s an example of using optparse module in a simple script:"
},
{
"code": null,
"e": 1510,
"s": 1502,
"text": "Python3"
},
{
"code": "# import OptionParser class# from optparse module.from optparse import OptionParser # create a OptionParser# class objectparser = OptionParser() # ass optionsparser.add_option(\"-f\", \"--file\", dest = \"filename\", help = \"write report to FILE\", metavar = \"FILE\")parser.add_option(\"-q\", \"--quiet\", action = \"store_false\", dest = \"verbose\", default = True, help = \"don't print status messages to stdout\") (options, args) = parser.parse_args()",
"e": 2050,
"s": 1510,
"text": null
},
{
"code": null,
"e": 2167,
"s": 2053,
"text": "With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:"
},
{
"code": null,
"e": 2200,
"s": 2169,
"text": "<yourscript> --file=outfile -q"
},
{
"code": null,
"e": 2252,
"s": 2202,
"text": "Code: Writing python script for print table of n."
},
{
"code": null,
"e": 2262,
"s": 2254,
"text": "Python3"
},
{
"code": "# import optparse moduleimport optparse # define a function for# table of ndef table(n, dest_cheak): for i in range(1,11): tab = i*n if dest_cheak: print(tab) return tab # define a function for# adding optionsdef Main(): # create OptionParser object parser = optparse.OptionParser() # add options parser.add_option('-n', dest = 'num', type = 'int', help = 'specify the n''th table number to output') parser.add_option('-o', dest = 'out', type = 'string', help = 'specify an output file (Optional)') parser.add_option(\"-a\", \"--all\", action = \"store_true\", dest = \"print\", default = False, help = \"print all numbers up to N\") (options, args) = parser.parse_args() if (options.num == None): print (parser.usage) exit(0) else: number = options.num # function calling result = table(number, options.print) print (\"The \" + str(number)+ \"th table is \" + str(result)) if (options.out != None): # open a file in append mode f = open(options.out,\"a\") # write in the file f.write(str(result) + '\\n') # Driver codeif __name__ == '__main__': # function calling Main()",
"e": 3683,
"s": 2262,
"text": null
},
{
"code": null,
"e": 3692,
"s": 3683,
"text": " Output:"
},
{
"code": null,
"e": 3717,
"s": 3692,
"text": "python file_name.py -n 4"
},
{
"code": null,
"e": 3745,
"s": 3717,
"text": "python file_name.py -n 4 -o"
},
{
"code": null,
"e": 3762,
"s": 3745,
"text": "file.txt created"
},
{
"code": null,
"e": 3790,
"s": 3762,
"text": "python file_name.py -n 4 -a"
},
{
"code": null,
"e": 3837,
"s": 3790,
"text": "For knowing more about this module click here."
},
{
"code": null,
"e": 3852,
"s": 3837,
"text": "varshagumber28"
},
{
"code": null,
"e": 3865,
"s": 3852,
"text": "simmytarika5"
},
{
"code": null,
"e": 3880,
"s": 3865,
"text": "python-modules"
},
{
"code": null,
"e": 3887,
"s": 3880,
"text": "Python"
},
{
"code": null,
"e": 3985,
"s": 3887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4017,
"s": 3985,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4044,
"s": 4017,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4065,
"s": 4044,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4088,
"s": 4065,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4119,
"s": 4088,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4175,
"s": 4119,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4217,
"s": 4175,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4259,
"s": 4217,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4298,
"s": 4259,
"text": "Python | Get unique values from a list"
}
] |
Print all triplets with given sum
|
08 Jun, 2022
Given an array of distinct elements. The task is to find triplets in array whose sum is equal to a given number.
Examples:
Input: arr[] = {0, -1, 2, -3, 1}
sum = -2
Output: 0 -3 1
-1 2 -3
If we calculate the sum of the output,
0 + (-3) + 1 = -2
(-1) + 2 + (-3) = -2
Input: arr[] = {1, -2, 1, 0, 5}
sum = 0
Output: 1 -2 1
If we calculate the sum of the output,
1 + (-2) + 1 = 0
Method 1: Brute Force.Approach: The brute force approach in these type of questions aim to check all possible triplets present in the array. The triplet with sum=Target sum will be the answer. Now the question that arises is how should one check all possible triplets. To check all possible duplets fix a pointer on one element and for every such element traverse the array and check the sum. This will be the sum of all possible duplets.
Likewise for checking all possible triplets one can fix two-pointers and move the third pointer over the array and as soon as it reaches the end of array increment the second pointer and again repeat the same.
Algorithm:
Take three pointers i, j, k.Initialize i with zero and start a nested loop for i.Initialize j with (i+1) and start a nested loop for j.Initialize k with (j+1) and start a loop for k.If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k].Else keep incrementing k till it is equal to last index.Goto step 2 and increment j and for every value of j run the inner loop of k.If j is equal to 2nd last index Goto step 1 and increment the value of i till 3rd last index and again continue the whole process till the value of i is equal to the last index.
Take three pointers i, j, k.
Initialize i with zero and start a nested loop for i.
Initialize j with (i+1) and start a nested loop for j.
Initialize k with (j+1) and start a loop for k.
If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k].
Else keep incrementing k till it is equal to last index.
Goto step 2 and increment j and for every value of j run the inner loop of k.
If j is equal to 2nd last index Goto step 1 and increment the value of i till 3rd last index and again continue the whole process till the value of i is equal to the last index.
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to find three elements// whose sum is equal to given sum#include <bits/stdc++.h>using namespace std; // Prints all triplets in arr[] with given sumvoid findTriplets(int arr[], int n, int sum){ for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { cout << arr[i] << " " << arr[j] << " " << arr[k] << endl; } } } }} // Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n, -2); return 0;}
// A simple Java program// to find three elements// whose sum is equal to// given sumimport java.io.*; class GFG { // Prints all triplets in // arr[] with given sum static void findTriplets(int arr[], int n, int sum) { for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { System.out.println( arr[i] + " " + arr[j] + " " + arr[k]); } } } } } // Driver code public static void main(String[] args) { int arr[] = { 0, -1, 2, -3, 1 }; int n = arr.length; findTriplets(arr, n, -2); }} // This code is contributed by m_kit
# A simple Python 3 program# to find three elements# whose sum is equal to# given sum # Prints all triplets in# arr[] with given sumdef findTriplets(arr, n, sum): for i in range(0, n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): if (arr[i] + arr[j] + arr[k] == sum): print(arr[i], " ", arr[j], " ", arr[k], sep = "") # Driver codearr = [ 0, -1, 2, -3, 1 ]n = len(arr)findTriplets(arr, n, -2) # This code is contributed# by Smitha
// A simple C# program// to find three elements// whose sum is equal to// given sumusing System; class GFG { // Prints all triplets in // arr[] with given sum static void findTriplets(int[] arr, int n, int sum) { for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { Console.WriteLine( arr[i] + " " + arr[j] + " " + arr[k]); } } } } } // Driver code static public void Main() { int[] arr = { 0, -1, 2, -3, 1 }; int n = arr.Length; findTriplets(arr, n, -2); }}// This code is contributed by akt_mit
<?php// A simple PHP program to// find three elements whose// sum is equal to given sum // Prints all triplets in// arr[] with given sumfunction findTriplets($arr, $n, $sum){ for ($i = 0; $i < $n - 2; $i++) { for ($j = $i + 1; $j < $n - 1; $j++) { for ($k = $j + 1; $k < $n; $k++) { if ($arr[$i] + $arr[$j] + $arr[$k] == $sum) { echo $arr[$i], " ", $arr[$j], " ", $arr[$k], "\n"; } } } }} // Driver code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n, -2); // This code is contributed by aj_36?>
<script> // A simple Javascript program to find three elements// whose sum is equal to given sum // Prints all triplets in arr[] with given sumfunction findTriplets(arr, n, sum){ for (let i = 0; i < n - 2; i++) { for (let j = i + 1; j < n - 1; j++) { for (let k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { document.write(arr[i]+ " " + arr[j] + " " + arr[k] + "<br>"); } } } }} // Driver code let arr = [ 0, -1, 2, -3, 1 ]; let n = arr.length; findTriplets(arr, n, -2); // This code is contributed by Mayank Tyagi </script>
0 -3 1
-1 2 -3
Complexity Analysis:
Time Complexity: O(n3). As three nested for loops have been used.
Auxiliary Space: O(1). As no data structure has been used for storing values.
Method 2: Hashing.
Approach: Hashing can be used to solve this problem. HashTable or HashMaps allows us to perform lookup or search operations in constant time complexity. If one can find that for every possible duplet there is an element already existing in the array which can make sum=target sum then the problem will be solved in an efficient manner.To implement Hashing, we can use unordered_set in C++ or HashSet in Java.
As we fix first pointer(say a), traverse the array using second pointer(say b) and keep storing the elements encountered in a HashTable.
As soon as we find that the element which is equal to remaining sum (Target sum -(a+b)) that is already present in the HashTable, we print our triplet.
Algorithm:
Start the outer loop from i=0 till the (n-2)th index.For every iteration make an unordered set and enter the inner loop.Start the inner loop[ from j = (i+1)(as the values with which we have already checked will not appear in a valid triplet) till last index.Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed.Else push the value in the set as for later reference.Increment i and Goto step 2.
Start the outer loop from i=0 till the (n-2)th index.
For every iteration make an unordered set and enter the inner loop.
Start the inner loop[ from j = (i+1)(as the values with which we have already checked will not appear in a valid triplet) till last index.
Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed.
Else push the value in the set as for later reference.
Increment i and Goto step 2.
Pseudo Code:
Run a loop from i=0 to n-2
Create an empty hash table
Run inner loop from j=i+1 to n-1
If -(arr[i] + arr[j]) is present in hash table
print arr[i], arr[j] and -(arr[i] + arr[j])
Else
Insert arr[j] in hash table.
C++
Java
Python3
C#
Javascript
// C++ program to find triplets in a given// array whose sum is equal to given sum.#include <bits/stdc++.h>using namespace std; // function to print triplets with given sumvoid findTriplets(int arr[], int n, int sum){ for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "sum-arr[i]" unordered_set<int> s; for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.find(x) != s.end()) printf("%d %d %d\n", x, arr[i], arr[j]); else s.insert(arr[j]); } }} // Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1 }; int sum = -2; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n, sum); return 0;}
// Java program to find triplets in a given// array whose sum is equal to given sum.import java.util.*; class GFG { // function to print triplets with given sum static void findTriplets(int arr[], int n, int sum) { for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "sum-arr[i]" HashSet<Integer> s = new HashSet<>(); for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.contains(x)) System.out.printf( "%d %d %d\n", x, arr[i], arr[j]); else s.add(arr[j]); } } } // Driver code public static void main(String[] args) { int arr[] = { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.length; findTriplets(arr, n, sum); }} // This code is contributed by Rajput-Ji
# Python3 program to find triplets in a given# array whose Sum is equal to given sum.import math as mt # function to print triplets with given sumdef findTriplets(arr, n, Sum): for i in range(n - 1): # Find all pairs with Sum equals # to "Sum-arr[i]" s = dict() for j in range(i + 1, n): x = Sum - (arr[i] + arr[j]) if x in s.keys(): print(x, arr[i], arr[j]) else: s[arr[j]] = 1 # Driver codearr = [ 0, -1, 2, -3, 1 ]Sum = -2n = len(arr)findTriplets(arr, n, Sum) # This code is contributed# by mohit kumar 29
// C# program to find triplets in a given// array whose sum is equal to given sum.using System;using System.Collections.Generic; public class GFG { // function to print triplets with given sum static void findTriplets(int[] arr, int n, int sum) { for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "sum-arr[i]" HashSet<int> s = new HashSet<int>(); for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.Contains(x)) Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]); else s.Add(arr[j]); } } } // Driver code public static void Main(String[] args) { int[] arr = { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.Length; findTriplets(arr, n, sum); }}// This code is contributed by Princi Singh
<script>// Javascript program to find triplets in a given// array whose sum is equal to given sum. // function to print triplets with given sum function findTriplets(arr,n,sum) { for (let i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "sum-arr[i]" let s = new Set(); for (let j = i + 1; j < n; j++) { let x = sum - (arr[i] + arr[j]); if (s.has(x)) document.write( x+" "+ arr[i]+" "+ arr[j]+"<br>"); else s.add(arr[j]); } } } // Driver code let arr=[0, -1, 2, -3, 1]; let sum = -2; let n = arr.length; findTriplets(arr, n, sum); // This code is contributed by unknown2108</script>
-3 0 1
2 -1 -3
Complexity Analysis:
Time Complexity: O(n2). Use of a nested for loop brings the time complexity to n2.
Auxiliary Space: O(n). As an unordered_set data structure has been used for storing values.
Method 3: This method uses the method of Sorting and Two-pointer Technique to solve the above problem. This execution will involve O(n2)) time complexity and O(1) space complexity. The idea is based on Method 2 of this post.
Approach : The two pointer technique can be brought into action using the sorting technique. In two pointer technique one can search for the pair having a target sum in linear time. The idea here is to fix one pointer (say a) and use the remaining pointers to find the pair having required sum Target-value at(a) efficiently. Now let’s discuss how we can find the required pair effectively using two pointer technique. The pointers used for two pointer technique are say (l and r).
So if the sum = value(a) + value(l) + value(r) exceeds the required sum, for same (a, l) the required value(r) should be less than the previous. Thus, decrementing the r pointer.
If the sum = value(a) + value(l) + value(r) is less than the required sum, for same (a, r) the required value(l) should be greater than the previous. Thus, incrementing the l pointer.
Algorithm:
Sort the array and for every element arr[i] search for the other two elements arr[l], arr[r] such that arr[i]+arr[l]+arr[r]=Target sum.Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted.Run an outer loop taking control variable as i and for every iteration initialize a value l which is the first pointer with i+1 and r with last index.Now enter into a while loop which will run till the value of l<r.If arr[i]+arr[l]+arr[r]>Target sum then decrement r by 1 as the required sum is less than the current sum and decreasing the value of will do the needful.If arr[i]+arr[l]+arr[r]<Target sum then increment l by 1 as the required sum is less than the current sum and increasing the value of will do the needful.If arr[i]+arr[l]+arr[r]==Target sum print the values.Increment i Goto Step 3.
Sort the array and for every element arr[i] search for the other two elements arr[l], arr[r] such that arr[i]+arr[l]+arr[r]=Target sum.
Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted.
Run an outer loop taking control variable as i and for every iteration initialize a value l which is the first pointer with i+1 and r with last index.
Now enter into a while loop which will run till the value of l<r.
If arr[i]+arr[l]+arr[r]>Target sum then decrement r by 1 as the required sum is less than the current sum and decreasing the value of will do the needful.
If arr[i]+arr[l]+arr[r]<Target sum then increment l by 1 as the required sum is less than the current sum and increasing the value of will do the needful.
If arr[i]+arr[l]+arr[r]==Target sum print the values.
Increment i Goto Step 3.
Pseudo Code :
1. Sort all element of array
2. Run loop from i=0 to n-2.
Initialize two index variables l=i+1 and r=n-1
4. while (l < r)
Check sum of arr[i], arr[l], arr[r] is
given sum or not if sum is 'sum', then print
the triplet and do l++ and r--.
5. If sum is less than given sum then l++
6. If sum is greater than given sum then r--
7. If not exist in array then print not found.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find triplets in a given// array whose sum is given sum.#include <bits/stdc++.h>using namespace std; // Function to print triplets with given sum vector<vector<int>> findTriplets(int nums[],int n,int sumTarget) { vector<vector<int>> res; if(n <=2) return res; sort(nums,nums + n); for(int i=0;i<n;i++){ if(i>0 && nums[i] == nums[i-1]) // avoid duplicate triplets count continue; int num = nums[i]; int target = sumTarget - num; for(int l=i+1, r=n-1; l<r; ) { if(nums[l]+nums[r] > target) r--; else if (nums[l]+nums[r] < target) l++; else { // nums[l] + nums[r] == target res.push_back({nums[i], nums[l], nums[r]}); // skip duplicates while( l<n-1 && nums[l]==nums[l+1]) l++; while( r>0 && nums[r]==nums[r-1]) r--; l++; r--; } } } return res; }// Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1, -1, 3, 0}; int sum = -2; int n = sizeof(arr) / sizeof(arr[0]); vector<vector<int>> res = findTriplets(arr, n, sum); cout<<"Unique triplets found are : \n"; for(int i = 0;i<res.size();i++) cout<<res[i][0]<<" "<<res[i][1]<<" "<<res[i][2]<<"\n"; return 0;}
// Java program to find triplets// in a given array whose sum// is given sum.import java.io.*;import java.util.*; class GFG { // function to print // triplets with given sum static void findTriplets(int[] arr, int n, int sum) { // sort array elements Arrays.sort(arr); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. System.out.println( x + " " + arr[l] + " " + arr[r]); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } // Driver code public static void main(String args[]) { int[] arr = new int[] { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.length; findTriplets(arr, n, sum); }} // This code is contributed// by Akanksha Rai(Abby_akku)
# Python3 program to find triplets in a# given array whose sum is given sum. # function to print triplets with# given sumdef findTriplets(arr, n, sum): # sort array elements arr.sort(); for i in range(0, n - 1): # initialize left and right l = i + 1; r = n - 1; x = arr[i]; while (l < r) : if (x + arr[l] + arr[r] == sum) : # print elements if it's sum # is given sum. print(x, arr[l], arr[r]); l = l + 1; r = r - 1; # If sum of three elements is less # than 'sum' then increment in left elif (x + arr[l] + arr[r] < sum): l = l + 1; # if sum is greater than given sum, # then decrement in right side else: r = r - 1; # Driver codearr = [ 0, -1, 2, -3, 1 ];sum = -2;n = len(arr);findTriplets(arr, n, sum); # This code is contributed by# Shivi_Aggarwal
// C# program to find triplets// in a given array whose sum// is given sum.using System; class GFG { // function to print // triplets with given sum static void findTriplets(int[] arr, int n, int sum) { // sort array elements Array.Sort(arr); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. Console.WriteLine(x + " " + arr[l] + " " + arr[r]); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } // Driver code static int Main() { int[] arr = new int[] { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.Length; findTriplets(arr, n, sum); return 0; }} // This code is contributed by rahul
<?php// PHP program to find triplets// in a given array whose sum// is given sum. // function to print triplets// with given sumfunction findTriplets($arr, $n, $sum){ // sort array elements sort($arr); for ($i = 0; $i < $n - 1; $i++) { // initialize left and right $l = $i + 1; $r = $n - 1; $x = $arr[$i]; while ($l < $r) { if ($x + $arr[$l] + $arr[$r] == $sum) { // print elements if it's // sum is given sum. echo $x, " ", $arr[$l], " ", $arr[$r], "\n"; $l++; $r--; } // If sum of three elements // is less than 'sum' then // increment in left else if ($x + $arr[$l] + $arr[$r] < $sum) $l++; // if sum is greater // than given sum, then // decrement in right side else $r--; } }} // Driver code$arr = array(0, -1, 2, -3, 1);$sum = -2;$n = sizeof($arr);findTriplets($arr, $n, $sum); // This code is contributed by ajit?>
<script> // Javascript program to find triplets // in a given array whose sum // is given sum. // function to print // triplets with given sum function findTriplets(arr, n, sum) { // sort array elements arr.sort(function(a, b){return a - b}); for (let i = 0; i < n - 1; i++) { // initialize left and right let l = i + 1; let r = n - 1; let x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. document.write(x + " " + arr[l] + " " + arr[r] + "</br>"); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } let arr = [ 0, -1, 2, -3, 1 ]; let sum = -2; let n = arr.length; findTriplets(arr, n, sum); // This code is contributed by rameshtravel07.</script>
-3 -1 2
-3 0 1
Complexity Analysis:
Time Complexity: O(n2). Use of a nested loop (one for iterating, other for two-pointer technique) brings the time complexity to O(n2).
Auxiliary Space: O(1). As no use of additional data structure is used.
jit_t
Smitha Dinesh Semwal
mithunkumarmnnit321
Akanksha_Rai
mohit kumar 29
Shivi_Aggarwal
Rajput-Ji
princi singh
bidibaaz123
mayanktyagi1709
RahulJain6
rameshtravel07
unknown2108
simranarora5sos
simmytarika5
Arrays
Hash
Searching
Sorting
Arrays
Searching
Hash
Sorting
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": 167,
"s": 54,
"text": "Given an array of distinct elements. The task is to find triplets in array whose sum is equal to a given number."
},
{
"code": null,
"e": 178,
"s": 167,
"text": "Examples: "
},
{
"code": null,
"e": 460,
"s": 178,
"text": "Input: arr[] = {0, -1, 2, -3, 1}\n sum = -2\nOutput: 0 -3 1\n -1 2 -3\nIf we calculate the sum of the output,\n0 + (-3) + 1 = -2\n(-1) + 2 + (-3) = -2\n\nInput: arr[] = {1, -2, 1, 0, 5}\n sum = 0\nOutput: 1 -2 1\nIf we calculate the sum of the output,\n1 + (-2) + 1 = 0"
},
{
"code": null,
"e": 900,
"s": 460,
"text": "Method 1: Brute Force.Approach: The brute force approach in these type of questions aim to check all possible triplets present in the array. The triplet with sum=Target sum will be the answer. Now the question that arises is how should one check all possible triplets. To check all possible duplets fix a pointer on one element and for every such element traverse the array and check the sum. This will be the sum of all possible duplets. "
},
{
"code": null,
"e": 1111,
"s": 900,
"text": "Likewise for checking all possible triplets one can fix two-pointers and move the third pointer over the array and as soon as it reaches the end of array increment the second pointer and again repeat the same. "
},
{
"code": null,
"e": 1124,
"s": 1111,
"text": "Algorithm: "
},
{
"code": null,
"e": 1715,
"s": 1124,
"text": "Take three pointers i, j, k.Initialize i with zero and start a nested loop for i.Initialize j with (i+1) and start a nested loop for j.Initialize k with (j+1) and start a loop for k.If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k].Else keep incrementing k till it is equal to last index.Goto step 2 and increment j and for every value of j run the inner loop of k.If j is equal to 2nd last index Goto step 1 and increment the value of i till 3rd last index and again continue the whole process till the value of i is equal to the last index. "
},
{
"code": null,
"e": 1744,
"s": 1715,
"text": "Take three pointers i, j, k."
},
{
"code": null,
"e": 1798,
"s": 1744,
"text": "Initialize i with zero and start a nested loop for i."
},
{
"code": null,
"e": 1853,
"s": 1798,
"text": "Initialize j with (i+1) and start a nested loop for j."
},
{
"code": null,
"e": 1901,
"s": 1853,
"text": "Initialize k with (j+1) and start a loop for k."
},
{
"code": null,
"e": 1998,
"s": 1901,
"text": "If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k]."
},
{
"code": null,
"e": 2055,
"s": 1998,
"text": "Else keep incrementing k till it is equal to last index."
},
{
"code": null,
"e": 2133,
"s": 2055,
"text": "Goto step 2 and increment j and for every value of j run the inner loop of k."
},
{
"code": null,
"e": 2313,
"s": 2133,
"text": "If j is equal to 2nd last index Goto step 1 and increment the value of i till 3rd last index and again continue the whole process till the value of i is equal to the last index. "
},
{
"code": null,
"e": 2317,
"s": 2313,
"text": "C++"
},
{
"code": null,
"e": 2322,
"s": 2317,
"text": "Java"
},
{
"code": null,
"e": 2330,
"s": 2322,
"text": "Python3"
},
{
"code": null,
"e": 2333,
"s": 2330,
"text": "C#"
},
{
"code": null,
"e": 2337,
"s": 2333,
"text": "PHP"
},
{
"code": null,
"e": 2348,
"s": 2337,
"text": "Javascript"
},
{
"code": "// A simple C++ program to find three elements// whose sum is equal to given sum#include <bits/stdc++.h>using namespace std; // Prints all triplets in arr[] with given sumvoid findTriplets(int arr[], int n, int sum){ for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { cout << arr[i] << \" \" << arr[j] << \" \" << arr[k] << endl; } } } }} // Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n, -2); return 0;}",
"e": 3062,
"s": 2348,
"text": null
},
{
"code": "// A simple Java program// to find three elements// whose sum is equal to// given sumimport java.io.*; class GFG { // Prints all triplets in // arr[] with given sum static void findTriplets(int arr[], int n, int sum) { for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { System.out.println( arr[i] + \" \" + arr[j] + \" \" + arr[k]); } } } } } // Driver code public static void main(String[] args) { int arr[] = { 0, -1, 2, -3, 1 }; int n = arr.length; findTriplets(arr, n, -2); }} // This code is contributed by m_kit",
"e": 3977,
"s": 3062,
"text": null
},
{
"code": "# A simple Python 3 program# to find three elements# whose sum is equal to# given sum # Prints all triplets in# arr[] with given sumdef findTriplets(arr, n, sum): for i in range(0, n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): if (arr[i] + arr[j] + arr[k] == sum): print(arr[i], \" \", arr[j], \" \", arr[k], sep = \"\") # Driver codearr = [ 0, -1, 2, -3, 1 ]n = len(arr)findTriplets(arr, n, -2) # This code is contributed# by Smitha",
"e": 4560,
"s": 3977,
"text": null
},
{
"code": "// A simple C# program// to find three elements// whose sum is equal to// given sumusing System; class GFG { // Prints all triplets in // arr[] with given sum static void findTriplets(int[] arr, int n, int sum) { for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { Console.WriteLine( arr[i] + \" \" + arr[j] + \" \" + arr[k]); } } } } } // Driver code static public void Main() { int[] arr = { 0, -1, 2, -3, 1 }; int n = arr.Length; findTriplets(arr, n, -2); }}// This code is contributed by akt_mit",
"e": 5456,
"s": 4560,
"text": null
},
{
"code": "<?php// A simple PHP program to// find three elements whose// sum is equal to given sum // Prints all triplets in// arr[] with given sumfunction findTriplets($arr, $n, $sum){ for ($i = 0; $i < $n - 2; $i++) { for ($j = $i + 1; $j < $n - 1; $j++) { for ($k = $j + 1; $k < $n; $k++) { if ($arr[$i] + $arr[$j] + $arr[$k] == $sum) { echo $arr[$i], \" \", $arr[$j], \" \", $arr[$k], \"\\n\"; } } } }} // Driver code$arr = array (0, -1, 2, -3, 1);$n = sizeof($arr);findTriplets($arr, $n, -2); // This code is contributed by aj_36?>",
"e": 6169,
"s": 5456,
"text": null
},
{
"code": "<script> // A simple Javascript program to find three elements// whose sum is equal to given sum // Prints all triplets in arr[] with given sumfunction findTriplets(arr, n, sum){ for (let i = 0; i < n - 2; i++) { for (let j = i + 1; j < n - 1; j++) { for (let k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == sum) { document.write(arr[i]+ \" \" + arr[j] + \" \" + arr[k] + \"<br>\"); } } } }} // Driver code let arr = [ 0, -1, 2, -3, 1 ]; let n = arr.length; findTriplets(arr, n, -2); // This code is contributed by Mayank Tyagi </script>",
"e": 6857,
"s": 6169,
"text": null
},
{
"code": null,
"e": 6872,
"s": 6857,
"text": "0 -3 1\n-1 2 -3"
},
{
"code": null,
"e": 6896,
"s": 6874,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 6962,
"s": 6896,
"text": "Time Complexity: O(n3). As three nested for loops have been used."
},
{
"code": null,
"e": 7040,
"s": 6962,
"text": "Auxiliary Space: O(1). As no data structure has been used for storing values."
},
{
"code": null,
"e": 7060,
"s": 7040,
"text": "Method 2: Hashing. "
},
{
"code": null,
"e": 7470,
"s": 7060,
"text": "Approach: Hashing can be used to solve this problem. HashTable or HashMaps allows us to perform lookup or search operations in constant time complexity. If one can find that for every possible duplet there is an element already existing in the array which can make sum=target sum then the problem will be solved in an efficient manner.To implement Hashing, we can use unordered_set in C++ or HashSet in Java. "
},
{
"code": null,
"e": 7607,
"s": 7470,
"text": "As we fix first pointer(say a), traverse the array using second pointer(say b) and keep storing the elements encountered in a HashTable."
},
{
"code": null,
"e": 7759,
"s": 7607,
"text": "As soon as we find that the element which is equal to remaining sum (Target sum -(a+b)) that is already present in the HashTable, we print our triplet."
},
{
"code": null,
"e": 7772,
"s": 7759,
"text": "Algorithm: "
},
{
"code": null,
"e": 8219,
"s": 7772,
"text": "Start the outer loop from i=0 till the (n-2)th index.For every iteration make an unordered set and enter the inner loop.Start the inner loop[ from j = (i+1)(as the values with which we have already checked will not appear in a valid triplet) till last index.Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed.Else push the value in the set as for later reference.Increment i and Goto step 2."
},
{
"code": null,
"e": 8273,
"s": 8219,
"text": "Start the outer loop from i=0 till the (n-2)th index."
},
{
"code": null,
"e": 8341,
"s": 8273,
"text": "For every iteration make an unordered set and enter the inner loop."
},
{
"code": null,
"e": 8480,
"s": 8341,
"text": "Start the inner loop[ from j = (i+1)(as the values with which we have already checked will not appear in a valid triplet) till last index."
},
{
"code": null,
"e": 8587,
"s": 8480,
"text": "Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed."
},
{
"code": null,
"e": 8642,
"s": 8587,
"text": "Else push the value in the set as for later reference."
},
{
"code": null,
"e": 8671,
"s": 8642,
"text": "Increment i and Goto step 2."
},
{
"code": null,
"e": 8686,
"s": 8671,
"text": "Pseudo Code: "
},
{
"code": null,
"e": 8932,
"s": 8686,
"text": "Run a loop from i=0 to n-2\n Create an empty hash table\n Run inner loop from j=i+1 to n-1\n If -(arr[i] + arr[j]) is present in hash table\n print arr[i], arr[j] and -(arr[i] + arr[j])\n Else\n Insert arr[j] in hash table."
},
{
"code": null,
"e": 8936,
"s": 8932,
"text": "C++"
},
{
"code": null,
"e": 8941,
"s": 8936,
"text": "Java"
},
{
"code": null,
"e": 8949,
"s": 8941,
"text": "Python3"
},
{
"code": null,
"e": 8952,
"s": 8949,
"text": "C#"
},
{
"code": null,
"e": 8963,
"s": 8952,
"text": "Javascript"
},
{
"code": "// C++ program to find triplets in a given// array whose sum is equal to given sum.#include <bits/stdc++.h>using namespace std; // function to print triplets with given sumvoid findTriplets(int arr[], int n, int sum){ for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"sum-arr[i]\" unordered_set<int> s; for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.find(x) != s.end()) printf(\"%d %d %d\\n\", x, arr[i], arr[j]); else s.insert(arr[j]); } }} // Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1 }; int sum = -2; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n, sum); return 0;}",
"e": 9720,
"s": 8963,
"text": null
},
{
"code": "// Java program to find triplets in a given// array whose sum is equal to given sum.import java.util.*; class GFG { // function to print triplets with given sum static void findTriplets(int arr[], int n, int sum) { for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"sum-arr[i]\" HashSet<Integer> s = new HashSet<>(); for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.contains(x)) System.out.printf( \"%d %d %d\\n\", x, arr[i], arr[j]); else s.add(arr[j]); } } } // Driver code public static void main(String[] args) { int arr[] = { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.length; findTriplets(arr, n, sum); }} // This code is contributed by Rajput-Ji",
"e": 10648,
"s": 9720,
"text": null
},
{
"code": "# Python3 program to find triplets in a given# array whose Sum is equal to given sum.import math as mt # function to print triplets with given sumdef findTriplets(arr, n, Sum): for i in range(n - 1): # Find all pairs with Sum equals # to \"Sum-arr[i]\" s = dict() for j in range(i + 1, n): x = Sum - (arr[i] + arr[j]) if x in s.keys(): print(x, arr[i], arr[j]) else: s[arr[j]] = 1 # Driver codearr = [ 0, -1, 2, -3, 1 ]Sum = -2n = len(arr)findTriplets(arr, n, Sum) # This code is contributed# by mohit kumar 29",
"e": 11269,
"s": 10648,
"text": null
},
{
"code": "// C# program to find triplets in a given// array whose sum is equal to given sum.using System;using System.Collections.Generic; public class GFG { // function to print triplets with given sum static void findTriplets(int[] arr, int n, int sum) { for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"sum-arr[i]\" HashSet<int> s = new HashSet<int>(); for (int j = i + 1; j < n; j++) { int x = sum - (arr[i] + arr[j]); if (s.Contains(x)) Console.Write(\"{0} {1} {2}\\n\", x, arr[i], arr[j]); else s.Add(arr[j]); } } } // Driver code public static void Main(String[] args) { int[] arr = { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.Length; findTriplets(arr, n, sum); }}// This code is contributed by Princi Singh",
"e": 12205,
"s": 11269,
"text": null
},
{
"code": "<script>// Javascript program to find triplets in a given// array whose sum is equal to given sum. // function to print triplets with given sum function findTriplets(arr,n,sum) { for (let i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // \"sum-arr[i]\" let s = new Set(); for (let j = i + 1; j < n; j++) { let x = sum - (arr[i] + arr[j]); if (s.has(x)) document.write( x+\" \"+ arr[i]+\" \"+ arr[j]+\"<br>\"); else s.add(arr[j]); } } } // Driver code let arr=[0, -1, 2, -3, 1]; let sum = -2; let n = arr.length; findTriplets(arr, n, sum); // This code is contributed by unknown2108</script>",
"e": 13001,
"s": 12205,
"text": null
},
{
"code": null,
"e": 13016,
"s": 13001,
"text": "-3 0 1\n2 -1 -3"
},
{
"code": null,
"e": 13041,
"s": 13018,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 13124,
"s": 13041,
"text": "Time Complexity: O(n2). Use of a nested for loop brings the time complexity to n2."
},
{
"code": null,
"e": 13216,
"s": 13124,
"text": "Auxiliary Space: O(n). As an unordered_set data structure has been used for storing values."
},
{
"code": null,
"e": 13441,
"s": 13216,
"text": "Method 3: This method uses the method of Sorting and Two-pointer Technique to solve the above problem. This execution will involve O(n2)) time complexity and O(1) space complexity. The idea is based on Method 2 of this post."
},
{
"code": null,
"e": 13924,
"s": 13441,
"text": "Approach : The two pointer technique can be brought into action using the sorting technique. In two pointer technique one can search for the pair having a target sum in linear time. The idea here is to fix one pointer (say a) and use the remaining pointers to find the pair having required sum Target-value at(a) efficiently. Now let’s discuss how we can find the required pair effectively using two pointer technique. The pointers used for two pointer technique are say (l and r). "
},
{
"code": null,
"e": 14104,
"s": 13924,
"text": "So if the sum = value(a) + value(l) + value(r) exceeds the required sum, for same (a, l) the required value(r) should be less than the previous. Thus, decrementing the r pointer. "
},
{
"code": null,
"e": 14288,
"s": 14104,
"text": "If the sum = value(a) + value(l) + value(r) is less than the required sum, for same (a, r) the required value(l) should be greater than the previous. Thus, incrementing the l pointer."
},
{
"code": null,
"e": 14301,
"s": 14288,
"text": "Algorithm: "
},
{
"code": null,
"e": 15149,
"s": 14301,
"text": "Sort the array and for every element arr[i] search for the other two elements arr[l], arr[r] such that arr[i]+arr[l]+arr[r]=Target sum.Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted.Run an outer loop taking control variable as i and for every iteration initialize a value l which is the first pointer with i+1 and r with last index.Now enter into a while loop which will run till the value of l<r.If arr[i]+arr[l]+arr[r]>Target sum then decrement r by 1 as the required sum is less than the current sum and decreasing the value of will do the needful.If arr[i]+arr[l]+arr[r]<Target sum then increment l by 1 as the required sum is less than the current sum and increasing the value of will do the needful.If arr[i]+arr[l]+arr[r]==Target sum print the values.Increment i Goto Step 3."
},
{
"code": null,
"e": 15285,
"s": 15149,
"text": "Sort the array and for every element arr[i] search for the other two elements arr[l], arr[r] such that arr[i]+arr[l]+arr[r]=Target sum."
},
{
"code": null,
"e": 15398,
"s": 15285,
"text": "Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted."
},
{
"code": null,
"e": 15549,
"s": 15398,
"text": "Run an outer loop taking control variable as i and for every iteration initialize a value l which is the first pointer with i+1 and r with last index."
},
{
"code": null,
"e": 15615,
"s": 15549,
"text": "Now enter into a while loop which will run till the value of l<r."
},
{
"code": null,
"e": 15770,
"s": 15615,
"text": "If arr[i]+arr[l]+arr[r]>Target sum then decrement r by 1 as the required sum is less than the current sum and decreasing the value of will do the needful."
},
{
"code": null,
"e": 15925,
"s": 15770,
"text": "If arr[i]+arr[l]+arr[r]<Target sum then increment l by 1 as the required sum is less than the current sum and increasing the value of will do the needful."
},
{
"code": null,
"e": 15979,
"s": 15925,
"text": "If arr[i]+arr[l]+arr[r]==Target sum print the values."
},
{
"code": null,
"e": 16004,
"s": 15979,
"text": "Increment i Goto Step 3."
},
{
"code": null,
"e": 16020,
"s": 16004,
"text": "Pseudo Code : "
},
{
"code": null,
"e": 16414,
"s": 16020,
"text": "1. Sort all element of array\n2. Run loop from i=0 to n-2.\n Initialize two index variables l=i+1 and r=n-1\n4. while (l < r) \n Check sum of arr[i], arr[l], arr[r] is\n given sum or not if sum is 'sum', then print \n the triplet and do l++ and r--.\n5. If sum is less than given sum then l++\n6. If sum is greater than given sum then r--\n7. If not exist in array then print not found."
},
{
"code": null,
"e": 16418,
"s": 16414,
"text": "C++"
},
{
"code": null,
"e": 16423,
"s": 16418,
"text": "Java"
},
{
"code": null,
"e": 16431,
"s": 16423,
"text": "Python3"
},
{
"code": null,
"e": 16434,
"s": 16431,
"text": "C#"
},
{
"code": null,
"e": 16438,
"s": 16434,
"text": "PHP"
},
{
"code": null,
"e": 16449,
"s": 16438,
"text": "Javascript"
},
{
"code": "// C++ program to find triplets in a given// array whose sum is given sum.#include <bits/stdc++.h>using namespace std; // Function to print triplets with given sum vector<vector<int>> findTriplets(int nums[],int n,int sumTarget) { vector<vector<int>> res; if(n <=2) return res; sort(nums,nums + n); for(int i=0;i<n;i++){ if(i>0 && nums[i] == nums[i-1]) // avoid duplicate triplets count continue; int num = nums[i]; int target = sumTarget - num; for(int l=i+1, r=n-1; l<r; ) { if(nums[l]+nums[r] > target) r--; else if (nums[l]+nums[r] < target) l++; else { // nums[l] + nums[r] == target res.push_back({nums[i], nums[l], nums[r]}); // skip duplicates while( l<n-1 && nums[l]==nums[l+1]) l++; while( r>0 && nums[r]==nums[r-1]) r--; l++; r--; } } } return res; }// Driver codeint main(){ int arr[] = { 0, -1, 2, -3, 1, -1, 3, 0}; int sum = -2; int n = sizeof(arr) / sizeof(arr[0]); vector<vector<int>> res = findTriplets(arr, n, sum); cout<<\"Unique triplets found are : \\n\"; for(int i = 0;i<res.size();i++) cout<<res[i][0]<<\" \"<<res[i][1]<<\" \"<<res[i][2]<<\"\\n\"; return 0;}",
"e": 18193,
"s": 16449,
"text": null
},
{
"code": "// Java program to find triplets// in a given array whose sum// is given sum.import java.io.*;import java.util.*; class GFG { // function to print // triplets with given sum static void findTriplets(int[] arr, int n, int sum) { // sort array elements Arrays.sort(arr); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. System.out.println( x + \" \" + arr[l] + \" \" + arr[r]); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } // Driver code public static void main(String args[]) { int[] arr = new int[] { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.length; findTriplets(arr, n, sum); }} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 19682,
"s": 18193,
"text": null
},
{
"code": "# Python3 program to find triplets in a# given array whose sum is given sum. # function to print triplets with# given sumdef findTriplets(arr, n, sum): # sort array elements arr.sort(); for i in range(0, n - 1): # initialize left and right l = i + 1; r = n - 1; x = arr[i]; while (l < r) : if (x + arr[l] + arr[r] == sum) : # print elements if it's sum # is given sum. print(x, arr[l], arr[r]); l = l + 1; r = r - 1; # If sum of three elements is less # than 'sum' then increment in left elif (x + arr[l] + arr[r] < sum): l = l + 1; # if sum is greater than given sum, # then decrement in right side else: r = r - 1; # Driver codearr = [ 0, -1, 2, -3, 1 ];sum = -2;n = len(arr);findTriplets(arr, n, sum); # This code is contributed by# Shivi_Aggarwal",
"e": 20709,
"s": 19682,
"text": null
},
{
"code": "// C# program to find triplets// in a given array whose sum// is given sum.using System; class GFG { // function to print // triplets with given sum static void findTriplets(int[] arr, int n, int sum) { // sort array elements Array.Sort(arr); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. Console.WriteLine(x + \" \" + arr[l] + \" \" + arr[r]); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } // Driver code static int Main() { int[] arr = new int[] { 0, -1, 2, -3, 1 }; int sum = -2; int n = arr.Length; findTriplets(arr, n, sum); return 0; }} // This code is contributed by rahul",
"e": 22088,
"s": 20709,
"text": null
},
{
"code": "<?php// PHP program to find triplets// in a given array whose sum// is given sum. // function to print triplets// with given sumfunction findTriplets($arr, $n, $sum){ // sort array elements sort($arr); for ($i = 0; $i < $n - 1; $i++) { // initialize left and right $l = $i + 1; $r = $n - 1; $x = $arr[$i]; while ($l < $r) { if ($x + $arr[$l] + $arr[$r] == $sum) { // print elements if it's // sum is given sum. echo $x, \" \", $arr[$l], \" \", $arr[$r], \"\\n\"; $l++; $r--; } // If sum of three elements // is less than 'sum' then // increment in left else if ($x + $arr[$l] + $arr[$r] < $sum) $l++; // if sum is greater // than given sum, then // decrement in right side else $r--; } }} // Driver code$arr = array(0, -1, 2, -3, 1);$sum = -2;$n = sizeof($arr);findTriplets($arr, $n, $sum); // This code is contributed by ajit?>",
"e": 23262,
"s": 22088,
"text": null
},
{
"code": "<script> // Javascript program to find triplets // in a given array whose sum // is given sum. // function to print // triplets with given sum function findTriplets(arr, n, sum) { // sort array elements arr.sort(function(a, b){return a - b}); for (let i = 0; i < n - 1; i++) { // initialize left and right let l = i + 1; let r = n - 1; let x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == sum) { // print elements if it's // sum is given sum. document.write(x + \" \" + arr[l] + \" \" + arr[r] + \"</br>\"); l++; r--; } // If sum of three elements // is less than 'sum' then // increment in left else if (x + arr[l] + arr[r] < sum) l++; // if sum is greater than // given sum, then decrement // in right side else r--; } } } let arr = [ 0, -1, 2, -3, 1 ]; let sum = -2; let n = arr.length; findTriplets(arr, n, sum); // This code is contributed by rameshtravel07.</script>",
"e": 24603,
"s": 23262,
"text": null
},
{
"code": null,
"e": 24618,
"s": 24603,
"text": "-3 -1 2\n-3 0 1"
},
{
"code": null,
"e": 24642,
"s": 24620,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 24777,
"s": 24642,
"text": "Time Complexity: O(n2). Use of a nested loop (one for iterating, other for two-pointer technique) brings the time complexity to O(n2)."
},
{
"code": null,
"e": 24848,
"s": 24777,
"text": "Auxiliary Space: O(1). As no use of additional data structure is used."
},
{
"code": null,
"e": 24856,
"s": 24850,
"text": "jit_t"
},
{
"code": null,
"e": 24877,
"s": 24856,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 24897,
"s": 24877,
"text": "mithunkumarmnnit321"
},
{
"code": null,
"e": 24910,
"s": 24897,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 24925,
"s": 24910,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 24940,
"s": 24925,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 24950,
"s": 24940,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 24963,
"s": 24950,
"text": "princi singh"
},
{
"code": null,
"e": 24975,
"s": 24963,
"text": "bidibaaz123"
},
{
"code": null,
"e": 24991,
"s": 24975,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 25002,
"s": 24991,
"text": "RahulJain6"
},
{
"code": null,
"e": 25017,
"s": 25002,
"text": "rameshtravel07"
},
{
"code": null,
"e": 25029,
"s": 25017,
"text": "unknown2108"
},
{
"code": null,
"e": 25045,
"s": 25029,
"text": "simranarora5sos"
},
{
"code": null,
"e": 25058,
"s": 25045,
"text": "simmytarika5"
},
{
"code": null,
"e": 25065,
"s": 25058,
"text": "Arrays"
},
{
"code": null,
"e": 25070,
"s": 25065,
"text": "Hash"
},
{
"code": null,
"e": 25080,
"s": 25070,
"text": "Searching"
},
{
"code": null,
"e": 25088,
"s": 25080,
"text": "Sorting"
},
{
"code": null,
"e": 25095,
"s": 25088,
"text": "Arrays"
},
{
"code": null,
"e": 25105,
"s": 25095,
"text": "Searching"
},
{
"code": null,
"e": 25110,
"s": 25105,
"text": "Hash"
},
{
"code": null,
"e": 25118,
"s": 25110,
"text": "Sorting"
}
] |
14 Lesser-Known Impressive Features of Scikit Learn Library | by Davis David | Towards Data Science
|
Scikit learn remains one of the most popular open-source and machine learning library in the world of Artificial Intelligence. The scikit-learn library contains a lot of efficient tools for machine learning and statistical modeling including classification, regression, clustering, and dimensionality reduction.
Scikit-learn is largely written in Python programming language and some core algorithms are written in Cython to improve its performance. It also integrates well with many other Python libraries, such as matplotlib and Plotly for plotting, NumPy for array vectorization, pandas dataframes, scipy, and many more.
Scikit-learn comes loaded with a lot of features. Here are a few of them
Datasets
Feature extraction
Feature selection
Parameter Tuning
Clustering
Cross-Validation
Supervised Models
Unsupervised Models
Dimensionality Reduction
Ensemble methods
Scikit learn has more than 1770 contributors and 41.2k stars on its GitHub repository, this means many data scientists, machine learning engineers and researchers rely on this library for machine learning projects.
I personally love using the scikit learn library because it offers a ton of flexibility and it’s easy to understand documentation with a lot of examples. In this article, I’m happy to share with you lesser-known impressive features in the scikit learn library that you did not exist.
If you want to duplicate an estimator and use it on another dataset clone function can help you do that. A clone function helps you to constructs a new estimator with the same parameters.
“Clone does a deep copy of the model in an estimator without actually copying the attached data. It yields a new estimator with the same parameters that have not been fit on any data.”- scikit learn documentation
Example:
We start by creating a classification dataset and estimators.
from sklearn.linear_model import LogisticRegressionfrom sklearn.datasets import make_classification# create dataset`X1, y1 = make_classification(n_classes=2, n_features=5, random_state=1)# create estimators logistic_classifier_1 = LogisticRegression()
Now we will use the clone function from sklearn.base to duplicate the logistic_classifier_1 model.
from sklearn.base import clone# duplicae the first classifier with clone function logistic_classifier_2 = clone(logistic_classifier_1)logistic_classifier_2
The output of the new estimator named logistic_classifier-2 cloned from logistic_classifier_1 is as follows.
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='auto', n_jobs=None, penalty='l2', random_state=None, solver='lbfgs', tol=0.0001, verbose=0, warm_start=False)
You can identify a model instance if it solves a classification or regression task in the scikit-learn library with two simple functions is_classifier and is_regressor. is_classifier function returns True if the given estimator is a classifier and is_regressor returns True if the given estimator is a Regressor.
Example:
Start by creating two estimators, the first one as regression and the second one as classification.
from sklearn.linear_model import LinearRegressionfrom sklearn.ensemble import RandomForestClassifier# create estimators model_1 = LinearRegression()model_2 = RandomForestClassifier()
Let check if the first model if regression.
# check if it regressorfrom sklearn.base import is_regressoris_regressor(model_1)
The output is True.
Now let check if the second model is classification.
# check if it classifier from sklearn.base import is_classifieris_classifier(model_2)
The output is True
Use make_column_selector with make_column_transformer to apply different preprocessing to different columns according to their data types (integers, categories) or column names.
Example:
In this example, we use make_column-_selector to select all object features in the dataset and transform them by using the OneHotEncoder method.
import numpy as np import pandas as pdfrom sklearn.preprocessing import StandardScaler, OneHotEncoderfrom sklearn.compose import make_column_transformerfrom sklearn.compose import make_column_selector# create a dataframe with different data typesdata = pd.DataFrame( {“gender”: [“male”, “female”, “female”, “male”], “age”: [23, 5, 11, 8]})# create a column transformer with make_column_selectorct = make_column_transformer( (StandardScaler(), make_column_selector(dtype_include=np.number)), # ages (OneHotEncoder(), make_column_selector(dtype_include=object)), # genders)transformed_data = ct.fit_transform(data)transformed_data
The output of the transformed data is:-
array([[ 1.6464639 , 0. , 1. ], [-0.98787834, 1. , 0. ], [-0.10976426, 1. , 0. ], [-0.5488213 , 0. , 1. ]])
You can visualize a decision tree model with plot_tree function. The plot function allows you to add features name with a parameter called feature_names.
Example:we start by creating a classification model for the iris dataset by using the Decision tree algorithm and then plot the decision tree.
# import librariesimport matplotlib.pyplot as plt from sklearn.model_selection import train_test_splitfrom sklearn.metrics import plot_confusion_matrixfrom sklearn.tree import DecisionTreeClassifier, plot_tree, export_text from sklearn.datasets import load_iris#load data iris = load_iris()# create our instancesmodel = DecisionTreeClassifier()# train test splitX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state = 0)# fit and predictmodel.fit(X_train, y_train)# plot the treeplt.figure(figsize = (20, 10))plot_tree(model,feature_names=iris.feature_names, filled = True) plt.show()
We passed the model and feature names in the plot_tree function to create a decision tree plot.
Openml is an online platform that aims at improving Open Machine Learning by providing an open, collaborative, frictionless, automated machine learning environment.
You can fetch the dataset from the openml platform by using fetch_openml function from scikit-learn.
Example:
Fetch bank-marketing dataset by using the name.
from sklearn.datasets import fetch_openml#fetch by using data namebank_marketing = fetch_openml(name=”bank-marketing”)# seperate independent variables and target variable x = bank_marketing.data y = bank_marketing.target
Access sample of the fetched dataset.
x[:2]
The output is
array([[ 5.800e+01, 4.000e+00, 1.000e+00, 2.000e+00, 0.000e+00, 2.143e+03, 1.000e+00, 0.000e+00, 2.000e+00, 5.000e+00, 8.000e+00, 2.610e+02, 1.000e+00, -1.000e+00, 0.000e+00, 3.000e+00], [ 4.400e+01, 9.000e+00, 2.000e+00, 1.000e+00, 0.000e+00, 2.900e+01, 1.000e+00, 0.000e+00, 2.000e+00, 5.000e+00, 8.000e+00, 1.510e+02, 1.000e+00, -1.000e+00, 0.000e+00, 3.000e+00]])
You can also fetch data by using the specified ID.
# fetch by using id from this link https://www.openml.org/d/1461bank_marketing = fetch_openml(data_id=1461)# seperate independent variables and target variable x = bank_marketing.data y = bank_marketing.target
In the example above we fetch data with an ID of 1461.
Learning curve function from scikit-learn let you determine the cross-validated training and test scores for different training set sizes.
“A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterward, the scores will be averaged over all k runs for each training subset size.” scikit learn documentation
Example:
from sklearn.datasets import make_classificationfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import learning_curve# create dataset`X, y = make_classification(n_classes=2, n_features=10, n_samples=5000, random_state=1)# create estimatorKNN_classifier = KNeighborsClassifier()#train_sizes, train_scores, test_scores = learning_curve(estimator = KNN_classifier,X = X,y = y,train_sizes=np.linspace(0.1, 1.0, 5),shuffle=True, cv = 5)
Show training size to generate a learning curve.
# the train sizetrain_sizes
The output is
array([ 400, 1300, 2200, 3100, 4000])
Show scores of the training sets.
# Scores on training setstrain_scores
The output is
array([[0.895 , 0.8875 , 0.85 , 0.8675 , 0.8975 ], [0.87384615, 0.88846154, 0.87692308, 0.88461538, 0.88230769], [0.88818182, 0.89363636, 0.88409091, 0.89045455, 0.88863636], [0.89354839, 0.89354839, 0.88903226, 0.88806452, 0.88387097], [0.893 , 0.894 , 0.88825 , 0.893 , 0.88625 ]])
Show validation scores
# show validation scorestest_scores
The output is
array([[0.83 , 0.812, 0.829, 0.841, 0.819], [0.837, 0.813, 0.853, 0.848, 0.828], [0.843, 0.823, 0.845, 0.853, 0.821], [0.832, 0.831, 0.855, 0.857, 0.83 ], [0.834, 0.828, 0.849, 0.86 , 0.835]])
let’s find the means of training scores and validation scores.
# find the mean of training scores and validation scores train_scores_mean = train_scores.mean(axis = 1)print(“Training Scores mean:{}”.format(train_scores_mean))test_scores_mean = test_scores.mean(axis = 1)print(“Test Scores mean:{}”.format(test_scores_mean))
The output is.
Training Scores mean:[0.8795 0.88123077 0.889 0.8896129 0.8909]Test Scores mean:[0.8262 0.8358 0.837 0.841 0.8412]
The below photo demonstrates how the data is split into k times and 5 cross-validations.
To learn more check another example here.
If you want to perform cross-validation and then prediction at the same time for your estimator, you can use cross_val_predict function from scikit-learn.
Example:
Perform cross_val_predict on the iris dataset.
from sklearn import datasets, linear_modelfrom sklearn.model_selection import cross_val_predictfrom sklearn.ensemble import RandomForestRegressor#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targetRF_regressor = RandomForestRegressor()# perfrom cross validation and predictiony_pred = cross_val_predict(estimator=RF_regressor, X= X, y=y, cv=5)
Show the first 10 predictions.
#show predictiony_pred[:10]
The output is:
array([225.41, 89.16, 172.4 , 164.03, 79.48, 116.87, 74.47, 157.5 ,155.99, 170.59])
Not all features presented in the dataset can useful for model performance, this means you can identify and select important features for your model by using SelectFromModel function. The function selects features based on importance weights. You can choose from a range of estimators but keep in mind that the estimator must have either a feature_importances_ or coef_ attribute after fitting.
SelectFromModel is a little less robust as it just removes less important features based on a threshold given as a parameter.
Example: Select important features from the diabetes dataset that contain 10 independent features.
from sklearn import datasets, linear_modelfrom sklearn.feature_selection import SelectFromModelfrom sklearn.linear_model import LogisticRegression#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targetlg_regressor = LogisticRegression()# identify and select important fatures by using SelectFromModelselector = SelectFromModel(estimator=lg_regressor).fit(X, y)#show estimator coefficient selector.estimator_.coef_
The output is as follows.
array([[-0.01631211, -0.04448689, -0.01041713, ..., -0.03925967, -0.02122777, -0.03405436], [ 0.00188878, -0.04444519, -0.00816801, ..., -0.03918144, -0.06436135, -0.05463903], [-0.02699287, -0.04433151, -0.06285579, ..., -0.0756844 , -0.05557734, -0.06683906], ..., [ 0.03415162, 0.05040128, 0.11077166, ..., -0.00292399, 0.027618 , 0.07302442], [ 0.03416799, 0.05030017, 0.12469165, ..., 0.10747183, -0.00019805, 0.02747969], [-0.04907612, -0.04462806, 0.16038187, ..., 0.0340123 , 0.02773604, 0.01114488]])
Show the threshold value used for feature selection.
# show the threshold valueselector.threshold_
The output is 12.197550946960686.
Now we can transform data with selected features.
transformed = selector.transform(X)transformed[:3]
The output is:-
array([[ 0.05068012, 0.06169621, 0.02187235, -0.04340085, -0.00259226, 0.01990842], [-0.04464164, -0.05147406, -0.02632783, 0.07441156, -0.03949338, -0.06832974], [ 0.05068012, 0.04445121, -0.00567061, -0.03235593, -0.00259226, 0.00286377]])
The dataset has been transformed from 10 features to 6 important features.
Apply function from pandas has been used to process data in Dataframe from one shape to another but is not useful if you want to use it in the pipeline.FunctionTransformer function can help you to add feature/variable transformation in your pipeline.
the FunctionTransformer provides some standard methods of other sklearn estimators (e.g., fit and transform).
Example:
Transform an array into a natural logarithm by using the np.log() method.
import numpy as npfrom sklearn.preprocessing import FunctionTransformerX = np.array([[89,34,9, 1,5,87,54,22,67,44], [12, 63,67,2,9,45,81,54,22,73]])#create FunctionTransformerlog_transformer = FunctionTransformer(np.log)#transform the datalog_transformer.transform(X)
The output after the transformation.
array([[4.48863637, 3.52636052, 2.19722458, 0. , 1.60943791, 4.46590812, 3.98898405, 3.09104245, 4.20469262, 3.78418963], [2.48490665, 4.14313473, 4.20469262, 0.69314718, 2.19722458, 3.80666249, 4.39444915, 3.98898405, 3.09104245, 4.29045944]])
In supervised machine learning tasks/problems, we have independent variables and the target variable. You also need to know the data type of the target variable to select which path are you going to use to solve the problem either regression or classification task. You can use the type_of_target function to check the type of data indicated by the target variable.
Example:Determine the type of target variable in the diabetes dataset.
from sklearn.utils.multiclass import type_of_targetfrom skearn import datasets#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targettype_of_target(y)
The output is ‘multiclass’.
You can add dummy features in your data with a specific value by using add_dummy_feature function.
“This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly.” scikit-learn documentation
Example:
The dataset object and dummy feature value(e.g 5) will be passed on the add_dummy-feature function to create a new dummy feature in our dataset.
import numpy as np from sklearn.preprocessing import add_dummy_featurep = np.array([[89,34], [12, 63]])add_dummy_feature(p, value=5)
A value of 5 will be added in each row in our p array.
array([[ 5., 89., 34.], [ 5., 12., 63.]])
Most of the time we use simple methods to impute missing values in our datasets. Methods like the mean/median for numerical features and mode for categorical features. You can also use advanced methods such as IterativeImputer.
IterativeImputer uses all features available in your dataset to estimate the missing values by using a machine learning model such as BayesianRidge.This means feature with missing values will be labeled as the dependent variable and other features will be independent variables.
Example:
import numpy as npfrom sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer# Create dataset with missing valuesdata = [[61, 22, 43,np.nan,67], [np.nan, 6, 27, 8, 11], [83, 51, np.nan, 32, 9], [74, np.nan, 35, 26, 97], [np.nan, 4, 13,45, 33]]
Now we can impute missing values with iterativeImputer function.
# Impute missing values using iterative imputeriter_imp = IterativeImputer(random_state= 42)iter_imp.fit_transform(data)
The output with no missing values:
The RandomizeSearchCV function tends to train and evaluates a series of models by taking a random number of a predetermined set of hyperparameter distributions. The function picks the most successful version of the model with the best parameters’s values after training N different versions of the model with different randomly selected hyperparameter combinations. This allows you to explicitly control the number of parameter combinations that are attempted.
Example:Creating a random search to find the best parameters of the XGBoost algorithm to classify iris into 3 classes.
from sklearn import linear_model, datasetsfrom sklearn.model_selection import RandomizedSearchCVfrom xgboost import XGBClassifierfrom scipy.stats import randint# Load datairis = datasets.load_iris()X = iris.datay = iris.target# create modelclassifier = XGBClassifier()# Create Hyperparameter Search Spaceparam_dist = { # randomly sample numbers from 50 to 400 estimators “n_estimators”: randint(50,400), “learning_rate”: [0.01, 0.03, 0.05], “subsample”: [0.5, 0.7], “max_depth”: [3, 4, 5], “min_child_weight”: [1, 2, 3],}# create random search# Create randomized search 5-fold cross validation and 100 iterationsclf = RandomizedSearchCV( estimator=classifier, param_distributions=param_dist, random_state=1, n_iter=100, cv=5, verbose=0, n_jobs=-1,)# Fit randomized searchbest_model = clf.fit(X, y)
After running a random search we can observe the best parameter’s values to increase model performance.
# View best hyperparametersprint(‘Best n_estimator:’, best_model.best_estimator_.get_params()[‘n_estimators’])print(‘Best learning_rate:’, best_model.best_estimator_.get_params()[‘learning_rate’])print(‘Best subsample:’, best_model.best_estimator_.get_params()[‘subsample’])print(‘Best max_depth:’, best_model.best_estimator_.get_params()[‘max_depth’])print(‘Best min_child_weight:’, best_model.best_estimator_.get_params()[‘min_child_weight’])
The output:
Best n_estimator: 259Best learning_rate: 0.03Best subsample: 0.5Best max_depth: 3Best min_child_weight: 1
Sometime RandomizedSearchCV will not provide the accurate result(s) as GridSearchCV, but when you have large data sets GridSearchCV will greatly slow down computation time and be very costly. In this instance, it is advised to use Randomized Search because you can define the number of iterations you want to runs.
If you want to load text files in scikit learn you can use load_files function. The load_files will treat each folder inside the root/main folder as one category and all the documents inside that folder will be assigned its corresponding category.
Example:Load data from a folder named news_report.
from sklearn.datasets import load_filesnews_reports = load_files( container_path=”news_report/”, description=”News reports in 2020", load_content=True,)
From the load_files function, we passed the name of the folder in the parameter called container_path.
Note: You can also use the ‘encoding’ parameter to specify the encoding of the text when you set load_content=True.
Now we can identify the targeted name with target_names attributes.
# show target names news_reports.target_names
The output will be.
['business', 'healthy', 'international', 'sport']
You can also specify the independent variable and the target variable by using two attributes called data and target.
# specify the independent variable and the target variable X = news_reports.datay = news_reports.target
As I said scikit-learn remains one the most popular open-source and machine learning library, with all features available you can do an end to end machine learning project. You can also implement scikit learn impressive features presented in this article in your machine learning project.
If you want to learn more about scikit-learn I recommend you take this free online course from AnalyticVidhya
You can download the notebook contains all 14 features presented in this article here.
github.com
If you learned something new or enjoyed reading this article, please share it so that others can see it. Feel free to leave a comment too. Till then, see you in the next post! I can also be reached on Twitter @Davis_McDavid.
One last thing: Read more articles like this in the following links.
|
[
{
"code": null,
"e": 484,
"s": 172,
"text": "Scikit learn remains one of the most popular open-source and machine learning library in the world of Artificial Intelligence. The scikit-learn library contains a lot of efficient tools for machine learning and statistical modeling including classification, regression, clustering, and dimensionality reduction."
},
{
"code": null,
"e": 796,
"s": 484,
"text": "Scikit-learn is largely written in Python programming language and some core algorithms are written in Cython to improve its performance. It also integrates well with many other Python libraries, such as matplotlib and Plotly for plotting, NumPy for array vectorization, pandas dataframes, scipy, and many more."
},
{
"code": null,
"e": 869,
"s": 796,
"text": "Scikit-learn comes loaded with a lot of features. Here are a few of them"
},
{
"code": null,
"e": 878,
"s": 869,
"text": "Datasets"
},
{
"code": null,
"e": 897,
"s": 878,
"text": "Feature extraction"
},
{
"code": null,
"e": 915,
"s": 897,
"text": "Feature selection"
},
{
"code": null,
"e": 932,
"s": 915,
"text": "Parameter Tuning"
},
{
"code": null,
"e": 943,
"s": 932,
"text": "Clustering"
},
{
"code": null,
"e": 960,
"s": 943,
"text": "Cross-Validation"
},
{
"code": null,
"e": 978,
"s": 960,
"text": "Supervised Models"
},
{
"code": null,
"e": 998,
"s": 978,
"text": "Unsupervised Models"
},
{
"code": null,
"e": 1023,
"s": 998,
"text": "Dimensionality Reduction"
},
{
"code": null,
"e": 1040,
"s": 1023,
"text": "Ensemble methods"
},
{
"code": null,
"e": 1255,
"s": 1040,
"text": "Scikit learn has more than 1770 contributors and 41.2k stars on its GitHub repository, this means many data scientists, machine learning engineers and researchers rely on this library for machine learning projects."
},
{
"code": null,
"e": 1539,
"s": 1255,
"text": "I personally love using the scikit learn library because it offers a ton of flexibility and it’s easy to understand documentation with a lot of examples. In this article, I’m happy to share with you lesser-known impressive features in the scikit learn library that you did not exist."
},
{
"code": null,
"e": 1727,
"s": 1539,
"text": "If you want to duplicate an estimator and use it on another dataset clone function can help you do that. A clone function helps you to constructs a new estimator with the same parameters."
},
{
"code": null,
"e": 1940,
"s": 1727,
"text": "“Clone does a deep copy of the model in an estimator without actually copying the attached data. It yields a new estimator with the same parameters that have not been fit on any data.”- scikit learn documentation"
},
{
"code": null,
"e": 1949,
"s": 1940,
"text": "Example:"
},
{
"code": null,
"e": 2011,
"s": 1949,
"text": "We start by creating a classification dataset and estimators."
},
{
"code": null,
"e": 2263,
"s": 2011,
"text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.datasets import make_classification# create dataset`X1, y1 = make_classification(n_classes=2, n_features=5, random_state=1)# create estimators logistic_classifier_1 = LogisticRegression()"
},
{
"code": null,
"e": 2362,
"s": 2263,
"text": "Now we will use the clone function from sklearn.base to duplicate the logistic_classifier_1 model."
},
{
"code": null,
"e": 2518,
"s": 2362,
"text": "from sklearn.base import clone# duplicae the first classifier with clone function logistic_classifier_2 = clone(logistic_classifier_1)logistic_classifier_2"
},
{
"code": null,
"e": 2627,
"s": 2518,
"text": "The output of the new estimator named logistic_classifier-2 cloned from logistic_classifier_1 is as follows."
},
{
"code": null,
"e": 2949,
"s": 2627,
"text": "LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, l1_ratio=None, max_iter=100, multi_class='auto', n_jobs=None, penalty='l2', random_state=None, solver='lbfgs', tol=0.0001, verbose=0, warm_start=False)"
},
{
"code": null,
"e": 3262,
"s": 2949,
"text": "You can identify a model instance if it solves a classification or regression task in the scikit-learn library with two simple functions is_classifier and is_regressor. is_classifier function returns True if the given estimator is a classifier and is_regressor returns True if the given estimator is a Regressor."
},
{
"code": null,
"e": 3271,
"s": 3262,
"text": "Example:"
},
{
"code": null,
"e": 3371,
"s": 3271,
"text": "Start by creating two estimators, the first one as regression and the second one as classification."
},
{
"code": null,
"e": 3554,
"s": 3371,
"text": "from sklearn.linear_model import LinearRegressionfrom sklearn.ensemble import RandomForestClassifier# create estimators model_1 = LinearRegression()model_2 = RandomForestClassifier()"
},
{
"code": null,
"e": 3598,
"s": 3554,
"text": "Let check if the first model if regression."
},
{
"code": null,
"e": 3680,
"s": 3598,
"text": "# check if it regressorfrom sklearn.base import is_regressoris_regressor(model_1)"
},
{
"code": null,
"e": 3700,
"s": 3680,
"text": "The output is True."
},
{
"code": null,
"e": 3753,
"s": 3700,
"text": "Now let check if the second model is classification."
},
{
"code": null,
"e": 3839,
"s": 3753,
"text": "# check if it classifier from sklearn.base import is_classifieris_classifier(model_2)"
},
{
"code": null,
"e": 3858,
"s": 3839,
"text": "The output is True"
},
{
"code": null,
"e": 4036,
"s": 3858,
"text": "Use make_column_selector with make_column_transformer to apply different preprocessing to different columns according to their data types (integers, categories) or column names."
},
{
"code": null,
"e": 4045,
"s": 4036,
"text": "Example:"
},
{
"code": null,
"e": 4190,
"s": 4045,
"text": "In this example, we use make_column-_selector to select all object features in the dataset and transform them by using the OneHotEncoder method."
},
{
"code": null,
"e": 4819,
"s": 4190,
"text": "import numpy as np import pandas as pdfrom sklearn.preprocessing import StandardScaler, OneHotEncoderfrom sklearn.compose import make_column_transformerfrom sklearn.compose import make_column_selector# create a dataframe with different data typesdata = pd.DataFrame( {“gender”: [“male”, “female”, “female”, “male”], “age”: [23, 5, 11, 8]})# create a column transformer with make_column_selectorct = make_column_transformer( (StandardScaler(), make_column_selector(dtype_include=np.number)), # ages (OneHotEncoder(), make_column_selector(dtype_include=object)), # genders)transformed_data = ct.fit_transform(data)transformed_data"
},
{
"code": null,
"e": 4859,
"s": 4819,
"text": "The output of the transformed data is:-"
},
{
"code": null,
"e": 5049,
"s": 4859,
"text": "array([[ 1.6464639 , 0. , 1. ], [-0.98787834, 1. , 0. ], [-0.10976426, 1. , 0. ], [-0.5488213 , 0. , 1. ]])"
},
{
"code": null,
"e": 5203,
"s": 5049,
"text": "You can visualize a decision tree model with plot_tree function. The plot function allows you to add features name with a parameter called feature_names."
},
{
"code": null,
"e": 5346,
"s": 5203,
"text": "Example:we start by creating a classification model for the iris dataset by using the Decision tree algorithm and then plot the decision tree."
},
{
"code": null,
"e": 5966,
"s": 5346,
"text": "# import librariesimport matplotlib.pyplot as plt from sklearn.model_selection import train_test_splitfrom sklearn.metrics import plot_confusion_matrixfrom sklearn.tree import DecisionTreeClassifier, plot_tree, export_text from sklearn.datasets import load_iris#load data iris = load_iris()# create our instancesmodel = DecisionTreeClassifier()# train test splitX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state = 0)# fit and predictmodel.fit(X_train, y_train)# plot the treeplt.figure(figsize = (20, 10))plot_tree(model,feature_names=iris.feature_names, filled = True) plt.show()"
},
{
"code": null,
"e": 6062,
"s": 5966,
"text": "We passed the model and feature names in the plot_tree function to create a decision tree plot."
},
{
"code": null,
"e": 6227,
"s": 6062,
"text": "Openml is an online platform that aims at improving Open Machine Learning by providing an open, collaborative, frictionless, automated machine learning environment."
},
{
"code": null,
"e": 6328,
"s": 6227,
"text": "You can fetch the dataset from the openml platform by using fetch_openml function from scikit-learn."
},
{
"code": null,
"e": 6337,
"s": 6328,
"text": "Example:"
},
{
"code": null,
"e": 6385,
"s": 6337,
"text": "Fetch bank-marketing dataset by using the name."
},
{
"code": null,
"e": 6606,
"s": 6385,
"text": "from sklearn.datasets import fetch_openml#fetch by using data namebank_marketing = fetch_openml(name=”bank-marketing”)# seperate independent variables and target variable x = bank_marketing.data y = bank_marketing.target"
},
{
"code": null,
"e": 6644,
"s": 6606,
"text": "Access sample of the fetched dataset."
},
{
"code": null,
"e": 6650,
"s": 6644,
"text": "x[:2]"
},
{
"code": null,
"e": 6664,
"s": 6650,
"text": "The output is"
},
{
"code": null,
"e": 7108,
"s": 6664,
"text": "array([[ 5.800e+01, 4.000e+00, 1.000e+00, 2.000e+00, 0.000e+00, 2.143e+03, 1.000e+00, 0.000e+00, 2.000e+00, 5.000e+00, 8.000e+00, 2.610e+02, 1.000e+00, -1.000e+00, 0.000e+00, 3.000e+00], [ 4.400e+01, 9.000e+00, 2.000e+00, 1.000e+00, 0.000e+00, 2.900e+01, 1.000e+00, 0.000e+00, 2.000e+00, 5.000e+00, 8.000e+00, 1.510e+02, 1.000e+00, -1.000e+00, 0.000e+00, 3.000e+00]])"
},
{
"code": null,
"e": 7159,
"s": 7108,
"text": "You can also fetch data by using the specified ID."
},
{
"code": null,
"e": 7369,
"s": 7159,
"text": "# fetch by using id from this link https://www.openml.org/d/1461bank_marketing = fetch_openml(data_id=1461)# seperate independent variables and target variable x = bank_marketing.data y = bank_marketing.target"
},
{
"code": null,
"e": 7424,
"s": 7369,
"text": "In the example above we fetch data with an ID of 1461."
},
{
"code": null,
"e": 7563,
"s": 7424,
"text": "Learning curve function from scikit-learn let you determine the cross-validated training and test scores for different training set sizes."
},
{
"code": null,
"e": 7927,
"s": 7563,
"text": "“A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterward, the scores will be averaged over all k runs for each training subset size.” scikit learn documentation"
},
{
"code": null,
"e": 7936,
"s": 7927,
"text": "Example:"
},
{
"code": null,
"e": 8399,
"s": 7936,
"text": "from sklearn.datasets import make_classificationfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import learning_curve# create dataset`X, y = make_classification(n_classes=2, n_features=10, n_samples=5000, random_state=1)# create estimatorKNN_classifier = KNeighborsClassifier()#train_sizes, train_scores, test_scores = learning_curve(estimator = KNN_classifier,X = X,y = y,train_sizes=np.linspace(0.1, 1.0, 5),shuffle=True, cv = 5)"
},
{
"code": null,
"e": 8448,
"s": 8399,
"text": "Show training size to generate a learning curve."
},
{
"code": null,
"e": 8476,
"s": 8448,
"text": "# the train sizetrain_sizes"
},
{
"code": null,
"e": 8490,
"s": 8476,
"text": "The output is"
},
{
"code": null,
"e": 8528,
"s": 8490,
"text": "array([ 400, 1300, 2200, 3100, 4000])"
},
{
"code": null,
"e": 8562,
"s": 8528,
"text": "Show scores of the training sets."
},
{
"code": null,
"e": 8600,
"s": 8562,
"text": "# Scores on training setstrain_scores"
},
{
"code": null,
"e": 8614,
"s": 8600,
"text": "The output is"
},
{
"code": null,
"e": 8956,
"s": 8614,
"text": "array([[0.895 , 0.8875 , 0.85 , 0.8675 , 0.8975 ], [0.87384615, 0.88846154, 0.87692308, 0.88461538, 0.88230769], [0.88818182, 0.89363636, 0.88409091, 0.89045455, 0.88863636], [0.89354839, 0.89354839, 0.88903226, 0.88806452, 0.88387097], [0.893 , 0.894 , 0.88825 , 0.893 , 0.88625 ]])"
},
{
"code": null,
"e": 8979,
"s": 8956,
"text": "Show validation scores"
},
{
"code": null,
"e": 9015,
"s": 8979,
"text": "# show validation scorestest_scores"
},
{
"code": null,
"e": 9029,
"s": 9015,
"text": "The output is"
},
{
"code": null,
"e": 9246,
"s": 9029,
"text": "array([[0.83 , 0.812, 0.829, 0.841, 0.819], [0.837, 0.813, 0.853, 0.848, 0.828], [0.843, 0.823, 0.845, 0.853, 0.821], [0.832, 0.831, 0.855, 0.857, 0.83 ], [0.834, 0.828, 0.849, 0.86 , 0.835]])"
},
{
"code": null,
"e": 9309,
"s": 9246,
"text": "let’s find the means of training scores and validation scores."
},
{
"code": null,
"e": 9570,
"s": 9309,
"text": "# find the mean of training scores and validation scores train_scores_mean = train_scores.mean(axis = 1)print(“Training Scores mean:{}”.format(train_scores_mean))test_scores_mean = test_scores.mean(axis = 1)print(“Test Scores mean:{}”.format(test_scores_mean))"
},
{
"code": null,
"e": 9585,
"s": 9570,
"text": "The output is."
},
{
"code": null,
"e": 9703,
"s": 9585,
"text": "Training Scores mean:[0.8795 0.88123077 0.889 0.8896129 0.8909]Test Scores mean:[0.8262 0.8358 0.837 0.841 0.8412]"
},
{
"code": null,
"e": 9792,
"s": 9703,
"text": "The below photo demonstrates how the data is split into k times and 5 cross-validations."
},
{
"code": null,
"e": 9834,
"s": 9792,
"text": "To learn more check another example here."
},
{
"code": null,
"e": 9989,
"s": 9834,
"text": "If you want to perform cross-validation and then prediction at the same time for your estimator, you can use cross_val_predict function from scikit-learn."
},
{
"code": null,
"e": 9998,
"s": 9989,
"text": "Example:"
},
{
"code": null,
"e": 10045,
"s": 9998,
"text": "Perform cross_val_predict on the iris dataset."
},
{
"code": null,
"e": 10420,
"s": 10045,
"text": "from sklearn import datasets, linear_modelfrom sklearn.model_selection import cross_val_predictfrom sklearn.ensemble import RandomForestRegressor#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targetRF_regressor = RandomForestRegressor()# perfrom cross validation and predictiony_pred = cross_val_predict(estimator=RF_regressor, X= X, y=y, cv=5)"
},
{
"code": null,
"e": 10451,
"s": 10420,
"text": "Show the first 10 predictions."
},
{
"code": null,
"e": 10479,
"s": 10451,
"text": "#show predictiony_pred[:10]"
},
{
"code": null,
"e": 10494,
"s": 10479,
"text": "The output is:"
},
{
"code": null,
"e": 10581,
"s": 10494,
"text": "array([225.41, 89.16, 172.4 , 164.03, 79.48, 116.87, 74.47, 157.5 ,155.99, 170.59])"
},
{
"code": null,
"e": 10976,
"s": 10581,
"text": "Not all features presented in the dataset can useful for model performance, this means you can identify and select important features for your model by using SelectFromModel function. The function selects features based on importance weights. You can choose from a range of estimators but keep in mind that the estimator must have either a feature_importances_ or coef_ attribute after fitting."
},
{
"code": null,
"e": 11102,
"s": 10976,
"text": "SelectFromModel is a little less robust as it just removes less important features based on a threshold given as a parameter."
},
{
"code": null,
"e": 11201,
"s": 11102,
"text": "Example: Select important features from the diabetes dataset that contain 10 independent features."
},
{
"code": null,
"e": 11643,
"s": 11201,
"text": "from sklearn import datasets, linear_modelfrom sklearn.feature_selection import SelectFromModelfrom sklearn.linear_model import LogisticRegression#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targetlg_regressor = LogisticRegression()# identify and select important fatures by using SelectFromModelselector = SelectFromModel(estimator=lg_regressor).fit(X, y)#show estimator coefficient selector.estimator_.coef_"
},
{
"code": null,
"e": 11669,
"s": 11643,
"text": "The output is as follows."
},
{
"code": null,
"e": 12270,
"s": 11669,
"text": "array([[-0.01631211, -0.04448689, -0.01041713, ..., -0.03925967, -0.02122777, -0.03405436], [ 0.00188878, -0.04444519, -0.00816801, ..., -0.03918144, -0.06436135, -0.05463903], [-0.02699287, -0.04433151, -0.06285579, ..., -0.0756844 , -0.05557734, -0.06683906], ..., [ 0.03415162, 0.05040128, 0.11077166, ..., -0.00292399, 0.027618 , 0.07302442], [ 0.03416799, 0.05030017, 0.12469165, ..., 0.10747183, -0.00019805, 0.02747969], [-0.04907612, -0.04462806, 0.16038187, ..., 0.0340123 , 0.02773604, 0.01114488]])"
},
{
"code": null,
"e": 12323,
"s": 12270,
"text": "Show the threshold value used for feature selection."
},
{
"code": null,
"e": 12369,
"s": 12323,
"text": "# show the threshold valueselector.threshold_"
},
{
"code": null,
"e": 12403,
"s": 12369,
"text": "The output is 12.197550946960686."
},
{
"code": null,
"e": 12453,
"s": 12403,
"text": "Now we can transform data with selected features."
},
{
"code": null,
"e": 12504,
"s": 12453,
"text": "transformed = selector.transform(X)transformed[:3]"
},
{
"code": null,
"e": 12520,
"s": 12504,
"text": "The output is:-"
},
{
"code": null,
"e": 12801,
"s": 12520,
"text": "array([[ 0.05068012, 0.06169621, 0.02187235, -0.04340085, -0.00259226, 0.01990842], [-0.04464164, -0.05147406, -0.02632783, 0.07441156, -0.03949338, -0.06832974], [ 0.05068012, 0.04445121, -0.00567061, -0.03235593, -0.00259226, 0.00286377]])"
},
{
"code": null,
"e": 12876,
"s": 12801,
"text": "The dataset has been transformed from 10 features to 6 important features."
},
{
"code": null,
"e": 13127,
"s": 12876,
"text": "Apply function from pandas has been used to process data in Dataframe from one shape to another but is not useful if you want to use it in the pipeline.FunctionTransformer function can help you to add feature/variable transformation in your pipeline."
},
{
"code": null,
"e": 13237,
"s": 13127,
"text": "the FunctionTransformer provides some standard methods of other sklearn estimators (e.g., fit and transform)."
},
{
"code": null,
"e": 13246,
"s": 13237,
"text": "Example:"
},
{
"code": null,
"e": 13320,
"s": 13246,
"text": "Transform an array into a natural logarithm by using the np.log() method."
},
{
"code": null,
"e": 13588,
"s": 13320,
"text": "import numpy as npfrom sklearn.preprocessing import FunctionTransformerX = np.array([[89,34,9, 1,5,87,54,22,67,44], [12, 63,67,2,9,45,81,54,22,73]])#create FunctionTransformerlog_transformer = FunctionTransformer(np.log)#transform the datalog_transformer.transform(X)"
},
{
"code": null,
"e": 13625,
"s": 13588,
"text": "The output after the transformation."
},
{
"code": null,
"e": 13897,
"s": 13625,
"text": "array([[4.48863637, 3.52636052, 2.19722458, 0. , 1.60943791, 4.46590812, 3.98898405, 3.09104245, 4.20469262, 3.78418963], [2.48490665, 4.14313473, 4.20469262, 0.69314718, 2.19722458, 3.80666249, 4.39444915, 3.98898405, 3.09104245, 4.29045944]])"
},
{
"code": null,
"e": 14263,
"s": 13897,
"text": "In supervised machine learning tasks/problems, we have independent variables and the target variable. You also need to know the data type of the target variable to select which path are you going to use to solve the problem either regression or classification task. You can use the type_of_target function to check the type of data indicated by the target variable."
},
{
"code": null,
"e": 14334,
"s": 14263,
"text": "Example:Determine the type of target variable in the diabetes dataset."
},
{
"code": null,
"e": 14513,
"s": 14334,
"text": "from sklearn.utils.multiclass import type_of_targetfrom skearn import datasets#load dataetdiabetes = datasets.load_diabetes()X = diabetes.datay = diabetes.targettype_of_target(y)"
},
{
"code": null,
"e": 14541,
"s": 14513,
"text": "The output is ‘multiclass’."
},
{
"code": null,
"e": 14640,
"s": 14541,
"text": "You can add dummy features in your data with a specific value by using add_dummy_feature function."
},
{
"code": null,
"e": 14775,
"s": 14640,
"text": "“This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly.” scikit-learn documentation"
},
{
"code": null,
"e": 14784,
"s": 14775,
"text": "Example:"
},
{
"code": null,
"e": 14929,
"s": 14784,
"text": "The dataset object and dummy feature value(e.g 5) will be passed on the add_dummy-feature function to create a new dummy feature in our dataset."
},
{
"code": null,
"e": 15062,
"s": 14929,
"text": "import numpy as np from sklearn.preprocessing import add_dummy_featurep = np.array([[89,34], [12, 63]])add_dummy_feature(p, value=5)"
},
{
"code": null,
"e": 15117,
"s": 15062,
"text": "A value of 5 will be added in each row in our p array."
},
{
"code": null,
"e": 15165,
"s": 15117,
"text": "array([[ 5., 89., 34.], [ 5., 12., 63.]])"
},
{
"code": null,
"e": 15393,
"s": 15165,
"text": "Most of the time we use simple methods to impute missing values in our datasets. Methods like the mean/median for numerical features and mode for categorical features. You can also use advanced methods such as IterativeImputer."
},
{
"code": null,
"e": 15672,
"s": 15393,
"text": "IterativeImputer uses all features available in your dataset to estimate the missing values by using a machine learning model such as BayesianRidge.This means feature with missing values will be labeled as the dependent variable and other features will be independent variables."
},
{
"code": null,
"e": 15681,
"s": 15672,
"text": "Example:"
},
{
"code": null,
"e": 15995,
"s": 15681,
"text": "import numpy as npfrom sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer# Create dataset with missing valuesdata = [[61, 22, 43,np.nan,67], [np.nan, 6, 27, 8, 11], [83, 51, np.nan, 32, 9], [74, np.nan, 35, 26, 97], [np.nan, 4, 13,45, 33]]"
},
{
"code": null,
"e": 16060,
"s": 15995,
"text": "Now we can impute missing values with iterativeImputer function."
},
{
"code": null,
"e": 16181,
"s": 16060,
"text": "# Impute missing values using iterative imputeriter_imp = IterativeImputer(random_state= 42)iter_imp.fit_transform(data)"
},
{
"code": null,
"e": 16216,
"s": 16181,
"text": "The output with no missing values:"
},
{
"code": null,
"e": 16677,
"s": 16216,
"text": "The RandomizeSearchCV function tends to train and evaluates a series of models by taking a random number of a predetermined set of hyperparameter distributions. The function picks the most successful version of the model with the best parameters’s values after training N different versions of the model with different randomly selected hyperparameter combinations. This allows you to explicitly control the number of parameter combinations that are attempted."
},
{
"code": null,
"e": 16796,
"s": 16677,
"text": "Example:Creating a random search to find the best parameters of the XGBoost algorithm to classify iris into 3 classes."
},
{
"code": null,
"e": 17594,
"s": 16796,
"text": "from sklearn import linear_model, datasetsfrom sklearn.model_selection import RandomizedSearchCVfrom xgboost import XGBClassifierfrom scipy.stats import randint# Load datairis = datasets.load_iris()X = iris.datay = iris.target# create modelclassifier = XGBClassifier()# Create Hyperparameter Search Spaceparam_dist = { # randomly sample numbers from 50 to 400 estimators “n_estimators”: randint(50,400), “learning_rate”: [0.01, 0.03, 0.05], “subsample”: [0.5, 0.7], “max_depth”: [3, 4, 5], “min_child_weight”: [1, 2, 3],}# create random search# Create randomized search 5-fold cross validation and 100 iterationsclf = RandomizedSearchCV( estimator=classifier, param_distributions=param_dist, random_state=1, n_iter=100, cv=5, verbose=0, n_jobs=-1,)# Fit randomized searchbest_model = clf.fit(X, y)"
},
{
"code": null,
"e": 17698,
"s": 17594,
"text": "After running a random search we can observe the best parameter’s values to increase model performance."
},
{
"code": null,
"e": 18143,
"s": 17698,
"text": "# View best hyperparametersprint(‘Best n_estimator:’, best_model.best_estimator_.get_params()[‘n_estimators’])print(‘Best learning_rate:’, best_model.best_estimator_.get_params()[‘learning_rate’])print(‘Best subsample:’, best_model.best_estimator_.get_params()[‘subsample’])print(‘Best max_depth:’, best_model.best_estimator_.get_params()[‘max_depth’])print(‘Best min_child_weight:’, best_model.best_estimator_.get_params()[‘min_child_weight’])"
},
{
"code": null,
"e": 18155,
"s": 18143,
"text": "The output:"
},
{
"code": null,
"e": 18261,
"s": 18155,
"text": "Best n_estimator: 259Best learning_rate: 0.03Best subsample: 0.5Best max_depth: 3Best min_child_weight: 1"
},
{
"code": null,
"e": 18576,
"s": 18261,
"text": "Sometime RandomizedSearchCV will not provide the accurate result(s) as GridSearchCV, but when you have large data sets GridSearchCV will greatly slow down computation time and be very costly. In this instance, it is advised to use Randomized Search because you can define the number of iterations you want to runs."
},
{
"code": null,
"e": 18824,
"s": 18576,
"text": "If you want to load text files in scikit learn you can use load_files function. The load_files will treat each folder inside the root/main folder as one category and all the documents inside that folder will be assigned its corresponding category."
},
{
"code": null,
"e": 18875,
"s": 18824,
"text": "Example:Load data from a folder named news_report."
},
{
"code": null,
"e": 19028,
"s": 18875,
"text": "from sklearn.datasets import load_filesnews_reports = load_files( container_path=”news_report/”, description=”News reports in 2020\", load_content=True,)"
},
{
"code": null,
"e": 19131,
"s": 19028,
"text": "From the load_files function, we passed the name of the folder in the parameter called container_path."
},
{
"code": null,
"e": 19247,
"s": 19131,
"text": "Note: You can also use the ‘encoding’ parameter to specify the encoding of the text when you set load_content=True."
},
{
"code": null,
"e": 19315,
"s": 19247,
"text": "Now we can identify the targeted name with target_names attributes."
},
{
"code": null,
"e": 19361,
"s": 19315,
"text": "# show target names news_reports.target_names"
},
{
"code": null,
"e": 19381,
"s": 19361,
"text": "The output will be."
},
{
"code": null,
"e": 19431,
"s": 19381,
"text": "['business', 'healthy', 'international', 'sport']"
},
{
"code": null,
"e": 19549,
"s": 19431,
"text": "You can also specify the independent variable and the target variable by using two attributes called data and target."
},
{
"code": null,
"e": 19653,
"s": 19549,
"text": "# specify the independent variable and the target variable X = news_reports.datay = news_reports.target"
},
{
"code": null,
"e": 19942,
"s": 19653,
"text": "As I said scikit-learn remains one the most popular open-source and machine learning library, with all features available you can do an end to end machine learning project. You can also implement scikit learn impressive features presented in this article in your machine learning project."
},
{
"code": null,
"e": 20052,
"s": 19942,
"text": "If you want to learn more about scikit-learn I recommend you take this free online course from AnalyticVidhya"
},
{
"code": null,
"e": 20139,
"s": 20052,
"text": "You can download the notebook contains all 14 features presented in this article here."
},
{
"code": null,
"e": 20150,
"s": 20139,
"text": "github.com"
},
{
"code": null,
"e": 20375,
"s": 20150,
"text": "If you learned something new or enjoyed reading this article, please share it so that others can see it. Feel free to leave a comment too. Till then, see you in the next post! I can also be reached on Twitter @Davis_McDavid."
}
] |
GATE | GATE CS Mock 2018 | Set 2 | Question 42 - GeeksforGeeks
|
08 Mar, 2018
S1 : Anyone of the followings can be used to declare a node for a singly linked list. If we use the first declaration, “struct node * nodePtr;” would be used to declare pointer to a node. If we use the second declaration, “NODEPTR nodePtr;” can be used to declare pointer to a node.
/* First declaration */
struct node {
int data;
struct node * nextPtr;
};
/* Second declaration */
typedef struct node{
int data;
NODEPTR nextPtr;
} * NODEPTR;
S2 : Anyone of the following can be used to declare a node for a singly linked list and “NODEPTR nodePtr;” can be used to declare pointer to a node using any of the following
/* First declaration */
typedef struct node
{
int data;
struct node *nextPtr;
}* NODEPTR;
/* Second declaration */
struct node
{
int data;
struct node * nextPtr;
};
typedef struct node * NODEPTR;
(A) Statement S1 is true and statement S2 is false(B) Statement S2 is true and statement S1 is false(C) Both statements S1 and S2 are true(D) Neither statement S1 nor statement S2 is trueAnswer: (B)Explanation: S1 : The typedef usage is incorrect. Basically, we can’t use yet to be typedef-ed data type inside while applying typedef itself. Here, NODEPTR is yet to be defined (i.e. typedef-ed) and we are using NODEPTR inside the struct itself.
S2 : Yes. Both are equivalent. Either of the above declarations can be used for “NODEPTR nodePtr;”. In fact, first one is the compact form of second one.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25831,
"s": 25803,
"text": "\n08 Mar, 2018"
},
{
"code": null,
"e": 26114,
"s": 25831,
"text": "S1 : Anyone of the followings can be used to declare a node for a singly linked list. If we use the first declaration, “struct node * nodePtr;” would be used to declare pointer to a node. If we use the second declaration, “NODEPTR nodePtr;” can be used to declare pointer to a node."
},
{
"code": null,
"e": 26276,
"s": 26114,
"text": "/* First declaration */\nstruct node {\nint data;\nstruct node * nextPtr;\n};\n\n/* Second declaration */\ntypedef struct node{\nint data;\nNODEPTR nextPtr;\n} * NODEPTR;\n"
},
{
"code": null,
"e": 26451,
"s": 26276,
"text": "S2 : Anyone of the following can be used to declare a node for a singly linked list and “NODEPTR nodePtr;” can be used to declare pointer to a node using any of the following"
},
{
"code": null,
"e": 26653,
"s": 26451,
"text": "/* First declaration */\ntypedef struct node\n{\n int data;\n struct node *nextPtr;\n}* NODEPTR;\n\n/* Second declaration */\nstruct node\n{\n int data;\n struct node * nextPtr;\n};\ntypedef struct node * NODEPTR;\n"
},
{
"code": null,
"e": 27098,
"s": 26653,
"text": "(A) Statement S1 is true and statement S2 is false(B) Statement S2 is true and statement S1 is false(C) Both statements S1 and S2 are true(D) Neither statement S1 nor statement S2 is trueAnswer: (B)Explanation: S1 : The typedef usage is incorrect. Basically, we can’t use yet to be typedef-ed data type inside while applying typedef itself. Here, NODEPTR is yet to be defined (i.e. typedef-ed) and we are using NODEPTR inside the struct itself."
},
{
"code": null,
"e": 27273,
"s": 27098,
"text": "S2 : Yes. Both are equivalent. Either of the above declarations can be used for “NODEPTR nodePtr;”. In fact, first one is the compact form of second one.Quiz of this Question"
},
{
"code": null,
"e": 27278,
"s": 27273,
"text": "GATE"
},
{
"code": null,
"e": 27376,
"s": 27278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27410,
"s": 27376,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27444,
"s": 27410,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27478,
"s": 27444,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27511,
"s": 27478,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27547,
"s": 27511,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27581,
"s": 27547,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27617,
"s": 27581,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27651,
"s": 27617,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27685,
"s": 27651,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
journalctl Command in Linux with Examples
|
10 Feb, 2022
journalctl command in Linux is used to view systemd, kernel and journal logs. The logs are presented in the following way:
-- Logs begin at [date_time_stamp], end at [dat_time_stamp]
[date_time_stamp] [host_name] kernel:
It displays the paginated output, hence it is a bit easy to navigate through a lot of logs. It prints the log in the chronological order with the oldest first.
1. To display all logs
$journalctl
It displays all the logs in the paginated view.
2. To reverse the order or to display the new entries first.
$journalctl -r
This will display the logs in the chronological order with the newest first.
3. To display only a few log entries
$journalctl -n 2
This will display just 2 log entries.
4. To get log entries containing a specific keyword.
$journalctl | grep Centaur
This will display all the entries containing the word Centaur in them.
5. To display priority specific log entries.
$journalctl -p warning
It displays all log entries with priority as a warning.
6. To print verbose customized output.
$journalctl -o verbose
This will display the formatted output in verbose mode.
7. To display the boots of the system.
$journalctl --list-boots
To display all the boots of the system.
8. To display journalctl help.
$journalctl --help
The above command will display the help section of the journalctl command.
rkbhola5
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "journalctl command in Linux is used to view systemd, kernel and journal logs. The logs are presented in the following way:"
},
{
"code": null,
"e": 250,
"s": 151,
"text": "-- Logs begin at [date_time_stamp], end at [dat_time_stamp]\n[date_time_stamp] [host_name] kernel:\n"
},
{
"code": null,
"e": 410,
"s": 250,
"text": "It displays the paginated output, hence it is a bit easy to navigate through a lot of logs. It prints the log in the chronological order with the oldest first."
},
{
"code": null,
"e": 433,
"s": 410,
"text": "1. To display all logs"
},
{
"code": null,
"e": 446,
"s": 433,
"text": "$journalctl\n"
},
{
"code": null,
"e": 494,
"s": 446,
"text": "It displays all the logs in the paginated view."
},
{
"code": null,
"e": 555,
"s": 494,
"text": "2. To reverse the order or to display the new entries first."
},
{
"code": null,
"e": 571,
"s": 555,
"text": "$journalctl -r\n"
},
{
"code": null,
"e": 648,
"s": 571,
"text": "This will display the logs in the chronological order with the newest first."
},
{
"code": null,
"e": 685,
"s": 648,
"text": "3. To display only a few log entries"
},
{
"code": null,
"e": 703,
"s": 685,
"text": "$journalctl -n 2\n"
},
{
"code": null,
"e": 741,
"s": 703,
"text": "This will display just 2 log entries."
},
{
"code": null,
"e": 794,
"s": 741,
"text": "4. To get log entries containing a specific keyword."
},
{
"code": null,
"e": 822,
"s": 794,
"text": "$journalctl | grep Centaur\n"
},
{
"code": null,
"e": 893,
"s": 822,
"text": "This will display all the entries containing the word Centaur in them."
},
{
"code": null,
"e": 938,
"s": 893,
"text": "5. To display priority specific log entries."
},
{
"code": null,
"e": 962,
"s": 938,
"text": "$journalctl -p warning\n"
},
{
"code": null,
"e": 1018,
"s": 962,
"text": "It displays all log entries with priority as a warning."
},
{
"code": null,
"e": 1057,
"s": 1018,
"text": "6. To print verbose customized output."
},
{
"code": null,
"e": 1081,
"s": 1057,
"text": "$journalctl -o verbose\n"
},
{
"code": null,
"e": 1137,
"s": 1081,
"text": "This will display the formatted output in verbose mode."
},
{
"code": null,
"e": 1176,
"s": 1137,
"text": "7. To display the boots of the system."
},
{
"code": null,
"e": 1202,
"s": 1176,
"text": "$journalctl --list-boots\n"
},
{
"code": null,
"e": 1242,
"s": 1202,
"text": "To display all the boots of the system."
},
{
"code": null,
"e": 1273,
"s": 1242,
"text": "8. To display journalctl help."
},
{
"code": null,
"e": 1293,
"s": 1273,
"text": "$journalctl --help\n"
},
{
"code": null,
"e": 1368,
"s": 1293,
"text": "The above command will display the help section of the journalctl command."
},
{
"code": null,
"e": 1377,
"s": 1368,
"text": "rkbhola5"
},
{
"code": null,
"e": 1391,
"s": 1377,
"text": "linux-command"
},
{
"code": null,
"e": 1413,
"s": 1391,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1424,
"s": 1413,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1522,
"s": 1424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1548,
"s": 1522,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1583,
"s": 1548,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1620,
"s": 1583,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1649,
"s": 1620,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1683,
"s": 1649,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1720,
"s": 1683,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1757,
"s": 1720,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1796,
"s": 1757,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1836,
"s": 1796,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
last command in Linux with Examples
|
22 May, 2019
The last command in Linux is used to display the list of all the users logged in and out since the file /var/log/wtmp was created. One or more usernames can be given as an argument to display their login in (and out) time and their host-name.
Syntax:
last [options] [username...] [tty...]
Example:
Options:
-[number]: This option is used to specify the number of lines to display.Example:last -5Output:
Example:
last -5
Output:
-R: This option is used to hide the host-name field.Example:last -R basil
Example:
last -R basil
-F: This option is used to display the login and logout time including the dates.Example:last -F
Example:
last -F
-a: This option is used is to display the host-name in the last column.Example:last -a
Example:
last -a
-s, -t: This option is used to display within a specific time period.(-s) since and (-t) until, these commands are used to frame the time period.Example:last -s yesterday -t todayThe valid formats for the above commands are:YYYYMMDDhhmmss
YYYY-MM-DD hh:mm:ss
YYYY-MM-DD hh:mm (seconds will be set to 00)
YYYY-MM-DD (time will be set to 00:00:00)
hh:mm:ss (date will be set to today)
hh:mm (date will be set to today, seconds to 00)
now
yesterday (time is set to 00:00:00)
today (time is set to 00:00:00)
tomorrow (time is set to 00:00:00)
+5min
-5days
Example:
last -s yesterday -t today
The valid formats for the above commands are:
YYYYMMDDhhmmss
YYYY-MM-DD hh:mm:ss
YYYY-MM-DD hh:mm (seconds will be set to 00)
YYYY-MM-DD (time will be set to 00:00:00)
hh:mm:ss (date will be set to today)
hh:mm (date will be set to today, seconds to 00)
now
yesterday (time is set to 00:00:00)
today (time is set to 00:00:00)
tomorrow (time is set to 00:00:00)
+5min
-5days
-d: This option is used to translate the IP address back into its host-name.Example:last -d
Example:
last -d
-x: This option is used to display information like system down entries and run level changes.Example:last -x
Example:
last -x
-w: This option is used to display full user and domain names.Example:last -w basil
Example:
last -w basil
–help: This option is used to display help regarding all options belonging to the last command.Syntax:last --help
Syntax:
last --help
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 271,
"s": 28,
"text": "The last command in Linux is used to display the list of all the users logged in and out since the file /var/log/wtmp was created. One or more usernames can be given as an argument to display their login in (and out) time and their host-name."
},
{
"code": null,
"e": 279,
"s": 271,
"text": "Syntax:"
},
{
"code": null,
"e": 317,
"s": 279,
"text": "last [options] [username...] [tty...]"
},
{
"code": null,
"e": 326,
"s": 317,
"text": "Example:"
},
{
"code": null,
"e": 335,
"s": 326,
"text": "Options:"
},
{
"code": null,
"e": 431,
"s": 335,
"text": "-[number]: This option is used to specify the number of lines to display.Example:last -5Output:"
},
{
"code": null,
"e": 440,
"s": 431,
"text": "Example:"
},
{
"code": null,
"e": 448,
"s": 440,
"text": "last -5"
},
{
"code": null,
"e": 456,
"s": 448,
"text": "Output:"
},
{
"code": null,
"e": 530,
"s": 456,
"text": "-R: This option is used to hide the host-name field.Example:last -R basil"
},
{
"code": null,
"e": 539,
"s": 530,
"text": "Example:"
},
{
"code": null,
"e": 553,
"s": 539,
"text": "last -R basil"
},
{
"code": null,
"e": 650,
"s": 553,
"text": "-F: This option is used to display the login and logout time including the dates.Example:last -F"
},
{
"code": null,
"e": 659,
"s": 650,
"text": "Example:"
},
{
"code": null,
"e": 667,
"s": 659,
"text": "last -F"
},
{
"code": null,
"e": 754,
"s": 667,
"text": "-a: This option is used is to display the host-name in the last column.Example:last -a"
},
{
"code": null,
"e": 763,
"s": 754,
"text": "Example:"
},
{
"code": null,
"e": 771,
"s": 763,
"text": "last -a"
},
{
"code": null,
"e": 1410,
"s": 771,
"text": "-s, -t: This option is used to display within a specific time period.(-s) since and (-t) until, these commands are used to frame the time period.Example:last -s yesterday -t todayThe valid formats for the above commands are:YYYYMMDDhhmmss\nYYYY-MM-DD hh:mm:ss\nYYYY-MM-DD hh:mm (seconds will be set to 00)\nYYYY-MM-DD (time will be set to 00:00:00)\nhh:mm:ss (date will be set to today)\nhh:mm (date will be set to today, seconds to 00)\nnow\nyesterday (time is set to 00:00:00)\ntoday (time is set to 00:00:00)\ntomorrow (time is set to 00:00:00)\n+5min\n-5days\n"
},
{
"code": null,
"e": 1419,
"s": 1410,
"text": "Example:"
},
{
"code": null,
"e": 1446,
"s": 1419,
"text": "last -s yesterday -t today"
},
{
"code": null,
"e": 1492,
"s": 1446,
"text": "The valid formats for the above commands are:"
},
{
"code": null,
"e": 1907,
"s": 1492,
"text": "YYYYMMDDhhmmss\nYYYY-MM-DD hh:mm:ss\nYYYY-MM-DD hh:mm (seconds will be set to 00)\nYYYY-MM-DD (time will be set to 00:00:00)\nhh:mm:ss (date will be set to today)\nhh:mm (date will be set to today, seconds to 00)\nnow\nyesterday (time is set to 00:00:00)\ntoday (time is set to 00:00:00)\ntomorrow (time is set to 00:00:00)\n+5min\n-5days\n"
},
{
"code": null,
"e": 1999,
"s": 1907,
"text": "-d: This option is used to translate the IP address back into its host-name.Example:last -d"
},
{
"code": null,
"e": 2008,
"s": 1999,
"text": "Example:"
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "last -d"
},
{
"code": null,
"e": 2126,
"s": 2016,
"text": "-x: This option is used to display information like system down entries and run level changes.Example:last -x"
},
{
"code": null,
"e": 2135,
"s": 2126,
"text": "Example:"
},
{
"code": null,
"e": 2143,
"s": 2135,
"text": "last -x"
},
{
"code": null,
"e": 2227,
"s": 2143,
"text": "-w: This option is used to display full user and domain names.Example:last -w basil"
},
{
"code": null,
"e": 2236,
"s": 2227,
"text": "Example:"
},
{
"code": null,
"e": 2250,
"s": 2236,
"text": "last -w basil"
},
{
"code": null,
"e": 2364,
"s": 2250,
"text": "–help: This option is used to display help regarding all options belonging to the last command.Syntax:last --help"
},
{
"code": null,
"e": 2372,
"s": 2364,
"text": "Syntax:"
},
{
"code": null,
"e": 2384,
"s": 2372,
"text": "last --help"
},
{
"code": null,
"e": 2398,
"s": 2384,
"text": "linux-command"
},
{
"code": null,
"e": 2420,
"s": 2398,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 2431,
"s": 2420,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2529,
"s": 2431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2555,
"s": 2529,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2590,
"s": 2555,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2627,
"s": 2590,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 2656,
"s": 2627,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 2693,
"s": 2656,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 2730,
"s": 2693,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2764,
"s": 2730,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2804,
"s": 2764,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2843,
"s": 2804,
"text": "Introduction to Linux Operating System"
}
] |
HTML - Elements
|
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag, where the element name is preceded by a forward slash as shown below with few tags −
So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br /> elements. These are known as void elements.
HTML documents consists of a tree of these elements and they specify how HTML documents should be built, and what kind of content should be placed in what part of an HTML document.
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.
For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.
It is very much allowed to keep one HTML element inside another HTML element −
<!DOCTYPE html>
<html>
<head>
<title>Nested Elements Example</title>
</head>
<body>
<h1>This is <i>italic</i> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
</body>
</html>
This will display the following result −
This is underlined paragraph
|
[
{
"code": null,
"e": 2706,
"s": 2508,
"text": "An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag, where the element name is preceded by a forward slash as shown below with few tags −"
},
{
"code": null,
"e": 2925,
"s": 2706,
"text": "So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br /> elements. These are known as void elements."
},
{
"code": null,
"e": 3106,
"s": 2925,
"text": "HTML documents consists of a tree of these elements and they specify how HTML documents should be built, and what kind of content should be placed in what part of an HTML document."
},
{
"code": null,
"e": 3219,
"s": 3106,
"text": "An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag."
},
{
"code": null,
"e": 3366,
"s": 3219,
"text": "For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element."
},
{
"code": null,
"e": 3445,
"s": 3366,
"text": "It is very much allowed to keep one HTML element inside another HTML element −"
},
{
"code": null,
"e": 3662,
"s": 3445,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Nested Elements Example</title>\n </head>\n\t\n <body>\n <h1>This is <i>italic</i> heading</h1>\n <p>This is <u>underlined</u> paragraph</p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3703,
"s": 3662,
"text": "This will display the following result −"
}
] |
Find missing element in a sorted array of consecutive numbers
|
05 Aug, 2021
Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples:
Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Output: -1 No element is missing.
Principles:
Look for inconsistency: Ideally, the difference between any element and its index must be arr[0] for every element. Example, A[] = {1, 2, 3, 4, 5} -> Consistent B[] = {101, 102, 103, 104} -> Consistent C[] = {1, 2, 4, 5, 6} -> Inconsistent as C[2] – 2 != C[0] i.e. 4 – 2 != 1
Finding inconsistency helps to scan only half of the array each time in O(logN).
Algorithm
Find middle element and check if it’s consistent.If middle element is consistent, then check if the difference between middle element and its next element is greater than 1 i.e. check if arr[mid + 1] – arr[mid] > 1 If yes, then arr[mid] + 1 is the missing element.If not, then we have to scan the right half array from the middle element and jump to step-1.If middle element is inconsistent, then check if the difference between middle element and its previous element is greater than 1 i.e. check if arr[mid] – arr[mid – 1] > 1 If yes, then arr[mid] – 1 is the missing element.If not, then we have to scan the left half array from the middle element and jump to step-1.
Find middle element and check if it’s consistent.
If middle element is consistent, then check if the difference between middle element and its next element is greater than 1 i.e. check if arr[mid + 1] – arr[mid] > 1 If yes, then arr[mid] + 1 is the missing element.If not, then we have to scan the right half array from the middle element and jump to step-1.
If yes, then arr[mid] + 1 is the missing element.
If not, then we have to scan the right half array from the middle element and jump to step-1.
If middle element is inconsistent, then check if the difference between middle element and its previous element is greater than 1 i.e. check if arr[mid] – arr[mid – 1] > 1 If yes, then arr[mid] – 1 is the missing element.If not, then we have to scan the left half array from the middle element and jump to step-1.
If yes, then arr[mid] – 1 is the missing element.
If not, then we have to scan the left half array from the middle element and jump to step-1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the missing elementint findMissing(int arr[], int n){ int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1;} // Driver codeint main(){ int arr[] = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (findMissing(arr, n));} // This code iscontributed by// Surendra_Gangwar
// Java implementation of the approachclass GFG { // Function to return the missing element public static int findMissing(int arr[], int n) { int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1; } // Driver code public static void main(String args[]) { int arr[] = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = arr.length; System.out.print(findMissing(arr, n)); }}
# Python implementation of the approach # Function to return the missing elementdef findMissing(arr, n): l, h = 0, n - 1 mid = 0 while (h > l): mid = l + (h - l) // 2 # Check if middle element is consistent if (arr[mid] - mid == arr[0]): # No inconsistency till middle elements # When missing element is just after # the middle element if (arr[mid + 1] - arr[mid] > 1): return arr[mid] + 1 else: # Move right l = mid + 1 else: # Inconsistency found # When missing element is just before # the middle element if (arr[mid] - arr[mid - 1] > 1): return arr[mid] - 1 else: # Move left h = mid - 1 # No missing element found return -1 # Driver codearr = [-9, -8, -7, -5, -4, -3, -2, -1, 0 ]n = len(arr) print(findMissing(arr, n)) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the missing element public static int findMissing(int[] arr, int n) { int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1; } // Driver code public static void Main() { int[] arr = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = arr.Length; Console.WriteLine(findMissing(arr, n)); }} // This code is contributed by Code_Mech
<?php// PHP implementation of the approach // Function to return the missing elementfunction findMissing($arr, $n){ $l = 0; $h = $n - 1; while ($h > $l) { $mid = floor($l + ($h - $l) / 2); // Check if middle element is consistent if ($arr[$mid] - $mid == $arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if ($arr[$mid + 1] - $arr[$mid] > 1) return $arr[$mid] + 1; else { // Move right $l = $mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if ($arr[$mid] - $arr[$mid - 1] > 1) return $arr[$mid] - 1; else { // Move left $h = $mid - 1; } } } // No missing element found return -1;} // Driver code$arr = array( -9, -8, -7, -5, - 4, -3, -2, -1, 0 );$n = count($arr); echo findMissing($arr, $n); // This code is contributed by Ryuga?>
<script>// JavaScript implementation of the approach // Function to return the missing elementfunction findMissing(arr, n){ let l = 0, h = n - 1; let mid; while (h > l) { mid = l + Math.floor((h - l) / 2); // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1;} // Driver code let arr = [ -9, -8, -7, -5, -4, -3, -2, -1, 0 ]; let n = arr.length; document.write(findMissing(arr, n)); // This code is contributed by Surbhi Tyagi.</script>
-6
Time Complexity : O(log(N) )Auxiliary Space: O(1)
mohit kumar 29
Code_Mech
ankthon
SURENDRA_GANGWAR
surbhityagi15
pankajsharmagfg
Binary Search
Arrays
Data Structures
Searching
Data Structures
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
What is Hashing | A Complete Tutorial
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 227,
"s": 52,
"text": "Given an array arr[] of n distinct integers. Elements are placed sequentially in ascending order with one element missing. The task is to find the missing element.Examples: "
},
{
"code": null,
"e": 387,
"s": 227,
"text": "Input: arr[] = {1, 2, 4, 5, 6, 7, 8, 9} Output: 3Input: arr[] = {-4, -3, -1, 0, 1, 2} Output: -2Input: arr[] = {1, 2, 3, 4} Output: -1 No element is missing. "
},
{
"code": null,
"e": 403,
"s": 389,
"text": "Principles: "
},
{
"code": null,
"e": 681,
"s": 403,
"text": "Look for inconsistency: Ideally, the difference between any element and its index must be arr[0] for every element. Example, A[] = {1, 2, 3, 4, 5} -> Consistent B[] = {101, 102, 103, 104} -> Consistent C[] = {1, 2, 4, 5, 6} -> Inconsistent as C[2] – 2 != C[0] i.e. 4 – 2 != 1 "
},
{
"code": null,
"e": 762,
"s": 681,
"text": "Finding inconsistency helps to scan only half of the array each time in O(logN)."
},
{
"code": null,
"e": 774,
"s": 762,
"text": "Algorithm "
},
{
"code": null,
"e": 1445,
"s": 774,
"text": "Find middle element and check if it’s consistent.If middle element is consistent, then check if the difference between middle element and its next element is greater than 1 i.e. check if arr[mid + 1] – arr[mid] > 1 If yes, then arr[mid] + 1 is the missing element.If not, then we have to scan the right half array from the middle element and jump to step-1.If middle element is inconsistent, then check if the difference between middle element and its previous element is greater than 1 i.e. check if arr[mid] – arr[mid – 1] > 1 If yes, then arr[mid] – 1 is the missing element.If not, then we have to scan the left half array from the middle element and jump to step-1."
},
{
"code": null,
"e": 1495,
"s": 1445,
"text": "Find middle element and check if it’s consistent."
},
{
"code": null,
"e": 1804,
"s": 1495,
"text": "If middle element is consistent, then check if the difference between middle element and its next element is greater than 1 i.e. check if arr[mid + 1] – arr[mid] > 1 If yes, then arr[mid] + 1 is the missing element.If not, then we have to scan the right half array from the middle element and jump to step-1."
},
{
"code": null,
"e": 1854,
"s": 1804,
"text": "If yes, then arr[mid] + 1 is the missing element."
},
{
"code": null,
"e": 1948,
"s": 1854,
"text": "If not, then we have to scan the right half array from the middle element and jump to step-1."
},
{
"code": null,
"e": 2262,
"s": 1948,
"text": "If middle element is inconsistent, then check if the difference between middle element and its previous element is greater than 1 i.e. check if arr[mid] – arr[mid – 1] > 1 If yes, then arr[mid] – 1 is the missing element.If not, then we have to scan the left half array from the middle element and jump to step-1."
},
{
"code": null,
"e": 2312,
"s": 2262,
"text": "If yes, then arr[mid] – 1 is the missing element."
},
{
"code": null,
"e": 2405,
"s": 2312,
"text": "If not, then we have to scan the left half array from the middle element and jump to step-1."
},
{
"code": null,
"e": 2458,
"s": 2405,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2462,
"s": 2458,
"text": "C++"
},
{
"code": null,
"e": 2467,
"s": 2462,
"text": "Java"
},
{
"code": null,
"e": 2475,
"s": 2467,
"text": "Python3"
},
{
"code": null,
"e": 2478,
"s": 2475,
"text": "C#"
},
{
"code": null,
"e": 2482,
"s": 2478,
"text": "PHP"
},
{
"code": null,
"e": 2493,
"s": 2482,
"text": "Javascript"
},
{
"code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the missing elementint findMissing(int arr[], int n){ int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1;} // Driver codeint main(){ int arr[] = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (findMissing(arr, n));} // This code iscontributed by// Surendra_Gangwar",
"e": 3746,
"s": 2493,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the missing element public static int findMissing(int arr[], int n) { int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1; } // Driver code public static void main(String args[]) { int arr[] = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = arr.length; System.out.print(findMissing(arr, n)); }}",
"e": 5077,
"s": 3746,
"text": null
},
{
"code": "# Python implementation of the approach # Function to return the missing elementdef findMissing(arr, n): l, h = 0, n - 1 mid = 0 while (h > l): mid = l + (h - l) // 2 # Check if middle element is consistent if (arr[mid] - mid == arr[0]): # No inconsistency till middle elements # When missing element is just after # the middle element if (arr[mid + 1] - arr[mid] > 1): return arr[mid] + 1 else: # Move right l = mid + 1 else: # Inconsistency found # When missing element is just before # the middle element if (arr[mid] - arr[mid - 1] > 1): return arr[mid] - 1 else: # Move left h = mid - 1 # No missing element found return -1 # Driver codearr = [-9, -8, -7, -5, -4, -3, -2, -1, 0 ]n = len(arr) print(findMissing(arr, n)) # This code is contributed# by mohit kumar",
"e": 6121,
"s": 5077,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the missing element public static int findMissing(int[] arr, int n) { int l = 0, h = n - 1; int mid; while (h > l) { mid = l + (h - l) / 2; // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1; } // Driver code public static void Main() { int[] arr = { -9, -8, -7, -5, -4, -3, -2, -1, 0 }; int n = arr.Length; Console.WriteLine(findMissing(arr, n)); }} // This code is contributed by Code_Mech",
"e": 7551,
"s": 6121,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the missing elementfunction findMissing($arr, $n){ $l = 0; $h = $n - 1; while ($h > $l) { $mid = floor($l + ($h - $l) / 2); // Check if middle element is consistent if ($arr[$mid] - $mid == $arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if ($arr[$mid + 1] - $arr[$mid] > 1) return $arr[$mid] + 1; else { // Move right $l = $mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if ($arr[$mid] - $arr[$mid - 1] > 1) return $arr[$mid] - 1; else { // Move left $h = $mid - 1; } } } // No missing element found return -1;} // Driver code$arr = array( -9, -8, -7, -5, - 4, -3, -2, -1, 0 );$n = count($arr); echo findMissing($arr, $n); // This code is contributed by Ryuga?>",
"e": 8740,
"s": 7551,
"text": null
},
{
"code": "<script>// JavaScript implementation of the approach // Function to return the missing elementfunction findMissing(arr, n){ let l = 0, h = n - 1; let mid; while (h > l) { mid = l + Math.floor((h - l) / 2); // Check if middle element is consistent if (arr[mid] - mid == arr[0]) { // No inconsistency till middle elements // When missing element is just after // the middle element if (arr[mid + 1] - arr[mid] > 1) return arr[mid] + 1; else { // Move right l = mid + 1; } } else { // Inconsistency found // When missing element is just before // the middle element if (arr[mid] - arr[mid - 1] > 1) return arr[mid] - 1; else { // Move left h = mid - 1; } } } // No missing element found return -1;} // Driver code let arr = [ -9, -8, -7, -5, -4, -3, -2, -1, 0 ]; let n = arr.length; document.write(findMissing(arr, n)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 9956,
"s": 8740,
"text": null
},
{
"code": null,
"e": 9959,
"s": 9956,
"text": "-6"
},
{
"code": null,
"e": 10012,
"s": 9961,
"text": "Time Complexity : O(log(N) )Auxiliary Space: O(1) "
},
{
"code": null,
"e": 10027,
"s": 10012,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10037,
"s": 10027,
"text": "Code_Mech"
},
{
"code": null,
"e": 10045,
"s": 10037,
"text": "ankthon"
},
{
"code": null,
"e": 10062,
"s": 10045,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10076,
"s": 10062,
"text": "surbhityagi15"
},
{
"code": null,
"e": 10092,
"s": 10076,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 10106,
"s": 10092,
"text": "Binary Search"
},
{
"code": null,
"e": 10113,
"s": 10106,
"text": "Arrays"
},
{
"code": null,
"e": 10129,
"s": 10113,
"text": "Data Structures"
},
{
"code": null,
"e": 10139,
"s": 10129,
"text": "Searching"
},
{
"code": null,
"e": 10155,
"s": 10139,
"text": "Data Structures"
},
{
"code": null,
"e": 10162,
"s": 10155,
"text": "Arrays"
},
{
"code": null,
"e": 10172,
"s": 10162,
"text": "Searching"
},
{
"code": null,
"e": 10186,
"s": 10172,
"text": "Binary Search"
},
{
"code": null,
"e": 10284,
"s": 10186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10316,
"s": 10284,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10341,
"s": 10316,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 10388,
"s": 10341,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 10452,
"s": 10388,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 10483,
"s": 10452,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 10508,
"s": 10483,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 10557,
"s": 10508,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 10589,
"s": 10557,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10645,
"s": 10589,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
R - JSON Files
|
JSON file stores data as text in human-readable format. Json stands for JavaScript Object Notation. R can read JSON files using the rjson package.
In the R console, you can issue the following command to install the rjson package.
install.packages("rjson")
Create a JSON file by copying the below data into a text editor like notepad. Save the file with a .json extension and choosing the file type as all files(*.*).
{
"ID":["1","2","3","4","5","6","7","8" ],
"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
"7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}
The JSON file is read by R using the function from JSON(). It is stored as a list in R.
# Load the package required to read JSON files.
library("rjson")
# Give the input file name to the function.
result <- fromJSON(file = "input.json")
# Print the result.
print(result)
When we execute the above code, it produces the following result −
$ID
[1] "1" "2" "3" "4" "5" "6" "7" "8"
$Name
[1] "Rick" "Dan" "Michelle" "Ryan" "Gary" "Nina" "Simon" "Guru"
$Salary
[1] "623.3" "515.2" "611" "729" "843.25" "578" "632.8" "722.5"
$StartDate
[1] "1/1/2012" "9/23/2013" "11/15/2014" "5/11/2014" "3/27/2015" "5/21/2013"
"7/30/2013" "6/17/2014"
$Dept
[1] "IT" "Operations" "IT" "HR" "Finance" "IT"
"Operations" "Finance"
We can convert the extracted data above to a R data frame for further analysis using the as.data.frame() function.
# Load the package required to read JSON files.
library("rjson")
# Give the input file name to the function.
result <- fromJSON(file = "input.json")
# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)
print(json_data_frame)
When we execute the above code, it produces the following result −
id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 NA Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance
|
[
{
"code": null,
"e": 2683,
"s": 2536,
"text": "JSON file stores data as text in human-readable format. Json stands for JavaScript Object Notation. R can read JSON files using the rjson package."
},
{
"code": null,
"e": 2767,
"s": 2683,
"text": "In the R console, you can issue the following command to install the rjson package."
},
{
"code": null,
"e": 2794,
"s": 2767,
"text": "install.packages(\"rjson\")\n"
},
{
"code": null,
"e": 2955,
"s": 2794,
"text": "Create a JSON file by copying the below data into a text editor like notepad. Save the file with a .json extension and choosing the file type as all files(*.*)."
},
{
"code": null,
"e": 3358,
"s": 2955,
"text": "{ \n \"ID\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\" ],\n \"Name\":[\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\",\"Nina\",\"Simon\",\"Guru\" ],\n \"Salary\":[\"623.3\",\"515.2\",\"611\",\"729\",\"843.25\",\"578\",\"632.8\",\"722.5\" ],\n \n \"StartDate\":[ \"1/1/2012\",\"9/23/2013\",\"11/15/2014\",\"5/11/2014\",\"3/27/2015\",\"5/21/2013\",\n \"7/30/2013\",\"6/17/2014\"],\n \"Dept\":[ \"IT\",\"Operations\",\"IT\",\"HR\",\"Finance\",\"IT\",\"Operations\",\"Finance\"]\n}"
},
{
"code": null,
"e": 3446,
"s": 3358,
"text": "The JSON file is read by R using the function from JSON(). It is stored as a list in R."
},
{
"code": null,
"e": 3631,
"s": 3446,
"text": "# Load the package required to read JSON files.\nlibrary(\"rjson\")\n\n# Give the input file name to the function.\nresult <- fromJSON(file = \"input.json\")\n\n# Print the result.\nprint(result)"
},
{
"code": null,
"e": 3698,
"s": 3631,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4160,
"s": 3698,
"text": "$ID\n[1] \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\"\n\n$Name\n[1] \"Rick\" \"Dan\" \"Michelle\" \"Ryan\" \"Gary\" \"Nina\" \"Simon\" \"Guru\"\n\n$Salary\n[1] \"623.3\" \"515.2\" \"611\" \"729\" \"843.25\" \"578\" \"632.8\" \"722.5\"\n\n$StartDate\n[1] \"1/1/2012\" \"9/23/2013\" \"11/15/2014\" \"5/11/2014\" \"3/27/2015\" \"5/21/2013\"\n \"7/30/2013\" \"6/17/2014\"\n\n$Dept\n[1] \"IT\" \"Operations\" \"IT\" \"HR\" \"Finance\" \"IT\"\n \"Operations\" \"Finance\"\n"
},
{
"code": null,
"e": 4275,
"s": 4160,
"text": "We can convert the extracted data above to a R data frame for further analysis using the as.data.frame() function."
},
{
"code": null,
"e": 4528,
"s": 4275,
"text": "# Load the package required to read JSON files.\nlibrary(\"rjson\")\n\n# Give the input file name to the function.\nresult <- fromJSON(file = \"input.json\")\n\n# Convert JSON file to a data frame.\njson_data_frame <- as.data.frame(result)\n\nprint(json_data_frame)"
},
{
"code": null,
"e": 4595,
"s": 4528,
"text": "When we execute the above code, it produces the following result −"
}
] |
Spring Boot – CRUD Operations
|
17 Dec, 2021
CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also does helps us relate better web development and also aids us while dealing with databases. So, standard CRUD Operations is as follows:
POST: Creates a new resource
GET: Reads/Retrieve a resource
PUT: Updates an existing resource
DELETE: Deletes a resource
As the name suggests
CREATE Operation: Performs the INSERT statement to create a new record.
READ Operation: Reads table records based on the input parameter.
UPDATE Operation: Executes an update statement on the table. It is based on the input parameter.
DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter.
So in this article, we are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the H2 Database. So here is a brief explanation of What’s Spring Boot and What’s H2 Database.
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time.
H2 is a relational database management system written in Java. It can be embedded in Java applications or run in client-server mode. The main features of H2 are:
Very fast, open-source, JDBC API
Embedded and server modes; in-memory databases
Browser-based Console application
Small footprint: around 2.5 MB jar file size
There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface.
Illustration:
public interface DepartmentRepository extends CrudRepository<Department, Long> { }
Where:
Department: Domain type that repository manages (Generally the Entity/Model class name)
Long: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
Example:
Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project.
Step 2: Add the following dependency
Spring Web
H2 Database
Lombok
Spring Data JPA
Below is the complete code for the pom.xml file. Please check if you have missed something.
XML
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
Step 3: Create 4 packages and later create some classes and interfaces inside these packages as seen in the below image:
entity
repository
service
controller
Note:
Green Rounded Icon ‘I’ Buttons are Interface
Blue Rounded Icon ‘C’ Buttons are Classes
Step 4: Inside the entity package
Create a simple POJO class inside the Department.java file.
Example
Java
// Java Program to Illustrate Department.java File // Importing required package modulespackage com.amiya.springbootdemoproject.entity; // Importing required classesimport javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}
Step 5: Inside the repository package
Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the CrudRepository as we have discussed above. Below is the code for the DepartmentRepository.java file
Example
Java
package com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository; @Repositorypublic interface DepartmentRepository extends CrudRepository<Department, Long> { }
Step 6: Inside the service package
Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl.
Example 1
Java
// Java Program to Illustrate DepartmentService.java File // Importing packagespackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Classpublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}
Below is the code for the DepartmentServiceImpl.java file
Example 2
Java
// Java Program to Illustrate DepartmentServiceImpl.java// File // Importing required packagespackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service// Class implementing DepartmentService classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !"".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}
Step 7: Inside the controller package
Inside the package create one class named as DepartmentController
Java
// Java Program to Illustrate DepartmentController.java File // Importing packages modulespackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController// Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping("/departments") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping("/departments") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping("/departments/{id}") public Department updateDepartment(@RequestBody Department department, @PathVariable("id") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping("/departments/{id}") public String deleteDepartmentById(@PathVariable("id") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return "Deleted Successfully"; }}
Step 8: Below is the code for the application.properties file
server.port = 8082
# H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database.
Endpoint 1: POST – http://localhost:8082/departments/
Endpoint 2: GET – http://localhost:8082/departments/
Endpoint 3: PUT – http://localhost:8082/departments/1
Endpoint 4: DELETE – http://localhost:8082/departments/1
Lastly, H2 Database is as depicted in the below media as follows:
surindertarika1234
Java-Spring-Boot
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Constructors in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 513,
"s": 28,
"text": "CRUD stands for Create, Read/Retrieve, Update and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a developmental point perspective in programming that also does helps us relate better web development and also aids us while dealing with databases. So, standard CRUD Operations is as follows:"
},
{
"code": null,
"e": 542,
"s": 513,
"text": "POST: Creates a new resource"
},
{
"code": null,
"e": 573,
"s": 542,
"text": "GET: Reads/Retrieve a resource"
},
{
"code": null,
"e": 607,
"s": 573,
"text": "PUT: Updates an existing resource"
},
{
"code": null,
"e": 634,
"s": 607,
"text": "DELETE: Deletes a resource"
},
{
"code": null,
"e": 656,
"s": 634,
"text": "As the name suggests "
},
{
"code": null,
"e": 728,
"s": 656,
"text": "CREATE Operation: Performs the INSERT statement to create a new record."
},
{
"code": null,
"e": 794,
"s": 728,
"text": "READ Operation: Reads table records based on the input parameter."
},
{
"code": null,
"e": 891,
"s": 794,
"text": "UPDATE Operation: Executes an update statement on the table. It is based on the input parameter."
},
{
"code": null,
"e": 988,
"s": 891,
"text": "DELETE Operation: Deletes a specified row in the table. It is also based on the input parameter."
},
{
"code": null,
"e": 1202,
"s": 988,
"text": "So in this article, we are going to perform some basic CRUD Operations by creating a Spring Boot Application and using the H2 Database. So here is a brief explanation of What’s Spring Boot and What’s H2 Database. "
},
{
"code": null,
"e": 1624,
"s": 1202,
"text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time."
},
{
"code": null,
"e": 1786,
"s": 1624,
"text": "H2 is a relational database management system written in Java. It can be embedded in Java applications or run in client-server mode. The main features of H2 are:"
},
{
"code": null,
"e": 1819,
"s": 1786,
"text": "Very fast, open-source, JDBC API"
},
{
"code": null,
"e": 1866,
"s": 1819,
"text": "Embedded and server modes; in-memory databases"
},
{
"code": null,
"e": 1900,
"s": 1866,
"text": "Browser-based Console application"
},
{
"code": null,
"e": 1945,
"s": 1900,
"text": "Small footprint: around 2.5 MB jar file size"
},
{
"code": null,
"e": 2375,
"s": 1945,
"text": "There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface. "
},
{
"code": null,
"e": 2389,
"s": 2375,
"text": "Illustration:"
},
{
"code": null,
"e": 2472,
"s": 2389,
"text": "public interface DepartmentRepository extends CrudRepository<Department, Long> { }"
},
{
"code": null,
"e": 2479,
"s": 2472,
"text": "Where:"
},
{
"code": null,
"e": 2567,
"s": 2479,
"text": "Department: Domain type that repository manages (Generally the Entity/Model class name)"
},
{
"code": null,
"e": 2714,
"s": 2567,
"text": "Long: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)"
},
{
"code": null,
"e": 2723,
"s": 2714,
"text": "Example:"
},
{
"code": null,
"e": 2843,
"s": 2723,
"text": "Step 1: Refer to this article How to Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. "
},
{
"code": null,
"e": 2880,
"s": 2843,
"text": "Step 2: Add the following dependency"
},
{
"code": null,
"e": 2891,
"s": 2880,
"text": "Spring Web"
},
{
"code": null,
"e": 2903,
"s": 2891,
"text": "H2 Database"
},
{
"code": null,
"e": 2910,
"s": 2903,
"text": "Lombok"
},
{
"code": null,
"e": 2926,
"s": 2910,
"text": "Spring Data JPA"
},
{
"code": null,
"e": 3018,
"s": 2926,
"text": "Below is the complete code for the pom.xml file. Please check if you have missed something."
},
{
"code": null,
"e": 3022,
"s": 3018,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>",
"e": 5479,
"s": 3022,
"text": null
},
{
"code": null,
"e": 5600,
"s": 5479,
"text": "Step 3: Create 4 packages and later create some classes and interfaces inside these packages as seen in the below image:"
},
{
"code": null,
"e": 5607,
"s": 5600,
"text": "entity"
},
{
"code": null,
"e": 5618,
"s": 5607,
"text": "repository"
},
{
"code": null,
"e": 5626,
"s": 5618,
"text": "service"
},
{
"code": null,
"e": 5637,
"s": 5626,
"text": "controller"
},
{
"code": null,
"e": 5643,
"s": 5637,
"text": "Note:"
},
{
"code": null,
"e": 5688,
"s": 5643,
"text": "Green Rounded Icon ‘I’ Buttons are Interface"
},
{
"code": null,
"e": 5730,
"s": 5688,
"text": "Blue Rounded Icon ‘C’ Buttons are Classes"
},
{
"code": null,
"e": 5764,
"s": 5730,
"text": "Step 4: Inside the entity package"
},
{
"code": null,
"e": 5825,
"s": 5764,
"text": "Create a simple POJO class inside the Department.java file. "
},
{
"code": null,
"e": 5833,
"s": 5825,
"text": "Example"
},
{
"code": null,
"e": 5838,
"s": 5833,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Department.java File // Importing required package modulespackage com.amiya.springbootdemoproject.entity; // Importing required classesimport javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Classpublic class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}",
"e": 6537,
"s": 5838,
"text": null
},
{
"code": null,
"e": 6575,
"s": 6537,
"text": "Step 5: Inside the repository package"
},
{
"code": null,
"e": 6787,
"s": 6575,
"text": "Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the CrudRepository as we have discussed above. Below is the code for the DepartmentRepository.java file"
},
{
"code": null,
"e": 6795,
"s": 6787,
"text": "Example"
},
{
"code": null,
"e": 6800,
"s": 6795,
"text": "Java"
},
{
"code": "package com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository; @Repositorypublic interface DepartmentRepository extends CrudRepository<Department, Long> { }",
"e": 7115,
"s": 6800,
"text": null
},
{
"code": null,
"e": 7150,
"s": 7115,
"text": "Step 6: Inside the service package"
},
{
"code": null,
"e": 7263,
"s": 7150,
"text": "Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl."
},
{
"code": null,
"e": 7273,
"s": 7263,
"text": "Example 1"
},
{
"code": null,
"e": 7278,
"s": 7273,
"text": "Java"
},
{
"code": "// Java Program to Illustrate DepartmentService.java File // Importing packagespackage com.amiya.springbootdemoproject.service;import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Classpublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}",
"e": 7902,
"s": 7278,
"text": null
},
{
"code": null,
"e": 7960,
"s": 7902,
"text": "Below is the code for the DepartmentServiceImpl.java file"
},
{
"code": null,
"e": 7970,
"s": 7960,
"text": "Example 2"
},
{
"code": null,
"e": 7975,
"s": 7970,
"text": "Java"
},
{
"code": "// Java Program to Illustrate DepartmentServiceImpl.java// File // Importing required packagespackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service// Class implementing DepartmentService classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !\"\".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !\"\".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !\"\".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}",
"e": 10167,
"s": 7975,
"text": null
},
{
"code": null,
"e": 10205,
"s": 10167,
"text": "Step 7: Inside the controller package"
},
{
"code": null,
"e": 10271,
"s": 10205,
"text": "Inside the package create one class named as DepartmentController"
},
{
"code": null,
"e": 10276,
"s": 10271,
"text": "Java"
},
{
"code": "// Java Program to Illustrate DepartmentController.java File // Importing packages modulespackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController// Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping(\"/departments\") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping(\"/departments\") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping(\"/departments/{id}\") public Department updateDepartment(@RequestBody Department department, @PathVariable(\"id\") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping(\"/departments/{id}\") public String deleteDepartmentById(@PathVariable(\"id\") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return \"Deleted Successfully\"; }}",
"e": 11841,
"s": 10276,
"text": null
},
{
"code": null,
"e": 11903,
"s": 11841,
"text": "Step 8: Below is the code for the application.properties file"
},
{
"code": null,
"e": 12184,
"s": 11903,
"text": "server.port = 8082\n\n# H2 Database\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:dcbapp\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=password\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect"
},
{
"code": null,
"e": 12284,
"s": 12184,
"text": "Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database."
},
{
"code": null,
"e": 12338,
"s": 12284,
"text": "Endpoint 1: POST – http://localhost:8082/departments/"
},
{
"code": null,
"e": 12391,
"s": 12338,
"text": "Endpoint 2: GET – http://localhost:8082/departments/"
},
{
"code": null,
"e": 12445,
"s": 12391,
"text": "Endpoint 3: PUT – http://localhost:8082/departments/1"
},
{
"code": null,
"e": 12502,
"s": 12445,
"text": "Endpoint 4: DELETE – http://localhost:8082/departments/1"
},
{
"code": null,
"e": 12568,
"s": 12502,
"text": "Lastly, H2 Database is as depicted in the below media as follows:"
},
{
"code": null,
"e": 12587,
"s": 12568,
"text": "surindertarika1234"
},
{
"code": null,
"e": 12604,
"s": 12587,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 12611,
"s": 12604,
"text": "Picked"
},
{
"code": null,
"e": 12616,
"s": 12611,
"text": "Java"
},
{
"code": null,
"e": 12621,
"s": 12616,
"text": "Java"
},
{
"code": null,
"e": 12719,
"s": 12621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12738,
"s": 12719,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 12756,
"s": 12738,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 12771,
"s": 12756,
"text": "Stream In Java"
},
{
"code": null,
"e": 12791,
"s": 12771,
"text": "Collections in Java"
},
{
"code": null,
"e": 12823,
"s": 12791,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 12847,
"s": 12823,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 12867,
"s": 12847,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 12895,
"s": 12867,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 12916,
"s": 12895,
"text": "Introduction to Java"
}
] |
Divide a Pandas DataFrame randomly in a given ratio
|
25 Oct, 2021
Divide a Pandas Dataframe task is very useful in case of split a given dataset into train and test data for training and testing purposes in the field of Machine Learning, Artificial Intelligence, etc. Let’s see how to divide the pandas dataframe randomly into given ratios. For this task, We will use Dataframe.sample() and Dataframe.drop() methods of pandas dataframe together.
The Syntax of these functions are as follows –
Dataframe.sample()
Syntax: DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Return Type: A new object of same type as caller containing n items randomly sampled from the caller object.
Dataframe.drop()
Syntax: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)
Return: Dataframe with dropped values.
Example: Now, let’s create a Dataframe:
Python3
# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # show the dataframedf
Output:
Dataframe
Example 1: Divide a Dataframe randomly into a 1:1 ratio.
Python3
# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # Creating a dataframe with 50%# values of original dataframepart_50 = df.sample(frac = 0.5) # Creating dataframe with# rest of the 50% valuesrest_part_50 = df.drop(part_50.index) print("\n50% of the given DataFrame:")print(part_50) print("\nrest 50% of the given DataFrame:")print(rest_part_50)
Output:
Divide dataframe
Example 2: Divide a Dataframe randomly into a 3:1 ratio.
Python3
# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # Creating a dataframe with 75%# values of original dataframepart_75 = df.sample(frac = 0.75) # Creating dataframe with# rest of the 25% valuesrest_part_25 = df.drop(part_75.index) print("\n75% of the given DataFrame:")print(part_75) print("\nrest 25% of the given DataFrame:")print(rest_part_25)
Output:
Divide Dataframe
prachisoda1234
pandas-dataframe-program
Python pandas-dataFrame
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
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 409,
"s": 28,
"text": "Divide a Pandas Dataframe task is very useful in case of split a given dataset into train and test data for training and testing purposes in the field of Machine Learning, Artificial Intelligence, etc. Let’s see how to divide the pandas dataframe randomly into given ratios. For this task, We will use Dataframe.sample() and Dataframe.drop() methods of pandas dataframe together."
},
{
"code": null,
"e": 457,
"s": 409,
"text": "The Syntax of these functions are as follows – "
},
{
"code": null,
"e": 476,
"s": 457,
"text": "Dataframe.sample()"
},
{
"code": null,
"e": 579,
"s": 476,
"text": "Syntax: DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)"
},
{
"code": null,
"e": 688,
"s": 579,
"text": "Return Type: A new object of same type as caller containing n items randomly sampled from the caller object."
},
{
"code": null,
"e": 705,
"s": 688,
"text": "Dataframe.drop()"
},
{
"code": null,
"e": 818,
"s": 705,
"text": "Syntax: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)"
},
{
"code": null,
"e": 857,
"s": 818,
"text": "Return: Dataframe with dropped values."
},
{
"code": null,
"e": 897,
"s": 857,
"text": "Example: Now, let’s create a Dataframe:"
},
{
"code": null,
"e": 905,
"s": 897,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # show the dataframedf",
"e": 1371,
"s": 905,
"text": null
},
{
"code": null,
"e": 1383,
"s": 1374,
"text": "Output: "
},
{
"code": null,
"e": 1395,
"s": 1385,
"text": "Dataframe"
},
{
"code": null,
"e": 1454,
"s": 1397,
"text": "Example 1: Divide a Dataframe randomly into a 1:1 ratio."
},
{
"code": null,
"e": 1464,
"s": 1456,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # Creating a dataframe with 50%# values of original dataframepart_50 = df.sample(frac = 0.5) # Creating dataframe with# rest of the 50% valuesrest_part_50 = df.drop(part_50.index) print(\"\\n50% of the given DataFrame:\")print(part_50) print(\"\\nrest 50% of the given DataFrame:\")print(rest_part_50)",
"e": 2203,
"s": 1464,
"text": null
},
{
"code": null,
"e": 2215,
"s": 2206,
"text": "Output: "
},
{
"code": null,
"e": 2234,
"s": 2217,
"text": "Divide dataframe"
},
{
"code": null,
"e": 2293,
"s": 2236,
"text": "Example 2: Divide a Dataframe randomly into a 3:1 ratio."
},
{
"code": null,
"e": 2303,
"s": 2295,
"text": "Python3"
},
{
"code": "# Importing required librariesimport pandas as pd record = { 'course_name': ['Data Structures', 'Python', 'Machine Learning', 'Web Development'], 'student_name': ['Ankit', 'Shivangi', 'Priya', 'Shaurya'], 'student_city': ['Chennai', 'Pune', 'Delhi', 'Mumbai'], 'student_gender': ['M', 'F', 'F', 'M'] } # Creating a dataframedf = pd.DataFrame(record) # Creating a dataframe with 75%# values of original dataframepart_75 = df.sample(frac = 0.75) # Creating dataframe with# rest of the 25% valuesrest_part_25 = df.drop(part_75.index) print(\"\\n75% of the given DataFrame:\")print(part_75) print(\"\\nrest 25% of the given DataFrame:\")print(rest_part_25)",
"e": 3043,
"s": 2303,
"text": null
},
{
"code": null,
"e": 3055,
"s": 3046,
"text": "Output: "
},
{
"code": null,
"e": 3074,
"s": 3057,
"text": "Divide Dataframe"
},
{
"code": null,
"e": 3091,
"s": 3076,
"text": "prachisoda1234"
},
{
"code": null,
"e": 3116,
"s": 3091,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 3140,
"s": 3116,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3154,
"s": 3140,
"text": "Python-pandas"
},
{
"code": null,
"e": 3161,
"s": 3154,
"text": "Python"
},
{
"code": null,
"e": 3259,
"s": 3161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3277,
"s": 3259,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3319,
"s": 3277,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3341,
"s": 3319,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3376,
"s": 3341,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3408,
"s": 3376,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3437,
"s": 3408,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3464,
"s": 3437,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3494,
"s": 3464,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3530,
"s": 3494,
"text": "Convert integer to string in Python"
}
] |
JavaScript | Creating a Custom Image Slider
|
26 Nov, 2019
What is an image slider?
Image Slider or Image Carousel is an expedient way to show multiple images on a website. Alluring flashy images can draw many visitors to the site. Below image shows a sample image slider:
In this post, we will create the above image slider using HTML, CSS and JavaScript. Let’s begin with creating the image slider.
Step – 1: Create the structure of image slider using HTML and insert images from the respective sources. Below is the complete HTML code for doing this:
<!--HTML Code--><!-- Slideshow Container Div --><div class="container"> <!-- Full-width images with caption text --> <div class="image-sliderfade fade"> <img src="img1.jpg" style="width:100%"> <div class="text">Image caption 1</div> </div> <div class="image-sliderfade fade"> <img src="img2.jpg" style="width:100%"> <div class="text">Image caption 2</div> </div> <div class="image-sliderfade fade"> <img src="img3.jpg" style="width:100%"> <div class="text">Image caption 3</div> </div> <div class="image-sliderfade fade"> <img src="img3.jpg" style="width:100%"> <div class="text">Image caption 4</div> </div> </div><br> <!-- The dots/circles --><div style="text-align:center"> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> </div>
Step – 2: Once we have created the HTML structure for our image slider, the next step is to style the slider using CSS. We will add styles to the images, backgrounds etc. We will also style the dots and make our images responsive and browser friendly using CSS. Below is the complete CSS code for styling our image slider:
// CSS code* { box-sizing: border-box;}body { font-family: Verdana, sans-serif;} .image-sliderfade { display: none;} img { vertical-align: middle;} /* Slideshow container */.container { max-width: 1000px; position: relative; margin: auto;} /* Caption text */.text { color: #f2f2f2; font-size: 15px; padding: 20px 15px; position: absolute; right: 10px; bottom: 10px; width: 40%; background: rgba(0, 0, 0, .7); text-align: left;} /* The dots/bullets/indicators */.dot { height: 15px; width: 15px; margin: 0 2px; background-color: transparent; border-color: #ddd; border-width: 5 px; border-style: solid; border-radius: 50%; display: inline-block; transition: border-color 0.6s ease;} .active { border-color: #666;} /* Animation */.fade { -webkit-animation-name: fade-image; -webkit-animation-duration: 1.5s; animation-name: fade-image; animation-duration: 1.5s;} @-webkit-keyframes fade-image{ from {opacity: .4} to {opacity: 1}} @keyframes fade-image{ from {opacity: .4} to {opacity: 1}} /* On smaller screens, decrease text size */@media only screen and (max-width: 300px) { .text {font-size: 11px}}
Step – 3: After adding styles to the slider, the last thing left is to use javascript to add the functionality of auto changing of images after a specific time interval.In the code snippet below, at the very beginning, we took all the div elements with class name ‘image-sliderfade’ in an array and did the same for div’s with class name ‘dots’ by using getElementByClassName() listener. After that, we set the display for all of the divs, containing images. In the last for-loop, we have erased the class name for each element of array dots[]. After we are done with these, we set the display as a block of the image to shown and append the class name to the corresponding element of dots[] array. Function setTimeout is used for calling the function showslides() in an interval of 2 seconds.
Below is the complete JavaScript code:
var slideIndex = 0;showSlides(); // call showslide method function showSlides(){ var i; // get the array of divs' with classname image-sliderfade var slides = document.getElementsByClassName("image-sliderfade"); // get the array of divs' with classname dot var dots = document.getElementsByClassName("dot"); for (i = 0; i < slides.length; i++) { // initially set the display to // none for every image. slides[i].style.display = "none"; } // increase by 1, Global variable slideIndex++; // check for boundary if (slideIndex > slides.length) { slideIndex = 1; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className. replace(" active", ""); } slides[slideIndex - 1].style.display = "block"; dots[slideIndex - 1].className += " active"; // Change image every 2 seconds setTimeout(showSlides, 2000); }
Once we are done with all of the above steps, we will get the slider up and working as shown below:
nidhi_biet
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": "\n26 Nov, 2019"
},
{
"code": null,
"e": 77,
"s": 52,
"text": "What is an image slider?"
},
{
"code": null,
"e": 266,
"s": 77,
"text": "Image Slider or Image Carousel is an expedient way to show multiple images on a website. Alluring flashy images can draw many visitors to the site. Below image shows a sample image slider:"
},
{
"code": null,
"e": 394,
"s": 266,
"text": "In this post, we will create the above image slider using HTML, CSS and JavaScript. Let’s begin with creating the image slider."
},
{
"code": null,
"e": 547,
"s": 394,
"text": "Step – 1: Create the structure of image slider using HTML and insert images from the respective sources. Below is the complete HTML code for doing this:"
},
{
"code": "<!--HTML Code--><!-- Slideshow Container Div --><div class=\"container\"> <!-- Full-width images with caption text --> <div class=\"image-sliderfade fade\"> <img src=\"img1.jpg\" style=\"width:100%\"> <div class=\"text\">Image caption 1</div> </div> <div class=\"image-sliderfade fade\"> <img src=\"img2.jpg\" style=\"width:100%\"> <div class=\"text\">Image caption 2</div> </div> <div class=\"image-sliderfade fade\"> <img src=\"img3.jpg\" style=\"width:100%\"> <div class=\"text\">Image caption 3</div> </div> <div class=\"image-sliderfade fade\"> <img src=\"img3.jpg\" style=\"width:100%\"> <div class=\"text\">Image caption 4</div> </div> </div><br> <!-- The dots/circles --><div style=\"text-align:center\"> <span class=\"dot\"></span> <span class=\"dot\"></span> <span class=\"dot\"></span> </div>",
"e": 1357,
"s": 547,
"text": null
},
{
"code": null,
"e": 1680,
"s": 1357,
"text": "Step – 2: Once we have created the HTML structure for our image slider, the next step is to style the slider using CSS. We will add styles to the images, backgrounds etc. We will also style the dots and make our images responsive and browser friendly using CSS. Below is the complete CSS code for styling our image slider:"
},
{
"code": "// CSS code* { box-sizing: border-box;}body { font-family: Verdana, sans-serif;} .image-sliderfade { display: none;} img { vertical-align: middle;} /* Slideshow container */.container { max-width: 1000px; position: relative; margin: auto;} /* Caption text */.text { color: #f2f2f2; font-size: 15px; padding: 20px 15px; position: absolute; right: 10px; bottom: 10px; width: 40%; background: rgba(0, 0, 0, .7); text-align: left;} /* The dots/bullets/indicators */.dot { height: 15px; width: 15px; margin: 0 2px; background-color: transparent; border-color: #ddd; border-width: 5 px; border-style: solid; border-radius: 50%; display: inline-block; transition: border-color 0.6s ease;} .active { border-color: #666;} /* Animation */.fade { -webkit-animation-name: fade-image; -webkit-animation-duration: 1.5s; animation-name: fade-image; animation-duration: 1.5s;} @-webkit-keyframes fade-image{ from {opacity: .4} to {opacity: 1}} @keyframes fade-image{ from {opacity: .4} to {opacity: 1}} /* On smaller screens, decrease text size */@media only screen and (max-width: 300px) { .text {font-size: 11px}}",
"e": 2828,
"s": 1680,
"text": null
},
{
"code": null,
"e": 3622,
"s": 2828,
"text": "Step – 3: After adding styles to the slider, the last thing left is to use javascript to add the functionality of auto changing of images after a specific time interval.In the code snippet below, at the very beginning, we took all the div elements with class name ‘image-sliderfade’ in an array and did the same for div’s with class name ‘dots’ by using getElementByClassName() listener. After that, we set the display for all of the divs, containing images. In the last for-loop, we have erased the class name for each element of array dots[]. After we are done with these, we set the display as a block of the image to shown and append the class name to the corresponding element of dots[] array. Function setTimeout is used for calling the function showslides() in an interval of 2 seconds."
},
{
"code": null,
"e": 3661,
"s": 3622,
"text": "Below is the complete JavaScript code:"
},
{
"code": "var slideIndex = 0;showSlides(); // call showslide method function showSlides(){ var i; // get the array of divs' with classname image-sliderfade var slides = document.getElementsByClassName(\"image-sliderfade\"); // get the array of divs' with classname dot var dots = document.getElementsByClassName(\"dot\"); for (i = 0; i < slides.length; i++) { // initially set the display to // none for every image. slides[i].style.display = \"none\"; } // increase by 1, Global variable slideIndex++; // check for boundary if (slideIndex > slides.length) { slideIndex = 1; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className. replace(\" active\", \"\"); } slides[slideIndex - 1].style.display = \"block\"; dots[slideIndex - 1].className += \" active\"; // Change image every 2 seconds setTimeout(showSlides, 2000); }",
"e": 4633,
"s": 3661,
"text": null
},
{
"code": null,
"e": 4733,
"s": 4633,
"text": "Once we are done with all of the above steps, we will get the slider up and working as shown below:"
},
{
"code": null,
"e": 4744,
"s": 4733,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4748,
"s": 4744,
"text": "CSS"
},
{
"code": null,
"e": 4753,
"s": 4748,
"text": "HTML"
},
{
"code": null,
"e": 4770,
"s": 4753,
"text": "Web Technologies"
},
{
"code": null,
"e": 4775,
"s": 4770,
"text": "HTML"
}
] |
Quiver Plot in Matplotlib
|
23 Feb, 2022
Quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plots are useful in Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering.
Let’s start creating a simple quiver plot containing one arrow which will explain how Matplotlib’s ax.quiver() function works. The ax.quiver() function takes four arguments:
Syntax:
ax.quiver(x_pos, y_pos, x_dir, y_dir, color)
Here x_pos and y_pos are the starting positions of the arrow while x_dir and y_dir are the directions of the arrow. The below plot contains one quiver arrow starting at x_pos = 0 and y_pos = 0.The direction of the arrow is pointing towards up and the right at x_dir = 1 and y_dir = 1.
Example:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx_pos = 0y_pos = 0x_direct = 1y_direct = 1 # Creating plotfig, ax = plt.subplots(figsize = (12, 7))ax.quiver(x_pos, y_pos, x_direct, y_direct)ax.set_title('Quiver plot with one arrow') # Show plotplt.show()
Output :
Let’s add another arrow to the plot passing through two starting points and two directions. By keeping the original arrow starting at origin(0, 0) and pointing towards up and to the right direction(1, 1), and create the second arrow starting at (0, 0) pointing down in direction(0, -1).To see the starting and ending point clearly, we will set axis limits to [-1.5, 1.5] using the method ax.axis() and passing the arguments in the form of [x_min, x_max, y_max, y_min] . By adding an additional argument scale=value to the ax.quiver() method we can manage the lengths of the arrows to look longer and show up better on the plot.
Example:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx_pos = [0, 0]y_pos = [0, 0]x_direct = [1, 0]y_direct = [1, -1] # Creating plotfig, ax = plt.subplots(figsize = (12, 7))ax.quiver(x_pos, y_pos, x_direct, y_direct, scale = 5) ax.axis([-1.5, 1.5, -1.5, 1.5]) # show plotplt.show()
Output :
A quiver plot containing two arrows is a good start, but it is too slow and too long to add arrows to the quiver plot one by one.So to create a fully 2D surface of arrows we will use meshgrid() method of Numpy. First, create a set of arrays named X and Y which represent the starting positions of x and y respectively of each arrow on the quiver plot. The starting positions of x, y arrows can also be used to define the x and y components of each arrow direction. In the following plot u and v denote the array of directions of the quiver arrows and we will define the arrow direction based on the arrow starting point by using the equations below:
x_{direction} = cos(x_{starting \ point})
y_{direction} = sin(y_{starting \ point})
Example:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx = np.arange(0, 2.2, 0.2)y = np.arange(0, 2.2, 0.2) X, Y = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(Y)*Y # creating plotfig, ax = plt.subplots(figsize =(14, 8))ax.quiver(X, Y, u, v) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.axis([-0.3, 2.3, -0.3, 2.3])ax.set_aspect('equal') # show plotplt.show()
Output :
Let us create a quiver plot which shows the gradient function.The np, gradient() method of Numpy can be used to apply the gradient function to each arrow’s x, y starting position. The equation is used to create the following plot:
z = xe^{-x^2-y^2}
Example:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowsx = np.arange(-2, 2.2, 0.2)y = np.arange(-2, 2.2, 0.2) # Creating gradientX, Y = np.meshgrid(x, y)z = X * np.exp(-X**2-Y**2)dx, dy = np.gradient(z) # Creating plotfig, ax = plt.subplots(figsize =(9, 9))ax.quiver(X, Y, dx, dy) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.set_aspect('equal') # show plotplt.show()
Output :
The ax.quiver() method of matplotlib library of python provides an optional attribute color that specifies the color of the arrow. The quiver color attribute requires the dimensions the same as the position and direction arrays.
Below is the code which modifies the quiver plots we made earlier:
Example 1:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Defining subplotsfig, (ax1, ax2) = plt.subplots(1, 2, figsize =(14, 8)) # first subplot# Creating arrowsx = np.arange(0, 2.2, 0.2)y = np.arange(0, 2.2, 0.2)X, Y = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(y)*Yn = -2 # Defining colorcolor = np.sqrt(((v-n)/2)*2 + ((u-n)/2)*2) # Creating plotax1.quiver(X, Y, u, v, color, alpha = 0.8)ax1.xaxis.set_ticks([])ax1.yaxis.set_ticks([])ax1.axis([-0.2, 2.3, -0.2, 2.3])ax1.set_aspect('equal')ax1.set_title('meshgrid function') # second subplot# Creating arrowsx = np.arange(-2, 2.2, 0.2)y = np.arange(-2, 2.2, 0.2)X, Y = np.meshgrid(x, y)z = X * np.exp(-X**2 -Y**2)dx, dy = np.gradient(z)n = -2 # Defining colorcolor = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2) # Creating plotax2.quiver(X, Y, dx, dy, color)ax2.xaxis.set_ticks([])ax2.yaxis.set_ticks([])ax2.set_aspect('equal')ax2.set_title('gradient') # show figureplt.tight_layout()plt.show()
Output :
Example 2: Building a quiver plot of function which defines the 2D field having four vertices as shown in the below plot:
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx = np.arange(0, 2 * np.pi + 2 * np.pi / 20, 2 * np.pi / 20)y = np.arange(0, 2 * np.pi + 2 * np.pi / 20, 2 * np.pi / 20) X, Y = np.meshgrid(x, y) u = np.sin(X)*np.cos(Y)v = -np.cos(X)*np.sin(Y) # Defining colorcolor = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2) # Creating plotfig, ax = plt.subplots(figsize =(14, 9))ax.quiver(X, Y, u, v, color, alpha = 1) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.axis([0, 2 * np.pi, 0, 2 * np.pi])ax.set_aspect('equal') # show plotplt.show()
Output :
simmytarika5
sumitgumber28
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 249,
"s": 28,
"text": "Quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plots are useful in Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering. "
},
{
"code": null,
"e": 424,
"s": 249,
"text": "Let’s start creating a simple quiver plot containing one arrow which will explain how Matplotlib’s ax.quiver() function works. The ax.quiver() function takes four arguments: "
},
{
"code": null,
"e": 433,
"s": 424,
"text": "Syntax: "
},
{
"code": null,
"e": 479,
"s": 433,
"text": "ax.quiver(x_pos, y_pos, x_dir, y_dir, color) "
},
{
"code": null,
"e": 764,
"s": 479,
"text": "Here x_pos and y_pos are the starting positions of the arrow while x_dir and y_dir are the directions of the arrow. The below plot contains one quiver arrow starting at x_pos = 0 and y_pos = 0.The direction of the arrow is pointing towards up and the right at x_dir = 1 and y_dir = 1."
},
{
"code": null,
"e": 775,
"s": 764,
"text": "Example: "
},
{
"code": null,
"e": 783,
"s": 775,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx_pos = 0y_pos = 0x_direct = 1y_direct = 1 # Creating plotfig, ax = plt.subplots(figsize = (12, 7))ax.quiver(x_pos, y_pos, x_direct, y_direct)ax.set_title('Quiver plot with one arrow') # Show plotplt.show()",
"e": 1075,
"s": 783,
"text": null
},
{
"code": null,
"e": 1085,
"s": 1075,
"text": "Output : "
},
{
"code": null,
"e": 1715,
"s": 1087,
"text": "Let’s add another arrow to the plot passing through two starting points and two directions. By keeping the original arrow starting at origin(0, 0) and pointing towards up and to the right direction(1, 1), and create the second arrow starting at (0, 0) pointing down in direction(0, -1).To see the starting and ending point clearly, we will set axis limits to [-1.5, 1.5] using the method ax.axis() and passing the arguments in the form of [x_min, x_max, y_max, y_min] . By adding an additional argument scale=value to the ax.quiver() method we can manage the lengths of the arrows to look longer and show up better on the plot."
},
{
"code": null,
"e": 1726,
"s": 1715,
"text": "Example: "
},
{
"code": null,
"e": 1734,
"s": 1726,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx_pos = [0, 0]y_pos = [0, 0]x_direct = [1, 0]y_direct = [1, -1] # Creating plotfig, ax = plt.subplots(figsize = (12, 7))ax.quiver(x_pos, y_pos, x_direct, y_direct, scale = 5) ax.axis([-1.5, 1.5, -1.5, 1.5]) # show plotplt.show()",
"e": 2056,
"s": 1734,
"text": null
},
{
"code": null,
"e": 2067,
"s": 2056,
"text": "Output : "
},
{
"code": null,
"e": 2720,
"s": 2069,
"text": "A quiver plot containing two arrows is a good start, but it is too slow and too long to add arrows to the quiver plot one by one.So to create a fully 2D surface of arrows we will use meshgrid() method of Numpy. First, create a set of arrays named X and Y which represent the starting positions of x and y respectively of each arrow on the quiver plot. The starting positions of x, y arrows can also be used to define the x and y components of each arrow direction. In the following plot u and v denote the array of directions of the quiver arrows and we will define the arrow direction based on the arrow starting point by using the equations below: "
},
{
"code": null,
"e": 2804,
"s": 2720,
"text": "x_{direction} = cos(x_{starting \\ point})\ny_{direction} = sin(y_{starting \\ point})"
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": "Example: "
},
{
"code": null,
"e": 2823,
"s": 2815,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx = np.arange(0, 2.2, 0.2)y = np.arange(0, 2.2, 0.2) X, Y = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(Y)*Y # creating plotfig, ax = plt.subplots(figsize =(14, 8))ax.quiver(X, Y, u, v) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.axis([-0.3, 2.3, -0.3, 2.3])ax.set_aspect('equal') # show plotplt.show()",
"e": 3213,
"s": 2823,
"text": null
},
{
"code": null,
"e": 3224,
"s": 3213,
"text": "Output : "
},
{
"code": null,
"e": 3457,
"s": 3226,
"text": "Let us create a quiver plot which shows the gradient function.The np, gradient() method of Numpy can be used to apply the gradient function to each arrow’s x, y starting position. The equation is used to create the following plot:"
},
{
"code": null,
"e": 3475,
"s": 3457,
"text": "z = xe^{-x^2-y^2}"
},
{
"code": null,
"e": 3485,
"s": 3475,
"text": "Example: "
},
{
"code": null,
"e": 3493,
"s": 3485,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowsx = np.arange(-2, 2.2, 0.2)y = np.arange(-2, 2.2, 0.2) # Creating gradientX, Y = np.meshgrid(x, y)z = X * np.exp(-X**2-Y**2)dx, dy = np.gradient(z) # Creating plotfig, ax = plt.subplots(figsize =(9, 9))ax.quiver(X, Y, dx, dy) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.set_aspect('equal') # show plotplt.show()",
"e": 3894,
"s": 3493,
"text": null
},
{
"code": null,
"e": 3905,
"s": 3894,
"text": "Output : "
},
{
"code": null,
"e": 4137,
"s": 3907,
"text": "The ax.quiver() method of matplotlib library of python provides an optional attribute color that specifies the color of the arrow. The quiver color attribute requires the dimensions the same as the position and direction arrays. "
},
{
"code": null,
"e": 4204,
"s": 4137,
"text": "Below is the code which modifies the quiver plots we made earlier:"
},
{
"code": null,
"e": 4216,
"s": 4204,
"text": "Example 1: "
},
{
"code": null,
"e": 4224,
"s": 4216,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Defining subplotsfig, (ax1, ax2) = plt.subplots(1, 2, figsize =(14, 8)) # first subplot# Creating arrowsx = np.arange(0, 2.2, 0.2)y = np.arange(0, 2.2, 0.2)X, Y = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(y)*Yn = -2 # Defining colorcolor = np.sqrt(((v-n)/2)*2 + ((u-n)/2)*2) # Creating plotax1.quiver(X, Y, u, v, color, alpha = 0.8)ax1.xaxis.set_ticks([])ax1.yaxis.set_ticks([])ax1.axis([-0.2, 2.3, -0.2, 2.3])ax1.set_aspect('equal')ax1.set_title('meshgrid function') # second subplot# Creating arrowsx = np.arange(-2, 2.2, 0.2)y = np.arange(-2, 2.2, 0.2)X, Y = np.meshgrid(x, y)z = X * np.exp(-X**2 -Y**2)dx, dy = np.gradient(z)n = -2 # Defining colorcolor = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2) # Creating plotax2.quiver(X, Y, dx, dy, color)ax2.xaxis.set_ticks([])ax2.yaxis.set_ticks([])ax2.set_aspect('equal')ax2.set_title('gradient') # show figureplt.tight_layout()plt.show()",
"e": 5177,
"s": 4224,
"text": null
},
{
"code": null,
"e": 5188,
"s": 5177,
"text": "Output : "
},
{
"code": null,
"e": 5310,
"s": 5188,
"text": "Example 2: Building a quiver plot of function which defines the 2D field having four vertices as shown in the below plot:"
},
{
"code": null,
"e": 5318,
"s": 5310,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Creating arrowx = np.arange(0, 2 * np.pi + 2 * np.pi / 20, 2 * np.pi / 20)y = np.arange(0, 2 * np.pi + 2 * np.pi / 20, 2 * np.pi / 20) X, Y = np.meshgrid(x, y) u = np.sin(X)*np.cos(Y)v = -np.cos(X)*np.sin(Y) # Defining colorcolor = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2) # Creating plotfig, ax = plt.subplots(figsize =(14, 9))ax.quiver(X, Y, u, v, color, alpha = 1) ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])ax.axis([0, 2 * np.pi, 0, 2 * np.pi])ax.set_aspect('equal') # show plotplt.show()",
"e": 5904,
"s": 5318,
"text": null
},
{
"code": null,
"e": 5915,
"s": 5904,
"text": "Output : "
},
{
"code": null,
"e": 5930,
"s": 5917,
"text": "simmytarika5"
},
{
"code": null,
"e": 5944,
"s": 5930,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5962,
"s": 5944,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 5969,
"s": 5962,
"text": "Python"
}
] |
Difference between “__eq__” VS “is” VS “==” in Python
|
01 Oct, 2020
There are various ways using which the objects of any type in Python can be compared. Python has “==” operator, “is” operator, and “__eq__” dunder method for comparing two objects of a class or to customize the comparison. This article explains the above said three operators and how they differ from each other.
The “==” operator compares the value or equality of two objects, whereas the Python “is” operator checks whether two variables point to the same object in memory.
Example 1:
Python3
# lists initializationx = [1, 2]y = [1, 2] z = y # comparisonsprint("x == y : ", x == y)print("z == y : ", z == y) # location in memoryprint("Location of x is ", id(x))print("Location of y is ", id(y))print("Location of z is ", id(z))
x == y : True
z == y : True
Location of x is 140169895643144
Location of y is 140169895642952
Location of z is 140169895642952
Example 2:
Python3
class Student: def __init__(self, name): self.name = name divyansh = Student("Divyansh")shivansh = Student("Divyansh") print("divyansh == shivansh : ", (divyansh == shivansh))
divyansh == shivansh : False
In the above example, we should have got an output True, but instead, the output we received was False. This is because, for objects of user-defined classes, we need to specify how we are going to compare them. The Student object that we created has no idea on what is the criteria for two Students being equal, maybe they have the same attribute ‘name’, maybe they have a bunch of other features about them. What needs to be the same for us to say that one Student object is the same as another Student. Well, that’s what we are going to specify by ourselves by implementing a method there called __eq__. This is one of the dunder methods in Python. It allows us to override the basic functionality of “==” operator in Python.
Example 3:
Python3
class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student("Divyansh")shivansh = Student("Divyansh") print("divyansh == shivansh : ", (divyansh == shivansh))
divyansh == shivansh : True
Implementing this dunder method, “==” operator is used between two objects of Student class and get an accurate value comparison, now this is going to be different if I switch this to ‘is‘ operator.
Example 4:
Python3
class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student("Divyansh")shivansh = Student("Divyansh") print("divyansh is shivansh : ", (divyansh is shivansh))
divyansh is shivansh : False
Here in the above code snippet, we received False as output, this is because divyansh is going to be different from the shivansh although these objects hold the same value. However, they have different memory locations i.e., they are different and unique objects that could change their properties at any point in time independently.
Example 5:
Python3
class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student("Divyansh")shivansh = divyansh print("divyansh is shivansh : ", (divyansh is shivansh))
divyansh is shivansh : True
Now in the example above, the output is True, this is because of shivansh points to the same Student object that divyansh points to.
The ‘is’ operator compares the identity of two objects. Here we compare the objects itself.
Example 6:
Python3
x = [1, 2]y = [1, 2]z = yprint("x is y : ", x is y)print("z is y : ", z is y)print("Location of x is ", id(x))print("Location of y is ", id(y))print("Location of z is ", id(z))
x is y : False
z is y : True
Location of x is 139987316430856
Location of y is 139987316430664
Location of z is 139987316430664
In the example above, even if x and y have the same values, they store them in different locations in memory. So it is clear that even though the objects are the same in terms of the values their locations in memory are actually different. We also see that in the above snippet z is y gives True, this is because these objects are actually identical i.e., the location of y and location of z above are exactly the same.
Python-Operators
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 367,
"s": 54,
"text": "There are various ways using which the objects of any type in Python can be compared. Python has “==” operator, “is” operator, and “__eq__” dunder method for comparing two objects of a class or to customize the comparison. This article explains the above said three operators and how they differ from each other."
},
{
"code": null,
"e": 530,
"s": 367,
"text": "The “==” operator compares the value or equality of two objects, whereas the Python “is” operator checks whether two variables point to the same object in memory."
},
{
"code": null,
"e": 541,
"s": 530,
"text": "Example 1:"
},
{
"code": null,
"e": 549,
"s": 541,
"text": "Python3"
},
{
"code": "# lists initializationx = [1, 2]y = [1, 2] z = y # comparisonsprint(\"x == y : \", x == y)print(\"z == y : \", z == y) # location in memoryprint(\"Location of x is \", id(x))print(\"Location of y is \", id(y))print(\"Location of z is \", id(z))",
"e": 787,
"s": 549,
"text": null
},
{
"code": null,
"e": 920,
"s": 787,
"text": "x == y : True\nz == y : True\nLocation of x is 140169895643144\nLocation of y is 140169895642952\nLocation of z is 140169895642952\n"
},
{
"code": null,
"e": 931,
"s": 920,
"text": "Example 2:"
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Python3"
},
{
"code": "class Student: def __init__(self, name): self.name = name divyansh = Student(\"Divyansh\")shivansh = Student(\"Divyansh\") print(\"divyansh == shivansh : \", (divyansh == shivansh))",
"e": 1129,
"s": 939,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1129,
"text": "divyansh == shivansh : False\n"
},
{
"code": null,
"e": 1889,
"s": 1160,
"text": "In the above example, we should have got an output True, but instead, the output we received was False. This is because, for objects of user-defined classes, we need to specify how we are going to compare them. The Student object that we created has no idea on what is the criteria for two Students being equal, maybe they have the same attribute ‘name’, maybe they have a bunch of other features about them. What needs to be the same for us to say that one Student object is the same as another Student. Well, that’s what we are going to specify by ourselves by implementing a method there called __eq__. This is one of the dunder methods in Python. It allows us to override the basic functionality of “==” operator in Python. "
},
{
"code": null,
"e": 1900,
"s": 1889,
"text": "Example 3:"
},
{
"code": null,
"e": 1908,
"s": 1900,
"text": "Python3"
},
{
"code": "class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student(\"Divyansh\")shivansh = Student(\"Divyansh\") print(\"divyansh == shivansh : \", (divyansh == shivansh))",
"e": 2252,
"s": 1908,
"text": null
},
{
"code": null,
"e": 2282,
"s": 2252,
"text": "divyansh == shivansh : True\n"
},
{
"code": null,
"e": 2481,
"s": 2282,
"text": "Implementing this dunder method, “==” operator is used between two objects of Student class and get an accurate value comparison, now this is going to be different if I switch this to ‘is‘ operator."
},
{
"code": null,
"e": 2492,
"s": 2481,
"text": "Example 4:"
},
{
"code": null,
"e": 2500,
"s": 2492,
"text": "Python3"
},
{
"code": "class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student(\"Divyansh\")shivansh = Student(\"Divyansh\") print(\"divyansh is shivansh : \", (divyansh is shivansh))",
"e": 2844,
"s": 2500,
"text": null
},
{
"code": null,
"e": 2875,
"s": 2844,
"text": "divyansh is shivansh : False\n"
},
{
"code": null,
"e": 3209,
"s": 2875,
"text": "Here in the above code snippet, we received False as output, this is because divyansh is going to be different from the shivansh although these objects hold the same value. However, they have different memory locations i.e., they are different and unique objects that could change their properties at any point in time independently."
},
{
"code": null,
"e": 3220,
"s": 3209,
"text": "Example 5:"
},
{
"code": null,
"e": 3228,
"s": 3220,
"text": "Python3"
},
{
"code": "class Student: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Student): if other.name == self.name: return True return False divyansh = Student(\"Divyansh\")shivansh = divyansh print(\"divyansh is shivansh : \", (divyansh is shivansh))",
"e": 3561,
"s": 3228,
"text": null
},
{
"code": null,
"e": 3591,
"s": 3561,
"text": "divyansh is shivansh : True\n"
},
{
"code": null,
"e": 3725,
"s": 3591,
"text": "Now in the example above, the output is True, this is because of shivansh points to the same Student object that divyansh points to. "
},
{
"code": null,
"e": 3817,
"s": 3725,
"text": "The ‘is’ operator compares the identity of two objects. Here we compare the objects itself."
},
{
"code": null,
"e": 3828,
"s": 3817,
"text": "Example 6:"
},
{
"code": null,
"e": 3836,
"s": 3828,
"text": "Python3"
},
{
"code": "x = [1, 2]y = [1, 2]z = yprint(\"x is y : \", x is y)print(\"z is y : \", z is y)print(\"Location of x is \", id(x))print(\"Location of y is \", id(y))print(\"Location of z is \", id(z))",
"e": 4013,
"s": 3836,
"text": null
},
{
"code": null,
"e": 4147,
"s": 4013,
"text": "x is y : False\nz is y : True\nLocation of x is 139987316430856\nLocation of y is 139987316430664\nLocation of z is 139987316430664\n"
},
{
"code": null,
"e": 4567,
"s": 4147,
"text": "In the example above, even if x and y have the same values, they store them in different locations in memory. So it is clear that even though the objects are the same in terms of the values their locations in memory are actually different. We also see that in the above snippet z is y gives True, this is because these objects are actually identical i.e., the location of y and location of z above are exactly the same."
},
{
"code": null,
"e": 4584,
"s": 4567,
"text": "Python-Operators"
},
{
"code": null,
"e": 4591,
"s": 4584,
"text": "Python"
},
{
"code": null,
"e": 4689,
"s": 4591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4707,
"s": 4689,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4749,
"s": 4707,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4771,
"s": 4749,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4806,
"s": 4771,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4832,
"s": 4806,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4864,
"s": 4832,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4893,
"s": 4864,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4920,
"s": 4893,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4950,
"s": 4920,
"text": "Iterate over a list in Python"
}
] |
Make all elements of an Array equal by adding or subtracting at most K
|
12 Jun, 2022
Given an array arr[] containing positive integers of size N and an integer K, the task is to make all the elements in the array equal to some value D (D > 0) such that |arr[i] – D| ≤ K. Print the value of D or -1 if it is not possible to make the array equal. Examples:
Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 3 Explanation: All the elements in the array can be made equal to 3 as: |arr[0] – 3| = 2 ≤ 2 |arr[1] – 3| = 1 ≤ 2 |arr[2] – 3| = 0 ≤ 2 |arr[3] – 3| = 1 ≤ 2 |arr[4] – 3| = 2 ≤ 2 Input: arr[] = {1, 6, 20}, K = 1 Output: -1 Explanation: It is not possible to equalize the array
Approach: The idea is to first find the minimum element of the array.
If M is the minimum element of the array, then M + K is the maximum possible value which this minimum element can take in order to satisfy the condition arr[i] – D ≤ K.
Then, D = M + K, if for all the elements in the array, (M + K) lies in the range [arr[i] – K, arr[i] + K].
Therefore, we simply iterate over every element in the array and check for this condition.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to make all elements// of an Array equal by adding or// subtracting at most K #include <bits/stdc++.h>using namespace std; // Function to equalize the array by// adding or subtracting at most K// value from each elementint equalize(int arr[], int n, int k){ // Finding the minimum element // from the array int min_ele = *min_element(arr, arr + n); // Boolean variable to check if the // array can be equalized or not bool flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codeint main(){ int K = 2; int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); cout << equalize(arr, N, K);}
// Java program to make all elements// of an Array equal by adding or// subtracting at most Kimport java.util.*; class GFG{ // Function to equalize the array by// adding or subtracting at most K// value from each elementstatic int equalize(int arr[], int n, int k){ // Finding the minimum element // from the array int min_ele = Arrays.stream(arr).min().getAsInt(); // Boolean variable to check if the // array can be equalized or not boolean flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codepublic static void main(String[] args){ int K = 2; int arr[] = { 1, 2, 3, 4, 5 }; int N = arr.length; System.out.print(equalize(arr, N, K));}} // This code is contributed by Princi Singh
# Python program to make all elements# of an Array equal by adding or# subtracting at most K # Function to equalize the array by# adding or subtracting at most K# value from each elementdef equalize(arr, n, k): # Finding the minimum element # from the array min_ele = min(arr); # Boolean variable to check if the # array can be equalized or not flag = True; # Traversing the array for i in range(n): # Checking if the values lie # within the possible range # for each element if (not((arr[i] + k) >= (min_ele + k) and (min_ele + k) >= (arr[i] - k))) : # If any value doesn't lie in # the range then exit the loop flag = False; break; if (flag): # Value after equalizing the array return min_ele + k; # Array cannot be equalized else: return -1; # Driver codeif __name__=='__main__': K = 2; arr = [ 1, 2, 3, 4, 5] ; N = len(arr) print(equalize(arr, N, K)) # This code is contributed by Princi Singh
// C# program to make all elements// of an Array equal by adding or// subtracting at most Kusing System;using System.Linq; class GFG{ // Function to equalize the array by// adding or subtracting at most K// value from each elementstatic int equalize(int []arr, int n, int k){ // Finding the minimum element // from the array int min_ele = arr.Min(); // Boolean variable to check if the // array can be equalized or not bool flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codepublic static void Main(String[] args){ int K = 2; int []arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; Console.Write(equalize(arr, N, K));}} // This code is contributed by Princi Singh
<script>// Javascript program to make all elements// of an Array equal by adding or// subtracting at most K // Function to equalize the array by// adding or subtracting at most K// value from each elementfunction equalize(arr, n, k){ // Finding the minimum element // from the array let min_ele = arr.sort((a, b) => a - b)[0]; // Boolean variable to check if the // array can be equalized or not let flag = true; // Traversing the array for (let i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver code let K = 2;let arr = [ 1, 2, 3, 4, 5 ];let N = arr.length; document.write(equalize(arr, N, K)); // This code is contributed by _saurabh_jaiswal</script>
3
Time Complexity: O(n), to traverse the array where n is the size of the given array Auxiliary Space: O(1), as no extra space is used
princi singh
_saurabh_jaiswal
singhh3010
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of subarrays with average K
Introduction to Data Structures
Window Sliding Technique
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Next Greater Element
What is Data Structure: Types, Classifications and Applications
Merge Overlapping Intervals
Count of longest possible subarrays with sum not divisible by K
Find a triplet that sum to a given value
Remove duplicates from sorted array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 324,
"s": 52,
"text": "Given an array arr[] containing positive integers of size N and an integer K, the task is to make all the elements in the array equal to some value D (D > 0) such that |arr[i] – D| ≤ K. Print the value of D or -1 if it is not possible to make the array equal. Examples: "
},
{
"code": null,
"e": 647,
"s": 324,
"text": "Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 3 Explanation: All the elements in the array can be made equal to 3 as: |arr[0] – 3| = 2 ≤ 2 |arr[1] – 3| = 1 ≤ 2 |arr[2] – 3| = 0 ≤ 2 |arr[3] – 3| = 1 ≤ 2 |arr[4] – 3| = 2 ≤ 2 Input: arr[] = {1, 6, 20}, K = 1 Output: -1 Explanation: It is not possible to equalize the array "
},
{
"code": null,
"e": 721,
"s": 649,
"text": "Approach: The idea is to first find the minimum element of the array. "
},
{
"code": null,
"e": 890,
"s": 721,
"text": "If M is the minimum element of the array, then M + K is the maximum possible value which this minimum element can take in order to satisfy the condition arr[i] – D ≤ K."
},
{
"code": null,
"e": 997,
"s": 890,
"text": "Then, D = M + K, if for all the elements in the array, (M + K) lies in the range [arr[i] – K, arr[i] + K]."
},
{
"code": null,
"e": 1088,
"s": 997,
"text": "Therefore, we simply iterate over every element in the array and check for this condition."
},
{
"code": null,
"e": 1141,
"s": 1088,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1145,
"s": 1141,
"text": "C++"
},
{
"code": null,
"e": 1150,
"s": 1145,
"text": "Java"
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Python3"
},
{
"code": null,
"e": 1161,
"s": 1158,
"text": "C#"
},
{
"code": null,
"e": 1172,
"s": 1161,
"text": "Javascript"
},
{
"code": "// C++ program to make all elements// of an Array equal by adding or// subtracting at most K #include <bits/stdc++.h>using namespace std; // Function to equalize the array by// adding or subtracting at most K// value from each elementint equalize(int arr[], int n, int k){ // Finding the minimum element // from the array int min_ele = *min_element(arr, arr + n); // Boolean variable to check if the // array can be equalized or not bool flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codeint main(){ int K = 2; int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); cout << equalize(arr, N, K);}",
"e": 2345,
"s": 1172,
"text": null
},
{
"code": "// Java program to make all elements// of an Array equal by adding or// subtracting at most Kimport java.util.*; class GFG{ // Function to equalize the array by// adding or subtracting at most K// value from each elementstatic int equalize(int arr[], int n, int k){ // Finding the minimum element // from the array int min_ele = Arrays.stream(arr).min().getAsInt(); // Boolean variable to check if the // array can be equalized or not boolean flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codepublic static void main(String[] args){ int K = 2; int arr[] = { 1, 2, 3, 4, 5 }; int N = arr.length; System.out.print(equalize(arr, N, K));}} // This code is contributed by Princi Singh",
"e": 3599,
"s": 2345,
"text": null
},
{
"code": "# Python program to make all elements# of an Array equal by adding or# subtracting at most K # Function to equalize the array by# adding or subtracting at most K# value from each elementdef equalize(arr, n, k): # Finding the minimum element # from the array min_ele = min(arr); # Boolean variable to check if the # array can be equalized or not flag = True; # Traversing the array for i in range(n): # Checking if the values lie # within the possible range # for each element if (not((arr[i] + k) >= (min_ele + k) and (min_ele + k) >= (arr[i] - k))) : # If any value doesn't lie in # the range then exit the loop flag = False; break; if (flag): # Value after equalizing the array return min_ele + k; # Array cannot be equalized else: return -1; # Driver codeif __name__=='__main__': K = 2; arr = [ 1, 2, 3, 4, 5] ; N = len(arr) print(equalize(arr, N, K)) # This code is contributed by Princi Singh",
"e": 4660,
"s": 3599,
"text": null
},
{
"code": "// C# program to make all elements// of an Array equal by adding or// subtracting at most Kusing System;using System.Linq; class GFG{ // Function to equalize the array by// adding or subtracting at most K// value from each elementstatic int equalize(int []arr, int n, int k){ // Finding the minimum element // from the array int min_ele = arr.Min(); // Boolean variable to check if the // array can be equalized or not bool flag = true; // Traversing the array for (int i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver codepublic static void Main(String[] args){ int K = 2; int []arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; Console.Write(equalize(arr, N, K));}} // This code is contributed by Princi Singh",
"e": 5896,
"s": 4660,
"text": null
},
{
"code": "<script>// Javascript program to make all elements// of an Array equal by adding or// subtracting at most K // Function to equalize the array by// adding or subtracting at most K// value from each elementfunction equalize(arr, n, k){ // Finding the minimum element // from the array let min_ele = arr.sort((a, b) => a - b)[0]; // Boolean variable to check if the // array can be equalized or not let flag = true; // Traversing the array for (let i = 0; i < n; i++) { // Checking if the values lie // within the possible range // for each element if (!((arr[i] + k) >= min_ele + k && min_ele + k >= (arr[i] - k))) { // If any value doesn't lie in // the range then exit the loop flag = false; break; } } if (flag) { // Value after equalizing the array return min_ele + k; } // Array cannot be equalized else return -1;} // Driver code let K = 2;let arr = [ 1, 2, 3, 4, 5 ];let N = arr.length; document.write(equalize(arr, N, K)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 7048,
"s": 5896,
"text": null
},
{
"code": null,
"e": 7050,
"s": 7048,
"text": "3"
},
{
"code": null,
"e": 7185,
"s": 7052,
"text": "Time Complexity: O(n), to traverse the array where n is the size of the given array Auxiliary Space: O(1), as no extra space is used"
},
{
"code": null,
"e": 7198,
"s": 7185,
"text": "princi singh"
},
{
"code": null,
"e": 7215,
"s": 7198,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 7226,
"s": 7215,
"text": "singhh3010"
},
{
"code": null,
"e": 7233,
"s": 7226,
"text": "Arrays"
},
{
"code": null,
"e": 7240,
"s": 7233,
"text": "Arrays"
},
{
"code": null,
"e": 7338,
"s": 7240,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7372,
"s": 7338,
"text": "Count of subarrays with average K"
},
{
"code": null,
"e": 7404,
"s": 7372,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7429,
"s": 7404,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7488,
"s": 7429,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 7509,
"s": 7488,
"text": "Next Greater Element"
},
{
"code": null,
"e": 7573,
"s": 7509,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 7601,
"s": 7573,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 7665,
"s": 7601,
"text": "Count of longest possible subarrays with sum not divisible by K"
},
{
"code": null,
"e": 7706,
"s": 7665,
"text": "Find a triplet that sum to a given value"
}
] |
IntStream of() in Java
|
18 May, 2021
IntStream of(int t) returns a sequential IntStream containing a single element. Syntax :
static IntStream of(int t)
Parameters :
IntStream : A sequence of primitive int-valued elements.t : Represents the single element in the IntStream.
IntStream : A sequence of primitive int-valued elements.
t : Represents the single element in the IntStream.
Return Value : IntStream of(int t) returns a sequential IntStream containing the single specified element.Example :
Java
// Java code for IntStream of(int t)// to get a sequential IntStream// containing a single element.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream having single element only IntStream stream = IntStream.of(-7); // Displaying the IntStream having single element stream.forEach(System.out::println); }}
Output :
-7
IntStream of(int... values) returns a sequential ordered stream whose elements are the specified values. Syntax :
static IntStream of(int... values)
Parameters :
IntStream : A sequence of primitive int-valued elements.values : Represents the elements of the new stream.
IntStream : A sequence of primitive int-valued elements.
values : Represents the elements of the new stream.
Return Value : IntStream of(int... values) returns a sequential ordered stream whose elements are the specified values.Example 1 :
Java
// Java code for IntStream of(int... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(-7, -9, -11); // Displaying the sequential ordered stream stream.forEach(System.out::println); }}
Output :
-7
-9
-11
Example 2 :
Java
// Java code for IntStream of(int... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(-7, -9, -11); // Storing the count of elements in IntStream long total = stream.count(); // Displaying the count of elements System.out.println(total); }}
Output :
3
Example 3
Streams are not reusable if we have performed terminal operation on stream and try to reuse them again IllegalStateExeception will be generated
Java
import java.util.stream.IntStream;import java.io.PrintStream;class GFG{ static final PrintStream out=System.out; public static void main(String $[]){ IntStream intStream=IntStream.of(10,20,30); out.println(intStream.min()); try{ out.println(intStream.min());//Trying to use a stream that has been closed previously }catch(IllegalStateException e){ out.println(e); } }}
Output :
OptionalInt[10]
java.lang.IllegalStateException: stream has already been operated upon or closed
To reuse a stream we need Supplier class when get() method of Supplier is called every time it will generate a new instance and return it.
Java
import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.List;import java.util.stream.Collectors;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ //Reusing a stream Supplier<IntStream>supplier=()->IntStream.of(343,434,61,1,512, 5234,613434,561); //supplier.get() will return an instance of IntStream //sorting -> printing each value supplier.get() .sorted() .forEach(System.out::println); out.println(); //filtering even numbers -> sorting -> printing each value supplier.get() .filter(x->x%2==0) .sorted() .forEach(System.out::println); out.println(); //filtering odd numbers -> boxing(converting to Integer) -> converted to List<Integer> -> streaming -> sorting in reverse order //-> printing each value supplier.get() .filter(x->(x&1)==0) .boxed() .collect(Collectors.toList()) .stream() .sorted((a,b)->b-a) .forEach(System.out::println); }}
Output :
1
61
343
434
512
561
5234
613434
434
512
5234
613434
613434
5234
512
434
Example 4
Finding min,max,sum and average from an IntStream
Java
import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.OptionalInt;import java.util.OptionalDouble;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ Supplier<IntStream>supplier=()->IntStream.of(343,434,61,1,512, 5234,613434,561); //Average OptionalDouble avg=supplier.get().average(); out.println("Average : "+avg.orElse(0)); // Sum int sum=supplier.get().sum(); out.println("Sum : "+sum); // Min OptionalInt min=supplier.get().min(); out.println("min : "+min.orElse(0)); // Max OptionalInt max=supplier.get().max(); out.println("max : "+max.orElse(0)); }}
Output :
Average : 77572.5
Sum : 620580
min : 1
max : 613434
Example 5
Range based operation
Java
import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.OptionalInt;import java.util.OptionalDouble;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ //Range //Will iterate from 0 to 5 IntStream.range(0,6) .forEach(System.out::println); out.println(); //Will iterate from 0 to 6 IntStream.rangeClosed(0,6) .forEach(System.out::println); out.println(); //rangeSum=0+1+2+3+...+99=4950 int rangeSum=IntStream.range(0,100).sum(); out.println("sum[0,100) : "+rangeSum); //rangeClosedSum=0+1+2+3+...+100=5050 int rangeClosedSum=IntStream.rangeClosed(0,100).sum(); out.println("sum[0,100] : "+rangeClosedSum); }}
DevParzival404
Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue Interface In Java
Object Oriented Programming (OOPs) Concept in Java
Stack Class in Java
Interfaces in Java
ArrayList in Java
HashMap in Java with Examples
Collections in Java
ChronoZonedDateTime isAfter() method in Java with Examples
Multidimensional Arrays in Java
Introduction to Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 143,
"s": 52,
"text": "IntStream of(int t) returns a sequential IntStream containing a single element. Syntax : "
},
{
"code": null,
"e": 170,
"s": 143,
"text": "static IntStream of(int t)"
},
{
"code": null,
"e": 185,
"s": 170,
"text": "Parameters : "
},
{
"code": null,
"e": 293,
"s": 185,
"text": "IntStream : A sequence of primitive int-valued elements.t : Represents the single element in the IntStream."
},
{
"code": null,
"e": 350,
"s": 293,
"text": "IntStream : A sequence of primitive int-valued elements."
},
{
"code": null,
"e": 402,
"s": 350,
"text": "t : Represents the single element in the IntStream."
},
{
"code": null,
"e": 520,
"s": 402,
"text": "Return Value : IntStream of(int t) returns a sequential IntStream containing the single specified element.Example : "
},
{
"code": null,
"e": 525,
"s": 520,
"text": "Java"
},
{
"code": "// Java code for IntStream of(int t)// to get a sequential IntStream// containing a single element.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream having single element only IntStream stream = IntStream.of(-7); // Displaying the IntStream having single element stream.forEach(System.out::println); }}",
"e": 967,
"s": 525,
"text": null
},
{
"code": null,
"e": 978,
"s": 967,
"text": "Output : "
},
{
"code": null,
"e": 981,
"s": 978,
"text": "-7"
},
{
"code": null,
"e": 1099,
"s": 983,
"text": "IntStream of(int... values) returns a sequential ordered stream whose elements are the specified values. Syntax : "
},
{
"code": null,
"e": 1134,
"s": 1099,
"text": "static IntStream of(int... values)"
},
{
"code": null,
"e": 1149,
"s": 1134,
"text": "Parameters : "
},
{
"code": null,
"e": 1257,
"s": 1149,
"text": "IntStream : A sequence of primitive int-valued elements.values : Represents the elements of the new stream."
},
{
"code": null,
"e": 1314,
"s": 1257,
"text": "IntStream : A sequence of primitive int-valued elements."
},
{
"code": null,
"e": 1366,
"s": 1314,
"text": "values : Represents the elements of the new stream."
},
{
"code": null,
"e": 1499,
"s": 1366,
"text": "Return Value : IntStream of(int... values) returns a sequential ordered stream whose elements are the specified values.Example 1 : "
},
{
"code": null,
"e": 1504,
"s": 1499,
"text": "Java"
},
{
"code": "// Java code for IntStream of(int... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(-7, -9, -11); // Displaying the sequential ordered stream stream.forEach(System.out::println); }}",
"e": 1947,
"s": 1504,
"text": null
},
{
"code": null,
"e": 1958,
"s": 1947,
"text": "Output : "
},
{
"code": null,
"e": 1968,
"s": 1958,
"text": "-7\n-9\n-11"
},
{
"code": null,
"e": 1982,
"s": 1968,
"text": "Example 2 : "
},
{
"code": null,
"e": 1987,
"s": 1982,
"text": "Java"
},
{
"code": "// Java code for IntStream of(int... values)// to get a sequential ordered stream whose// elements are the specified values.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(-7, -9, -11); // Storing the count of elements in IntStream long total = stream.count(); // Displaying the count of elements System.out.println(total); }}",
"e": 2502,
"s": 1987,
"text": null
},
{
"code": null,
"e": 2513,
"s": 2502,
"text": "Output : "
},
{
"code": null,
"e": 2515,
"s": 2513,
"text": "3"
},
{
"code": null,
"e": 2526,
"s": 2515,
"text": " Example 3"
},
{
"code": null,
"e": 2671,
"s": 2526,
"text": "Streams are not reusable if we have performed terminal operation on stream and try to reuse them again IllegalStateExeception will be generated "
},
{
"code": null,
"e": 2676,
"s": 2671,
"text": "Java"
},
{
"code": "import java.util.stream.IntStream;import java.io.PrintStream;class GFG{ static final PrintStream out=System.out; public static void main(String $[]){ IntStream intStream=IntStream.of(10,20,30); out.println(intStream.min()); try{ out.println(intStream.min());//Trying to use a stream that has been closed previously }catch(IllegalStateException e){ out.println(e); } }}",
"e": 3111,
"s": 2676,
"text": null
},
{
"code": null,
"e": 3120,
"s": 3111,
"text": "Output :"
},
{
"code": null,
"e": 3218,
"s": 3120,
"text": "OptionalInt[10]\n\njava.lang.IllegalStateException: stream has already been operated upon or closed"
},
{
"code": null,
"e": 3358,
"s": 3218,
"text": "To reuse a stream we need Supplier class when get() method of Supplier is called every time it will generate a new instance and return it."
},
{
"code": null,
"e": 3363,
"s": 3358,
"text": "Java"
},
{
"code": "import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.List;import java.util.stream.Collectors;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ //Reusing a stream Supplier<IntStream>supplier=()->IntStream.of(343,434,61,1,512, 5234,613434,561); //supplier.get() will return an instance of IntStream //sorting -> printing each value supplier.get() .sorted() .forEach(System.out::println); out.println(); //filtering even numbers -> sorting -> printing each value supplier.get() .filter(x->x%2==0) .sorted() .forEach(System.out::println); out.println(); //filtering odd numbers -> boxing(converting to Integer) -> converted to List<Integer> -> streaming -> sorting in reverse order //-> printing each value supplier.get() .filter(x->(x&1)==0) .boxed() .collect(Collectors.toList()) .stream() .sorted((a,b)->b-a) .forEach(System.out::println); }}",
"e": 4602,
"s": 3363,
"text": null
},
{
"code": null,
"e": 4611,
"s": 4602,
"text": "Output :"
},
{
"code": null,
"e": 4686,
"s": 4611,
"text": "1\n61\n343\n434\n512\n561\n5234\n613434\n\n434\n512\n5234\n613434\n\n613434\n5234\n512\n434"
},
{
"code": null,
"e": 4696,
"s": 4686,
"text": "Example 4"
},
{
"code": null,
"e": 4746,
"s": 4696,
"text": "Finding min,max,sum and average from an IntStream"
},
{
"code": null,
"e": 4751,
"s": 4746,
"text": "Java"
},
{
"code": "import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.OptionalInt;import java.util.OptionalDouble;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ Supplier<IntStream>supplier=()->IntStream.of(343,434,61,1,512, 5234,613434,561); //Average OptionalDouble avg=supplier.get().average(); out.println(\"Average : \"+avg.orElse(0)); // Sum int sum=supplier.get().sum(); out.println(\"Sum : \"+sum); // Min OptionalInt min=supplier.get().min(); out.println(\"min : \"+min.orElse(0)); // Max OptionalInt max=supplier.get().max(); out.println(\"max : \"+max.orElse(0)); }}",
"e": 5584,
"s": 4751,
"text": null
},
{
"code": null,
"e": 5593,
"s": 5584,
"text": "Output :"
},
{
"code": null,
"e": 5645,
"s": 5593,
"text": "Average : 77572.5\nSum : 620580\nmin : 1\nmax : 613434"
},
{
"code": null,
"e": 5655,
"s": 5645,
"text": "Example 5"
},
{
"code": null,
"e": 5677,
"s": 5655,
"text": "Range based operation"
},
{
"code": null,
"e": 5682,
"s": 5677,
"text": "Java"
},
{
"code": "import java.util.stream.IntStream;import java.io.PrintStream;import java.util.function.Supplier;import java.util.OptionalInt;import java.util.OptionalDouble;public class IntStreamClass{ static final PrintStream out=System.out; public static void main(String $[]){ //Range //Will iterate from 0 to 5 IntStream.range(0,6) .forEach(System.out::println); out.println(); //Will iterate from 0 to 6 IntStream.rangeClosed(0,6) .forEach(System.out::println); out.println(); //rangeSum=0+1+2+3+...+99=4950 int rangeSum=IntStream.range(0,100).sum(); out.println(\"sum[0,100) : \"+rangeSum); //rangeClosedSum=0+1+2+3+...+100=5050 int rangeClosedSum=IntStream.rangeClosed(0,100).sum(); out.println(\"sum[0,100] : \"+rangeClosedSum); }}",
"e": 6563,
"s": 5682,
"text": null
},
{
"code": null,
"e": 6578,
"s": 6563,
"text": "DevParzival404"
},
{
"code": null,
"e": 6598,
"s": 6578,
"text": "Java - util package"
},
{
"code": null,
"e": 6613,
"s": 6598,
"text": "Java-Functions"
},
{
"code": null,
"e": 6628,
"s": 6613,
"text": "java-intstream"
},
{
"code": null,
"e": 6640,
"s": 6628,
"text": "java-stream"
},
{
"code": null,
"e": 6645,
"s": 6640,
"text": "Java"
},
{
"code": null,
"e": 6650,
"s": 6645,
"text": "Java"
},
{
"code": null,
"e": 6748,
"s": 6650,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6772,
"s": 6748,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 6823,
"s": 6772,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6843,
"s": 6823,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 6862,
"s": 6843,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6880,
"s": 6862,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6910,
"s": 6880,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6930,
"s": 6910,
"text": "Collections in Java"
},
{
"code": null,
"e": 6989,
"s": 6930,
"text": "ChronoZonedDateTime isAfter() method in Java with Examples"
},
{
"code": null,
"e": 7021,
"s": 6989,
"text": "Multidimensional Arrays in Java"
}
] |
Project Idea | AI Therapist
|
23 Nov, 2021
Project Title : AI therapist
Introduction: Input is user provided description about how his day went in two-three lines. Using natural language processing, our program detects how user is feeling. He may be feeling depressed, feared, angry etc. Then a recommender system is used to show him content based on his current emotions. For example if user is feeling depressed, program will show him motivational thoughts, blogs etc.
Conceptual framework:The project will be a combination of natural language processing and recommender system. The pipeline model built through NLP will put user input in any one of the classes ‘A’, ’B’, ’C’, ’D’ .Class A: AngerClass B: Minor DepressionClass C: Serious DepressionClass D: FearAfter this the recommender system will recommend quotes and speeches pertaining to a particular class in order to assist user.
Code:
import numpy as npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineimport stringfrom nltk.corpus import stopwords #data is our input dataset containing user input lines and it has a column of emotional class. #The code will not work in IDE as no dataset has been provided #function to remove punctuations and stopwordsdef function_preprocess (mess): nopunc = [] for char in mess : if char not in string.punctuation: nopunc.append(char) nopunc=''.join(nopunc) clean = [] for word in nopunc.split(): word = word.lower() if word not in stopwords.words('english'): clean.append(word) return clean from sklearn.pipeline import Pipeline from sklearn.naive_bayes import MultinomialNBfrom sklearn.feature_extraction.text import CountVectorizer as cvfrom sklearn.feature_extraction.text import TfidfTransformer #building our NLP model using naive bayes as classifierpipeline = Pipeline([('bow', cv(analyzer=function_preprocess)), ('tfidf', TfidfTransformer()), ('classifier', MultinomialNB()), ])pipeline.fit(data, emotional_class)
Recommender system will be created using neighbour based collaborative filtering techniques as it would suggest the things which were helpful for similar users.
Tools Used:1. Language used: Python2. Algorithms : Collaborative filtering, Naive bayes, Natural Language Processing
Application:1. Can be used to identify people suffering from depression, anxiety etc and at the same time help them too.2. If user is suffering from depression, program will recommend him to visit a doctor and also inform his relatives about the same.3. If user is often angry, program will suggest him tips for anger management.4. This model will be helpful to psychiatrists and therapists for curing their clients.
Team members:1. Abhay Gupta2. Abhinav Tripathi
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.
surindertarika1234
ProGeek
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
10 Best Web Development Projects For Your Resume
E-commerce Website using Django
Banking Transaction System using Java
Voting System Project Using Django Framework
Browser Automation Using Selenium
Setup Sending Email in Django Project
Handling Ajax request in Django
Student record management system using linked list
How to Build Portfolio Website And Host It on GitHub Pages?
College Management System using Django - Python Project
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 81,
"s": 52,
"text": "Project Title : AI therapist"
},
{
"code": null,
"e": 480,
"s": 81,
"text": "Introduction: Input is user provided description about how his day went in two-three lines. Using natural language processing, our program detects how user is feeling. He may be feeling depressed, feared, angry etc. Then a recommender system is used to show him content based on his current emotions. For example if user is feeling depressed, program will show him motivational thoughts, blogs etc."
},
{
"code": null,
"e": 899,
"s": 480,
"text": "Conceptual framework:The project will be a combination of natural language processing and recommender system. The pipeline model built through NLP will put user input in any one of the classes ‘A’, ’B’, ’C’, ’D’ .Class A: AngerClass B: Minor DepressionClass C: Serious DepressionClass D: FearAfter this the recommender system will recommend quotes and speeches pertaining to a particular class in order to assist user."
},
{
"code": null,
"e": 905,
"s": 899,
"text": "Code:"
},
{
"code": "import numpy as npimport pandas as pdfrom pandas import Series, DataFrameimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineimport stringfrom nltk.corpus import stopwords #data is our input dataset containing user input lines and it has a column of emotional class. #The code will not work in IDE as no dataset has been provided #function to remove punctuations and stopwordsdef function_preprocess (mess): nopunc = [] for char in mess : if char not in string.punctuation: nopunc.append(char) nopunc=''.join(nopunc) clean = [] for word in nopunc.split(): word = word.lower() if word not in stopwords.words('english'): clean.append(word) return clean from sklearn.pipeline import Pipeline from sklearn.naive_bayes import MultinomialNBfrom sklearn.feature_extraction.text import CountVectorizer as cvfrom sklearn.feature_extraction.text import TfidfTransformer #building our NLP model using naive bayes as classifierpipeline = Pipeline([('bow', cv(analyzer=function_preprocess)), ('tfidf', TfidfTransformer()), ('classifier', MultinomialNB()), ])pipeline.fit(data, emotional_class)",
"e": 2128,
"s": 905,
"text": null
},
{
"code": null,
"e": 2289,
"s": 2128,
"text": "Recommender system will be created using neighbour based collaborative filtering techniques as it would suggest the things which were helpful for similar users."
},
{
"code": null,
"e": 2406,
"s": 2289,
"text": "Tools Used:1. Language used: Python2. Algorithms : Collaborative filtering, Naive bayes, Natural Language Processing"
},
{
"code": null,
"e": 2823,
"s": 2406,
"text": "Application:1. Can be used to identify people suffering from depression, anxiety etc and at the same time help them too.2. If user is suffering from depression, program will recommend him to visit a doctor and also inform his relatives about the same.3. If user is often angry, program will suggest him tips for anger management.4. This model will be helpful to psychiatrists and therapists for curing their clients."
},
{
"code": null,
"e": 2870,
"s": 2823,
"text": "Team members:1. Abhay Gupta2. Abhinav Tripathi"
},
{
"code": null,
"e": 3121,
"s": 2870,
"text": "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."
},
{
"code": null,
"e": 3246,
"s": 3121,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3265,
"s": 3246,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3273,
"s": 3265,
"text": "ProGeek"
},
{
"code": null,
"e": 3281,
"s": 3273,
"text": "Project"
},
{
"code": null,
"e": 3379,
"s": 3281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3428,
"s": 3379,
"text": "10 Best Web Development Projects For Your Resume"
},
{
"code": null,
"e": 3460,
"s": 3428,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 3498,
"s": 3460,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 3543,
"s": 3498,
"text": "Voting System Project Using Django Framework"
},
{
"code": null,
"e": 3577,
"s": 3543,
"text": "Browser Automation Using Selenium"
},
{
"code": null,
"e": 3615,
"s": 3577,
"text": "Setup Sending Email in Django Project"
},
{
"code": null,
"e": 3647,
"s": 3615,
"text": "Handling Ajax request in Django"
},
{
"code": null,
"e": 3698,
"s": 3647,
"text": "Student record management system using linked list"
},
{
"code": null,
"e": 3758,
"s": 3698,
"text": "How to Build Portfolio Website And Host It on GitHub Pages?"
}
] |
Pygame – Creating Sprites
|
28 Jul, 2021
Sprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys.
Let first look at our first-class i.e., the class in which our sprite is defined, we will call that class Sprite. This Sprite class defines its positions(x and y coordinates), dimension of an object, color, etc. First, we will be calling our __init__() method. It is called a constructor for a class.
Example: Creating Sprite class
Python3
import pygame # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500 # Object classclass Sprite(pygame.sprite.Sprite): def __init__(self, color, height, width): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(SURFACE_COLOR) self.image.set_colorkey(COLOR) pygame.draw.rect(self.image, color, pygame.Rect(0, 0, width, height)) self.rect = self.image.get_rect()
Now, that the class has been created, we can create objects from the class. It enables us to create as many objects as we need using the same class. Now we will create an object using our Class Sprite.
Syntax:
object = Sprite(RED,WIDTH,HEIGHT)
By default, the object will be on position (0,0) i.e., top-left of the screen. We can change the x and y properties of the object.
Syntax:
object.rect.x = value
object.rect.y = value
We can define n of sprites that we want to create, but for the purpose of understanding, let’s simplify. Here we have created a rectangle sprite of certain dimensions, on which we can perform different operations to perform on sprites like move forward, backward, jump, slow, accelerate, etc.
Example: Creating sprite
Python3
import pygameimport random # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500 # Object classclass Sprite(pygame.sprite.Sprite): def __init__(self, color, height, width): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(SURFACE_COLOR) self.image.set_colorkey(COLOR) pygame.draw.rect(self.image,color,pygame.Rect(0, 0, width, height)) self.rect = self.image.get_rect() pygame.init() RED = (255, 0, 0) size = (WIDTH, HEIGHT)screen = pygame.display.set_mode(size)pygame.display.set_caption("Creating Sprite") all_sprites_list = pygame.sprite.Group() object_ = Sprite(RED, 20, 30)object_.rect.x = 200object_.rect.y = 300 all_sprites_list.add(object_) exit = Trueclock = pygame.time.Clock() while exit: for event in pygame.event.get(): if event.type == pygame.QUIT: exit = False all_sprites_list.update() screen.fill(SURFACE_COLOR) all_sprites_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()
Output:
Picked
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Sprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys."
},
{
"code": null,
"e": 623,
"s": 322,
"text": "Let first look at our first-class i.e., the class in which our sprite is defined, we will call that class Sprite. This Sprite class defines its positions(x and y coordinates), dimension of an object, color, etc. First, we will be calling our __init__() method. It is called a constructor for a class."
},
{
"code": null,
"e": 654,
"s": 623,
"text": "Example: Creating Sprite class"
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Python3"
},
{
"code": "import pygame # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500 # Object classclass Sprite(pygame.sprite.Sprite): def __init__(self, color, height, width): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(SURFACE_COLOR) self.image.set_colorkey(COLOR) pygame.draw.rect(self.image, color, pygame.Rect(0, 0, width, height)) self.rect = self.image.get_rect()",
"e": 1194,
"s": 662,
"text": null
},
{
"code": null,
"e": 1397,
"s": 1194,
"text": "Now, that the class has been created, we can create objects from the class. It enables us to create as many objects as we need using the same class. Now we will create an object using our Class Sprite. "
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Syntax:"
},
{
"code": null,
"e": 1439,
"s": 1405,
"text": "object = Sprite(RED,WIDTH,HEIGHT)"
},
{
"code": null,
"e": 1570,
"s": 1439,
"text": "By default, the object will be on position (0,0) i.e., top-left of the screen. We can change the x and y properties of the object."
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Syntax:"
},
{
"code": null,
"e": 1600,
"s": 1578,
"text": "object.rect.x = value"
},
{
"code": null,
"e": 1622,
"s": 1600,
"text": "object.rect.y = value"
},
{
"code": null,
"e": 1916,
"s": 1622,
"text": "We can define n of sprites that we want to create, but for the purpose of understanding, let’s simplify. Here we have created a rectangle sprite of certain dimensions, on which we can perform different operations to perform on sprites like move forward, backward, jump, slow, accelerate, etc. "
},
{
"code": null,
"e": 1941,
"s": 1916,
"text": "Example: Creating sprite"
},
{
"code": null,
"e": 1949,
"s": 1941,
"text": "Python3"
},
{
"code": "import pygameimport random # GLOBAL VARIABLESCOLOR = (255, 100, 98)SURFACE_COLOR = (167, 255, 100)WIDTH = 500HEIGHT = 500 # Object classclass Sprite(pygame.sprite.Sprite): def __init__(self, color, height, width): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(SURFACE_COLOR) self.image.set_colorkey(COLOR) pygame.draw.rect(self.image,color,pygame.Rect(0, 0, width, height)) self.rect = self.image.get_rect() pygame.init() RED = (255, 0, 0) size = (WIDTH, HEIGHT)screen = pygame.display.set_mode(size)pygame.display.set_caption(\"Creating Sprite\") all_sprites_list = pygame.sprite.Group() object_ = Sprite(RED, 20, 30)object_.rect.x = 200object_.rect.y = 300 all_sprites_list.add(object_) exit = Trueclock = pygame.time.Clock() while exit: for event in pygame.event.get(): if event.type == pygame.QUIT: exit = False all_sprites_list.update() screen.fill(SURFACE_COLOR) all_sprites_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit()",
"e": 3033,
"s": 1949,
"text": null
},
{
"code": null,
"e": 3041,
"s": 3033,
"text": "Output:"
},
{
"code": null,
"e": 3048,
"s": 3041,
"text": "Picked"
},
{
"code": null,
"e": 3062,
"s": 3048,
"text": "Python-PyGame"
},
{
"code": null,
"e": 3069,
"s": 3062,
"text": "Python"
}
] |
real() function in C++
|
08 Oct, 2018
The real() function is defined in the complex header file. The real() function is used to find the real part of the complex number.
Syntax:
template<class T> T
real(const complex<T>& z);
Parameter: This method takes a mandatory parameter z: which represents the given complex number.
Return: It returns the real part of the specified complex number.
Below programs illustrate the above function:-
Example 1:-
// C++ program to demonstrate// example of real() function. #include <bits/stdC++.h>using namespace std; // driver functionint main(){ // defines the complex number: (20.3 + 4.9i) complex<double> realpart(20.3, 4.9); // print the complex number cout << "Complex Number = " << realpart << endl; // prints the real part using the real function cout << "Real part of the complex number is =" << real(realpart) << endl; return 0;}
Complex Number = (20.3, 4.9)
Real part of the complex number is =20.3
Example 2:-
// C++ program to demonstrate// example of real() function. #include <bits/stdC++.h>using namespace std; // driver functionint main(){ // defines the complex number: (2 + 2i) complex<double> realpart(2, 2); // print the complex number cout << "Complex Number = " << realpart << endl; // prints the real part using the real function cout << "Real part of the complex number is =" << real(realpart) << endl; return 0;}
Complex Number = (2, 2)
Real part of the complex number is =2
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Oct, 2018"
},
{
"code": null,
"e": 186,
"s": 54,
"text": "The real() function is defined in the complex header file. The real() function is used to find the real part of the complex number."
},
{
"code": null,
"e": 194,
"s": 186,
"text": "Syntax:"
},
{
"code": null,
"e": 247,
"s": 194,
"text": "template<class T> T \n real(const complex<T>& z);\n"
},
{
"code": null,
"e": 344,
"s": 247,
"text": "Parameter: This method takes a mandatory parameter z: which represents the given complex number."
},
{
"code": null,
"e": 410,
"s": 344,
"text": "Return: It returns the real part of the specified complex number."
},
{
"code": null,
"e": 457,
"s": 410,
"text": "Below programs illustrate the above function:-"
},
{
"code": null,
"e": 469,
"s": 457,
"text": "Example 1:-"
},
{
"code": "// C++ program to demonstrate// example of real() function. #include <bits/stdC++.h>using namespace std; // driver functionint main(){ // defines the complex number: (20.3 + 4.9i) complex<double> realpart(20.3, 4.9); // print the complex number cout << \"Complex Number = \" << realpart << endl; // prints the real part using the real function cout << \"Real part of the complex number is =\" << real(realpart) << endl; return 0;}",
"e": 941,
"s": 469,
"text": null
},
{
"code": null,
"e": 1012,
"s": 941,
"text": "Complex Number = (20.3, 4.9)\nReal part of the complex number is =20.3\n"
},
{
"code": null,
"e": 1024,
"s": 1012,
"text": "Example 2:-"
},
{
"code": "// C++ program to demonstrate// example of real() function. #include <bits/stdC++.h>using namespace std; // driver functionint main(){ // defines the complex number: (2 + 2i) complex<double> realpart(2, 2); // print the complex number cout << \"Complex Number = \" << realpart << endl; // prints the real part using the real function cout << \"Real part of the complex number is =\" << real(realpart) << endl; return 0;}",
"e": 1486,
"s": 1024,
"text": null
},
{
"code": null,
"e": 1549,
"s": 1486,
"text": "Complex Number = (2, 2)\nReal part of the complex number is =2\n"
},
{
"code": null,
"e": 1563,
"s": 1549,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1567,
"s": 1563,
"text": "C++"
},
{
"code": null,
"e": 1580,
"s": 1567,
"text": "C++ Programs"
},
{
"code": null,
"e": 1584,
"s": 1580,
"text": "CPP"
}
] |
What are Ambients in TypeScript ?
|
26 Jul, 2021
Typescript provides a way for using third-party libraries like Node.js, jQuery, AngularJS, etc. in an easier and safer manner. These are done with the help of Ambient declarations.
Ambient Declarations are a method which informs the TypeScript compiler that the real source code (like functions or variables) exists in another place. If we attempt to utilize these source codes when they do not exist at runtime, then without giving hint it will break. We have to always write ambient declarations if our TypeScript code needs to use third-party JavaScript libraries such as jQuery, AngularJS, Node.js, etc.
When using these JavaScript libraries such as jQuery, AngularJS, Node.js, etc, then validating code completion and typesafety becomes difficult for a TypeScript programmer. So, Ambient declarations assist to directly integrate other JavaScript libraries into TypeScript.
Defining Ambients Declarations: Ambient Declarations files has to be saved with the extension d.ts. There must have the declare keyword prefixed to each root level definition in Ambient declarations files with extension d.ts. The author will be cleared by this that there will not be any code released by TypeScript. The author requires to confirm that at runtime the declared item will exist.
Ambient declarations files are similar to doc files (The doc file needs to be kept updated if the source changes). So, If the ambient declaration files are not updated then they will return compilation errors. By convention Ambient declarations files are kept in a type declaration file having extension d.ts. As given below :
Trial.d.ts
The above file cannot be trans-compiled into JavaScript file. It can be used for code completion and type-safety.
Now to declare the ambient methods and variables, we have to use the declare keyword. The syntax for declaring ambient variables or ambient declarations are as given below:
Syntax:
declare module module_name {
}
Syntax to mention the ambient files in the client TypeScript file is given below :
/// <reference path = "Trial.d.ts" />
Features: Following are the features of ambient in TypeScript:
Ambient declarations permits to safely use existing well-liked JavaScript libraries.
Ambient declarations assist to directly integrate other JavaScript libraries into TypeScript..
Ambient declarations is a way to tell the compiler about existing variable/functions/etc.
There is a declare keyword in ambient declaration, which means that we declare the typing of a variable without their implementation, and TypeScript will just suppose that we will somehow comprise that implementation (through adding a script tag or whatever custom compiler we have).
Applications: Ambients in TypeScript are used to describe the shape of libraries that are not written in TypeScript, to do so we have to declare the API which the library reveals. It is because hardly any top-level objects are revealed by JavaScript libraries, one better way to represent them is namespaces.
We call a declare keyword in the ambient declaration, which means that we declare the typing of a variable without their implementation, and TypeScript will just suppose that we will somehow comprise that implementation (through adding a script tag or whatever custom compiler we have). Generally, they are described in .d.ts files. So, we have to write an ambient module to write type declarations for code that is already written in JavaScript. As declared above that that these are defined in a file that ends with .d.ts file extension.
So fundamentally ambient declarations are an assurance that is made with the compiler. If third-party libraries do not exist at runtime and if we try to use them then things will break without warning.
Example 1: To understand the ambient declaration look at the example which is given below. Here the third-party JavaScript library is used with the code given below:
Javascript
var TestSum; (function (TestSum) { var Calc = (function () { function Calc() { } Calc.prototype.doSum = function (x, z) { return x + z; } }) })
Being a JS file we have no time to re-write this library given into typescript. But however, you do require to add the doAdd() function with type safety, then by using ambient declaration we can do this. So, now we will create an ambient declaration file.
Javascript
declare module TestAdd{ export class Calc { doAdd(x:number, z:number) : number; } }
Now, we will include this ambient declaration file (CalAdd.d.ts) in the typescript file. It is given below –
Main.ts
var obj = new TestAdd.Calc(); console.log("Add: " +obj.doAdd(60, 15));
Now, by using the following command on the console, compile and execute the Main.ts file:
$ tsc main.ts
$ node Main.js
Output: We will get the following output:
75
Example 2: To understand the ambient declaration look at the example which is given below. Here the third-party JavaScript library is used with the code given below :
Javascript
var TestDif;(function (TestDif) { var Calc = (function () { function Calc() { } Calc.prototype.doDif = function (x, z) { return x - z; } }) })
Being a JS file we have no time to re-write this library given into typescript. But however, you do require to add the doSubtract() function with type safety, then by using ambient declaration we can do this. So, now we will create an ambient declaration file.
Javascript
declare module TestDif{ export class Calc { doSubtract(x:number, z:number) : number; } }
Now, we will include this ambient declaration file in the typescript file. It is given below :
Main.ts
var obj = new TestDif.Calc(); console.log("Subtract: " + obj.doSubtract(50, 10));
Now, by using the following command on the console, compile and execute the Main.ts file :
$ tsc main.ts
$ node Main.js
Output: We will get the following output:
40
JavaScript-Questions
Picked
TypeScript
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": "\n26 Jul, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "Typescript provides a way for using third-party libraries like Node.js, jQuery, AngularJS, etc. in an easier and safer manner. These are done with the help of Ambient declarations."
},
{
"code": null,
"e": 637,
"s": 209,
"text": "Ambient Declarations are a method which informs the TypeScript compiler that the real source code (like functions or variables) exists in another place. If we attempt to utilize these source codes when they do not exist at runtime, then without giving hint it will break. We have to always write ambient declarations if our TypeScript code needs to use third-party JavaScript libraries such as jQuery, AngularJS, Node.js, etc. "
},
{
"code": null,
"e": 909,
"s": 637,
"text": "When using these JavaScript libraries such as jQuery, AngularJS, Node.js, etc, then validating code completion and typesafety becomes difficult for a TypeScript programmer. So, Ambient declarations assist to directly integrate other JavaScript libraries into TypeScript."
},
{
"code": null,
"e": 1303,
"s": 909,
"text": "Defining Ambients Declarations: Ambient Declarations files has to be saved with the extension d.ts. There must have the declare keyword prefixed to each root level definition in Ambient declarations files with extension d.ts. The author will be cleared by this that there will not be any code released by TypeScript. The author requires to confirm that at runtime the declared item will exist."
},
{
"code": null,
"e": 1630,
"s": 1303,
"text": "Ambient declarations files are similar to doc files (The doc file needs to be kept updated if the source changes). So, If the ambient declaration files are not updated then they will return compilation errors. By convention Ambient declarations files are kept in a type declaration file having extension d.ts. As given below :"
},
{
"code": null,
"e": 1641,
"s": 1630,
"text": "Trial.d.ts"
},
{
"code": null,
"e": 1755,
"s": 1641,
"text": "The above file cannot be trans-compiled into JavaScript file. It can be used for code completion and type-safety."
},
{
"code": null,
"e": 1928,
"s": 1755,
"text": "Now to declare the ambient methods and variables, we have to use the declare keyword. The syntax for declaring ambient variables or ambient declarations are as given below:"
},
{
"code": null,
"e": 1936,
"s": 1928,
"text": "Syntax:"
},
{
"code": null,
"e": 1967,
"s": 1936,
"text": "declare module module_name {\n}"
},
{
"code": null,
"e": 2050,
"s": 1967,
"text": "Syntax to mention the ambient files in the client TypeScript file is given below :"
},
{
"code": null,
"e": 2088,
"s": 2050,
"text": "/// <reference path = \"Trial.d.ts\" />"
},
{
"code": null,
"e": 2151,
"s": 2088,
"text": "Features: Following are the features of ambient in TypeScript:"
},
{
"code": null,
"e": 2236,
"s": 2151,
"text": "Ambient declarations permits to safely use existing well-liked JavaScript libraries."
},
{
"code": null,
"e": 2331,
"s": 2236,
"text": "Ambient declarations assist to directly integrate other JavaScript libraries into TypeScript.."
},
{
"code": null,
"e": 2421,
"s": 2331,
"text": "Ambient declarations is a way to tell the compiler about existing variable/functions/etc."
},
{
"code": null,
"e": 2705,
"s": 2421,
"text": "There is a declare keyword in ambient declaration, which means that we declare the typing of a variable without their implementation, and TypeScript will just suppose that we will somehow comprise that implementation (through adding a script tag or whatever custom compiler we have)."
},
{
"code": null,
"e": 3014,
"s": 2705,
"text": "Applications: Ambients in TypeScript are used to describe the shape of libraries that are not written in TypeScript, to do so we have to declare the API which the library reveals. It is because hardly any top-level objects are revealed by JavaScript libraries, one better way to represent them is namespaces."
},
{
"code": null,
"e": 3554,
"s": 3014,
"text": "We call a declare keyword in the ambient declaration, which means that we declare the typing of a variable without their implementation, and TypeScript will just suppose that we will somehow comprise that implementation (through adding a script tag or whatever custom compiler we have). Generally, they are described in .d.ts files. So, we have to write an ambient module to write type declarations for code that is already written in JavaScript. As declared above that that these are defined in a file that ends with .d.ts file extension."
},
{
"code": null,
"e": 3757,
"s": 3554,
"text": "So fundamentally ambient declarations are an assurance that is made with the compiler. If third-party libraries do not exist at runtime and if we try to use them then things will break without warning. "
},
{
"code": null,
"e": 3923,
"s": 3757,
"text": "Example 1: To understand the ambient declaration look at the example which is given below. Here the third-party JavaScript library is used with the code given below:"
},
{
"code": null,
"e": 3934,
"s": 3923,
"text": "Javascript"
},
{
"code": "var TestSum; (function (TestSum) { var Calc = (function () { function Calc() { } Calc.prototype.doSum = function (x, z) { return x + z; } }) })",
"e": 4133,
"s": 3934,
"text": null
},
{
"code": null,
"e": 4390,
"s": 4133,
"text": "Being a JS file we have no time to re-write this library given into typescript. But however, you do require to add the doAdd() function with type safety, then by using ambient declaration we can do this. So, now we will create an ambient declaration file."
},
{
"code": null,
"e": 4401,
"s": 4390,
"text": "Javascript"
},
{
"code": "declare module TestAdd{ export class Calc { doAdd(x:number, z:number) : number; } }",
"e": 4504,
"s": 4401,
"text": null
},
{
"code": null,
"e": 4613,
"s": 4504,
"text": "Now, we will include this ambient declaration file (CalAdd.d.ts) in the typescript file. It is given below –"
},
{
"code": null,
"e": 4621,
"s": 4613,
"text": "Main.ts"
},
{
"code": "var obj = new TestAdd.Calc(); console.log(\"Add: \" +obj.doAdd(60, 15));",
"e": 4694,
"s": 4621,
"text": null
},
{
"code": null,
"e": 4784,
"s": 4694,
"text": "Now, by using the following command on the console, compile and execute the Main.ts file:"
},
{
"code": null,
"e": 4814,
"s": 4784,
"text": "$ tsc main.ts\n$ node Main.js\n"
},
{
"code": null,
"e": 4856,
"s": 4814,
"text": "Output: We will get the following output:"
},
{
"code": null,
"e": 4859,
"s": 4856,
"text": "75"
},
{
"code": null,
"e": 5028,
"s": 4861,
"text": "Example 2: To understand the ambient declaration look at the example which is given below. Here the third-party JavaScript library is used with the code given below :"
},
{
"code": null,
"e": 5039,
"s": 5028,
"text": "Javascript"
},
{
"code": "var TestDif;(function (TestDif) { var Calc = (function () { function Calc() { } Calc.prototype.doDif = function (x, z) { return x - z; } }) })",
"e": 5234,
"s": 5039,
"text": null
},
{
"code": null,
"e": 5496,
"s": 5234,
"text": "Being a JS file we have no time to re-write this library given into typescript. But however, you do require to add the doSubtract() function with type safety, then by using ambient declaration we can do this. So, now we will create an ambient declaration file."
},
{
"code": null,
"e": 5507,
"s": 5496,
"text": "Javascript"
},
{
"code": "declare module TestDif{ export class Calc { doSubtract(x:number, z:number) : number; } }",
"e": 5615,
"s": 5507,
"text": null
},
{
"code": null,
"e": 5710,
"s": 5615,
"text": "Now, we will include this ambient declaration file in the typescript file. It is given below :"
},
{
"code": null,
"e": 5718,
"s": 5710,
"text": "Main.ts"
},
{
"code": "var obj = new TestDif.Calc(); console.log(\"Subtract: \" + obj.doSubtract(50, 10));",
"e": 5802,
"s": 5718,
"text": null
},
{
"code": null,
"e": 5893,
"s": 5802,
"text": "Now, by using the following command on the console, compile and execute the Main.ts file :"
},
{
"code": null,
"e": 5924,
"s": 5893,
"text": "$ tsc main.ts \n$ node Main.js\n"
},
{
"code": null,
"e": 5966,
"s": 5924,
"text": "Output: We will get the following output:"
},
{
"code": null,
"e": 5969,
"s": 5966,
"text": "40"
},
{
"code": null,
"e": 5990,
"s": 5969,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 5997,
"s": 5990,
"text": "Picked"
},
{
"code": null,
"e": 6008,
"s": 5997,
"text": "TypeScript"
},
{
"code": null,
"e": 6019,
"s": 6008,
"text": "JavaScript"
},
{
"code": null,
"e": 6036,
"s": 6019,
"text": "Web Technologies"
}
] |
PayTm Interview Experience | Set 23 (For 2 Years Experienced)
|
11 Mar, 2018
Round 1:
First round was taken on mettl, online judge. There was two questions and that required to be done in 1hr
1. A paragraph which contained some dates in format DD-MM-YYYY, find number of distinct years in the paragraph.
For e.g Some random words with date 12-01-1990 and some more words with date 12-12-2017 and again some random words with same date 12-05-1990
Output will be: 2
Since two different years (1990 and 2017)
2. Given an array containing positive integers. Find count of magic numbers in the array.
A magic number is that number which can be expressed as sum of two numbers and those two numbers should be reverse of each other. For e.g 22 is magic number which can be expressed as 11+11, 121 is magic number which can be expressed as 29+92
Input: [4, 22, 121, 13]Output: 3
Round 2:Round 2 was F2F.1. Write a function to clone a link list with random pointers.Expected complexity was O(N) with O(1) space
2. What are MySQL engines ?
3. What is load balancer ?
4. What is session and cookies ? How sessions are maintained and how these values are passed from client to server ?
5. How to handle high request per second (distributed systems)?
6. Write mysql query to find 2nd highest salary.
Round 3:
In this round there were discussions on current employment and the projects. Discussion on DB designs and some modules. Some questions on AngularJS(I have experience in that, thats why)
1. Given a long string and an array of words. Find the minimum window in the string where all the words in given array are present in that window.For e.g if string isA B B A C E Y I J A BArray is [ B, I, Y ]So the output will be 7, 11
Where 7 is starting index and 11 is end index of window.
Paytm
Experienced
Interview Experiences
Paytm
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience SDE-2 (3 Years Experienced)
Google Interview Experience for Software Engineer L3 Bangalore (6 Years Experienced)
SAMSUNG R&D Interview Experience for Team Lead
Adobe Interview Experience for MTS-1 (Off-Campus) 1 Year Experienced
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Questions
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Mar, 2018"
},
{
"code": null,
"e": 63,
"s": 54,
"text": "Round 1:"
},
{
"code": null,
"e": 169,
"s": 63,
"text": "First round was taken on mettl, online judge. There was two questions and that required to be done in 1hr"
},
{
"code": null,
"e": 281,
"s": 169,
"text": "1. A paragraph which contained some dates in format DD-MM-YYYY, find number of distinct years in the paragraph."
},
{
"code": null,
"e": 425,
"s": 283,
"text": "For e.g Some random words with date 12-01-1990 and some more words with date 12-12-2017 and again some random words with same date 12-05-1990"
},
{
"code": null,
"e": 445,
"s": 427,
"text": "Output will be: 2"
},
{
"code": null,
"e": 487,
"s": 445,
"text": "Since two different years (1990 and 2017)"
},
{
"code": null,
"e": 579,
"s": 489,
"text": "2. Given an array containing positive integers. Find count of magic numbers in the array."
},
{
"code": null,
"e": 821,
"s": 579,
"text": "A magic number is that number which can be expressed as sum of two numbers and those two numbers should be reverse of each other. For e.g 22 is magic number which can be expressed as 11+11, 121 is magic number which can be expressed as 29+92"
},
{
"code": null,
"e": 856,
"s": 823,
"text": "Input: [4, 22, 121, 13]Output: 3"
},
{
"code": null,
"e": 987,
"s": 856,
"text": "Round 2:Round 2 was F2F.1. Write a function to clone a link list with random pointers.Expected complexity was O(N) with O(1) space"
},
{
"code": null,
"e": 1015,
"s": 987,
"text": "2. What are MySQL engines ?"
},
{
"code": null,
"e": 1042,
"s": 1015,
"text": "3. What is load balancer ?"
},
{
"code": null,
"e": 1159,
"s": 1042,
"text": "4. What is session and cookies ? How sessions are maintained and how these values are passed from client to server ?"
},
{
"code": null,
"e": 1223,
"s": 1159,
"text": "5. How to handle high request per second (distributed systems)?"
},
{
"code": null,
"e": 1272,
"s": 1223,
"text": "6. Write mysql query to find 2nd highest salary."
},
{
"code": null,
"e": 1281,
"s": 1272,
"text": "Round 3:"
},
{
"code": null,
"e": 1467,
"s": 1281,
"text": "In this round there were discussions on current employment and the projects. Discussion on DB designs and some modules. Some questions on AngularJS(I have experience in that, thats why)"
},
{
"code": null,
"e": 1702,
"s": 1467,
"text": "1. Given a long string and an array of words. Find the minimum window in the string where all the words in given array are present in that window.For e.g if string isA B B A C E Y I J A BArray is [ B, I, Y ]So the output will be 7, 11"
},
{
"code": null,
"e": 1759,
"s": 1702,
"text": "Where 7 is starting index and 11 is end index of window."
},
{
"code": null,
"e": 1765,
"s": 1759,
"text": "Paytm"
},
{
"code": null,
"e": 1777,
"s": 1765,
"text": "Experienced"
},
{
"code": null,
"e": 1799,
"s": 1777,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1805,
"s": 1799,
"text": "Paytm"
},
{
"code": null,
"e": 1903,
"s": 1805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1959,
"s": 1903,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 2044,
"s": 1959,
"text": "Google Interview Experience for Software Engineer L3 Bangalore (6 Years Experienced)"
},
{
"code": null,
"e": 2091,
"s": 2044,
"text": "SAMSUNG R&D Interview Experience for Team Lead"
},
{
"code": null,
"e": 2160,
"s": 2091,
"text": "Adobe Interview Experience for MTS-1 (Off-Campus) 1 Year Experienced"
},
{
"code": null,
"e": 2225,
"s": 2160,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 2252,
"s": 2225,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 2322,
"s": 2252,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 2354,
"s": 2322,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 2427,
"s": 2354,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
}
] |
Python Decorators: A Complete Guide
|
22 Jun, 2020
A decorator is a design pattern tool in Python for wrapping code around functions or classes (defined blocks). This design pattern allows a programmer to add new functionality to existing functions or classes without modifying the existing structure. The section provides an overview of what decorators are, how to decorate functions and classes, and what problem can it solve.
Decorators
A decorator is a function that takes another function as an argument, does some actions, and then returns the argument based on the actions performed. Since functions are first-class object in Python, they can be passed as arguments to another functions.Hence we can say that a decorator is a callable that accepts and returns a callable.Below code shows a simple decorator that add additional notes to the my_function docstring:
def decorated_docstring(function): function.__doc__ += '\n Hi George, I''m a simple Decorator.' return function def my_function(string1): """Return the string.""" return string1 def main(): myFunc = decorated_docstring(my_function) myFunc('Hai') help(myFunc) if __name__ == "__main__": main()
Output:
Help on function my_function in module __main__:
my_function(string1)
Return the string.
Hi George, Im a simple Decorator.
From the above explanation, you can understand how to decorate a function. But it is unacceptable to define a function, assign it to a variable, then reassign the decorated function to the same variable. Hence Python 2.5 introduced a syntax for decorating function by prepending an @ character with the decorator name and adding directly above the function declaration. Below code shows how to use the syntax:
def reverse_decorator(function): def reverse_wrapper(): make_reverse = "".join(reversed(function())) return make_reverse return reverse_wrapper @reverse_decoratordef say_hi(): return 'Hi George' def main(): print(say_hi()) if __name__ == "__main__": main()
Output:
egroeG iH
Here we use @ character for decorating function.
@reverse_decoratordef say_hi(): return 'Hi George'
The above code is syntactically equivalent to the following code reverse_decorator(say_hi())
In this case, the reverse_decorator function executes and creates the reference for revserse_wrapper. Let’s look into the below example for better understanding:
def reverse_decorator(function): print('Inside reverse_decorator function') def reverse_wrapper(): print('Inside reverse_wrapper function') return 'Return reverse_wrapper function' return reverse_wrapper @reverse_decoratordef say_hi(): return 'Inside say_hi'
Output:
Inside reverse_decorator function
Here the reverse_decorator does not execute the function reverse_wrapper instead it creates the reference and returns it when the callable invokes the function.
def reverse_decorator(function): print('Inside reverse_decorator function') def reverse_wrapper(): print('Inside reverse_wrapper function') return 'reverse_wrapper' return reverse_wrapper @reverse_decoratordef say_hi(): return 'Inside say_hi' def main(): print('Inside main()') print(say_hi) print(''); print(say_hi()) # main executes the reference main()
Output:
Inside reverse_decorator functionInside main()<function reverse_decorator..reverse_wrapper at 0x0000015762A16708>
Inside reverse_wrapper functionreverse_wrapper
Now you are clear about how to use the @syntax to decorate a function. Another cool stuff is that we can use multiple decorators on a single function. One important thing to note here is the order of the decorator applied is important, which is applied from bottom to top. Let’s look into multiple decorators.
def reverse_decorator(function): def reverse_wrapper(): make_reverse = "".join(reversed(function())) return make_reverse return reverse_wrapper def uppercase_decorator(function): def uppercase_wrapper(): var_uppercase = function().upper() return var_uppercase return uppercase_wrapper @uppercase_decorator@reverse_decoratordef say_hi(): return 'hi george' def main(): print(say_hi()) if __name__ == "__main__": main()
Output:
EGROEG IH
Here the string is reversed first and foremost, and secondarily it converts to uppercase.
@uppercase_decorator@reverse_decoratordef say_hi(): return 'hi george'
The above code is syntactically equivalent touppercase_decorator(reverse_decorator(say_hi()))
So far, you have seen decorators without any arguments. In certain cases, it’s necessary to pass arguments to decorate the method accordingly.
def decorator_arguments(function): def wrapper_arguments(arg1, arg2): print("Arguments accepted are: {0}, {1}".format(arg1, arg2)) function(arg1, arg2) # calls the function hobbies return wrapper_arguments @decorator_argumentsdef hobbies(hobby_one, hobby_two): print("My Hobbies are {0} and {1}".format(hobby_one, hobby_two)) def main(): hobbies("Travelling", "Reading") if __name__ == "__main__": main()
Output:
Arguments accepted are: Travelling, ReadingMy Hobbies are Travelling and Reading
In the above case, the decorator will not take any arguments instead it is passed to the wrapper function by the callable. The below code provides more clarity in the process of passing the arguments using reference.
def decorator_arguments(function): def wrapper_arguments(arg1, arg2): print(" Arguments accepted are: {0}, {1}".format(arg1, arg2)) return wrapper_arguments @decorator_argumentsdef hobbies(hobby_one, hobby_two): print("My Hobbies are {0} and {1}".format(hobby_one, hobby_two)) def main(): # the reference of wrapper_arguments # is returned hob = hobbies print(hob) # passing the arguments to the # wrapper_arguments hob('Travelling', 'Reading') main()
Output
<function decorator_arguments..wrapper_arguments at 0x7f100315e158>Arguments accepted are: Travelling, Reading
The standard library provides many modules that include decorators and many Python tools and frameworks that make use of decorators. Few examples are:
You can use @classmethod or @staticmethod decorator for creating a method without creating an instance
The mock module permits the use of @mock.patch or @mock.patch.object as a decorator which is used for unit testing.
Common tools such as Django (uses @login_required) for setting login privileges and Flask (uses @app.route) for function registry uses decorators.
To identify a function as an asynchronous task Celery uses @task decorator.
Two important reasons to write this reusable piece of Python functionality are when written properly the decorators are modular and explicit.
Modularity of Decorators
Decorators are Explicit
Using decorators’ programmers can add or remove functionalities easily in defined blocks of code, which refrains the repetition of boilerplate setup.
Programmers can apply Decorators to all callable based on the need. This ensures readability and provides clean code.
Here we will discuss a few decorator use-cases which help you to understand When to write Decorators.
Functional AddonsData SanitizationFunction Registration
Functional Addons
Data Sanitization
Function Registration
The first and foremost reason to write a decorator is its flexibility to add extra functionality to the defined blocks of code(functions and classes).
With proper data sanitization methods, you can remove or destroy the data that is stored on memory and make it impossible to recover it. For example, you may use the facility of cache to avoid running the same function or you may use methods to validate the user login credentials and so on, which points to the importance of data sanitization. A decorator can properly sanitize the arguments that passed to the decorated function and also sanitize the data returned from the function.
Another point to write a decorator is to register a function. Here decorator allows two or more subsystems to communicate without having much information about each other.
The above section shows how decorators help in decorating functions. We have seen that decorators are callable that accepts and returns a callable. Since classes are callable, decorators are also used to decorate classes. Some of the uses of decorating classes are:
Addition or enhancement of attributes
Attribute interaction
Alter the API of a class (alter the way of declaring classes and its instance use)
Let’s go through how to decorate a function using class.
class MyDecorator: def __init__(self, function): self.function = function def __call__(self): print("Inside Function Call") self.function() @MyDecoratordef function(): print("GeeksforGeeks") def main(): function() if __name__ == "__main__": main()
Output:
Inside Function Call
GeeksforGeeks
Let’s look into an another example. Below code, sort the instance based on their creation time. Here we require three additional attributes- the instantiation timestamp, __lt__ and __gt__ methods.
import functoolsimport time def sort_by_creation_time(cl): org_init = cl.__init__ # Enhance the class to store the creation # time based on the instantiation. @functools.wraps(org_init) def new_init(self, *args, **kwargs): org_init(self, *args, **kwargs) self._created = time.time() # __lt__ and __gt__ methods return true or false # based on the creation time. cl.__init__ = new_init cl.__lt = lambda self, other: self._created < other._created cl.__gt__ = lambda self, other: self._created > other._created return cl @sort_by_creation_timeclass Sort(object): def __init__(self, identifier): self.identifier = identifier def __repr__(self): return self.identifier def main(): first = Sort('Python') second = Sort('Data Analysis') third = Sort('Machine Learning') sortables = [third, first, second] print(sorted(sortables)) if __name__ == "__main__": main()
Output
[Python, Data Analysis, Machine Learning]
new_init, its primary responsibility is to run the wrapped function and also add an extra functionality to the wrapped function. The @functools.wraps(org_init) update the wrapper function to reflect the look of wrapped function. Check functools for detail understanding.
@functools.wraps(org_init)def new_init(self, *args, **kwargs): # calls the init method of class org_init(self, *args, **kwargs) # add an extra attribute and store # creation time self._created = time.time() # reference of new_init is assigned to# __init__ method and executes when# callable creates the class object.cl.__init__ = new_init
Sometimes it’s necessary to decorate a function and return a class. Say, for example, advanced cases developers can subclass a class in an API. It can also avoid an increase in boilerplate code.
class Addition(object): def __call__(self, *args, **kwargs): return self.run(*args, **kwargs) def run(self, *args, **kwargs): raise NotImplementedError('Subclass must implement `run`.') def identity(self): return 'Hi George, I''m here to help you with addition !' def addition(decorated): class AddSubclass(Addition): def run(self, *args, **kwargs): if args: add = 0 for arg in args: add = arg + add # add arguments return add else: # func is called if there are no arguments passed. return decorated(*args, **kwargs) return AddSubclass() @additiondef func(*args): return 1 + 1 print(func.identity())print(func())print(func(2, 2))print(func(2, 1, 4))
Output
Hi George, Im here to help you with addition!
2
4
7
Here the decorator creates a subclass of Addition and returns the instance of the subclass rather than reference (return AddSubclass()).
def addition(decorated): class AddSubclass(Addition): def run(self, *args, **kwargs): if args: add = 0 for arg in args: add = arg + add return add else: return decorated(*args, **kwargs) return AddSubclass()
And the __call__ method in the class `Addition` means that its instance is callable. Hence the instance of subclass `AddSubclass()` can run the task and as a result the programmer can avoid calling the run method as func().run().
Decorators are an excellent tool for wrapping code around functions and classes, which provides an efficient way to use boilerplate code and also contributes to readability. Even though they are modular and explicit, there are drawbacks to this tool. Since it’s a tool for wrapping code around defined blocks, debugging becomes more challenging. And also, poorly written decorators may result in an error.After all, a well-written decorator can be treated as an efficient reusable piece of Python functionality for wrapping defined blocks of code.
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 432,
"s": 54,
"text": "A decorator is a design pattern tool in Python for wrapping code around functions or classes (defined blocks). This design pattern allows a programmer to add new functionality to existing functions or classes without modifying the existing structure. The section provides an overview of what decorators are, how to decorate functions and classes, and what problem can it solve."
},
{
"code": null,
"e": 443,
"s": 432,
"text": "Decorators"
},
{
"code": null,
"e": 873,
"s": 443,
"text": "A decorator is a function that takes another function as an argument, does some actions, and then returns the argument based on the actions performed. Since functions are first-class object in Python, they can be passed as arguments to another functions.Hence we can say that a decorator is a callable that accepts and returns a callable.Below code shows a simple decorator that add additional notes to the my_function docstring:"
},
{
"code": "def decorated_docstring(function): function.__doc__ += '\\n Hi George, I''m a simple Decorator.' return function def my_function(string1): \"\"\"Return the string.\"\"\" return string1 def main(): myFunc = decorated_docstring(my_function) myFunc('Hai') help(myFunc) if __name__ == \"__main__\": main()",
"e": 1193,
"s": 873,
"text": null
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Output:"
},
{
"code": null,
"e": 1334,
"s": 1201,
"text": "Help on function my_function in module __main__:\n\nmy_function(string1)\n Return the string.\n Hi George, Im a simple Decorator.\n"
},
{
"code": null,
"e": 1744,
"s": 1334,
"text": "From the above explanation, you can understand how to decorate a function. But it is unacceptable to define a function, assign it to a variable, then reassign the decorated function to the same variable. Hence Python 2.5 introduced a syntax for decorating function by prepending an @ character with the decorator name and adding directly above the function declaration. Below code shows how to use the syntax:"
},
{
"code": "def reverse_decorator(function): def reverse_wrapper(): make_reverse = \"\".join(reversed(function())) return make_reverse return reverse_wrapper @reverse_decoratordef say_hi(): return 'Hi George' def main(): print(say_hi()) if __name__ == \"__main__\": main()",
"e": 2037,
"s": 1744,
"text": null
},
{
"code": null,
"e": 2045,
"s": 2037,
"text": "Output:"
},
{
"code": null,
"e": 2055,
"s": 2045,
"text": "egroeG iH"
},
{
"code": null,
"e": 2104,
"s": 2055,
"text": "Here we use @ character for decorating function."
},
{
"code": "@reverse_decoratordef say_hi(): return 'Hi George'",
"e": 2158,
"s": 2104,
"text": null
},
{
"code": null,
"e": 2251,
"s": 2158,
"text": "The above code is syntactically equivalent to the following code reverse_decorator(say_hi())"
},
{
"code": null,
"e": 2413,
"s": 2251,
"text": "In this case, the reverse_decorator function executes and creates the reference for revserse_wrapper. Let’s look into the below example for better understanding:"
},
{
"code": "def reverse_decorator(function): print('Inside reverse_decorator function') def reverse_wrapper(): print('Inside reverse_wrapper function') return 'Return reverse_wrapper function' return reverse_wrapper @reverse_decoratordef say_hi(): return 'Inside say_hi'",
"e": 2705,
"s": 2413,
"text": null
},
{
"code": null,
"e": 2713,
"s": 2705,
"text": "Output:"
},
{
"code": null,
"e": 2747,
"s": 2713,
"text": "Inside reverse_decorator function"
},
{
"code": null,
"e": 2908,
"s": 2747,
"text": "Here the reverse_decorator does not execute the function reverse_wrapper instead it creates the reference and returns it when the callable invokes the function."
},
{
"code": "def reverse_decorator(function): print('Inside reverse_decorator function') def reverse_wrapper(): print('Inside reverse_wrapper function') return 'reverse_wrapper' return reverse_wrapper @reverse_decoratordef say_hi(): return 'Inside say_hi' def main(): print('Inside main()') print(say_hi) print(''); print(say_hi()) # main executes the reference main()",
"e": 3320,
"s": 2908,
"text": null
},
{
"code": null,
"e": 3328,
"s": 3320,
"text": "Output:"
},
{
"code": null,
"e": 3442,
"s": 3328,
"text": "Inside reverse_decorator functionInside main()<function reverse_decorator..reverse_wrapper at 0x0000015762A16708>"
},
{
"code": null,
"e": 3489,
"s": 3442,
"text": "Inside reverse_wrapper functionreverse_wrapper"
},
{
"code": null,
"e": 3799,
"s": 3489,
"text": "Now you are clear about how to use the @syntax to decorate a function. Another cool stuff is that we can use multiple decorators on a single function. One important thing to note here is the order of the decorator applied is important, which is applied from bottom to top. Let’s look into multiple decorators."
},
{
"code": "def reverse_decorator(function): def reverse_wrapper(): make_reverse = \"\".join(reversed(function())) return make_reverse return reverse_wrapper def uppercase_decorator(function): def uppercase_wrapper(): var_uppercase = function().upper() return var_uppercase return uppercase_wrapper @uppercase_decorator@reverse_decoratordef say_hi(): return 'hi george' def main(): print(say_hi()) if __name__ == \"__main__\": main()",
"e": 4278,
"s": 3799,
"text": null
},
{
"code": null,
"e": 4286,
"s": 4278,
"text": "Output:"
},
{
"code": null,
"e": 4296,
"s": 4286,
"text": "EGROEG IH"
},
{
"code": null,
"e": 4386,
"s": 4296,
"text": "Here the string is reversed first and foremost, and secondarily it converts to uppercase."
},
{
"code": "@uppercase_decorator@reverse_decoratordef say_hi(): return 'hi george'",
"e": 4460,
"s": 4386,
"text": null
},
{
"code": null,
"e": 4554,
"s": 4460,
"text": "The above code is syntactically equivalent touppercase_decorator(reverse_decorator(say_hi()))"
},
{
"code": null,
"e": 4697,
"s": 4554,
"text": "So far, you have seen decorators without any arguments. In certain cases, it’s necessary to pass arguments to decorate the method accordingly."
},
{
"code": "def decorator_arguments(function): def wrapper_arguments(arg1, arg2): print(\"Arguments accepted are: {0}, {1}\".format(arg1, arg2)) function(arg1, arg2) # calls the function hobbies return wrapper_arguments @decorator_argumentsdef hobbies(hobby_one, hobby_two): print(\"My Hobbies are {0} and {1}\".format(hobby_one, hobby_two)) def main(): hobbies(\"Travelling\", \"Reading\") if __name__ == \"__main__\": main()",
"e": 5137,
"s": 4697,
"text": null
},
{
"code": null,
"e": 5145,
"s": 5137,
"text": "Output:"
},
{
"code": null,
"e": 5226,
"s": 5145,
"text": "Arguments accepted are: Travelling, ReadingMy Hobbies are Travelling and Reading"
},
{
"code": null,
"e": 5443,
"s": 5226,
"text": "In the above case, the decorator will not take any arguments instead it is passed to the wrapper function by the callable. The below code provides more clarity in the process of passing the arguments using reference."
},
{
"code": "def decorator_arguments(function): def wrapper_arguments(arg1, arg2): print(\" Arguments accepted are: {0}, {1}\".format(arg1, arg2)) return wrapper_arguments @decorator_argumentsdef hobbies(hobby_one, hobby_two): print(\"My Hobbies are {0} and {1}\".format(hobby_one, hobby_two)) def main(): # the reference of wrapper_arguments # is returned hob = hobbies print(hob) # passing the arguments to the # wrapper_arguments hob('Travelling', 'Reading') main()",
"e": 5944,
"s": 5443,
"text": null
},
{
"code": null,
"e": 5951,
"s": 5944,
"text": "Output"
},
{
"code": null,
"e": 6062,
"s": 5951,
"text": "<function decorator_arguments..wrapper_arguments at 0x7f100315e158>Arguments accepted are: Travelling, Reading"
},
{
"code": null,
"e": 6213,
"s": 6062,
"text": "The standard library provides many modules that include decorators and many Python tools and frameworks that make use of decorators. Few examples are:"
},
{
"code": null,
"e": 6316,
"s": 6213,
"text": "You can use @classmethod or @staticmethod decorator for creating a method without creating an instance"
},
{
"code": null,
"e": 6432,
"s": 6316,
"text": "The mock module permits the use of @mock.patch or @mock.patch.object as a decorator which is used for unit testing."
},
{
"code": null,
"e": 6579,
"s": 6432,
"text": "Common tools such as Django (uses @login_required) for setting login privileges and Flask (uses @app.route) for function registry uses decorators."
},
{
"code": null,
"e": 6655,
"s": 6579,
"text": "To identify a function as an asynchronous task Celery uses @task decorator."
},
{
"code": null,
"e": 6797,
"s": 6655,
"text": "Two important reasons to write this reusable piece of Python functionality are when written properly the decorators are modular and explicit."
},
{
"code": null,
"e": 6822,
"s": 6797,
"text": "Modularity of Decorators"
},
{
"code": null,
"e": 6846,
"s": 6822,
"text": "Decorators are Explicit"
},
{
"code": null,
"e": 6996,
"s": 6846,
"text": "Using decorators’ programmers can add or remove functionalities easily in defined blocks of code, which refrains the repetition of boilerplate setup."
},
{
"code": null,
"e": 7114,
"s": 6996,
"text": "Programmers can apply Decorators to all callable based on the need. This ensures readability and provides clean code."
},
{
"code": null,
"e": 7216,
"s": 7114,
"text": "Here we will discuss a few decorator use-cases which help you to understand When to write Decorators."
},
{
"code": null,
"e": 7272,
"s": 7216,
"text": "Functional AddonsData SanitizationFunction Registration"
},
{
"code": null,
"e": 7290,
"s": 7272,
"text": "Functional Addons"
},
{
"code": null,
"e": 7308,
"s": 7290,
"text": "Data Sanitization"
},
{
"code": null,
"e": 7330,
"s": 7308,
"text": "Function Registration"
},
{
"code": null,
"e": 7481,
"s": 7330,
"text": "The first and foremost reason to write a decorator is its flexibility to add extra functionality to the defined blocks of code(functions and classes)."
},
{
"code": null,
"e": 7967,
"s": 7481,
"text": "With proper data sanitization methods, you can remove or destroy the data that is stored on memory and make it impossible to recover it. For example, you may use the facility of cache to avoid running the same function or you may use methods to validate the user login credentials and so on, which points to the importance of data sanitization. A decorator can properly sanitize the arguments that passed to the decorated function and also sanitize the data returned from the function."
},
{
"code": null,
"e": 8139,
"s": 7967,
"text": "Another point to write a decorator is to register a function. Here decorator allows two or more subsystems to communicate without having much information about each other."
},
{
"code": null,
"e": 8406,
"s": 8139,
"text": "The above section shows how decorators help in decorating functions. We have seen that decorators are callable that accepts and returns a callable. Since classes are callable, decorators are also used to decorate classes. Some of the uses of decorating classes are:"
},
{
"code": null,
"e": 8444,
"s": 8406,
"text": "Addition or enhancement of attributes"
},
{
"code": null,
"e": 8466,
"s": 8444,
"text": "Attribute interaction"
},
{
"code": null,
"e": 8549,
"s": 8466,
"text": "Alter the API of a class (alter the way of declaring classes and its instance use)"
},
{
"code": null,
"e": 8606,
"s": 8549,
"text": "Let’s go through how to decorate a function using class."
},
{
"code": "class MyDecorator: def __init__(self, function): self.function = function def __call__(self): print(\"Inside Function Call\") self.function() @MyDecoratordef function(): print(\"GeeksforGeeks\") def main(): function() if __name__ == \"__main__\": main()",
"e": 8897,
"s": 8606,
"text": null
},
{
"code": null,
"e": 8905,
"s": 8897,
"text": "Output:"
},
{
"code": null,
"e": 8941,
"s": 8905,
"text": "Inside Function Call\nGeeksforGeeks\n"
},
{
"code": null,
"e": 9138,
"s": 8941,
"text": "Let’s look into an another example. Below code, sort the instance based on their creation time. Here we require three additional attributes- the instantiation timestamp, __lt__ and __gt__ methods."
},
{
"code": "import functoolsimport time def sort_by_creation_time(cl): org_init = cl.__init__ # Enhance the class to store the creation # time based on the instantiation. @functools.wraps(org_init) def new_init(self, *args, **kwargs): org_init(self, *args, **kwargs) self._created = time.time() # __lt__ and __gt__ methods return true or false # based on the creation time. cl.__init__ = new_init cl.__lt = lambda self, other: self._created < other._created cl.__gt__ = lambda self, other: self._created > other._created return cl @sort_by_creation_timeclass Sort(object): def __init__(self, identifier): self.identifier = identifier def __repr__(self): return self.identifier def main(): first = Sort('Python') second = Sort('Data Analysis') third = Sort('Machine Learning') sortables = [third, first, second] print(sorted(sortables)) if __name__ == \"__main__\": main()",
"e": 10098,
"s": 9138,
"text": null
},
{
"code": null,
"e": 10105,
"s": 10098,
"text": "Output"
},
{
"code": null,
"e": 10148,
"s": 10105,
"text": "[Python, Data Analysis, Machine Learning]\n"
},
{
"code": null,
"e": 10419,
"s": 10148,
"text": "new_init, its primary responsibility is to run the wrapped function and also add an extra functionality to the wrapped function. The @functools.wraps(org_init) update the wrapper function to reflect the look of wrapped function. Check functools for detail understanding."
},
{
"code": "@functools.wraps(org_init)def new_init(self, *args, **kwargs): # calls the init method of class org_init(self, *args, **kwargs) # add an extra attribute and store # creation time self._created = time.time() # reference of new_init is assigned to# __init__ method and executes when# callable creates the class object.cl.__init__ = new_init ",
"e": 10781,
"s": 10419,
"text": null
},
{
"code": null,
"e": 10976,
"s": 10781,
"text": "Sometimes it’s necessary to decorate a function and return a class. Say, for example, advanced cases developers can subclass a class in an API. It can also avoid an increase in boilerplate code."
},
{
"code": "class Addition(object): def __call__(self, *args, **kwargs): return self.run(*args, **kwargs) def run(self, *args, **kwargs): raise NotImplementedError('Subclass must implement `run`.') def identity(self): return 'Hi George, I''m here to help you with addition !' def addition(decorated): class AddSubclass(Addition): def run(self, *args, **kwargs): if args: add = 0 for arg in args: add = arg + add # add arguments return add else: # func is called if there are no arguments passed. return decorated(*args, **kwargs) return AddSubclass() @additiondef func(*args): return 1 + 1 print(func.identity())print(func())print(func(2, 2))print(func(2, 1, 4))",
"e": 11886,
"s": 10976,
"text": null
},
{
"code": null,
"e": 11893,
"s": 11886,
"text": "Output"
},
{
"code": null,
"e": 11946,
"s": 11893,
"text": "Hi George, Im here to help you with addition!\n2\n4\n7\n"
},
{
"code": null,
"e": 12083,
"s": 11946,
"text": "Here the decorator creates a subclass of Addition and returns the instance of the subclass rather than reference (return AddSubclass())."
},
{
"code": "def addition(decorated): class AddSubclass(Addition): def run(self, *args, **kwargs): if args: add = 0 for arg in args: add = arg + add return add else: return decorated(*args, **kwargs) return AddSubclass()",
"e": 12427,
"s": 12083,
"text": null
},
{
"code": null,
"e": 12657,
"s": 12427,
"text": "And the __call__ method in the class `Addition` means that its instance is callable. Hence the instance of subclass `AddSubclass()` can run the task and as a result the programmer can avoid calling the run method as func().run()."
},
{
"code": null,
"e": 13205,
"s": 12657,
"text": "Decorators are an excellent tool for wrapping code around functions and classes, which provides an efficient way to use boilerplate code and also contributes to readability. Even though they are modular and explicit, there are drawbacks to this tool. Since it’s a tool for wrapping code around defined blocks, debugging becomes more challenging. And also, poorly written decorators may result in an error.After all, a well-written decorator can be treated as an efficient reusable piece of Python functionality for wrapping defined blocks of code."
},
{
"code": null,
"e": 13223,
"s": 13205,
"text": "Python Decorators"
},
{
"code": null,
"e": 13230,
"s": 13223,
"text": "Python"
}
] |
cc command in Linux with Examples - GeeksforGeeks
|
15 May, 2019
cc command is stands for C Compiler, usually an alias command to gcc or clang. As the name suggests, executing the cc command will usually call the gcc on Linux systems. It is used to compile the C language codes and create executables. The number of options available for the cc command is very high. The most important options are explained below with examples.
Syntax:
cc [options] files
Example: Below command will compile the source_file.c file, and create the default executable output file, a.out.
cc example.c
Important Options:
cc command with -o option: This command will compile the source_file.c file, and create a executable output file with the specified name.cc example.c -o examp_out
cc example.c -o examp_out
cc command with -Wall option: This command will compile the source_file.c file, and check for all errors and warnings in the program.cc example.c -Wall -o examp_out
cc example.c -Wall -o examp_out
cc command with -w option: This command will compile the source_file.c file, but suppress all the warnings.cc example.c -w
cc example.c -w
cc command with -g option: This command will compile the source_file.c file, and create a debugging version of the executable output file. This output file can be used by the debugger, and is usually much larger in size than the normal output files.cc example.c -g -o examp_out_debug
cc example.c -g -o examp_out_debug
cc command with -c option: This command will compile the source_file.c file, and create an object file source_file.o, which can later be linked to create an executable output file.cc example.c -c
cc example.c -c
cc command with -Ldir option: This command, while compiling the source_file.c file, will also search the specified directory for header files.cc example.c -L /home/mukkesh/Desktop
cc example.c -L /home/mukkesh/Desktop
cc command with -ansi option: This command will compile the source_file.c file, and makes sure that the code follows strict ANSI standards. This will make sure that the code is portable to be compiled on any other system.cc -ansi example.c
cc -ansi example.c
cc command with –dump options: These commands specified below will print the version of the cc command, the default target machine and built-in specification strings.cc -dumpversioncc -dumpmachinecc -dumpspecs
cc -dumpversion
cc -dumpmachine
cc -dumpspecs
cc command with -v option: This command will compile the source_file.c file, and gives a verbose output.cc example.c -v
cc example.c -v
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24039,
"s": 24011,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24403,
"s": 24039,
"text": "cc command is stands for C Compiler, usually an alias command to gcc or clang. As the name suggests, executing the cc command will usually call the gcc on Linux systems. It is used to compile the C language codes and create executables. The number of options available for the cc command is very high. The most important options are explained below with examples."
},
{
"code": null,
"e": 24411,
"s": 24403,
"text": "Syntax:"
},
{
"code": null,
"e": 24431,
"s": 24411,
"text": "cc [options] files\n"
},
{
"code": null,
"e": 24545,
"s": 24431,
"text": "Example: Below command will compile the source_file.c file, and create the default executable output file, a.out."
},
{
"code": null,
"e": 24558,
"s": 24545,
"text": "cc example.c"
},
{
"code": null,
"e": 24577,
"s": 24558,
"text": "Important Options:"
},
{
"code": null,
"e": 24740,
"s": 24577,
"text": "cc command with -o option: This command will compile the source_file.c file, and create a executable output file with the specified name.cc example.c -o examp_out"
},
{
"code": null,
"e": 24766,
"s": 24740,
"text": "cc example.c -o examp_out"
},
{
"code": null,
"e": 24931,
"s": 24766,
"text": "cc command with -Wall option: This command will compile the source_file.c file, and check for all errors and warnings in the program.cc example.c -Wall -o examp_out"
},
{
"code": null,
"e": 24963,
"s": 24931,
"text": "cc example.c -Wall -o examp_out"
},
{
"code": null,
"e": 25087,
"s": 24963,
"text": "cc command with -w option: This command will compile the source_file.c file, but suppress all the warnings.cc example.c -w "
},
{
"code": null,
"e": 25104,
"s": 25087,
"text": "cc example.c -w "
},
{
"code": null,
"e": 25388,
"s": 25104,
"text": "cc command with -g option: This command will compile the source_file.c file, and create a debugging version of the executable output file. This output file can be used by the debugger, and is usually much larger in size than the normal output files.cc example.c -g -o examp_out_debug"
},
{
"code": null,
"e": 25423,
"s": 25388,
"text": "cc example.c -g -o examp_out_debug"
},
{
"code": null,
"e": 25620,
"s": 25423,
"text": "cc command with -c option: This command will compile the source_file.c file, and create an object file source_file.o, which can later be linked to create an executable output file.cc example.c -c "
},
{
"code": null,
"e": 25637,
"s": 25620,
"text": "cc example.c -c "
},
{
"code": null,
"e": 25817,
"s": 25637,
"text": "cc command with -Ldir option: This command, while compiling the source_file.c file, will also search the specified directory for header files.cc example.c -L /home/mukkesh/Desktop"
},
{
"code": null,
"e": 25855,
"s": 25817,
"text": "cc example.c -L /home/mukkesh/Desktop"
},
{
"code": null,
"e": 26096,
"s": 25855,
"text": "cc command with -ansi option: This command will compile the source_file.c file, and makes sure that the code follows strict ANSI standards. This will make sure that the code is portable to be compiled on any other system.cc -ansi example.c "
},
{
"code": null,
"e": 26116,
"s": 26096,
"text": "cc -ansi example.c "
},
{
"code": null,
"e": 26326,
"s": 26116,
"text": "cc command with –dump options: These commands specified below will print the version of the cc command, the default target machine and built-in specification strings.cc -dumpversioncc -dumpmachinecc -dumpspecs"
},
{
"code": null,
"e": 26342,
"s": 26326,
"text": "cc -dumpversion"
},
{
"code": null,
"e": 26358,
"s": 26342,
"text": "cc -dumpmachine"
},
{
"code": null,
"e": 26372,
"s": 26358,
"text": "cc -dumpspecs"
},
{
"code": null,
"e": 26492,
"s": 26372,
"text": "cc command with -v option: This command will compile the source_file.c file, and gives a verbose output.cc example.c -v"
},
{
"code": null,
"e": 26508,
"s": 26492,
"text": "cc example.c -v"
},
{
"code": null,
"e": 26522,
"s": 26508,
"text": "linux-command"
},
{
"code": null,
"e": 26544,
"s": 26522,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 26551,
"s": 26544,
"text": "Picked"
},
{
"code": null,
"e": 26562,
"s": 26551,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26660,
"s": 26562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26669,
"s": 26660,
"text": "Comments"
},
{
"code": null,
"e": 26682,
"s": 26669,
"text": "Old Comments"
},
{
"code": null,
"e": 26708,
"s": 26682,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26745,
"s": 26708,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26779,
"s": 26745,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26814,
"s": 26779,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26840,
"s": 26814,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26877,
"s": 26840,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26917,
"s": 26877,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 26946,
"s": 26917,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26988,
"s": 26946,
"text": "Named Pipe or FIFO with example C program"
}
] |
Accessing nth element from Python tuples in list
|
A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present as the elements in the given tuple.
We can design a for loop to access the elements from the list with the in clause applied for nth index. Then we store the result into a new list.
Live Demo
Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]
#Given list
print("Given list: ",Alist)
# Use index
res = [x[1] for x in Alist]
print("The 1 st element form each tuple in the list: \n",res)
Running the above code gives us the following result −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
['3 pm', '12pm', '9 am', '6 am']
The itegetter function from operator module can fetch each item form the given iterable till the end of the iterable is searched. In this program we search for index position 2 from the given list and apply a map function to apply the same function again and again to each result from the result of the itemgetter function. Finally we store the result as a list.
Live Demo
from operator import itemgetter
Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]
#Given list
print("Given list: ",Alist)
# Use itemgetter
res = list(map(itemgetter(2), Alist))
print("The 1 st element form each tuple in the list: \n",res)
Running the above code gives us the following result −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
[10, 8, 8, 5]
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present as the elements in the given tuple."
},
{
"code": null,
"e": 1391,
"s": 1245,
"text": "We can design a for loop to access the elements from the list with the in clause applied for nth index. Then we store the result into a new list."
},
{
"code": null,
"e": 1402,
"s": 1391,
"text": " Live Demo"
},
{
"code": null,
"e": 1626,
"s": 1402,
"text": "Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]\n\n#Given list\nprint(\"Given list: \",Alist)\n\n# Use index\nres = [x[1] for x in Alist]\n\nprint(\"The 1 st element form each tuple in the list: \\n\",res)"
},
{
"code": null,
"e": 1681,
"s": 1626,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1854,
"s": 1681,
"text": "Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]\nThe 1 st element form each tuple in the list:\n['3 pm', '12pm', '9 am', '6 am']"
},
{
"code": null,
"e": 2217,
"s": 1854,
"text": "The itegetter function from operator module can fetch each item form the given iterable till the end of the iterable is searched. In this program we search for index position 2 from the given list and apply a map function to apply the same function again and again to each result from the result of the itemgetter function. Finally we store the result as a list."
},
{
"code": null,
"e": 2228,
"s": 2217,
"text": " Live Demo"
},
{
"code": null,
"e": 2500,
"s": 2228,
"text": "from operator import itemgetter\n\nAlist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]\n\n#Given list\nprint(\"Given list: \",Alist)\n\n# Use itemgetter\nres = list(map(itemgetter(2), Alist))\n\nprint(\"The 1 st element form each tuple in the list: \\n\",res)"
},
{
"code": null,
"e": 2555,
"s": 2500,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2709,
"s": 2555,
"text": "Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]\nThe 1 st element form each tuple in the list:\n[10, 8, 8, 5]"
}
] |
How to create clickable links in a textView on Android?
|
This example demonstrates how do I create clickable links in a textView on android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="24sp"
android:textStyle="bold"
android:gravity="center"
android:text="@string/messageWithLink" />
</RelativeLayout>
Step 3 – Open res/values/strings.xml and add the following code −
<resources>
<string name="app_name">Sample</string>
<string
name="messageWithLink"><a href="https://www.google.com/">Tap here to open Link</a></string>
</resources>
Step 4 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textViewLink);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
Step 5 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "This example demonstrates how do I create clickable links in a textView on android."
},
{
"code": null,
"e": 1275,
"s": 1146,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1340,
"s": 1275,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1954,
"s": 1340,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n\n <TextView\n android:id=\"@+id/textViewLink\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:gravity=\"center\"\n android:text=\"@string/messageWithLink\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2020,
"s": 1954,
"text": "Step 3 – Open res/values/strings.xml and add the following code −"
},
{
"code": null,
"e": 2197,
"s": 2020,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string\n name=\"messageWithLink\"><a href=\"https://www.google.com/\">Tap here to open Link</a></string>\n</resources>"
},
{
"code": null,
"e": 2254,
"s": 2197,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2793,
"s": 2254,
"text": "package app.com.sample;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.method.LinkMovementMethod;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n textView = findViewById(R.id.textViewLink);\n textView.setMovementMethod(LinkMovementMethod.getInstance());\n }\n}"
},
{
"code": null,
"e": 2848,
"s": 2793,
"text": "Step 5 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3522,
"s": 2848,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3869,
"s": 3522,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Builtin functions of GCC compiler in C++
|
In the GCC compiler there are some builtin functions. These functions are like below.
This builtin function is used to count the number of 1s in an integer type data. Let us see an example of _builtin_popcount() function.
Live Demo
#include<iostream>
using namespace std;
int main() {
int n = 13; //The binary is 1101
cout << "Count of 1s in binary of "<< n <<" is " << __builtin_popcount(n);
return 0;
}
Count of 1s in binary of 13 is 3
This builtin function is used to check the parity of a number. If the number has odd parity, it will return true, otherwise it will return false. Let us see an example of _builtin_parity() function.
Live Demo
#include<iostream>
using namespace std;
int main() {
int n = 13; //The binary is 1101
cout << "Parity of "<< n <<" is " << __builtin_parity(n);
return 0;
}
Parity of 13 is 1
This builtin function is used to count the leading zeros of an integer. The clz stands for Count Leading Zeros. Let us see an example of _builtin_clz() function.
Live Demo
#include<iostream>
using namespace std;
int main() {
int n = 13; //The binary is 1101
//0000 0000 0000 0000 0000 0000 0000 1101 (32bit integer )
cout << "Leading zero count of "<< n <<" is " << __builtin_clz(n);
return 0;
}
Leading zero count of 13 is 28
This builtin function is used to count the trailing zeros of an integer. The ctz stands for Count Trailing Zeros. Let us see an example of _builtin_ctz() function.
Live Demo
#include<iostream>
using namespace std;
int main() {
int n = 12; //The binary is 1100
//0000 0000 0000 0000 0000 0000 0000 1100 (32bit integer )
cout << "Trailing zero count of "<< n <<" is " << __builtin_ctz(n);
return 0;
}
Trailing zero count of 12 is 2
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "In the GCC compiler there are some builtin functions. These functions are like below."
},
{
"code": null,
"e": 1284,
"s": 1148,
"text": "This builtin function is used to count the number of 1s in an integer type data. Let us see an example of _builtin_popcount() function."
},
{
"code": null,
"e": 1295,
"s": 1284,
"text": " Live Demo"
},
{
"code": null,
"e": 1477,
"s": 1295,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int n = 13; //The binary is 1101\n cout << \"Count of 1s in binary of \"<< n <<\" is \" << __builtin_popcount(n);\n return 0;\n}"
},
{
"code": null,
"e": 1510,
"s": 1477,
"text": "Count of 1s in binary of 13 is 3"
},
{
"code": null,
"e": 1709,
"s": 1510,
"text": "This builtin function is used to check the parity of a number. If the number has odd parity, it will return true, otherwise it will return false. Let us see an example of _builtin_parity() function."
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": " Live Demo"
},
{
"code": null,
"e": 1885,
"s": 1720,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int n = 13; //The binary is 1101\n cout << \"Parity of \"<< n <<\" is \" << __builtin_parity(n);\n return 0;\n}"
},
{
"code": null,
"e": 1903,
"s": 1885,
"text": "Parity of 13 is 1"
},
{
"code": null,
"e": 2065,
"s": 1903,
"text": "This builtin function is used to count the leading zeros of an integer. The clz stands for Count Leading Zeros. Let us see an example of _builtin_clz() function."
},
{
"code": null,
"e": 2076,
"s": 2065,
"text": " Live Demo"
},
{
"code": null,
"e": 2312,
"s": 2076,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int n = 13; //The binary is 1101\n //0000 0000 0000 0000 0000 0000 0000 1101 (32bit integer )\n cout << \"Leading zero count of \"<< n <<\" is \" << __builtin_clz(n);\n return 0;\n}"
},
{
"code": null,
"e": 2343,
"s": 2312,
"text": "Leading zero count of 13 is 28"
},
{
"code": null,
"e": 2507,
"s": 2343,
"text": "This builtin function is used to count the trailing zeros of an integer. The ctz stands for Count Trailing Zeros. Let us see an example of _builtin_ctz() function."
},
{
"code": null,
"e": 2518,
"s": 2507,
"text": " Live Demo"
},
{
"code": null,
"e": 2755,
"s": 2518,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int n = 12; //The binary is 1100\n //0000 0000 0000 0000 0000 0000 0000 1100 (32bit integer )\n cout << \"Trailing zero count of \"<< n <<\" is \" << __builtin_ctz(n);\n return 0;\n}"
},
{
"code": null,
"e": 2786,
"s": 2755,
"text": "Trailing zero count of 12 is 2"
}
] |
Permutation Sequence in C++
|
Suppose the set is like [1,2,3,...,n], contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get these sequence for n = 3: ["123","132","213","231","312","321"] So if n and k are given, then return the kth permutation sequence. The n will be between 1 to 9 (inclusive) and k will be between 1 to n! (inclusive). For example if n = 3.
Let us see the steps −
ans := empty string, define array called candidates of size n
for i in range 0 to n – 1candidates[i] := ((i + 1) + character ‘0’)
candidates[i] := ((i + 1) + character ‘0’)
create one array called fact of size n + 1, set fact[0] := 1
for i in range 1 to nfact[i] := fact[i – 1] * i
fact[i] := fact[i – 1] * i
decrease k by 1
for i := n – 1 down to 0idx := k / fact[i]ans := ans + candidates[idx]for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]k := k mod fact[i]
idx := k / fact[i]
ans := ans + candidates[idx]
for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]
candidates[j] := candidates[j + 1]
k := k mod fact[i]
return ans
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
string getPermutation(int n, int k) {
string ans = "";
vector <char> candidates(n);
for(lli i = 0; i < n; i++)
candidates[i] = ((i + 1) + '0');
vector <lli> fact(n + 1);
fact[0] = 1;
for(lli i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i;
k--;
for(lli i = n - 1; i >= 0; i--){
lli idx = k / fact[i];
ans += candidates[idx];
for(lli j = idx; j + 1< candidates.size(); j++)
candidates[j] = candidates[j + 1];
k = k % fact[i];
}
return ans;
}
};
main(){
Solution ob;
cout << ob.getPermutation(4, 9);
}
4
9
2314
|
[
{
"code": null,
"e": 1447,
"s": 1062,
"text": "Suppose the set is like [1,2,3,...,n], contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get these sequence for n = 3: [\"123\",\"132\",\"213\",\"231\",\"312\",\"321\"] So if n and k are given, then return the kth permutation sequence. The n will be between 1 to 9 (inclusive) and k will be between 1 to n! (inclusive). For example if n = 3."
},
{
"code": null,
"e": 1470,
"s": 1447,
"text": "Let us see the steps −"
},
{
"code": null,
"e": 1532,
"s": 1470,
"text": "ans := empty string, define array called candidates of size n"
},
{
"code": null,
"e": 1600,
"s": 1532,
"text": "for i in range 0 to n – 1candidates[i] := ((i + 1) + character ‘0’)"
},
{
"code": null,
"e": 1643,
"s": 1600,
"text": "candidates[i] := ((i + 1) + character ‘0’)"
},
{
"code": null,
"e": 1704,
"s": 1643,
"text": "create one array called fact of size n + 1, set fact[0] := 1"
},
{
"code": null,
"e": 1752,
"s": 1704,
"text": "for i in range 1 to nfact[i] := fact[i – 1] * i"
},
{
"code": null,
"e": 1779,
"s": 1752,
"text": "fact[i] := fact[i – 1] * i"
},
{
"code": null,
"e": 1795,
"s": 1779,
"text": "decrease k by 1"
},
{
"code": null,
"e": 1958,
"s": 1795,
"text": "for i := n – 1 down to 0idx := k / fact[i]ans := ans + candidates[idx]for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]k := k mod fact[i]"
},
{
"code": null,
"e": 1977,
"s": 1958,
"text": "idx := k / fact[i]"
},
{
"code": null,
"e": 2006,
"s": 1977,
"text": "ans := ans + candidates[idx]"
},
{
"code": null,
"e": 2081,
"s": 2006,
"text": "for j := idx, j + 1 < size of candidatescandidates[j] := candidates[j + 1]"
},
{
"code": null,
"e": 2116,
"s": 2081,
"text": "candidates[j] := candidates[j + 1]"
},
{
"code": null,
"e": 2135,
"s": 2116,
"text": "k := k mod fact[i]"
},
{
"code": null,
"e": 2146,
"s": 2135,
"text": "return ans"
},
{
"code": null,
"e": 2216,
"s": 2146,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2227,
"s": 2216,
"text": " Live Demo"
},
{
"code": null,
"e": 2964,
"s": 2227,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\n public:\n string getPermutation(int n, int k) {\n string ans = \"\";\n vector <char> candidates(n);\n for(lli i = 0; i < n; i++)\n candidates[i] = ((i + 1) + '0');\n vector <lli> fact(n + 1);\n fact[0] = 1;\n for(lli i = 1; i <= n; i++)\n fact[i] = fact[i - 1] * i;\n k--;\n for(lli i = n - 1; i >= 0; i--){\n lli idx = k / fact[i];\n ans += candidates[idx];\n for(lli j = idx; j + 1< candidates.size(); j++)\n candidates[j] = candidates[j + 1];\n k = k % fact[i];\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout << ob.getPermutation(4, 9);\n}"
},
{
"code": null,
"e": 2968,
"s": 2964,
"text": "4\n9"
},
{
"code": null,
"e": 2973,
"s": 2968,
"text": "2314"
}
] |
numpy.squeeze
|
This function removes one-dimensional entry from the shape of the given array. Two parameters are required for this function.
numpy.squeeze(arr, axis)
Where,
arr
Input array
axis
int or tuple of int. selects a subset of single dimensional entries in the shape
import numpy as np
x = np.arange(9).reshape(1,3,3)
print 'Array X:'
print x
print '\n'
y = np.squeeze(x)
print 'Array Y:'
print y
print '\n'
print 'The shapes of X and Y array:'
print x.shape, y.shape
Its output is as follows −
Array X:
[[[0 1 2]
[3 4 5]
[6 7 8]]]
Array Y:
[[0 1 2]
[3 4 5]
[6 7 8]]
The shapes of X and Y array:
(1, 3, 3) (3, 3)
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2369,
"s": 2243,
"text": "This function removes one-dimensional entry from the shape of the given array. Two parameters are required for this function."
},
{
"code": null,
"e": 2395,
"s": 2369,
"text": "numpy.squeeze(arr, axis)\n"
},
{
"code": null,
"e": 2402,
"s": 2395,
"text": "Where,"
},
{
"code": null,
"e": 2406,
"s": 2402,
"text": "arr"
},
{
"code": null,
"e": 2418,
"s": 2406,
"text": "Input array"
},
{
"code": null,
"e": 2423,
"s": 2418,
"text": "axis"
},
{
"code": null,
"e": 2504,
"s": 2423,
"text": "int or tuple of int. selects a subset of single dimensional entries in the shape"
},
{
"code": null,
"e": 2721,
"s": 2504,
"text": "import numpy as np \nx = np.arange(9).reshape(1,3,3) \n\nprint 'Array X:' \nprint x \nprint '\\n' \ny = np.squeeze(x) \n\nprint 'Array Y:' \nprint y \nprint '\\n' \n\nprint 'The shapes of X and Y array:' \nprint x.shape, y.shape"
},
{
"code": null,
"e": 2748,
"s": 2721,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 2873,
"s": 2748,
"text": "Array X:\n[[[0 1 2]\n [3 4 5]\n [6 7 8]]]\n\nArray Y:\n[[0 1 2]\n [3 4 5]\n [6 7 8]]\n\nThe shapes of X and Y array:\n(1, 3, 3) (3, 3)\n"
},
{
"code": null,
"e": 2906,
"s": 2873,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2923,
"s": 2906,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 2956,
"s": 2923,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2991,
"s": 2956,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3024,
"s": 2991,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3059,
"s": 3024,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3094,
"s": 3059,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3106,
"s": 3094,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3139,
"s": 3106,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3154,
"s": 3139,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 3187,
"s": 3154,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3194,
"s": 3187,
"text": " Anmol"
},
{
"code": null,
"e": 3201,
"s": 3194,
"text": " Print"
},
{
"code": null,
"e": 3212,
"s": 3201,
"text": " Add Notes"
}
] |
Output of C programs | Set 64 (Pointers) - GeeksforGeeks
|
25 Apr, 2018
Prerequisite : Pointers in CQuestion 1 : What will be the output of following program?
#include "stdio.h"int main(){ char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &a[0]; *ppp++; // Line 1 printf("%c %c ", *++ppp, --*ppp); // Line 2}
OPTIONS:a)C Bb)B Ac)B Cd)C A
OUTPUT: (d) C A
Explanation:Line 1 : Now, ppp points to next memory location i.e., index 1 of the character array.Line 2 : Firstly, –*ppp= –(*ppp) is executed and hence the value ‘B’ (which is in the index 1 position of the char[] array) gets decremented by 1(i.e., it becomes ‘A’)and it is sent for printing. Then *++ppp= *(++ppp) is executed which initially increments the pointer to the next element of the array and prints the value in that index number 2 which is ‘C’. Although –*ppp is executed first compared to *++ppp, the display will be shown in the order as we mentioned in the printf() function in line 2. Hence we get output as C A.
Question 2 : What will be the output of following program?
#include <stdio.h>int main(){ int* ptr; *ptr = 5; printf("%d", *ptr); return 0;}
OPTIONS:a) compilation errorb) Runtime errorc) 5d) linker error
OUTPUT: (b) Runtime error
Explanation: Pointer variable (*ptr) cannot be initialized.
Question 3 : What will be the output of following program?
#include <stdio.h>int main(){ int a = 36; int* ptr; ptr = &a; printf("%u %u", *&ptr, &*ptr); return 0;}
OPTIONS:a) Address Valueb) Value Addressc) Address Addressd) Compilation error
OUTPUT: (c)Address Address
Explanation: & and * cancelled each other and display the address stored in a pointer variable ptr i.e) the address of a.
Question 4 : What will be the output of following program?
#include <stdio.h>int main(){ int num = 10; printf("num = %d addresss of num = %u", num, &num); num++; printf("\n num = %d addresss of num = %u", num, &num); return 0;}
OPTIONS:a) Compilation errorb) num = 10 address of num = 2293436num = 11 address of num = 2293438c) num = 10 address of num = 2293436num = 11 address of num = 2293440d) num = 10 address of num = 2293436num = 11 address of num = 2293436
OUTPUT: (d)
Explanation: Here a variable num holds the value 10 and get its address as 2293436, then increment is done as num++ which uses the same address space to store the incremented value.
Question 5 : What will be the output of following program?
#include <stdio.h>int main(){ int i = 25; int* j; int** k; j = &i; k = &j; printf("%u %u %u ", k, *k, **k); return 0;}
OPTIONS:a) address address valueb) address value valuec) address address addressd) compilation error
OUTPUT : (a)address address value
Explanation : Here a pointer variable *j hold the address of i and then another pointer variable *k hold the address of j.nowk = address of j*k = address of i**k = value of i.
This article is contributed by Abhishek kurmi.
BhanuSashankReddy
C-Output
C-Pointers
C Quiz
MCQ
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C | Structure & Union | Question 10
C | Pointer Basics | Question 15
C | Advanced Pointer | Question 1
C | Structure & Union | Question 4
C | Pointer Basics | Question 1
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
Compiler Theory | Set 1
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n25 Apr, 2018"
},
{
"code": null,
"e": 24453,
"s": 24366,
"text": "Prerequisite : Pointers in CQuestion 1 : What will be the output of following program?"
},
{
"code": "#include \"stdio.h\"int main(){ char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &a[0]; *ppp++; // Line 1 printf(\"%c %c \", *++ppp, --*ppp); // Line 2}",
"e": 24612,
"s": 24453,
"text": null
},
{
"code": null,
"e": 24641,
"s": 24612,
"text": "OPTIONS:a)C Bb)B Ac)B Cd)C A"
},
{
"code": null,
"e": 24658,
"s": 24641,
"text": "OUTPUT: (d) C A\n"
},
{
"code": null,
"e": 25288,
"s": 24658,
"text": "Explanation:Line 1 : Now, ppp points to next memory location i.e., index 1 of the character array.Line 2 : Firstly, –*ppp= –(*ppp) is executed and hence the value ‘B’ (which is in the index 1 position of the char[] array) gets decremented by 1(i.e., it becomes ‘A’)and it is sent for printing. Then *++ppp= *(++ppp) is executed which initially increments the pointer to the next element of the array and prints the value in that index number 2 which is ‘C’. Although –*ppp is executed first compared to *++ppp, the display will be shown in the order as we mentioned in the printf() function in line 2. Hence we get output as C A."
},
{
"code": null,
"e": 25347,
"s": 25288,
"text": "Question 2 : What will be the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int* ptr; *ptr = 5; printf(\"%d\", *ptr); return 0;}",
"e": 25440,
"s": 25347,
"text": null
},
{
"code": null,
"e": 25504,
"s": 25440,
"text": "OPTIONS:a) compilation errorb) Runtime errorc) 5d) linker error"
},
{
"code": null,
"e": 25531,
"s": 25504,
"text": "OUTPUT: (b) Runtime error\n"
},
{
"code": null,
"e": 25591,
"s": 25531,
"text": "Explanation: Pointer variable (*ptr) cannot be initialized."
},
{
"code": null,
"e": 25650,
"s": 25591,
"text": "Question 3 : What will be the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int a = 36; int* ptr; ptr = &a; printf(\"%u %u\", *&ptr, &*ptr); return 0;}",
"e": 25769,
"s": 25650,
"text": null
},
{
"code": null,
"e": 25848,
"s": 25769,
"text": "OPTIONS:a) Address Valueb) Value Addressc) Address Addressd) Compilation error"
},
{
"code": null,
"e": 25876,
"s": 25848,
"text": "OUTPUT: (c)Address Address\n"
},
{
"code": null,
"e": 25998,
"s": 25876,
"text": "Explanation: & and * cancelled each other and display the address stored in a pointer variable ptr i.e) the address of a."
},
{
"code": null,
"e": 26057,
"s": 25998,
"text": "Question 4 : What will be the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int num = 10; printf(\"num = %d addresss of num = %u\", num, &num); num++; printf(\"\\n num = %d addresss of num = %u\", num, &num); return 0;}",
"e": 26241,
"s": 26057,
"text": null
},
{
"code": null,
"e": 26477,
"s": 26241,
"text": "OPTIONS:a) Compilation errorb) num = 10 address of num = 2293436num = 11 address of num = 2293438c) num = 10 address of num = 2293436num = 11 address of num = 2293440d) num = 10 address of num = 2293436num = 11 address of num = 2293436"
},
{
"code": null,
"e": 26490,
"s": 26477,
"text": "OUTPUT: (d)\n"
},
{
"code": null,
"e": 26672,
"s": 26490,
"text": "Explanation: Here a variable num holds the value 10 and get its address as 2293436, then increment is done as num++ which uses the same address space to store the incremented value."
},
{
"code": null,
"e": 26731,
"s": 26672,
"text": "Question 5 : What will be the output of following program?"
},
{
"code": "#include <stdio.h>int main(){ int i = 25; int* j; int** k; j = &i; k = &j; printf(\"%u %u %u \", k, *k, **k); return 0;}",
"e": 26871,
"s": 26731,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26871,
"text": "OPTIONS:a) address address valueb) address value valuec) address address addressd) compilation error"
},
{
"code": null,
"e": 27007,
"s": 26972,
"text": "OUTPUT : (a)address address value\n"
},
{
"code": null,
"e": 27183,
"s": 27007,
"text": "Explanation : Here a pointer variable *j hold the address of i and then another pointer variable *k hold the address of j.nowk = address of j*k = address of i**k = value of i."
},
{
"code": null,
"e": 27230,
"s": 27183,
"text": "This article is contributed by Abhishek kurmi."
},
{
"code": null,
"e": 27248,
"s": 27230,
"text": "BhanuSashankReddy"
},
{
"code": null,
"e": 27257,
"s": 27248,
"text": "C-Output"
},
{
"code": null,
"e": 27268,
"s": 27257,
"text": "C-Pointers"
},
{
"code": null,
"e": 27275,
"s": 27268,
"text": "C Quiz"
},
{
"code": null,
"e": 27279,
"s": 27275,
"text": "MCQ"
},
{
"code": null,
"e": 27294,
"s": 27279,
"text": "Program Output"
},
{
"code": null,
"e": 27392,
"s": 27294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27428,
"s": 27392,
"text": "C | Structure & Union | Question 10"
},
{
"code": null,
"e": 27461,
"s": 27428,
"text": "C | Pointer Basics | Question 15"
},
{
"code": null,
"e": 27495,
"s": 27461,
"text": "C | Advanced Pointer | Question 1"
},
{
"code": null,
"e": 27530,
"s": 27495,
"text": "C | Structure & Union | Question 4"
},
{
"code": null,
"e": 27562,
"s": 27530,
"text": "C | Pointer Basics | Question 1"
},
{
"code": null,
"e": 27609,
"s": 27562,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 27635,
"s": 27609,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 27661,
"s": 27635,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 27687,
"s": 27661,
"text": "Computer Networks | Set 2"
}
] |
What is Non-Immediate Left Recursion in compiler design?
|
A Grammar G (V, T, P, S) is left recursive if it has a production in the form.
A → A α |β.
The above Grammar is left recursive because the left of production is occurring at a first position on the right side of production. It can eliminate left recursion by replacing a pair of production with
A → βA′
A → αA′|ε
The general form for left recursion is
A → Aα1|Aα2| ... . |Aαm|β1|β2| ... . . βn
can be replaced by
A → β1A′|β2A′| ... . . | ... . . |βnA′
A → α1A′|α2A′| ... . . |αmA′|ε
In the following grammar, it does not have the immediate or direct left recursion. But here, it can have non-immediate left recursion.
S → Ab
A → Sc|d
Here, S is left Recursive, because S ⇒ A b ⇒ S c b
Algorithm to Remove Left-Recursion
Input − Grammar G with no cycles or ε − productions.
Output − Equivalent Grammar with no Left Recursion.
Method
Order the non-terminals as A1, A2, ... ... ... . . An
Order the non-terminals as A1, A2, ... ... ... . . An
for i = 1 to n
{
for j = 1 to i – 1
{
replace each production Ai → Ajγ
by productions Ai → δ1γ| δ2γ| ... ... . . |δKγ
where Aj → δ1|δ2| ... ... . |δK
}
Remove immediate left Recursion among Ai productions.
}
Example1 − Remove or Eliminate Left Recursion from the following Grammar.
S → Ab
A → Sc | d
Solution
These productions don’t have immediate left Recursion. So it cannot be eliminated directly. We can use the algorithm here to remove Left Recursion.
Step1 − Order the non-terminals S, A as A1, A2i.e., Mark S =A1, A = A2
Substituting values
∴ A1 → A2b ............... (1)
A2 → A1c|d ............... (2)
Step2 − Put values of (1) in (2)
∴ A1 → A2b
A2 → A1bc|d
Step3 − Again substitutes A1 = S and A2 = A
∴ S → A b ................ (3)
A → A b c | d ................ (4)
Step4 − Remove Immediate Left recursion in A → A b c | d
So,
Example2 − Remove left recursion from the following Grammar.
S → Aa |b
A → Ac | Sd|e
Solution
As we don’t have immediate left recursion so, we have to apply the algorithm here.
Step1 − Rename S, A as A1, A2 respectively.
A1 → A2 a | b ............... (1)
A2 → A2c | A1d|e ................ (2)
Step2 − Substitute value of A1 of the statement (1) in R.H.S of the statement (2).
A1 → A2 a | b
A2 → A2 c |A2 a d|bd|e.
Step3 − Again, substitute A1 = S, A2 = A
S → Aa |b ................. (3)
A → Ac |A a d|bd|e .................. (4)
Step4 − Statement (4) has an immediate left recursion. Removing immediate left recursion we get
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "A Grammar G (V, T, P, S) is left recursive if it has a production in the form."
},
{
"code": null,
"e": 1153,
"s": 1141,
"text": "A → A α |β."
},
{
"code": null,
"e": 1357,
"s": 1153,
"text": "The above Grammar is left recursive because the left of production is occurring at a first position on the right side of production. It can eliminate left recursion by replacing a pair of production with"
},
{
"code": null,
"e": 1365,
"s": 1357,
"text": "A → βA′"
},
{
"code": null,
"e": 1375,
"s": 1365,
"text": "A → αA′|ε"
},
{
"code": null,
"e": 1414,
"s": 1375,
"text": "The general form for left recursion is"
},
{
"code": null,
"e": 1456,
"s": 1414,
"text": "A → Aα1|Aα2| ... . |Aαm|β1|β2| ... . . βn"
},
{
"code": null,
"e": 1475,
"s": 1456,
"text": "can be replaced by"
},
{
"code": null,
"e": 1514,
"s": 1475,
"text": "A → β1A′|β2A′| ... . . | ... . . |βnA′"
},
{
"code": null,
"e": 1545,
"s": 1514,
"text": "A → α1A′|α2A′| ... . . |αmA′|ε"
},
{
"code": null,
"e": 1680,
"s": 1545,
"text": "In the following grammar, it does not have the immediate or direct left recursion. But here, it can have non-immediate left recursion."
},
{
"code": null,
"e": 1687,
"s": 1680,
"text": "S → Ab"
},
{
"code": null,
"e": 1696,
"s": 1687,
"text": "A → Sc|d"
},
{
"code": null,
"e": 1747,
"s": 1696,
"text": "Here, S is left Recursive, because S ⇒ A b ⇒ S c b"
},
{
"code": null,
"e": 1782,
"s": 1747,
"text": "Algorithm to Remove Left-Recursion"
},
{
"code": null,
"e": 1835,
"s": 1782,
"text": "Input − Grammar G with no cycles or ε − productions."
},
{
"code": null,
"e": 1887,
"s": 1835,
"text": "Output − Equivalent Grammar with no Left Recursion."
},
{
"code": null,
"e": 1894,
"s": 1887,
"text": "Method"
},
{
"code": null,
"e": 1948,
"s": 1894,
"text": "Order the non-terminals as A1, A2, ... ... ... . . An"
},
{
"code": null,
"e": 2002,
"s": 1948,
"text": "Order the non-terminals as A1, A2, ... ... ... . . An"
},
{
"code": null,
"e": 2237,
"s": 2002,
"text": "for i = 1 to n\n{\n for j = 1 to i – 1\n {\n replace each production Ai → Ajγ\n by productions Ai → δ1γ| δ2γ| ... ... . . |δKγ\n where Aj → δ1|δ2| ... ... . |δK\n }\nRemove immediate left Recursion among Ai productions.\n}"
},
{
"code": null,
"e": 2311,
"s": 2237,
"text": "Example1 − Remove or Eliminate Left Recursion from the following Grammar."
},
{
"code": null,
"e": 2318,
"s": 2311,
"text": "S → Ab"
},
{
"code": null,
"e": 2329,
"s": 2318,
"text": "A → Sc | d"
},
{
"code": null,
"e": 2338,
"s": 2329,
"text": "Solution"
},
{
"code": null,
"e": 2486,
"s": 2338,
"text": "These productions don’t have immediate left Recursion. So it cannot be eliminated directly. We can use the algorithm here to remove Left Recursion."
},
{
"code": null,
"e": 2557,
"s": 2486,
"text": "Step1 − Order the non-terminals S, A as A1, A2i.e., Mark S =A1, A = A2"
},
{
"code": null,
"e": 2577,
"s": 2557,
"text": "Substituting values"
},
{
"code": null,
"e": 2638,
"s": 2577,
"text": "∴ A1 → A2b ............... (1)"
},
{
"code": null,
"e": 2700,
"s": 2638,
"text": " A2 → A1c|d ............... (2)"
},
{
"code": null,
"e": 2733,
"s": 2700,
"text": "Step2 − Put values of (1) in (2)"
},
{
"code": null,
"e": 2745,
"s": 2733,
"text": "∴ A1 → A2b"
},
{
"code": null,
"e": 2761,
"s": 2745,
"text": " A2 → A1bc|d"
},
{
"code": null,
"e": 2805,
"s": 2761,
"text": "Step3 − Again substitutes A1 = S and A2 = A"
},
{
"code": null,
"e": 2866,
"s": 2805,
"text": "∴ S → A b ................ (3)"
},
{
"code": null,
"e": 2928,
"s": 2866,
"text": " A → A b c | d ................ (4)"
},
{
"code": null,
"e": 2985,
"s": 2928,
"text": "Step4 − Remove Immediate Left recursion in A → A b c | d"
},
{
"code": null,
"e": 2989,
"s": 2985,
"text": "So,"
},
{
"code": null,
"e": 3050,
"s": 2989,
"text": "Example2 − Remove left recursion from the following Grammar."
},
{
"code": null,
"e": 3060,
"s": 3050,
"text": "S → Aa |b"
},
{
"code": null,
"e": 3074,
"s": 3060,
"text": "A → Ac | Sd|e"
},
{
"code": null,
"e": 3083,
"s": 3074,
"text": "Solution"
},
{
"code": null,
"e": 3166,
"s": 3083,
"text": "As we don’t have immediate left recursion so, we have to apply the algorithm here."
},
{
"code": null,
"e": 3210,
"s": 3166,
"text": "Step1 − Rename S, A as A1, A2 respectively."
},
{
"code": null,
"e": 3267,
"s": 3210,
"text": "A1 → A2 a | b ............... (1)"
},
{
"code": null,
"e": 3322,
"s": 3267,
"text": "A2 → A2c | A1d|e ................ (2)"
},
{
"code": null,
"e": 3405,
"s": 3322,
"text": "Step2 − Substitute value of A1 of the statement (1) in R.H.S of the statement (2)."
},
{
"code": null,
"e": 3419,
"s": 3405,
"text": "A1 → A2 a | b"
},
{
"code": null,
"e": 3443,
"s": 3419,
"text": "A2 → A2 c |A2 a d|bd|e."
},
{
"code": null,
"e": 3484,
"s": 3443,
"text": "Step3 − Again, substitute A1 = S, A2 = A"
},
{
"code": null,
"e": 3546,
"s": 3484,
"text": "S → Aa |b ................. (3)"
},
{
"code": null,
"e": 3606,
"s": 3546,
"text": "A → Ac |A a d|bd|e .................. (4)"
},
{
"code": null,
"e": 3702,
"s": 3606,
"text": "Step4 − Statement (4) has an immediate left recursion. Removing immediate left recursion we get"
}
] |
Find the size of a HashMap in Java
|
Use the size() method to get the size of HashMap. Let us first create a HashMap
HashMap hm = new HashMap();
Now, add some elements −
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Franes", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Since, we added 5 elements above, therefore, the size() method will give 5 as the result −
set.size()
The following is an example to find the size of HashMap −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Franes", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
Set set = hm.entrySet();
System.out.println("Elements in HashMap...");
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
System.out.println("Size of HashMap = "+set.size());
}
}
Elements in HashMap...
Franes: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000
Size of HashMap = 5
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Use the size() method to get the size of HashMap. Let us first create a HashMap"
},
{
"code": null,
"e": 1170,
"s": 1142,
"text": "HashMap hm = new HashMap();"
},
{
"code": null,
"e": 1195,
"s": 1170,
"text": "Now, add some elements −"
},
{
"code": null,
"e": 1376,
"s": 1195,
"text": "hm.put(\"Bag\", new Integer(1100));\nhm.put(\"Sunglasses\", new Integer(2000));\nhm.put(\"Franes\", new Integer(800));\nhm.put(\"Wallet\", new Integer(700));\nhm.put(\"Belt\", new Integer(600));"
},
{
"code": null,
"e": 1467,
"s": 1376,
"text": "Since, we added 5 elements above, therefore, the size() method will give 5 as the result −"
},
{
"code": null,
"e": 1478,
"s": 1467,
"text": "set.size()"
},
{
"code": null,
"e": 1536,
"s": 1478,
"text": "The following is an example to find the size of HashMap −"
},
{
"code": null,
"e": 1547,
"s": 1536,
"text": " Live Demo"
},
{
"code": null,
"e": 2370,
"s": 1547,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // Create a hash map\n HashMap hm = new HashMap();\n // Put elements to the map\n hm.put(\"Bag\", new Integer(1100));\n hm.put(\"Sunglasses\", new Integer(2000));\n hm.put(\"Franes\", new Integer(800));\n hm.put(\"Wallet\", new Integer(700));\n hm.put(\"Belt\", new Integer(600));\n Set set = hm.entrySet();\n System.out.println(\"Elements in HashMap...\");\n // Get an iterator\n Iterator i = set.iterator();\n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n System.out.println(\"Size of HashMap = \"+set.size());\n }\n}"
},
{
"code": null,
"e": 2474,
"s": 2370,
"text": "Elements in HashMap...\nFranes: 800\nBelt: 600\nWallet: 700\nBag: 1100\nSunglasses: 2000\nSize of HashMap = 5"
}
] |
$("#submitButton").attr("disabled", "disabled")
|
This would modify the disabled attribute to the value "disabled" while clicking Submit button.
Here is the simple syntax to use this method −
selector.attr("disabled","disabled");
Here is the description of all the parameters used by this method −
disabled This is the CSS property of the matched element.
disabled This is the CSS property of the matched element.
disabled This is the value to be set to the matched element.
disabled This is the value to be set to the matched element.
Following example would modify the disabled attribute to the value "disabled" while clicking Submit button.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
function disableSubmit(){
$("#submitButton").attr("disabled", "disabled");
}
</script>
</head>
<body>
<div>
<form name = "sampleForm">
<input type = "text" id = "result1" title="The jQuery Example" value = "sample" ></input><br/><br/>
<input type = "text" id = "result2" title="The jQuery Example" value = "sample" ></input> <br/><br/>
<input type = "button" id = "submitButton" onclick="disableSubmit();" value = "submit"/>
</form>
</div>
</body>
</html>
This will produce following result −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1783,
"s": 1688,
"text": "This would modify the disabled attribute to the value \"disabled\" while clicking Submit button."
},
{
"code": null,
"e": 1830,
"s": 1783,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 1869,
"s": 1830,
"text": "selector.attr(\"disabled\",\"disabled\");\n"
},
{
"code": null,
"e": 1937,
"s": 1869,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 1995,
"s": 1937,
"text": "disabled This is the CSS property of the matched element."
},
{
"code": null,
"e": 2053,
"s": 1995,
"text": "disabled This is the CSS property of the matched element."
},
{
"code": null,
"e": 2114,
"s": 2053,
"text": "disabled This is the value to be set to the matched element."
},
{
"code": null,
"e": 2175,
"s": 2114,
"text": "disabled This is the value to be set to the matched element."
},
{
"code": null,
"e": 2283,
"s": 2175,
"text": "Following example would modify the disabled attribute to the value \"disabled\" while clicking Submit button."
},
{
"code": null,
"e": 3108,
"s": 2283,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\t\t\n <script type = \"text/javascript\" language = \"javascript\">\t \n function disableSubmit(){\n $(\"#submitButton\").attr(\"disabled\", \"disabled\");\n }\n </script>\n </head>\t\n \n <body>\n <div>\n <form name = \"sampleForm\">\n <input type = \"text\" id = \"result1\" title=\"The jQuery Example\" value = \"sample\" ></input><br/><br/>\n <input type = \"text\" id = \"result2\" title=\"The jQuery Example\" value = \"sample\" ></input> <br/><br/>\n <input type = \"button\" id = \"submitButton\" onclick=\"disableSubmit();\" value = \"submit\"/>\n </form>\n </div>\n </body>\t\n</html>"
},
{
"code": null,
"e": 3145,
"s": 3108,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3152,
"s": 3145,
"text": " Print"
},
{
"code": null,
"e": 3163,
"s": 3152,
"text": " Add Notes"
}
] |
The Fastest and Easiest Way to Forecast Data on Python | by Rohan Gupta | Towards Data Science
|
Recently, I learned about Prophet (fbprophet). If you’re a Data Scientist who works with time-series data, you will love this tool.
For those not aware, Prophet was developed by Facebook to aid Data Scientists with automated forecasting for time-series data through its simple Sk-Learn style API. Prophet can be fine-tuned by a data scientist to achieve more specificity. It is an additive forecasting model, and assumed that seasonal effects will be similar each year. Therefore, it doesn’t take a lot into account, but its accuracy can be improved over time through multiple feedback mechanisms. Its website states that Prophet works best with time-series data that has regular seasonality components and lots of historical data to refer to.
Since it is open-source, anyone can download and use Prophet. Check out the link below for more information on Prophet and why you should use to forecast your time-series data:
facebook.github.io
I won’t go into much detail here, but since I did have some issues downloading Prophet for the first time, I’ll explain what I did to install it properly:
Firstly, you can try a simple pip install if that works: pip install fbprophet
However, fbprophet has one major dependency that may cause problems: pystan
Ideally, you want to pip install pystan before fbprophet : https://pystan.readthedocs.io/en/latest/installation_beginner.html
WINDOWS: pystan needs a compiler. Follow instructions here.
The easiest way is to install Prophet in anaconda. Use conda install gcc to set up gcc. Then install Prophet is through conda-forge: conda install -c conda-forge fbprophet
We will be using the following libraries for the tutorial. All basic libraries except Prophet.
import matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport osfrom fbprophet import Prophet
For Dataset, I downloaded almost 10 years of game data for James Harden from here. Essentially, we have data for almost every single game Harden has played (both in the Regular Season, as well as in the Playoffs.)
To use the same data that I’m using, head over to this GitHub page and download the CSV files.
Below, I have imported each of the CSV files containing data on James Harden. ‘19rs’ would be “Regular Season 2019–2020” and ‘18po’ would be “Playoffs 2018–2019” to give you an idea of how each file is named.
harden19rs = pd.read_csv('Downloads/NBAML/harden19rs.csv')harden19po = pd.read_csv('Downloads/NBAML/harden19po.csv')harden18rs = pd.read_csv('Downloads/NBAML/harden18rs.csv')harden18po = pd.read_csv('Downloads/NBAML/harden18po.csv')harden17rs = pd.read_csv('Downloads/NBAML/harden17rs.csv')harden17po = pd.read_csv('Downloads/NBAML/harden17po.csv')harden16rs = pd.read_csv('Downloads/NBAML/harden16rs.csv')harden16po = pd.read_csv('Downloads/NBAML/harden16po.csv')harden15rs = pd.read_csv('Downloads/NBAML/harden15rs.csv')harden15po = pd.read_csv('Downloads/NBAML/harden15po.csv')harden14rs = pd.read_csv('Downloads/NBAML/harden14rs.csv')harden14po = pd.read_csv('Downloads/NBAML/harden14po.csv')harden13rs = pd.read_csv('Downloads/NBAML/harden13rs.csv')harden13po = pd.read_csv('Downloads/NBAML/harden13po.csv')harden12rs = pd.read_csv('Downloads/NBAML/harden12rs.csv')harden12po = pd.read_csv('Downloads/NBAML/harden12po.csv')harden11rs = pd.read_csv('Downloads/NBAML/harden11rs.csv')harden11po = pd.read_csv('Downloads/NBAML/harden11po.csv')harden10rs = pd.read_csv('Downloads/NBAML/harden10po.csv')harden10po = pd.read_csv('Downloads/NBAML/harden10rs.csv')harden09rs = pd.read_csv('Downloads/NBAML/harden09rs.csv')
The next step is super important as we want to make sure our data contains all the required fields or else we wouldn’t be able to do much with it.
Let’s start off by appending each of the CSV files. We can make them chronological as there’s a date component. First, we append each file in the following way:
harden = harden19rs.append(harden19po, ignore_index=True, sort=True)harden = harden.append(harden18rs, ignore_index=True, sort=True)...harden = harden.append(harden09rs, ignore_index=True, sort=True)
Next, I’ll rename some columns so we can understand what they are, and drop the unnecessary columns that aren’t required:
harden = harden.rename(columns={'Unnamed: 7': 'Game', 'MP':'Mins'})#harden['Game'] = pd.concat([harden['Unnamed: 7'].dropna(), harden['Game'].dropna()]).reindex_like(harden)#harden = harden.drop(columns=['Unnamed: 7'])harden = harden.drop(columns=['Unnamed: 5']) harden = harden.drop(columns=['▲'])harden = harden.sort_values(by=['Date'])harden = harden.reset_index(drop=True)
The final dataset looks somewhat like this:
There are some columns in between that we can’t see, but for the most part, it’s all game statistics. Different stats for each game played by James Harden.
Since we want the data to be in chronological order, we set the date as our index value and change the datatype to a pandas datetime variable:
harden.set_index(‘Date’)harden[‘Date’] = pd.to_datetime(harden[‘Date’])
Next, we want to drop any values in our data (even though I doubt we have any). We will use the pandas dropna function and will drop a row in which all values are null. Once we do that, we’ll reset the index to make sure it’s still coherent.
harden = harden.dropna(how='all')harden = harden.reset_index(drop=True)
Next, we have another important step in the data cleanup. During some games, James Harden was inactive, suspended, did not play or did not dress. Certain columns would have these values “suspended” rather than the numeric value that should be there.
Thus, we can remove all the rows (games) in which Harden did not play/dress or was inactive/suspended. However, that might reduce the size of my data by a lot. So instead, I will replace the values with the median of each respective column.
for i in harden: harden[i] = harden[i].replace('Inactive', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Did Not Play', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Did Not Dress', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Player Suspended', np.median(pd.to_numeric(harden[i], errors='coerce'))) harden = harden.dropna(how='any')harden = harden.reset_index(drop=True)harden.set_index('Date')
A column containing numeric data should be explicitly assigned that datatype, in order to avoid errors in the future. Therefore, I will assign each column its correct data type. Using downcast='float' for float (decimal) columns.
harden['3P'] = pd.to_numeric(harden['3P'])harden['3PA'] = pd.to_numeric(harden['3PA'])harden['AST'] = pd.to_numeric(harden['AST'])harden['BLK'] = pd.to_numeric(harden['BLK'])harden['DRB'] = pd.to_numeric(harden['DRB'])harden['ORB'] = pd.to_numeric(harden['ORB'])harden['FG'] = pd.to_numeric(harden['FG'])harden['FGA'] = pd.to_numeric(harden['FGA'])harden['PTS'] = pd.to_numeric(harden['PTS'])harden['PF'] = pd.to_numeric(harden['PF'])harden['TOV'] = pd.to_numeric(harden['TOV'])harden['STL'] = pd.to_numeric(harden['STL'])harden['TRB'] = pd.to_numeric(harden['TRB'])harden['3P%'] = pd.to_numeric(harden['3P%'], downcast='float')harden['FG%'] = pd.to_numeric(harden['FG%'], downcast='float')harden['FT%'] = pd.to_numeric(harden['FT%'], downcast='float')harden['GmSc'] = pd.to_numeric(harden['GmSc'], downcast='float')harden['FTA'] = pd.to_numeric(harden['FTA'])harden['FT'] = pd.to_numeric(harden['FT'])print(harden.dtypes)Output: 3P int643P% float323PA int64AST int64BLK int64DRB int64Date datetime64[ns]FG int64FG% float32FGA int64FT int64FT% float32FTA int64GmSc float32ORB int64Opp objectPF int64PTS int64STL int64TOV int64TRB int64dtype: object
Now to the best part. We will forecast any column in this dataset using Prophet. The output will give us an image (graph) of the forecast. In order to create the graph, we need to first fit the Prophet model to our dataset. We will separate the column we want, along with the date column. In this case, I’m predicting points, so I’ll take the ‘PTS’ and ‘Date’ columns.
df = harden[['PTS', 'Date']]
These next steps are quite important, as we will be fitting the prophet model to our data. We want to rename our columns to ‘ds’ (date) and ‘y’ (target). We then define our Prophet model with any given interval_width. Then we fit our Prophet model to the dataset with the date and target variable.
jh = df.rename(columns={'Date': 'ds', 'PTS': 'y'})jh_model = Prophet(interval_width=0.95)jh_model.fit(jh)
To forecast values, we use the make_future_dataframe function, specify the number of periods, frequency as ‘MS’, which is Multiplicative Seasonality.We then create our matplotlib figure for the forecast. The image below the code shows you the output.
jh_forecast = jh_model.make_future_dataframe(periods=36, freq='MS')jh_forecast = jh_model.predict(jh_forecast)plt.figure(figsize=(18, 6))jh_model.plot(jh_forecast, xlabel = 'Date', ylabel = 'PTS')plt.title('James Harden Points')
Now, what if I wanted to compare James Harden’s forecast to Giannis Antetokounmpo, LeBron James, and Kawhi Leonard.
To do this, I’ll take all of the pre-processing and put it in a single function, so I can pre-process the data without repeating lines of code. Below, I’ve supplied a gist that contains the required functions.
Once you have the data processed, we can start merging all the frames and graph them as below.
harden = harden.rename(columns={'Date': 'ds', 'PTS': 'y'})jh_model = Prophet(interval_width=0.95)jh_model.fit(harden)lebron = lebron.rename(columns={'Date': 'ds', 'PTS': 'y'})lj_model = Prophet(interval_width=0.95)lj_model.fit(lebron)giannis = giannis.rename(columns={'Date': 'ds', 'PTS': 'y'})ga_model = Prophet(interval_width=0.95)ga_model.fit(giannis)kawhi = kawhi.rename(columns={'Date': 'ds', 'PTS': 'y'})kl_model = Prophet(interval_width=0.95)kl_model.fit(kawhi)jh_forecast = jh_model.make_future_dataframe(periods=36, freq='MS')jh_forecast = jh_model.predict(jh_forecast)lj_forecast = lj_model.make_future_dataframe(periods=36, freq='MS')lj_forecast = lj_model.predict(lj_forecast)ga_forecast = ga_model.make_future_dataframe(periods=36, freq='MS')ga_forecast = ga_model.predict(ga_forecast)kl_forecast = kl_model.make_future_dataframe(periods=36, freq='MS')kl_forecast = kl_model.predict(kl_forecast)hardens = ['harden_%s' % column for column in jh_forecast.columns]lebrons = ['lebron_%s' % column for column in lj_forecast.columns]kawhis = ['kawhi_%s' % column for column in kl_forecast.columns]gianniss = ['giannis_%s' % column for column in ga_forecast.columns]merge_jh_forecast = jh_forecast.copy()merge_lj_forecast = lj_forecast.copy()merge_kl_forecast = kl_forecast.copy()merge_ga_forecast = ga_forecast.copy()merge_jh_forecast.columns = hardensmerge_lj_forecast.columns = lebronsmerge_kl_forecast.columns = kawhismerge_ga_forecast.columns = giannissforecast = pd.merge(merge_jh_forecast, merge_lj_forecast, how = 'inner', left_on='harden_ds', right_on='lebron_ds')forecast = pd.merge(forecast, merge_kl_forecast, how = 'inner', left_on='lebron_ds', right_on='kawhi_ds')forecast = pd.merge(forecast, merge_ga_forecast, how = 'inner', left_on='kawhi_ds', right_on='giannis_ds')forecast = forecast.rename(columns={'harden_ds': 'Date'})forecast.head()plt.figure(figsize=(10, 7))plt.plot(forecast['Date'], forecast['harden_yhat'], 'b-')plt.plot(forecast['Date'], forecast['lebron_yhat'], 'r-')plt.plot(forecast['Date'], forecast['kawhi_yhat'], 'g-')plt.plot(forecast['Date'], forecast['giannis_yhat'], 'y-')plt.legend(['Harden', 'Lebron', 'Kawhi', 'Giannis'])plt.xlabel('Date')plt.ylabel('Points')plt.title('Harden vs LeBron vs Giannis vs Kawhi');plt.show()
The final output should look like this:
Looks like James Harden has everyone beat when it comes to points per game, although Giannis has some seasonal spikes (maybe he performs well on Fridays). For next time, I might write another tutorial, comparing more players with a lot more specificity. Let me know in the comments if you have any feedback/ideas.
Thanks for the read! Hope you learned something useful. Follow Me for more content on Data Science!
|
[
{
"code": null,
"e": 303,
"s": 171,
"text": "Recently, I learned about Prophet (fbprophet). If you’re a Data Scientist who works with time-series data, you will love this tool."
},
{
"code": null,
"e": 915,
"s": 303,
"text": "For those not aware, Prophet was developed by Facebook to aid Data Scientists with automated forecasting for time-series data through its simple Sk-Learn style API. Prophet can be fine-tuned by a data scientist to achieve more specificity. It is an additive forecasting model, and assumed that seasonal effects will be similar each year. Therefore, it doesn’t take a lot into account, but its accuracy can be improved over time through multiple feedback mechanisms. Its website states that Prophet works best with time-series data that has regular seasonality components and lots of historical data to refer to."
},
{
"code": null,
"e": 1092,
"s": 915,
"text": "Since it is open-source, anyone can download and use Prophet. Check out the link below for more information on Prophet and why you should use to forecast your time-series data:"
},
{
"code": null,
"e": 1111,
"s": 1092,
"text": "facebook.github.io"
},
{
"code": null,
"e": 1266,
"s": 1111,
"text": "I won’t go into much detail here, but since I did have some issues downloading Prophet for the first time, I’ll explain what I did to install it properly:"
},
{
"code": null,
"e": 1345,
"s": 1266,
"text": "Firstly, you can try a simple pip install if that works: pip install fbprophet"
},
{
"code": null,
"e": 1421,
"s": 1345,
"text": "However, fbprophet has one major dependency that may cause problems: pystan"
},
{
"code": null,
"e": 1547,
"s": 1421,
"text": "Ideally, you want to pip install pystan before fbprophet : https://pystan.readthedocs.io/en/latest/installation_beginner.html"
},
{
"code": null,
"e": 1607,
"s": 1547,
"text": "WINDOWS: pystan needs a compiler. Follow instructions here."
},
{
"code": null,
"e": 1779,
"s": 1607,
"text": "The easiest way is to install Prophet in anaconda. Use conda install gcc to set up gcc. Then install Prophet is through conda-forge: conda install -c conda-forge fbprophet"
},
{
"code": null,
"e": 1874,
"s": 1779,
"text": "We will be using the following libraries for the tutorial. All basic libraries except Prophet."
},
{
"code": null,
"e": 1981,
"s": 1874,
"text": "import matplotlib.pyplot as pltimport pandas as pdimport numpy as npimport osfrom fbprophet import Prophet"
},
{
"code": null,
"e": 2195,
"s": 1981,
"text": "For Dataset, I downloaded almost 10 years of game data for James Harden from here. Essentially, we have data for almost every single game Harden has played (both in the Regular Season, as well as in the Playoffs.)"
},
{
"code": null,
"e": 2290,
"s": 2195,
"text": "To use the same data that I’m using, head over to this GitHub page and download the CSV files."
},
{
"code": null,
"e": 2499,
"s": 2290,
"text": "Below, I have imported each of the CSV files containing data on James Harden. ‘19rs’ would be “Regular Season 2019–2020” and ‘18po’ would be “Playoffs 2018–2019” to give you an idea of how each file is named."
},
{
"code": null,
"e": 3718,
"s": 2499,
"text": "harden19rs = pd.read_csv('Downloads/NBAML/harden19rs.csv')harden19po = pd.read_csv('Downloads/NBAML/harden19po.csv')harden18rs = pd.read_csv('Downloads/NBAML/harden18rs.csv')harden18po = pd.read_csv('Downloads/NBAML/harden18po.csv')harden17rs = pd.read_csv('Downloads/NBAML/harden17rs.csv')harden17po = pd.read_csv('Downloads/NBAML/harden17po.csv')harden16rs = pd.read_csv('Downloads/NBAML/harden16rs.csv')harden16po = pd.read_csv('Downloads/NBAML/harden16po.csv')harden15rs = pd.read_csv('Downloads/NBAML/harden15rs.csv')harden15po = pd.read_csv('Downloads/NBAML/harden15po.csv')harden14rs = pd.read_csv('Downloads/NBAML/harden14rs.csv')harden14po = pd.read_csv('Downloads/NBAML/harden14po.csv')harden13rs = pd.read_csv('Downloads/NBAML/harden13rs.csv')harden13po = pd.read_csv('Downloads/NBAML/harden13po.csv')harden12rs = pd.read_csv('Downloads/NBAML/harden12rs.csv')harden12po = pd.read_csv('Downloads/NBAML/harden12po.csv')harden11rs = pd.read_csv('Downloads/NBAML/harden11rs.csv')harden11po = pd.read_csv('Downloads/NBAML/harden11po.csv')harden10rs = pd.read_csv('Downloads/NBAML/harden10po.csv')harden10po = pd.read_csv('Downloads/NBAML/harden10rs.csv')harden09rs = pd.read_csv('Downloads/NBAML/harden09rs.csv')"
},
{
"code": null,
"e": 3865,
"s": 3718,
"text": "The next step is super important as we want to make sure our data contains all the required fields or else we wouldn’t be able to do much with it."
},
{
"code": null,
"e": 4026,
"s": 3865,
"text": "Let’s start off by appending each of the CSV files. We can make them chronological as there’s a date component. First, we append each file in the following way:"
},
{
"code": null,
"e": 4226,
"s": 4026,
"text": "harden = harden19rs.append(harden19po, ignore_index=True, sort=True)harden = harden.append(harden18rs, ignore_index=True, sort=True)...harden = harden.append(harden09rs, ignore_index=True, sort=True)"
},
{
"code": null,
"e": 4348,
"s": 4226,
"text": "Next, I’ll rename some columns so we can understand what they are, and drop the unnecessary columns that aren’t required:"
},
{
"code": null,
"e": 4725,
"s": 4348,
"text": "harden = harden.rename(columns={'Unnamed: 7': 'Game', 'MP':'Mins'})#harden['Game'] = pd.concat([harden['Unnamed: 7'].dropna(), harden['Game'].dropna()]).reindex_like(harden)#harden = harden.drop(columns=['Unnamed: 7'])harden = harden.drop(columns=['Unnamed: 5']) harden = harden.drop(columns=['▲'])harden = harden.sort_values(by=['Date'])harden = harden.reset_index(drop=True)"
},
{
"code": null,
"e": 4769,
"s": 4725,
"text": "The final dataset looks somewhat like this:"
},
{
"code": null,
"e": 4925,
"s": 4769,
"text": "There are some columns in between that we can’t see, but for the most part, it’s all game statistics. Different stats for each game played by James Harden."
},
{
"code": null,
"e": 5068,
"s": 4925,
"text": "Since we want the data to be in chronological order, we set the date as our index value and change the datatype to a pandas datetime variable:"
},
{
"code": null,
"e": 5140,
"s": 5068,
"text": "harden.set_index(‘Date’)harden[‘Date’] = pd.to_datetime(harden[‘Date’])"
},
{
"code": null,
"e": 5382,
"s": 5140,
"text": "Next, we want to drop any values in our data (even though I doubt we have any). We will use the pandas dropna function and will drop a row in which all values are null. Once we do that, we’ll reset the index to make sure it’s still coherent."
},
{
"code": null,
"e": 5454,
"s": 5382,
"text": "harden = harden.dropna(how='all')harden = harden.reset_index(drop=True)"
},
{
"code": null,
"e": 5704,
"s": 5454,
"text": "Next, we have another important step in the data cleanup. During some games, James Harden was inactive, suspended, did not play or did not dress. Certain columns would have these values “suspended” rather than the numeric value that should be there."
},
{
"code": null,
"e": 5945,
"s": 5704,
"text": "Thus, we can remove all the rows (games) in which Harden did not play/dress or was inactive/suspended. However, that might reduce the size of my data by a lot. So instead, I will replace the values with the median of each respective column."
},
{
"code": null,
"e": 6550,
"s": 5945,
"text": "for i in harden: harden[i] = harden[i].replace('Inactive', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Did Not Play', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Did Not Dress', np.median(pd.to_numeric(harden[i], errors='coerce'))) for i in harden: harden[i] = harden[i].replace('Player Suspended', np.median(pd.to_numeric(harden[i], errors='coerce'))) harden = harden.dropna(how='any')harden = harden.reset_index(drop=True)harden.set_index('Date')"
},
{
"code": null,
"e": 6780,
"s": 6550,
"text": "A column containing numeric data should be explicitly assigned that datatype, in order to avoid errors in the future. Therefore, I will assign each column its correct data type. Using downcast='float' for float (decimal) columns."
},
{
"code": null,
"e": 8186,
"s": 6780,
"text": "harden['3P'] = pd.to_numeric(harden['3P'])harden['3PA'] = pd.to_numeric(harden['3PA'])harden['AST'] = pd.to_numeric(harden['AST'])harden['BLK'] = pd.to_numeric(harden['BLK'])harden['DRB'] = pd.to_numeric(harden['DRB'])harden['ORB'] = pd.to_numeric(harden['ORB'])harden['FG'] = pd.to_numeric(harden['FG'])harden['FGA'] = pd.to_numeric(harden['FGA'])harden['PTS'] = pd.to_numeric(harden['PTS'])harden['PF'] = pd.to_numeric(harden['PF'])harden['TOV'] = pd.to_numeric(harden['TOV'])harden['STL'] = pd.to_numeric(harden['STL'])harden['TRB'] = pd.to_numeric(harden['TRB'])harden['3P%'] = pd.to_numeric(harden['3P%'], downcast='float')harden['FG%'] = pd.to_numeric(harden['FG%'], downcast='float')harden['FT%'] = pd.to_numeric(harden['FT%'], downcast='float')harden['GmSc'] = pd.to_numeric(harden['GmSc'], downcast='float')harden['FTA'] = pd.to_numeric(harden['FTA'])harden['FT'] = pd.to_numeric(harden['FT'])print(harden.dtypes)Output: 3P int643P% float323PA int64AST int64BLK int64DRB int64Date datetime64[ns]FG int64FG% float32FGA int64FT int64FT% float32FTA int64GmSc float32ORB int64Opp objectPF int64PTS int64STL int64TOV int64TRB int64dtype: object"
},
{
"code": null,
"e": 8555,
"s": 8186,
"text": "Now to the best part. We will forecast any column in this dataset using Prophet. The output will give us an image (graph) of the forecast. In order to create the graph, we need to first fit the Prophet model to our dataset. We will separate the column we want, along with the date column. In this case, I’m predicting points, so I’ll take the ‘PTS’ and ‘Date’ columns."
},
{
"code": null,
"e": 8584,
"s": 8555,
"text": "df = harden[['PTS', 'Date']]"
},
{
"code": null,
"e": 8882,
"s": 8584,
"text": "These next steps are quite important, as we will be fitting the prophet model to our data. We want to rename our columns to ‘ds’ (date) and ‘y’ (target). We then define our Prophet model with any given interval_width. Then we fit our Prophet model to the dataset with the date and target variable."
},
{
"code": null,
"e": 8988,
"s": 8882,
"text": "jh = df.rename(columns={'Date': 'ds', 'PTS': 'y'})jh_model = Prophet(interval_width=0.95)jh_model.fit(jh)"
},
{
"code": null,
"e": 9239,
"s": 8988,
"text": "To forecast values, we use the make_future_dataframe function, specify the number of periods, frequency as ‘MS’, which is Multiplicative Seasonality.We then create our matplotlib figure for the forecast. The image below the code shows you the output."
},
{
"code": null,
"e": 9468,
"s": 9239,
"text": "jh_forecast = jh_model.make_future_dataframe(periods=36, freq='MS')jh_forecast = jh_model.predict(jh_forecast)plt.figure(figsize=(18, 6))jh_model.plot(jh_forecast, xlabel = 'Date', ylabel = 'PTS')plt.title('James Harden Points')"
},
{
"code": null,
"e": 9584,
"s": 9468,
"text": "Now, what if I wanted to compare James Harden’s forecast to Giannis Antetokounmpo, LeBron James, and Kawhi Leonard."
},
{
"code": null,
"e": 9794,
"s": 9584,
"text": "To do this, I’ll take all of the pre-processing and put it in a single function, so I can pre-process the data without repeating lines of code. Below, I’ve supplied a gist that contains the required functions."
},
{
"code": null,
"e": 9889,
"s": 9794,
"text": "Once you have the data processed, we can start merging all the frames and graph them as below."
},
{
"code": null,
"e": 12217,
"s": 9889,
"text": "harden = harden.rename(columns={'Date': 'ds', 'PTS': 'y'})jh_model = Prophet(interval_width=0.95)jh_model.fit(harden)lebron = lebron.rename(columns={'Date': 'ds', 'PTS': 'y'})lj_model = Prophet(interval_width=0.95)lj_model.fit(lebron)giannis = giannis.rename(columns={'Date': 'ds', 'PTS': 'y'})ga_model = Prophet(interval_width=0.95)ga_model.fit(giannis)kawhi = kawhi.rename(columns={'Date': 'ds', 'PTS': 'y'})kl_model = Prophet(interval_width=0.95)kl_model.fit(kawhi)jh_forecast = jh_model.make_future_dataframe(periods=36, freq='MS')jh_forecast = jh_model.predict(jh_forecast)lj_forecast = lj_model.make_future_dataframe(periods=36, freq='MS')lj_forecast = lj_model.predict(lj_forecast)ga_forecast = ga_model.make_future_dataframe(periods=36, freq='MS')ga_forecast = ga_model.predict(ga_forecast)kl_forecast = kl_model.make_future_dataframe(periods=36, freq='MS')kl_forecast = kl_model.predict(kl_forecast)hardens = ['harden_%s' % column for column in jh_forecast.columns]lebrons = ['lebron_%s' % column for column in lj_forecast.columns]kawhis = ['kawhi_%s' % column for column in kl_forecast.columns]gianniss = ['giannis_%s' % column for column in ga_forecast.columns]merge_jh_forecast = jh_forecast.copy()merge_lj_forecast = lj_forecast.copy()merge_kl_forecast = kl_forecast.copy()merge_ga_forecast = ga_forecast.copy()merge_jh_forecast.columns = hardensmerge_lj_forecast.columns = lebronsmerge_kl_forecast.columns = kawhismerge_ga_forecast.columns = giannissforecast = pd.merge(merge_jh_forecast, merge_lj_forecast, how = 'inner', left_on='harden_ds', right_on='lebron_ds')forecast = pd.merge(forecast, merge_kl_forecast, how = 'inner', left_on='lebron_ds', right_on='kawhi_ds')forecast = pd.merge(forecast, merge_ga_forecast, how = 'inner', left_on='kawhi_ds', right_on='giannis_ds')forecast = forecast.rename(columns={'harden_ds': 'Date'})forecast.head()plt.figure(figsize=(10, 7))plt.plot(forecast['Date'], forecast['harden_yhat'], 'b-')plt.plot(forecast['Date'], forecast['lebron_yhat'], 'r-')plt.plot(forecast['Date'], forecast['kawhi_yhat'], 'g-')plt.plot(forecast['Date'], forecast['giannis_yhat'], 'y-')plt.legend(['Harden', 'Lebron', 'Kawhi', 'Giannis'])plt.xlabel('Date')plt.ylabel('Points')plt.title('Harden vs LeBron vs Giannis vs Kawhi');plt.show()"
},
{
"code": null,
"e": 12257,
"s": 12217,
"text": "The final output should look like this:"
},
{
"code": null,
"e": 12571,
"s": 12257,
"text": "Looks like James Harden has everyone beat when it comes to points per game, although Giannis has some seasonal spikes (maybe he performs well on Fridays). For next time, I might write another tutorial, comparing more players with a lot more specificity. Let me know in the comments if you have any feedback/ideas."
}
] |
How to get file URI reference in Java?
|
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
In general, an URI (Uniform Resource Identifier) represents a resource. The URI class of Java represents this format You can get the URI format of a file by invoking the toURI() method.
Following Java example, prints the URI format of the file named samplefile.txt
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class GetURI {
public static void main(String args[]) throws IOException {
//Instantiating the File class
String filePath = "D:\\ExampleDirectory\\sampleFile.txt";
File file = new File(filePath);
//Getting the URI object
URI uri = file.toURI();
System.out.println(uri.toString());
}
}
file:/D:/ExampleDirectory/sampleFile.txt
|
[
{
"code": null,
"e": 1253,
"s": 1062,
"text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories."
},
{
"code": null,
"e": 1439,
"s": 1253,
"text": "In general, an URI (Uniform Resource Identifier) represents a resource. The URI class of Java represents this format You can get the URI format of a file by invoking the toURI() method."
},
{
"code": null,
"e": 1518,
"s": 1439,
"text": "Following Java example, prints the URI format of the file named samplefile.txt"
},
{
"code": null,
"e": 1922,
"s": 1518,
"text": "import java.io.File;\nimport java.io.IOException;\nimport java.net.URI;\npublic class GetURI {\n public static void main(String args[]) throws IOException {\n //Instantiating the File class\n String filePath = \"D:\\\\ExampleDirectory\\\\sampleFile.txt\";\n File file = new File(filePath);\n //Getting the URI object\n URI uri = file.toURI();\n System.out.println(uri.toString());\n }\n}"
},
{
"code": null,
"e": 1963,
"s": 1922,
"text": "file:/D:/ExampleDirectory/sampleFile.txt"
}
] |
Count the numbers divisible by ‘M’ in a given range in C++
|
We are given three numbers A,B and M. A and B define the range [A,B] of numbers.The goal is
to count numbers between A and B that are divisible by M.
We will start from i=A till first multiple of M. Increment count if i%M=0. Now increment i till i<=B
and increase count.
Let’s understand with examples.
A=11,B=20, M=5
Count of numbers divisible by M in given range: 2
15 and 20 are only numbers that are divisible by 5 and lie in range [11,20].
A=20, B=50, M=11
Count of numbers divisible by M in given range: 3
22,33,44 are only numbers that are divisible by 11 and lie in range [20,50].
We take A,B and M as integers.
Function divisiblebyM (int a, int b, int m) take A,B and M as parameters and return the
count of numbers between A and B that are divisible by M.
Take the initial count as 0.
Using for loop, start from i=A to i=B. Increment i by 1.
If i%m=0, increment count.
At the end, count as numbers between A and B that are divisible by m.
Return count as result.
Live Demo
// Program to count the numbers divisible by
// M in a given range
#include <bits/stdc++.h>
using namespace std;
int divisiblebyM(int a, int b, int m){
int count = 0;
// Running a loop from A to B and check
// if a number is divisible by M.
for (int i = a; i <= b;i++ ){
if (i % m == 0){
count++;
}
}
return count;
}
int main(){
// A and B define the range, M is the dividend
int A = 3, B = 15, M = 4;
cout<<"Numbers divisible by M in given range:"<<divisiblebyM(A, B, M) << endl;
return 0;
}
Numbers divisible by M in given range:3
|
[
{
"code": null,
"e": 1212,
"s": 1062,
"text": "We are given three numbers A,B and M. A and B define the range [A,B] of numbers.The goal is\nto count numbers between A and B that are divisible by M."
},
{
"code": null,
"e": 1333,
"s": 1212,
"text": "We will start from i=A till first multiple of M. Increment count if i%M=0. Now increment i till i<=B\nand increase count."
},
{
"code": null,
"e": 1365,
"s": 1333,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1380,
"s": 1365,
"text": "A=11,B=20, M=5"
},
{
"code": null,
"e": 1430,
"s": 1380,
"text": "Count of numbers divisible by M in given range: 2"
},
{
"code": null,
"e": 1507,
"s": 1430,
"text": "15 and 20 are only numbers that are divisible by 5 and lie in range [11,20]."
},
{
"code": null,
"e": 1524,
"s": 1507,
"text": "A=20, B=50, M=11"
},
{
"code": null,
"e": 1574,
"s": 1524,
"text": "Count of numbers divisible by M in given range: 3"
},
{
"code": null,
"e": 1651,
"s": 1574,
"text": "22,33,44 are only numbers that are divisible by 11 and lie in range [20,50]."
},
{
"code": null,
"e": 1682,
"s": 1651,
"text": "We take A,B and M as integers."
},
{
"code": null,
"e": 1828,
"s": 1682,
"text": "Function divisiblebyM (int a, int b, int m) take A,B and M as parameters and return the\ncount of numbers between A and B that are divisible by M."
},
{
"code": null,
"e": 1857,
"s": 1828,
"text": "Take the initial count as 0."
},
{
"code": null,
"e": 1914,
"s": 1857,
"text": "Using for loop, start from i=A to i=B. Increment i by 1."
},
{
"code": null,
"e": 1941,
"s": 1914,
"text": "If i%m=0, increment count."
},
{
"code": null,
"e": 2011,
"s": 1941,
"text": "At the end, count as numbers between A and B that are divisible by m."
},
{
"code": null,
"e": 2035,
"s": 2011,
"text": "Return count as result."
},
{
"code": null,
"e": 2046,
"s": 2035,
"text": " Live Demo"
},
{
"code": null,
"e": 2592,
"s": 2046,
"text": "// Program to count the numbers divisible by\n// M in a given range\n#include <bits/stdc++.h>\nusing namespace std;\nint divisiblebyM(int a, int b, int m){\n int count = 0;\n // Running a loop from A to B and check\n // if a number is divisible by M.\n for (int i = a; i <= b;i++ ){\n if (i % m == 0){\n count++;\n }\n }\n return count;\n}\nint main(){\n // A and B define the range, M is the dividend\n int A = 3, B = 15, M = 4;\n cout<<\"Numbers divisible by M in given range:\"<<divisiblebyM(A, B, M) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2632,
"s": 2592,
"text": "Numbers divisible by M in given range:3"
}
] |
Yii - Gii
|
Gii is the extension, that provides a web-based code generator for generating models, forms, modules, CRUD, and so forth.
By default, the following generators are available −
Model Generator − Generates an ActiveRecord class for the specified database table.
Model Generator − Generates an ActiveRecord class for the specified database table.
CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model.
CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model.
Controller Generator − Generates a new controller class with one or several controller actions and their corresponding views.
Controller Generator − Generates a new controller class with one or several controller actions and their corresponding views.
Form Generator − Generates a view script file that displays a form to collect input for the specified model class.
Form Generator − Generates a view script file that displays a form to collect input for the specified model class.
Module Generator − Generates the skeleton code needed by an Yii module.
Module Generator − Generates the skeleton code needed by an Yii module.
Extension Generator − GenerateS the files needed by a Yii extension.
Extension Generator − GenerateS the files needed by a Yii extension.
To open the gii generation tool, type http://localhost:8080/index.php?r=gii: in the address bar of the web browser.
Step 1 − Create a new database. Database can be prepared in the following two ways −
In the terminal run mysql -u root –p
In the terminal run mysql -u root –p
Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;
Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;
Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently.
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=helloworld',
'username' => 'vladimir',
'password' => '12345',
'charset' => 'utf8',
];
?>
Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root.
Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way.
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160106_163154_test_table extends Migration {
public function safeUp() {
$this->createTable("user", [
"id" => Schema::TYPE_PK,
"name" => Schema::TYPE_STRING,
"email" => Schema::TYPE_STRING,
]);
$this->batchInsert("user", ["name", "email"], [
["User1", "user1@gmail.com"],
["User2", "user2@gmail.com"],
["User3", "user3@gmail.com"],
["User4", "user4@gmail.com"],
["User5", "user5@gmail.com"],
["User6", "user6@gmail.com"],
["User7", "user7@gmail.com"],
["User8", "user8@gmail.com"],
["User9", "user9@gmail.com"],
["User10", "user10@gmail.com"],
["User11", "user11@gmail.com"],
]);
}
public function safeDown() {
$this->dropTable('user');
}
}
?>
The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users.
Step 5 − Inside the project root run ./yii migrate to apply the migration to the database.
Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button.
The MyUser model should appear in the models directory.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2955,
"s": 2833,
"text": "Gii is the extension, that provides a web-based code generator for generating models, forms, modules, CRUD, and so forth."
},
{
"code": null,
"e": 3008,
"s": 2955,
"text": "By default, the following generators are available −"
},
{
"code": null,
"e": 3092,
"s": 3008,
"text": "Model Generator − Generates an ActiveRecord class for the specified database table."
},
{
"code": null,
"e": 3176,
"s": 3092,
"text": "Model Generator − Generates an ActiveRecord class for the specified database table."
},
{
"code": null,
"e": 3313,
"s": 3176,
"text": "CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model."
},
{
"code": null,
"e": 3450,
"s": 3313,
"text": "CRUD Generator − Generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified model."
},
{
"code": null,
"e": 3576,
"s": 3450,
"text": "Controller Generator − Generates a new controller class with one or several controller actions and their corresponding views."
},
{
"code": null,
"e": 3702,
"s": 3576,
"text": "Controller Generator − Generates a new controller class with one or several controller actions and their corresponding views."
},
{
"code": null,
"e": 3817,
"s": 3702,
"text": "Form Generator − Generates a view script file that displays a form to collect input for the specified model class."
},
{
"code": null,
"e": 3932,
"s": 3817,
"text": "Form Generator − Generates a view script file that displays a form to collect input for the specified model class."
},
{
"code": null,
"e": 4004,
"s": 3932,
"text": "Module Generator − Generates the skeleton code needed by an Yii module."
},
{
"code": null,
"e": 4076,
"s": 4004,
"text": "Module Generator − Generates the skeleton code needed by an Yii module."
},
{
"code": null,
"e": 4145,
"s": 4076,
"text": "Extension Generator − GenerateS the files needed by a Yii extension."
},
{
"code": null,
"e": 4214,
"s": 4145,
"text": "Extension Generator − GenerateS the files needed by a Yii extension."
},
{
"code": null,
"e": 4330,
"s": 4214,
"text": "To open the gii generation tool, type http://localhost:8080/index.php?r=gii: in the address bar of the web browser."
},
{
"code": null,
"e": 4415,
"s": 4330,
"text": "Step 1 − Create a new database. Database can be prepared in the following two ways −"
},
{
"code": null,
"e": 4452,
"s": 4415,
"text": "In the terminal run mysql -u root –p"
},
{
"code": null,
"e": 4489,
"s": 4452,
"text": "In the terminal run mysql -u root –p"
},
{
"code": null,
"e": 4586,
"s": 4489,
"text": "Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;"
},
{
"code": null,
"e": 4683,
"s": 4586,
"text": "Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;"
},
{
"code": null,
"e": 4815,
"s": 4683,
"text": "Step 2 − Configure the database connection in the config/db.php file. The following configuration is for the system used currently."
},
{
"code": null,
"e": 5025,
"s": 4815,
"text": "<?php\n return [\n 'class' => 'yii\\db\\Connection',\n 'dsn' => 'mysql:host=localhost;dbname=helloworld',\n 'username' => 'vladimir',\n 'password' => '12345',\n 'charset' => 'utf8',\n ];\n?>"
},
{
"code": null,
"e": 5240,
"s": 5025,
"text": "Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root."
},
{
"code": null,
"e": 5330,
"s": 5240,
"text": "Step 4 − Modify the migration file (m160106_163154_test_table.php in this case) this way."
},
{
"code": null,
"e": 6276,
"s": 5330,
"text": "<?php\n use yii\\db\\Schema;\n use yii\\db\\Migration;\n class m160106_163154_test_table extends Migration {\n public function safeUp() {\n $this->createTable(\"user\", [\n \"id\" => Schema::TYPE_PK,\n \"name\" => Schema::TYPE_STRING,\n \"email\" => Schema::TYPE_STRING,\n ]);\n $this->batchInsert(\"user\", [\"name\", \"email\"], [\n [\"User1\", \"user1@gmail.com\"],\n [\"User2\", \"user2@gmail.com\"],\n [\"User3\", \"user3@gmail.com\"],\n [\"User4\", \"user4@gmail.com\"],\n [\"User5\", \"user5@gmail.com\"],\n [\"User6\", \"user6@gmail.com\"],\n [\"User7\", \"user7@gmail.com\"],\n [\"User8\", \"user8@gmail.com\"],\n [\"User9\", \"user9@gmail.com\"],\n [\"User10\", \"user10@gmail.com\"],\n [\"User11\", \"user11@gmail.com\"],\n ]);\n }\n public function safeDown() {\n $this->dropTable('user');\n }\n }\n?>"
},
{
"code": null,
"e": 6388,
"s": 6276,
"text": "The above migration creates a user table with these fields: id, name, and email. It also adds a few demo users."
},
{
"code": null,
"e": 6479,
"s": 6388,
"text": "Step 5 − Inside the project root run ./yii migrate to apply the migration to the database."
},
{
"code": null,
"e": 6874,
"s": 6479,
"text": "Step 6 − Now, we need to create a model for our user table. For the sake of simplicity, we are going to use the Gii code generation tool. Open up this url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button."
},
{
"code": null,
"e": 6930,
"s": 6874,
"text": "The MyUser model should appear in the models directory."
},
{
"code": null,
"e": 6937,
"s": 6930,
"text": " Print"
},
{
"code": null,
"e": 6948,
"s": 6937,
"text": " Add Notes"
}
] |
Bootstrap 4 .card-header-tabs class
|
Use the card-header-tabs in Bootstrap to style navigation links in card header −
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs">
<li class="nav-item">
<a class="nav-link active" href="#">Drupal Commerce</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">WooCommerce</a>
</li>
</ul>
</div>
The header tabs are set on Unordered List using nav-tabs and card-header-tabs class as shown above −
<ul class="nav nav-tabs card-header-tabs">
Let us see an example to learn how to create Bootstrap 4 card header −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>E-commerce Technologies</h2>
<div class="card">
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs">
<li class="nav-item">
<a class="nav-link active" href="#">Drupal Commerce</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">WooCommerce</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Prestashop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Shopify</a>
</li>
</ul>
</div>
<div class="card-body">
<h5 class="card-title">Add title here</h5>
<p class="card-text">Add content here</p>
</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Use the card-header-tabs in Bootstrap to style navigation links in card header −"
},
{
"code": null,
"e": 1414,
"s": 1143,
"text": "<div class=\"card-header\">\n <ul class=\"nav nav-tabs card-header-tabs\">\n <li class=\"nav-item\">\n <a class=\"nav-link active\" href=\"#\">Drupal Commerce</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"#\">WooCommerce</a>\n </li>\n </ul>\n</div>"
},
{
"code": null,
"e": 1515,
"s": 1414,
"text": "The header tabs are set on Unordered List using nav-tabs and card-header-tabs class as shown above −"
},
{
"code": null,
"e": 1558,
"s": 1515,
"text": "<ul class=\"nav nav-tabs card-header-tabs\">"
},
{
"code": null,
"e": 1630,
"s": 1558,
"text": "Let us see an example to learn how to create Bootstrap 4 card header − "
},
{
"code": null,
"e": 1640,
"s": 1630,
"text": "Live Demo"
},
{
"code": null,
"e": 2922,
"s": 1640,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\"> \n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\">\n <h2>E-commerce Technologies</h2>\n <div class=\"card\">\n <div class=\"card-header\">\n <ul class=\"nav nav-tabs card-header-tabs\">\n <li class=\"nav-item\">\n <a class=\"nav-link active\" href=\"#\">Drupal Commerce</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"#\">WooCommerce</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"#\">Prestashop</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"#\">Shopify</a>\n </li>\n </ul>\n </div>\n <div class=\"card-body\">\n <h5 class=\"card-title\">Add title here</h5>\n <p class=\"card-text\">Add content here</p>\n </div>\n </div>\n</div>\n</body>\n</html>"
}
] |
TreeSet comparator() Method in Java with Examples
|
01 Nov, 2021
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
The comparator() method been present inside java.util.TreeSet shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns a Null value if the set follows the natural ordering pattern of the elements.
Syntax:
comp_set = (TreeSet)tree_set.comparator()
Parameters: The method does not take any parameters.
Return Value: The comparator set is used to order the elements of the set in a specific order. It returns a Null value if the set follows the default or natural ordering pattern.
Here we will be proposing two examples below one earlier we will be using the natural ordering of the elements later using a specific comparator to understand it better.
Example 1: Using the natural ordering of the elements
Java
// Java Program to illustrate the use of comparator() method// While using the natural ordering of the elements // Importing utility classesimport java.util.*; // Main class// TreeSet Demo classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeSet of integer type TreeSet<Integer> tree_set = new TreeSet<Integer>(); // Adding elements to the set // using add() method tree_set.add(20); tree_set.add(24); tree_set.add(30); tree_set.add(35); tree_set.add(45); tree_set.add(50); // Printing elements inside TreeSet object System.out.println("Tree Set values are: " + tree_set); // Creating a comparator Comparator comp = tree_set.comparator(); // Print and display the comparator values System.out.println("Since the Comparator value is: " + comp); // Display message only System.out.println("it follows natural ordering"); }}
Tree Set values are: [20, 24, 30, 35, 45, 50]
Since the Comparator value is: null
it follows natural ordering
Example 2: Using a specific comparator
Java
// Java code to illustrate the use of comparator()// While using a specific comparator // Importing Comparator and TreeSet classes// from java.util packageimport java.util.Comparator;import java.util.TreeSet; // Class 1// Helper classclass Helper implements Comparator<String> { // Method // To compare two strings public int compare(String str1, String str2) { String first_Str; String second_Str; first_Str = str1; second_Str = str2; // using compareTo() to ensure return second_Str.compareTo(first_Str); }} // Main class// TreeSetDemo classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeSet of string type TreeSet<String> tree_set = new TreeSet<String>(); // Adding elements to our TreeSet object // using add() method tree_set.add("G"); tree_set.add("E"); tree_set.add("E"); tree_set.add("K"); tree_set.add("S"); tree_set.add("4"); // Printing elements in set before using comparator System.out.println("Set before using the comparator: " + tree_set); // Again creating an empty TreeSet of string type // with reference to Helper class TreeSet<String> tree_set1 = new TreeSet<String>(new Helper()); // Adding elements to our TreeSet object // using add() method tree_set1.add("G"); tree_set1.add("E"); tree_set1.add("E"); tree_set1.add("K"); tree_set1.add("S"); tree_set1.add("4"); // Printing elements in set before using comparator System.out.println("The elements sorted in descending order:" + tree_set1); }}
Set before using the comparator: [4, E, G, K, S]
The elements sorted in descending order:[S, K, G, E, 4]
sooda367
ayush123ngp
anikakapoor
solankimayank
Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
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": 365,
"s": 28,
"text": "TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface."
},
{
"code": null,
"e": 646,
"s": 365,
"text": "The comparator() method been present inside java.util.TreeSet shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns a Null value if the set follows the natural ordering pattern of the elements."
},
{
"code": null,
"e": 655,
"s": 646,
"text": "Syntax: "
},
{
"code": null,
"e": 697,
"s": 655,
"text": "comp_set = (TreeSet)tree_set.comparator()"
},
{
"code": null,
"e": 750,
"s": 697,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 930,
"s": 750,
"text": "Return Value: The comparator set is used to order the elements of the set in a specific order. It returns a Null value if the set follows the default or natural ordering pattern. "
},
{
"code": null,
"e": 1100,
"s": 930,
"text": "Here we will be proposing two examples below one earlier we will be using the natural ordering of the elements later using a specific comparator to understand it better."
},
{
"code": null,
"e": 1154,
"s": 1100,
"text": "Example 1: Using the natural ordering of the elements"
},
{
"code": null,
"e": 1159,
"s": 1154,
"text": "Java"
},
{
"code": "// Java Program to illustrate the use of comparator() method// While using the natural ordering of the elements // Importing utility classesimport java.util.*; // Main class// TreeSet Demo classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeSet of integer type TreeSet<Integer> tree_set = new TreeSet<Integer>(); // Adding elements to the set // using add() method tree_set.add(20); tree_set.add(24); tree_set.add(30); tree_set.add(35); tree_set.add(45); tree_set.add(50); // Printing elements inside TreeSet object System.out.println(\"Tree Set values are: \" + tree_set); // Creating a comparator Comparator comp = tree_set.comparator(); // Print and display the comparator values System.out.println(\"Since the Comparator value is: \" + comp); // Display message only System.out.println(\"it follows natural ordering\"); }}",
"e": 2253,
"s": 1159,
"text": null
},
{
"code": null,
"e": 2363,
"s": 2253,
"text": "Tree Set values are: [20, 24, 30, 35, 45, 50]\nSince the Comparator value is: null\nit follows natural ordering"
},
{
"code": null,
"e": 2404,
"s": 2365,
"text": "Example 2: Using a specific comparator"
},
{
"code": null,
"e": 2409,
"s": 2404,
"text": "Java"
},
{
"code": "// Java code to illustrate the use of comparator()// While using a specific comparator // Importing Comparator and TreeSet classes// from java.util packageimport java.util.Comparator;import java.util.TreeSet; // Class 1// Helper classclass Helper implements Comparator<String> { // Method // To compare two strings public int compare(String str1, String str2) { String first_Str; String second_Str; first_Str = str1; second_Str = str2; // using compareTo() to ensure return second_Str.compareTo(first_Str); }} // Main class// TreeSetDemo classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeSet of string type TreeSet<String> tree_set = new TreeSet<String>(); // Adding elements to our TreeSet object // using add() method tree_set.add(\"G\"); tree_set.add(\"E\"); tree_set.add(\"E\"); tree_set.add(\"K\"); tree_set.add(\"S\"); tree_set.add(\"4\"); // Printing elements in set before using comparator System.out.println(\"Set before using the comparator: \" + tree_set); // Again creating an empty TreeSet of string type // with reference to Helper class TreeSet<String> tree_set1 = new TreeSet<String>(new Helper()); // Adding elements to our TreeSet object // using add() method tree_set1.add(\"G\"); tree_set1.add(\"E\"); tree_set1.add(\"E\"); tree_set1.add(\"K\"); tree_set1.add(\"S\"); tree_set1.add(\"4\"); // Printing elements in set before using comparator System.out.println(\"The elements sorted in descending order:\" + tree_set1); }}",
"e": 4155,
"s": 2409,
"text": null
},
{
"code": null,
"e": 4260,
"s": 4155,
"text": "Set before using the comparator: [4, E, G, K, S]\nThe elements sorted in descending order:[S, K, G, E, 4]"
},
{
"code": null,
"e": 4269,
"s": 4260,
"text": "sooda367"
},
{
"code": null,
"e": 4281,
"s": 4269,
"text": "ayush123ngp"
},
{
"code": null,
"e": 4293,
"s": 4281,
"text": "anikakapoor"
},
{
"code": null,
"e": 4307,
"s": 4293,
"text": "solankimayank"
},
{
"code": null,
"e": 4327,
"s": 4307,
"text": "Java - util package"
},
{
"code": null,
"e": 4344,
"s": 4327,
"text": "Java-Collections"
},
{
"code": null,
"e": 4359,
"s": 4344,
"text": "Java-Functions"
},
{
"code": null,
"e": 4372,
"s": 4359,
"text": "java-treeset"
},
{
"code": null,
"e": 4377,
"s": 4372,
"text": "Java"
},
{
"code": null,
"e": 4382,
"s": 4377,
"text": "Java"
},
{
"code": null,
"e": 4399,
"s": 4382,
"text": "Java-Collections"
}
] |
Python – PyTorch abs() method
|
26 May, 2020
PyTorch torch.abs() method computes the element-wise absolute value of the given input tensor.
Syntax: torch.abs(inp, out=None) ? Tensor
Arguments
inp: This is input tensor.
out: This is optional parameter and is the output tensor.
Return: It returns a Tensor having absolute value of input inp.
# Importing the PyTorch library import torch # A constant tensor of size 1 a = torch.FloatTensor([-15]) print(a) # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b)
Output:
-15
[torch.FloatTensor of size 1]
15
[torch.FloatTensor of size 1]
Example 2:
# Importing the PyTorch library import torch # A constant tensor of size n a = torch.FloatTensor([15, -5, 3, -2]) print(a) # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b)
Output:
15
-5
3
-2
[torch.FloatTensor of size 4]
15
5
3
2
[torch.FloatTensor of size 4]
Python-PyTorch
Python
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "PyTorch torch.abs() method computes the element-wise absolute value of the given input tensor."
},
{
"code": null,
"e": 165,
"s": 123,
"text": "Syntax: torch.abs(inp, out=None) ? Tensor"
},
{
"code": null,
"e": 175,
"s": 165,
"text": "Arguments"
},
{
"code": null,
"e": 202,
"s": 175,
"text": "inp: This is input tensor."
},
{
"code": null,
"e": 260,
"s": 202,
"text": "out: This is optional parameter and is the output tensor."
},
{
"code": null,
"e": 324,
"s": 260,
"text": "Return: It returns a Tensor having absolute value of input inp."
},
{
"code": "# Importing the PyTorch library import torch # A constant tensor of size 1 a = torch.FloatTensor([-15]) print(a) # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b) ",
"e": 532,
"s": 324,
"text": null
},
{
"code": null,
"e": 540,
"s": 532,
"text": "Output:"
},
{
"code": null,
"e": 609,
"s": 540,
"text": "-15\n[torch.FloatTensor of size 1]\n 15\n[torch.FloatTensor of size 1]\n"
},
{
"code": null,
"e": 620,
"s": 609,
"text": "Example 2:"
},
{
"code": "# Importing the PyTorch library import torch # A constant tensor of size n a = torch.FloatTensor([15, -5, 3, -2]) print(a) # Applying the abs function and # storing the result in 'b' b = torch.abs(a) print(b) ",
"e": 838,
"s": 620,
"text": null
},
{
"code": null,
"e": 846,
"s": 838,
"text": "Output:"
},
{
"code": null,
"e": 939,
"s": 846,
"text": " 15\n -5\n 3\n -2\n[torch.FloatTensor of size 4]\n 15\n 5\n 3\n 2\n[torch.FloatTensor of size 4]\n"
},
{
"code": null,
"e": 954,
"s": 939,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 961,
"s": 954,
"text": "Python"
},
{
"code": null,
"e": 1059,
"s": 961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1091,
"s": 1059,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1118,
"s": 1091,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1139,
"s": 1118,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1162,
"s": 1139,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1218,
"s": 1162,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1249,
"s": 1218,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1291,
"s": 1249,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1333,
"s": 1291,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1372,
"s": 1333,
"text": "Python | Get unique values from a list"
}
] |
Nested list in C++ STL
|
18 Sep, 2018
list in STL is used to represent a linked list in C++. How to create a nested list. We are given n lists, we need to create a list of n lists.
Examples:
Input : Number of lists: 2
1st list: {1 2}
2nd list: {3 4 5 6
Output :
[
[ 1 2 ]
[ 3 4 5 6 ]
]
Input : Number of lists: 3
1st list : {0 1}
2nd list : {1 2 3}
3rd list : {2 3 4 5}
Output :
[
[ 0 1 ]
[ 1 2 3 ]
[ 2 3 4 5 ]
]
// c++ program for nested list #include <iostream>#include <iterator>#include <list>using namespace std; void printNestedList(list<list<int> > nested_list){ cout << "[\n"; // nested_list`s iterator(same type as nested_list) // to iterate the nested_list list<list<int> >::iterator nested_list_itr; // Print the nested_list for (nested_list_itr = nested_list.begin(); nested_list_itr != nested_list.end(); ++nested_list_itr) { cout << " ["; // normal_list`s iterator(same type as temp_list) // to iterate the normal_list list<int>::iterator single_list_itr; // pointer of each list one by one in nested list // as loop goes on list<int>& single_list_pointer = *nested_list_itr; for (single_list_itr = single_list_pointer.begin(); single_list_itr != single_list_pointer.end(); single_list_itr++) { cout << " " << *single_list_itr << " "; } cout << "]\n"; } cout << "]";} // Driver codeint main(){ // instead integer type can have any data type list<list<int> > nested_list; list<int> single_list; int n, m, num; // number of lists in nested list n = 3; for (int i = 0; i < n; i++) { // number of elements in list m = i + 2; for (int j = 0; j < m; j++) { num = i + j; single_list.push_back(num); } nested_list.push_back(single_list); // delete all elements from single_list single_list.erase(single_list.begin(), single_list.end()); } printNestedList(nested_list); return 0;}
[
[ 0 1 ]
[ 1 2 3 ]
[ 2 3 4 5 ]
]
cpp-list
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Sep, 2018"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "list in STL is used to represent a linked list in C++. How to create a nested list. We are given n lists, we need to create a list of n lists."
},
{
"code": null,
"e": 181,
"s": 171,
"text": "Examples:"
},
{
"code": null,
"e": 429,
"s": 181,
"text": "Input : Number of lists: 2\n1st list: {1 2}\n2nd list: {3 4 5 6\nOutput : \n[\n [ 1 2 ]\n [ 3 4 5 6 ]\n]\n\nInput : Number of lists: 3\n1st list : {0 1} \n2nd list : {1 2 3}\n3rd list : {2 3 4 5}\nOutput :\n[\n [ 0 1 ]\n [ 1 2 3 ]\n [ 2 3 4 5 ]\n]\n"
},
{
"code": "// c++ program for nested list #include <iostream>#include <iterator>#include <list>using namespace std; void printNestedList(list<list<int> > nested_list){ cout << \"[\\n\"; // nested_list`s iterator(same type as nested_list) // to iterate the nested_list list<list<int> >::iterator nested_list_itr; // Print the nested_list for (nested_list_itr = nested_list.begin(); nested_list_itr != nested_list.end(); ++nested_list_itr) { cout << \" [\"; // normal_list`s iterator(same type as temp_list) // to iterate the normal_list list<int>::iterator single_list_itr; // pointer of each list one by one in nested list // as loop goes on list<int>& single_list_pointer = *nested_list_itr; for (single_list_itr = single_list_pointer.begin(); single_list_itr != single_list_pointer.end(); single_list_itr++) { cout << \" \" << *single_list_itr << \" \"; } cout << \"]\\n\"; } cout << \"]\";} // Driver codeint main(){ // instead integer type can have any data type list<list<int> > nested_list; list<int> single_list; int n, m, num; // number of lists in nested list n = 3; for (int i = 0; i < n; i++) { // number of elements in list m = i + 2; for (int j = 0; j < m; j++) { num = i + j; single_list.push_back(num); } nested_list.push_back(single_list); // delete all elements from single_list single_list.erase(single_list.begin(), single_list.end()); } printNestedList(nested_list); return 0;}",
"e": 2103,
"s": 429,
"text": null
},
{
"code": null,
"e": 2150,
"s": 2103,
"text": "[\n [ 0 1 ]\n [ 1 2 3 ]\n [ 2 3 4 5 ]\n]\n"
},
{
"code": null,
"e": 2159,
"s": 2150,
"text": "cpp-list"
},
{
"code": null,
"e": 2163,
"s": 2159,
"text": "STL"
},
{
"code": null,
"e": 2167,
"s": 2163,
"text": "C++"
},
{
"code": null,
"e": 2180,
"s": 2167,
"text": "C++ Programs"
},
{
"code": null,
"e": 2184,
"s": 2180,
"text": "STL"
},
{
"code": null,
"e": 2188,
"s": 2184,
"text": "CPP"
},
{
"code": null,
"e": 2286,
"s": 2188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2340,
"s": 2286,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2383,
"s": 2340,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2417,
"s": 2383,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2442,
"s": 2417,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2459,
"s": 2442,
"text": "Substring in C++"
},
{
"code": null,
"e": 2494,
"s": 2459,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2528,
"s": 2494,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2572,
"s": 2528,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2631,
"s": 2572,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Generate all Combinations of xCm in R Programming – combn() Function
|
08 Jun, 2020
combn() function in R Language is used to generate all combinations of the elements of x taken m at a time.
Syntax: combn(x, m)
Parameters:x: total number of elements takenr: number of elements taken at a time out of “x” elements
Example 1:
# R program to illustrate# combn function # Calling the combn() functioncombn(5, 3)combn(6, 5)combn(2, 2)
Output:
[, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]
[1, ] 1 1 1 1 1 1 2 2 2 3
[2, ] 2 2 2 3 3 4 3 3 4 4
[3, ] 3 4 5 4 5 5 4 5 5 5
[, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
[1, ] 1 1 1 1 1 2
[2, ] 2 2 2 2 3 3
[3, ] 3 3 3 4 4 4
[4, ] 4 4 5 5 5 5
[5, ] 5 6 6 6 6 6
[, 1]
[1, ] 1
[2, ] 2
Example 2:
# R program to illustrate# combn function # Calling the combn() functioncombn(LETTERS[1: 4], 2)combn(LETTERS[2: 6], 3)
Output:
[, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
[1, ] "A" "A" "A" "B" "B" "C"
[2, ] "B" "C" "D" "C" "D" "D"
[, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]
[1, ] "B" "B" "B" "B" "B" "B" "C" "C" "C" "D"
[2, ] "C" "C" "C" "D" "D" "E" "D" "D" "E" "E"
[3, ] "D" "E" "F" "E" "F" "F" "E" "F" "F" "F"
R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "combn() function in R Language is used to generate all combinations of the elements of x taken m at a time."
},
{
"code": null,
"e": 156,
"s": 136,
"text": "Syntax: combn(x, m)"
},
{
"code": null,
"e": 258,
"s": 156,
"text": "Parameters:x: total number of elements takenr: number of elements taken at a time out of “x” elements"
},
{
"code": null,
"e": 269,
"s": 258,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# combn function # Calling the combn() functioncombn(5, 3)combn(6, 5)combn(2, 2)",
"e": 376,
"s": 269,
"text": null
},
{
"code": null,
"e": 384,
"s": 376,
"text": "Output:"
},
{
"code": null,
"e": 878,
"s": 384,
"text": " [, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]\n[1, ] 1 1 1 1 1 1 2 2 2 3\n[2, ] 2 2 2 3 3 4 3 3 4 4\n[3, ] 3 4 5 4 5 5 4 5 5 5\n\n [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]\n[1, ] 1 1 1 1 1 2\n[2, ] 2 2 2 2 3 3\n[3, ] 3 3 3 4 4 4\n[4, ] 4 4 5 5 5 5\n[5, ] 5 6 6 6 6 6\n\n [, 1]\n[1, ] 1\n[2, ] 2\n"
},
{
"code": null,
"e": 889,
"s": 878,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# combn function # Calling the combn() functioncombn(LETTERS[1: 4], 2)combn(LETTERS[2: 6], 3)",
"e": 1009,
"s": 889,
"text": null
},
{
"code": null,
"e": 1017,
"s": 1009,
"text": "Output:"
},
{
"code": null,
"e": 1369,
"s": 1017,
"text": " [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]\n[1, ] \"A\" \"A\" \"A\" \"B\" \"B\" \"C\" \n[2, ] \"B\" \"C\" \"D\" \"C\" \"D\" \"D\" \n\n [, 1] [, 2] [, 3] [, 4] [, 5] [, 6] [, 7] [, 8] [, 9] [, 10]\n[1, ] \"B\" \"B\" \"B\" \"B\" \"B\" \"B\" \"C\" \"C\" \"C\" \"D\" \n[2, ] \"C\" \"C\" \"C\" \"D\" \"D\" \"E\" \"D\" \"D\" \"E\" \"E\" \n[3, ] \"D\" \"E\" \"F\" \"E\" \"F\" \"F\" \"E\" \"F\" \"F\" \"F\" \n"
},
{
"code": null,
"e": 1385,
"s": 1369,
"text": "R Math-Function"
},
{
"code": null,
"e": 1396,
"s": 1385,
"text": "R Language"
},
{
"code": null,
"e": 1494,
"s": 1396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1546,
"s": 1494,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 1604,
"s": 1546,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 1656,
"s": 1604,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1714,
"s": 1656,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1746,
"s": 1714,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 1781,
"s": 1746,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1825,
"s": 1781,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 1857,
"s": 1825,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 1895,
"s": 1857,
"text": "How to Change Axis Scales in R Plots?"
}
] |
How to Create a Coin Flipping App using ReactJS?
|
07 Jul, 2021
Basically, we want to build an app to toss or flip the coin. each time coin is flipped randomly a side of a coin is shown from head and tail and also we want to keep track of how many times coins are flipped and how many times heads and tails appear from those.
We create three components ‘App’ and ‘FlipCoin’ and ‘Coin’. The app component renders a single FlipCoin component only. There is no actual logic put inside the App component. FlipCoin component contains all the behind the logic. It has a default prop coin that is an array that contains two images head and tail (sides of a coin). It is a stateful component and has three states’ current faces, the total number of flips, and the number of heads. A click event handler is set to the button ‘flip’. The handler function basically chooses face head or tail randomly based on a randomly generated value and updates the current face state from the chosen face each time handler runs. The handler function also keeps track of how many times the flip button is clicked and how many times the head face generated randomly and updates its value to the respective state. The last Coin component is responsible for showing the correct coin face according to the randomly chosen side from the handler function in the FlipCoin component. FlipCoin uses a props system to communicate with the Coin component.
Example: In this example, we will make a few changes on App.js, to import a component. In that component, we will include two sides of a coin of an image. And flip that as a single image.
Filename- index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
Filename- App.js: App component renders single FlipCoin component only
Javascript
import React from 'react';import FlipCoin from './FlipCoin' const App=()=> { return ( <div className="App"> <FlipCoin /> </div> );} export default App;
Filename- FlipCoin.js: It contains all the behind logic. It is a stateful component. The states are currFace, totalFlips, and heads. It contains two sides of a coin as a default prop and updates the currFace state according to a random number that generates each time the component re-render. It is responsible for Setting event handler, updating all the states according to the user interaction render Coin component.
Javascript
import React,{ Component } from 'react'import Coin from './Coin' class FlipCoin extends Component{ static defaultProps = { coins : [ // Sides of the coin {side:'head', imgSrc:'https://media.geeksforgeeks.org/wp-content/uploads/20200916123059/SHalfDollarObverse2016head-300x300.jpg'}, {side:'tail', imgSrc:'https://media.geeksforgeeks.org/wp-content/uploads/20200916123125/tails-200x200.jpg'} ] } constructor(props){ super(props) // Responsible to render current updated coin face this.state = { // Track total number of flips currFace : null, totalFlips:0, heads: 0 } // Binding context of this keyword this.handleClick = this.handleClick.bind(this) } // Function takes array of different faces of a coin // and return a random chosen single face choice(arr){ const randomIdx = Math.floor(Math.random() * arr.length) return arr[randomIdx] } // Function responsible to update the states // according to users interactions flipCoin(){ const newFace = this.choice(this.props.coins) this.setState(curState => { const heads = curState.heads + (newFace.side === 'head' ? 1 : 0) return { currFace:newFace, totalFlips:curState.totalFlips + 1, heads:heads } }) } handleClick(){ this.flipCoin() } render(){ const {currFace, totalFlips, heads} = this.state return( <div> <h2>Let's flip a coin</h2> {/* If current face exist then show current face */} {currFace && <Coin info={currFace} />} {/* Button to flip the coin */} <button onClick={this.handleClick}>Flip Me!</button> <p> Out of {totalFlips} flips, there have been {heads} heads and {totalFlips - heads} tails </p> </div> ) }} export default FlipCoin
Filename- Coin.js: Responsible to show a side of a coin according to the currFace state of FlipCoin component. FlipCoin component communicates with the Coin component through the props system
Javascript
import React,{ Component } from 'react' class Coin extends Component{ render(){ return( <div class='Coin'> <img style={{ width:'200px', height:'200px' }} src={this.props.info.imgSrc} /> </div> ) }} export default Coin
Output :
shubhamyadav4
varshagumber28
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "Basically, we want to build an app to toss or flip the coin. each time coin is flipped randomly a side of a coin is shown from head and tail and also we want to keep track of how many times coins are flipped and how many times heads and tails appear from those."
},
{
"code": null,
"e": 1386,
"s": 290,
"text": "We create three components ‘App’ and ‘FlipCoin’ and ‘Coin’. The app component renders a single FlipCoin component only. There is no actual logic put inside the App component. FlipCoin component contains all the behind the logic. It has a default prop coin that is an array that contains two images head and tail (sides of a coin). It is a stateful component and has three states’ current faces, the total number of flips, and the number of heads. A click event handler is set to the button ‘flip’. The handler function basically chooses face head or tail randomly based on a randomly generated value and updates the current face state from the chosen face each time handler runs. The handler function also keeps track of how many times the flip button is clicked and how many times the head face generated randomly and updates its value to the respective state. The last Coin component is responsible for showing the correct coin face according to the randomly chosen side from the handler function in the FlipCoin component. FlipCoin uses a props system to communicate with the Coin component. "
},
{
"code": null,
"e": 1575,
"s": 1386,
"text": "Example: In this example, we will make a few changes on App.js, to import a component. In that component, we will include two sides of a coin of an image. And flip that as a single image."
},
{
"code": null,
"e": 1595,
"s": 1575,
"text": "Filename- index.js:"
},
{
"code": null,
"e": 1606,
"s": 1595,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 1745,
"s": 1606,
"text": null
},
{
"code": null,
"e": 1817,
"s": 1745,
"text": "Filename- App.js: App component renders single FlipCoin component only "
},
{
"code": null,
"e": 1828,
"s": 1817,
"text": "Javascript"
},
{
"code": "import React from 'react';import FlipCoin from './FlipCoin' const App=()=> { return ( <div className=\"App\"> <FlipCoin /> </div> );} export default App;",
"e": 1993,
"s": 1828,
"text": null
},
{
"code": null,
"e": 2412,
"s": 1993,
"text": "Filename- FlipCoin.js: It contains all the behind logic. It is a stateful component. The states are currFace, totalFlips, and heads. It contains two sides of a coin as a default prop and updates the currFace state according to a random number that generates each time the component re-render. It is responsible for Setting event handler, updating all the states according to the user interaction render Coin component."
},
{
"code": null,
"e": 2423,
"s": 2412,
"text": "Javascript"
},
{
"code": "import React,{ Component } from 'react'import Coin from './Coin' class FlipCoin extends Component{ static defaultProps = { coins : [ // Sides of the coin {side:'head', imgSrc:'https://media.geeksforgeeks.org/wp-content/uploads/20200916123059/SHalfDollarObverse2016head-300x300.jpg'}, {side:'tail', imgSrc:'https://media.geeksforgeeks.org/wp-content/uploads/20200916123125/tails-200x200.jpg'} ] } constructor(props){ super(props) // Responsible to render current updated coin face this.state = { // Track total number of flips currFace : null, totalFlips:0, heads: 0 } // Binding context of this keyword this.handleClick = this.handleClick.bind(this) } // Function takes array of different faces of a coin // and return a random chosen single face choice(arr){ const randomIdx = Math.floor(Math.random() * arr.length) return arr[randomIdx] } // Function responsible to update the states // according to users interactions flipCoin(){ const newFace = this.choice(this.props.coins) this.setState(curState => { const heads = curState.heads + (newFace.side === 'head' ? 1 : 0) return { currFace:newFace, totalFlips:curState.totalFlips + 1, heads:heads } }) } handleClick(){ this.flipCoin() } render(){ const {currFace, totalFlips, heads} = this.state return( <div> <h2>Let's flip a coin</h2> {/* If current face exist then show current face */} {currFace && <Coin info={currFace} />} {/* Button to flip the coin */} <button onClick={this.handleClick}>Flip Me!</button> <p> Out of {totalFlips} flips, there have been {heads} heads and {totalFlips - heads} tails </p> </div> ) }} export default FlipCoin",
"e": 4303,
"s": 2423,
"text": null
},
{
"code": null,
"e": 4496,
"s": 4303,
"text": " Filename- Coin.js: Responsible to show a side of a coin according to the currFace state of FlipCoin component. FlipCoin component communicates with the Coin component through the props system"
},
{
"code": null,
"e": 4507,
"s": 4496,
"text": "Javascript"
},
{
"code": "import React,{ Component } from 'react' class Coin extends Component{ render(){ return( <div class='Coin'> <img style={{ width:'200px', height:'200px' }} src={this.props.info.imgSrc} /> </div> ) }} export default Coin",
"e": 4775,
"s": 4507,
"text": null
},
{
"code": null,
"e": 4786,
"s": 4775,
"text": " Output :"
},
{
"code": null,
"e": 4800,
"s": 4786,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 4815,
"s": 4800,
"text": "varshagumber28"
},
{
"code": null,
"e": 4824,
"s": 4815,
"text": "react-js"
},
{
"code": null,
"e": 4841,
"s": 4824,
"text": "Web Technologies"
},
{
"code": null,
"e": 4939,
"s": 4841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4972,
"s": 4939,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5034,
"s": 4972,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5095,
"s": 5034,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5145,
"s": 5095,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5188,
"s": 5145,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5228,
"s": 5188,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5252,
"s": 5228,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5285,
"s": 5252,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 5345,
"s": 5285,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Why Does C Treat Array Parameters as Pointers?
|
25 Nov, 2021
In C, array parameters are treated as pointers mainly to,
To increase the efficiency of code
To save time
It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array.
The following two definitions of fun() look different, but to the compiler, they mean exactly the same thing.
void fun(int arr[]) {
// body
}
// This is valid
void fun(int *arr) {
// body
}
// This is valid too
It’s preferable to use whichever syntax is more accurate for readability.
Note: If the pointer coming in really is the base address of a whole array, then we should use [ ].
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Example: In this example, the array parameters are being used as pointers.
C
// C Program to demonstrate that C treats array parameters// as pointers#include <stdio.h> void findSum1(int arr[]){ int sum = 0; for (int i = 0; i < 5; i++) sum = sum + arr[i]; printf("The sum of the array is: %d\n", sum);} void findSum2(int* arr){ int sum = 0; for (int i = 0; i < 5; i++) sum = sum + arr[i]; printf("\nThe sum of the array is: %d \n", sum);} // Driver codeint main(){ int arr[5] = { 1, 2, 3, 4, 5 }; findSum1(arr); findSum2(arr); return 0;}
The sum of the array is: 15
The sum of the array is: 15
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
C-Pointers
pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction
Memory Layout of C Programs
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "In C, array parameters are treated as pointers mainly to,"
},
{
"code": null,
"e": 145,
"s": 110,
"text": "To increase the efficiency of code"
},
{
"code": null,
"e": 158,
"s": 145,
"text": "To save time"
},
{
"code": null,
"e": 378,
"s": 158,
"text": "It is inefficient to copy the array data in terms of both memory and time; and most of the time, when we pass an array our intention is to just refer to the array we are interested in, not to create a copy of the array."
},
{
"code": null,
"e": 489,
"s": 378,
"text": "The following two definitions of fun() look different, but to the compiler, they mean exactly the same thing. "
},
{
"code": null,
"e": 602,
"s": 489,
"text": "void fun(int arr[]) { \n // body\n}\n// This is valid\n\n\nvoid fun(int *arr) { \n // body\n}\n// This is valid too"
},
{
"code": null,
"e": 676,
"s": 602,
"text": "It’s preferable to use whichever syntax is more accurate for readability."
},
{
"code": null,
"e": 776,
"s": 676,
"text": "Note: If the pointer coming in really is the base address of a whole array, then we should use [ ]."
},
{
"code": null,
"e": 785,
"s": 776,
"text": "Chapters"
},
{
"code": null,
"e": 812,
"s": 785,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 862,
"s": 812,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 885,
"s": 862,
"text": "captions off, selected"
},
{
"code": null,
"e": 893,
"s": 885,
"text": "English"
},
{
"code": null,
"e": 917,
"s": 893,
"text": "This is a modal window."
},
{
"code": null,
"e": 986,
"s": 917,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1008,
"s": 986,
"text": "End of dialog window."
},
{
"code": null,
"e": 1083,
"s": 1008,
"text": "Example: In this example, the array parameters are being used as pointers."
},
{
"code": null,
"e": 1085,
"s": 1083,
"text": "C"
},
{
"code": "// C Program to demonstrate that C treats array parameters// as pointers#include <stdio.h> void findSum1(int arr[]){ int sum = 0; for (int i = 0; i < 5; i++) sum = sum + arr[i]; printf(\"The sum of the array is: %d\\n\", sum);} void findSum2(int* arr){ int sum = 0; for (int i = 0; i < 5; i++) sum = sum + arr[i]; printf(\"\\nThe sum of the array is: %d \\n\", sum);} // Driver codeint main(){ int arr[5] = { 1, 2, 3, 4, 5 }; findSum1(arr); findSum2(arr); return 0;}",
"e": 1590,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1648,
"s": 1590,
"text": "The sum of the array is: 15\n\nThe sum of the array is: 15 "
},
{
"code": null,
"e": 1774,
"s": 1648,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1788,
"s": 1774,
"text": "anshikajain26"
},
{
"code": null,
"e": 1799,
"s": 1788,
"text": "C-Pointers"
},
{
"code": null,
"e": 1807,
"s": 1799,
"text": "pointer"
},
{
"code": null,
"e": 1818,
"s": 1807,
"text": "C Language"
},
{
"code": null,
"e": 1916,
"s": 1818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1933,
"s": 1916,
"text": "Substring in C++"
},
{
"code": null,
"e": 1968,
"s": 1933,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2014,
"s": 1968,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2059,
"s": 2014,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2084,
"s": 2059,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2132,
"s": 2084,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2160,
"s": 2132,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2187,
"s": 2160,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 2211,
"s": 2187,
"text": "C Language Introduction"
}
] |
Python Program for Finding the vertex, focus and directrix of a parabola
|
03 Dec, 2018
A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve.
The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix.
Example –
Input : 5 3 2
Output : Vertex:(-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198
Consult the formula below for explanation.
# Python program to calculate Vertex, Focus and Directrix def parabola(a, b, c): print ("Vertex: (" , (-b / (2 * a)) , ", " ,(((4 * a * c) - (b * b)) / (4 * a)) , ")" ) print ("Focus: (" , (-b / (2 * a)) , ", " , (((4 * a * c) - (b * b) + 1) / (4 * a)) , ")" ) print ("Directrix: y=" , (int)(c - ((b * b) + 1) * 4 * a )) # main()a = 5b = 3c = 2 parabola(a, b, c) # Contributed by _omg
Output :
Vertex:(-0.3, 1.55)
Focus: (-0.3, 1.6)
Directrix: y=-198
Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Iterate over characters of a string in Python
Python | Convert set into a list
Python program to interchange first and last elements in a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve."
},
{
"code": null,
"e": 462,
"s": 296,
"text": "The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix."
},
{
"code": null,
"e": 472,
"s": 462,
"text": "Example –"
},
{
"code": null,
"e": 614,
"s": 472,
"text": "Input : 5 3 2\nOutput : Vertex:(-0.3, 1.55)\n Focus: (-0.3, 1.6)\n Directrix: y=-198\nConsult the formula below for explanation.\n"
},
{
"code": "# Python program to calculate Vertex, Focus and Directrix def parabola(a, b, c): print (\"Vertex: (\" , (-b / (2 * a)) , \", \" ,(((4 * a * c) - (b * b)) / (4 * a)) , \")\" ) print (\"Focus: (\" , (-b / (2 * a)) , \", \" , (((4 * a * c) - (b * b) + 1) / (4 * a)) , \")\" ) print (\"Directrix: y=\" , (int)(c - ((b * b) + 1) * 4 * a )) # main()a = 5b = 3c = 2 parabola(a, b, c) # Contributed by _omg",
"e": 1067,
"s": 614,
"text": null
},
{
"code": null,
"e": 1076,
"s": 1067,
"text": "Output :"
},
{
"code": null,
"e": 1134,
"s": 1076,
"text": "Vertex:(-0.3, 1.55)\nFocus: (-0.3, 1.6)\nDirectrix: y=-198\n"
},
{
"code": null,
"e": 1239,
"s": 1134,
"text": "Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details!"
},
{
"code": null,
"e": 1255,
"s": 1239,
"text": "Python Programs"
},
{
"code": null,
"e": 1353,
"s": 1255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1391,
"s": 1353,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1428,
"s": 1391,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 1477,
"s": 1428,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 1534,
"s": 1477,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 1568,
"s": 1534,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 1627,
"s": 1568,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 1668,
"s": 1627,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 1714,
"s": 1668,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 1747,
"s": 1714,
"text": "Python | Convert set into a list"
}
] |
How to check for empty string in PHP ?
|
07 Oct, 2021
In this article, we will see how to check for empty string in PHP. String is a set of characters. A string is said to be empty, if it contains no characters. We can use empty() function to check whether a string is empty or not.
The function is used to check whether the string is empty or not. It will return true if the string is empty.
Syntax:
bool empty(string)
Parameter: Variable to check whether it is empty or not.
Return Value: If string is empty, it returns true and false otherwise.
Example 1: PHP program to check whether the string is empty or not.
PHP
<?php // Consider a string which is empty$s = ""; // Return a message if string is emptyif(empty($s)) { echo "Empty string";}else { echo "Not empty";} ?>
Empty string
Example 2:
PHP
<?php // Consider a string which is not empty$s = "Welcome to GFG"; // Return a message if string is emptyif(empty($s)) { echo "Empty string";}else { echo "Not empty";} ?>
Not empty
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
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": 257,
"s": 28,
"text": "In this article, we will see how to check for empty string in PHP. String is a set of characters. A string is said to be empty, if it contains no characters. We can use empty() function to check whether a string is empty or not."
},
{
"code": null,
"e": 367,
"s": 257,
"text": "The function is used to check whether the string is empty or not. It will return true if the string is empty."
},
{
"code": null,
"e": 375,
"s": 367,
"text": "Syntax:"
},
{
"code": null,
"e": 394,
"s": 375,
"text": "bool empty(string)"
},
{
"code": null,
"e": 451,
"s": 394,
"text": "Parameter: Variable to check whether it is empty or not."
},
{
"code": null,
"e": 522,
"s": 451,
"text": "Return Value: If string is empty, it returns true and false otherwise."
},
{
"code": null,
"e": 590,
"s": 522,
"text": "Example 1: PHP program to check whether the string is empty or not."
},
{
"code": null,
"e": 594,
"s": 590,
"text": "PHP"
},
{
"code": "<?php // Consider a string which is empty$s = \"\"; // Return a message if string is emptyif(empty($s)) { echo \"Empty string\";}else { echo \"Not empty\";} ?>",
"e": 757,
"s": 594,
"text": null
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Empty string"
},
{
"code": null,
"e": 781,
"s": 770,
"text": "Example 2:"
},
{
"code": null,
"e": 785,
"s": 781,
"text": "PHP"
},
{
"code": "<?php // Consider a string which is not empty$s = \"Welcome to GFG\"; // Return a message if string is emptyif(empty($s)) { echo \"Empty string\";}else { echo \"Not empty\";} ?>",
"e": 966,
"s": 785,
"text": null
},
{
"code": null,
"e": 976,
"s": 966,
"text": "Not empty"
},
{
"code": null,
"e": 989,
"s": 976,
"text": "PHP-function"
},
{
"code": null,
"e": 1003,
"s": 989,
"text": "PHP-Questions"
},
{
"code": null,
"e": 1014,
"s": 1003,
"text": "PHP-string"
},
{
"code": null,
"e": 1021,
"s": 1014,
"text": "Picked"
},
{
"code": null,
"e": 1025,
"s": 1021,
"text": "PHP"
},
{
"code": null,
"e": 1042,
"s": 1025,
"text": "Web Technologies"
},
{
"code": null,
"e": 1046,
"s": 1042,
"text": "PHP"
}
] |
POJI in Java
|
05 May, 2021
POJI: stands for Plain Old Java Interface. A POJI is an ordinary interface without any specialties. The interfaces that do not extend from technology/framework specific interfaces. For example all user defined interfaces are POJI and an interface that inherits from AppletInitializer of Java Beans is not POJI.Examples:
JAVA
// A POJI interfaceinterface GFG { public void method1();} interface Geeks extends GFG { public void method2();}
Explanation: Here both the interfaces i.e. GFG and Geeks are POJI in nature. Because both GFG and Geeks does not extends from any technology specific interface.
JAVA
// Another POJI interfaceinterface GFG extends java.io.Serializable { }
Explanation: Here GFG is also a POJI. Here the interface is extending from Serializable interface but that serializable interface is not the part of any Technology, it is about Java API. Therefore, we can say that GFG is POJI in nature.
JAVA
// Not a POJI Interfaceinterface GFG1 extends java.rmi.Remote { } // Not a POJI Interfaceinterface GFG2 extends java.beans.AppletInitializer { }
Explanation: Here GFG1 and GFG2 are not POJI in nature. Because Remote and AppletInitializer not part of API, it is technology.
hritikbhatnagar2182
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "POJI: stands for Plain Old Java Interface. A POJI is an ordinary interface without any specialties. The interfaces that do not extend from technology/framework specific interfaces. For example all user defined interfaces are POJI and an interface that inherits from AppletInitializer of Java Beans is not POJI.Examples:"
},
{
"code": null,
"e": 353,
"s": 348,
"text": "JAVA"
},
{
"code": "// A POJI interfaceinterface GFG { public void method1();} interface Geeks extends GFG { public void method2();}",
"e": 468,
"s": 353,
"text": null
},
{
"code": null,
"e": 633,
"s": 468,
"text": "Explanation: Here both the interfaces i.e. GFG and Geeks are POJI in nature. Because both GFG and Geeks does not extends from any technology specific interface. "
},
{
"code": null,
"e": 638,
"s": 633,
"text": "JAVA"
},
{
"code": "// Another POJI interfaceinterface GFG extends java.io.Serializable { }",
"e": 710,
"s": 638,
"text": null
},
{
"code": null,
"e": 951,
"s": 710,
"text": "Explanation: Here GFG is also a POJI. Here the interface is extending from Serializable interface but that serializable interface is not the part of any Technology, it is about Java API. Therefore, we can say that GFG is POJI in nature. "
},
{
"code": null,
"e": 956,
"s": 951,
"text": "JAVA"
},
{
"code": "// Not a POJI Interfaceinterface GFG1 extends java.rmi.Remote { } // Not a POJI Interfaceinterface GFG2 extends java.beans.AppletInitializer { }",
"e": 1101,
"s": 956,
"text": null
},
{
"code": null,
"e": 1230,
"s": 1101,
"text": "Explanation: Here GFG1 and GFG2 are not POJI in nature. Because Remote and AppletInitializer not part of API, it is technology. "
},
{
"code": null,
"e": 1250,
"s": 1230,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 1266,
"s": 1250,
"text": "java-interfaces"
},
{
"code": null,
"e": 1271,
"s": 1266,
"text": "Java"
},
{
"code": null,
"e": 1276,
"s": 1271,
"text": "Java"
}
] |
Using Certbot Manually for SSL certificates
|
24 Nov, 2020
Let’s Encrypt has become one of the most important organizations for creating a secure Internet. Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit, a service provided by the Internet Security Research Group (ISRG). They give people the digital certificates they need in order to enable HTTPS (SSL/TLS) for websites for free of cost. It is supported by EFF, ISRG, Linux Foundation, Google, Facebook, and more company. In February 2020, they have issued their our billionth certificate
The key principles behind Let’s Encrypt are(as in their website):
Free: Anyone who owns a domain name can use Let’s Encrypt to obtain a trusted certificate at zero cost valid for 9 days.
Automatic: Software running on a web server can interact with Let’s Encrypt to painlessly obtain a certificate, securely configure it for use, and automatically take care of renewal mostly known as certbot.
Secure: Let’s Encrypt will serve as a platform for advancing TLS security best practices, both on the CA side and by helping site operators properly secure their servers.
Transparent: All certificates issued or revoked will be publicly recorded and available for anyone to inspect.
Open Source: The automatic issuance and renewal protocol will be published as an open standard that others can adopt.
Certbot is a free, open-source software tool for automatically using Let’s Encrypt certificates on manually-administrated websites to enable HTTPS. It’s mostly built over python by Electronic Frontier Foundation (EFF). Almost many of the shared and some cloud hosting providers integrate certbot or an equivalent plugin in the website hosting panel which allows you to get, renew, and manage SSL/TLS certificates using some buttons.
In this article we are going to learn how to get an SSL certificate by using certbot manually which can help you to understand how certbot works, I will be using Ubuntu(you can use any UNIX like operating system) for this tutorial.
Requirements:
Certbot is meant to be run directly on a web server. You can use your PC for this tutorial
Make sure you have python installed which makes installation faster
Its better to have root privileges
For Ubuntu or Debian systems you can use APT to install certbot
sudo apt-get install certbot
After you have installed type this long command
certbot certonly –manual -d *.exampledomain.com -d exampledomain.com –agree-tos –manual-public-ip-logging-ok –preferred-challenges dns-01 –server https://acme-v02.api.letsencrypt.org/directory –register-unsafely-without-email –rsa-key-size 4096
Going into the command
certbot: the certbot program
certonly: run the certbot once, certbot-auto runs certbot automatically
manual: run certbot in manual mode
d: domains to be included in certificate, use your domain an its wildcard instead of exampledomain.com
agree-tos: agreeing terms of Service of letsencrypt and eff
manual-public-ip-logging-ok: logging IP of our the system you are using for security purposes
preferred-challenges: The way used to verify domain ownership, We used DNS challenge
server: The letsencrypt ACME server
register-unsafely-without-email: getting certificate without register unsafely without email, but while in production use email to receive information about getting, renewing and revoking of certificate
rsa-key-size: the length of RSA key size
By this time you can see something like the below picture
getting certificate
Now log into your DNS manager and add TXT record with the acme-challenge, don’t change the acme-challenge
TXT record
After the verification is complete, certbot will get an SSL certificate for your domain. You can find SSL certificate in /etc/letsencrypt/live/exampledomain.com/ folder
SSL
Technical Scripter 2020
Python
Technical Scripter
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 564,
"s": 28,
"text": "Let’s Encrypt has become one of the most important organizations for creating a secure Internet. Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit, a service provided by the Internet Security Research Group (ISRG). They give people the digital certificates they need in order to enable HTTPS (SSL/TLS) for websites for free of cost. It is supported by EFF, ISRG, Linux Foundation, Google, Facebook, and more company. In February 2020, they have issued their our billionth certificate"
},
{
"code": null,
"e": 630,
"s": 564,
"text": "The key principles behind Let’s Encrypt are(as in their website):"
},
{
"code": null,
"e": 751,
"s": 630,
"text": "Free: Anyone who owns a domain name can use Let’s Encrypt to obtain a trusted certificate at zero cost valid for 9 days."
},
{
"code": null,
"e": 958,
"s": 751,
"text": "Automatic: Software running on a web server can interact with Let’s Encrypt to painlessly obtain a certificate, securely configure it for use, and automatically take care of renewal mostly known as certbot."
},
{
"code": null,
"e": 1129,
"s": 958,
"text": "Secure: Let’s Encrypt will serve as a platform for advancing TLS security best practices, both on the CA side and by helping site operators properly secure their servers."
},
{
"code": null,
"e": 1240,
"s": 1129,
"text": "Transparent: All certificates issued or revoked will be publicly recorded and available for anyone to inspect."
},
{
"code": null,
"e": 1358,
"s": 1240,
"text": "Open Source: The automatic issuance and renewal protocol will be published as an open standard that others can adopt."
},
{
"code": null,
"e": 1792,
"s": 1358,
"text": "Certbot is a free, open-source software tool for automatically using Let’s Encrypt certificates on manually-administrated websites to enable HTTPS. It’s mostly built over python by Electronic Frontier Foundation (EFF). Almost many of the shared and some cloud hosting providers integrate certbot or an equivalent plugin in the website hosting panel which allows you to get, renew, and manage SSL/TLS certificates using some buttons. "
},
{
"code": null,
"e": 2024,
"s": 1792,
"text": "In this article we are going to learn how to get an SSL certificate by using certbot manually which can help you to understand how certbot works, I will be using Ubuntu(you can use any UNIX like operating system) for this tutorial."
},
{
"code": null,
"e": 2038,
"s": 2024,
"text": "Requirements:"
},
{
"code": null,
"e": 2129,
"s": 2038,
"text": "Certbot is meant to be run directly on a web server. You can use your PC for this tutorial"
},
{
"code": null,
"e": 2197,
"s": 2129,
"text": "Make sure you have python installed which makes installation faster"
},
{
"code": null,
"e": 2232,
"s": 2197,
"text": "Its better to have root privileges"
},
{
"code": null,
"e": 2296,
"s": 2232,
"text": "For Ubuntu or Debian systems you can use APT to install certbot"
},
{
"code": null,
"e": 2325,
"s": 2296,
"text": "sudo apt-get install certbot"
},
{
"code": null,
"e": 2373,
"s": 2325,
"text": "After you have installed type this long command"
},
{
"code": null,
"e": 2618,
"s": 2373,
"text": "certbot certonly –manual -d *.exampledomain.com -d exampledomain.com –agree-tos –manual-public-ip-logging-ok –preferred-challenges dns-01 –server https://acme-v02.api.letsencrypt.org/directory –register-unsafely-without-email –rsa-key-size 4096"
},
{
"code": null,
"e": 2642,
"s": 2618,
"text": "Going into the command "
},
{
"code": null,
"e": 2671,
"s": 2642,
"text": "certbot: the certbot program"
},
{
"code": null,
"e": 2743,
"s": 2671,
"text": "certonly: run the certbot once, certbot-auto runs certbot automatically"
},
{
"code": null,
"e": 2778,
"s": 2743,
"text": "manual: run certbot in manual mode"
},
{
"code": null,
"e": 2881,
"s": 2778,
"text": "d: domains to be included in certificate, use your domain an its wildcard instead of exampledomain.com"
},
{
"code": null,
"e": 2941,
"s": 2881,
"text": "agree-tos: agreeing terms of Service of letsencrypt and eff"
},
{
"code": null,
"e": 3035,
"s": 2941,
"text": "manual-public-ip-logging-ok: logging IP of our the system you are using for security purposes"
},
{
"code": null,
"e": 3120,
"s": 3035,
"text": "preferred-challenges: The way used to verify domain ownership, We used DNS challenge"
},
{
"code": null,
"e": 3156,
"s": 3120,
"text": "server: The letsencrypt ACME server"
},
{
"code": null,
"e": 3359,
"s": 3156,
"text": "register-unsafely-without-email: getting certificate without register unsafely without email, but while in production use email to receive information about getting, renewing and revoking of certificate"
},
{
"code": null,
"e": 3400,
"s": 3359,
"text": "rsa-key-size: the length of RSA key size"
},
{
"code": null,
"e": 3458,
"s": 3400,
"text": "By this time you can see something like the below picture"
},
{
"code": null,
"e": 3478,
"s": 3458,
"text": "getting certificate"
},
{
"code": null,
"e": 3584,
"s": 3478,
"text": "Now log into your DNS manager and add TXT record with the acme-challenge, don’t change the acme-challenge"
},
{
"code": null,
"e": 3595,
"s": 3584,
"text": "TXT record"
},
{
"code": null,
"e": 3764,
"s": 3595,
"text": "After the verification is complete, certbot will get an SSL certificate for your domain. You can find SSL certificate in /etc/letsencrypt/live/exampledomain.com/ folder"
},
{
"code": null,
"e": 3768,
"s": 3764,
"text": "SSL"
},
{
"code": null,
"e": 3792,
"s": 3768,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3799,
"s": 3792,
"text": "Python"
},
{
"code": null,
"e": 3818,
"s": 3799,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3916,
"s": 3818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3948,
"s": 3916,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3975,
"s": 3948,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3996,
"s": 3975,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4019,
"s": 3996,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4075,
"s": 4019,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4106,
"s": 4075,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4148,
"s": 4106,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4190,
"s": 4148,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4229,
"s": 4190,
"text": "Python | Get unique values from a list"
}
] |
C# | String vs StringBuilder
|
23 Jan, 2019
StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type. It will not create a new modified instance of the current string object but do the modifications in the existing string object. The complete functionality of StringBuilder is provided by StringBuilder class which is present in System.Text namespace.
Need of the StringBuilder: As stated above that the String class objects are immutable which means that if the user will modify any string object it will result into the creation of a new string object. It makes the use of string costly. So when the user needs the repetitive operations on the string then the need of StringBuilder come into existence. It provides the optimized way to deal with the repetitive and multiple string manipulation operations.
Example:
// C# program to demonstrate the// difference between String,// StringBuilderusing System;using System.Text;using System.Collections; class GFG { // Concatenates to String public static void concat1(String s1) { // taking a string which // is to be Concatenate String st = "forGeeks"; // using String.Concat method // you can also replace it with // s1 = s1 + "forgeeks"; s1 = String.Concat(s1, st); } // Concatenates to StringBuilder public static void concat2(StringBuilder s2) { // using Append method // of StringBuilder class s2.Append("forGeeks"); } // Main Method public static void Main(String[] args) { String s1 = "Geeks"; concat1(s1); // s1 is not changed Console.WriteLine("Using String Class: " + s1); StringBuilder s2 = new StringBuilder("Geeks"); concat2(s2); // s2 is changed Console.WriteLine("Using StringBuilder Class: " + s2); }}
Output:
Using String Class: Geeks
Using StringBuilder Class: GeeksforGeeks
Explanation:
Use of concat1 Method: In this method, we are passing a string “Geeks” and performing “s1 = String.Concat(s1, st);” where st is “forGeeks” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and s1 in concat1() stores reference of the new string. But the references s1 in Main() and concat1() refer to different strings.
Use of concat2 Method: In this method, we are passing a string “Geeks” and performing “s2.Append(“forGeeks”)” which changes the actual value of the string (in Main) to “GeeksforGeeks”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
When to use which one:
If a string is going to remain constant throughout the program, then use String class object because a String object is immutable.
If a string can change (example: lots of logic and operations in the construction of the string) then using a StringBuilder is the best option.
Converting String to StringBuilder:To convert a String class object to StringBuilder class object, just pass the string object to the StringBuilder class constructor.
Example:
// C# program to demonstrate the// conversion from String to StringBuilder.using System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { String str = "Geeks"; // conversion from String object // to StringBuilder StringBuilder sbl = new StringBuilder(str); sbl.Append("ForGeeks"); Console.WriteLine(sbl); }}
Output:
GeeksForGeeks
Converting StringBuilder to String:This conversions can be performed using ToString() method.
Example:
// C# program to demonstrate the// conversion from String to StringBuilderusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { StringBuilder sbdr = new StringBuilder("Builder"); // conversion from StringBuilder // object to String using ToString method String str1 = sbdr.ToString(); Console.Write("StringBuilder object to String: "); Console.WriteLine(str1); }}
Output:
StringBuilder object to String: Builder
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Multiple inheritance using interfaces
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 496,
"s": 54,
"text": "StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type. It will not create a new modified instance of the current string object but do the modifications in the existing string object. The complete functionality of StringBuilder is provided by StringBuilder class which is present in System.Text namespace."
},
{
"code": null,
"e": 952,
"s": 496,
"text": "Need of the StringBuilder: As stated above that the String class objects are immutable which means that if the user will modify any string object it will result into the creation of a new string object. It makes the use of string costly. So when the user needs the repetitive operations on the string then the need of StringBuilder come into existence. It provides the optimized way to deal with the repetitive and multiple string manipulation operations."
},
{
"code": null,
"e": 961,
"s": 952,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// difference between String,// StringBuilderusing System;using System.Text;using System.Collections; class GFG { // Concatenates to String public static void concat1(String s1) { // taking a string which // is to be Concatenate String st = \"forGeeks\"; // using String.Concat method // you can also replace it with // s1 = s1 + \"forgeeks\"; s1 = String.Concat(s1, st); } // Concatenates to StringBuilder public static void concat2(StringBuilder s2) { // using Append method // of StringBuilder class s2.Append(\"forGeeks\"); } // Main Method public static void Main(String[] args) { String s1 = \"Geeks\"; concat1(s1); // s1 is not changed Console.WriteLine(\"Using String Class: \" + s1); StringBuilder s2 = new StringBuilder(\"Geeks\"); concat2(s2); // s2 is changed Console.WriteLine(\"Using StringBuilder Class: \" + s2); }}",
"e": 1974,
"s": 961,
"text": null
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 1982,
"text": "Using String Class: Geeks\nUsing StringBuilder Class: GeeksforGeeks\n"
},
{
"code": null,
"e": 2063,
"s": 2050,
"text": "Explanation:"
},
{
"code": null,
"e": 2500,
"s": 2063,
"text": "Use of concat1 Method: In this method, we are passing a string “Geeks” and performing “s1 = String.Concat(s1, st);” where st is “forGeeks” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and s1 in concat1() stores reference of the new string. But the references s1 in Main() and concat1() refer to different strings."
},
{
"code": null,
"e": 2775,
"s": 2500,
"text": "Use of concat2 Method: In this method, we are passing a string “Geeks” and performing “s2.Append(“forGeeks”)” which changes the actual value of the string (in Main) to “GeeksforGeeks”. This is due to the simple fact that StringBuilder is mutable and hence changes its value."
},
{
"code": null,
"e": 2798,
"s": 2775,
"text": "When to use which one:"
},
{
"code": null,
"e": 2929,
"s": 2798,
"text": "If a string is going to remain constant throughout the program, then use String class object because a String object is immutable."
},
{
"code": null,
"e": 3073,
"s": 2929,
"text": "If a string can change (example: lots of logic and operations in the construction of the string) then using a StringBuilder is the best option."
},
{
"code": null,
"e": 3240,
"s": 3073,
"text": "Converting String to StringBuilder:To convert a String class object to StringBuilder class object, just pass the string object to the StringBuilder class constructor."
},
{
"code": null,
"e": 3249,
"s": 3240,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// conversion from String to StringBuilder.using System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { String str = \"Geeks\"; // conversion from String object // to StringBuilder StringBuilder sbl = new StringBuilder(str); sbl.Append(\"ForGeeks\"); Console.WriteLine(sbl); }}",
"e": 3653,
"s": 3249,
"text": null
},
{
"code": null,
"e": 3661,
"s": 3653,
"text": "Output:"
},
{
"code": null,
"e": 3675,
"s": 3661,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 3770,
"s": 3675,
"text": " Converting StringBuilder to String:This conversions can be performed using ToString() method."
},
{
"code": null,
"e": 3779,
"s": 3770,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the// conversion from String to StringBuilderusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { StringBuilder sbdr = new StringBuilder(\"Builder\"); // conversion from StringBuilder // object to String using ToString method String str1 = sbdr.ToString(); Console.Write(\"StringBuilder object to String: \"); Console.WriteLine(str1); }}",
"e": 4252,
"s": 3779,
"text": null
},
{
"code": null,
"e": 4260,
"s": 4252,
"text": "Output:"
},
{
"code": null,
"e": 4300,
"s": 4260,
"text": "StringBuilder object to String: Builder"
},
{
"code": null,
"e": 4314,
"s": 4300,
"text": "CSharp-string"
},
{
"code": null,
"e": 4317,
"s": 4314,
"text": "C#"
},
{
"code": null,
"e": 4415,
"s": 4317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4469,
"s": 4415,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 4531,
"s": 4469,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 4554,
"s": 4531,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 4582,
"s": 4554,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 4624,
"s": 4582,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 4667,
"s": 4624,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4682,
"s": 4667,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4731,
"s": 4682,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4771,
"s": 4731,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Extract substrings between any pair of delimiters
|
14 Dec, 2021
Given a string str, the task is to extract the substrings present between two delimiters, i.e. ‘[‘ and ‘]’.
Examples:
Input: str = “[This is a string to be extracted]”Output: This is a string to be extractedExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Input: str= “[This is first] ignored text [This is second]”Output: This is firstThis is secondExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string.
Stack-based Approach: Iterate over the characters of the string and insert the index of every ‘[‘ encountered into the stack. For every ‘]’ encountered, simply pop the index stored at the top of the stack and print the substring lying in between.
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){ // Stores the indices of stack<int> dels; for (int i = 0; i < str.size(); i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.push(i); } // If closing delimiter // is encountered else if (str[i] == ']' && !dels.empty()) { // Extract the position // of opening delimiter int pos = dels.top(); dels.pop(); // Length of substring int len = i - 1 - pos; // Extract the substring string ans = str.substr( pos + 1, len); cout << ans << endl; } }} // Driver Codeint main(){ string str = "[This is first] ignored text [This is second]"; printSubsInDelimiters(str); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print Strings present// between any pair of delimitersstatic void printSubsInDelimiters(String str){ // Stores the indices of Stack<Integer> dels = new Stack<Integer>(); for(int i = 0; i < str.length(); i++) { // If opening delimiter // is encountered if (str.charAt(i) == '[') { dels.add(i); } // If closing delimiter // is encountered else if (str.charAt(i) == ']' && !dels.isEmpty()) { // Extract the position // of opening delimiter int pos = dels.peek(); dels.pop(); // Length of subString int len = i - 1 - pos; // Extract the subString String ans = str.substring( pos + 1, pos + 1 + len); System.out.print(ans + "\n"); } }} // Driver Codepublic static void main(String[] args){ String str = "[This is first] ignored text [This is second]"; printSubsInDelimiters(str);}} // This code is contributed by shikhasingrajput
# Python3 Program to implement# the above approach # Function to print strings present# between any pair of delimitersdef printSubsInDelimiters(string) : # Stores the indices dels = []; for i in range(len(string)): # If opening delimiter # is encountered if (string[i] == '[') : dels.append(i); # If closing delimiter # is encountered elif (string[i] == ']' and len(dels) != 0) : # Extract the position # of opening delimiter pos = dels[-1]; dels.pop(); # Length of substring length = i - 1 - pos; # Extract the substring ans = string[pos + 1 : pos + 1 + length]; print(ans); # Driver Codeif __name__ == "__main__" : string = "[This is first] ignored text [This is second]"; printSubsInDelimiters(string); # This code is contributed by AnkThon
// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to print strings present// between any pair of delimitersstatic void printSubsInDelimiters(string str){ // Stores the indices of Stack dels = new Stack(); for(int i = 0; i < str.Length; i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.Push(i); } // If closing delimiter // is encountered else if (str[i] == ']' && dels.Count > 0) { // Extract the position // of opening delimiter int pos = (int)dels.Peek(); dels.Pop(); // Length of substring int len = i - 1 - pos; // Extract the substring string ans = str.Substring( pos + 1, len); Console.WriteLine(ans); } }} // Driver Codestatic void Main(){ string str = "[This is first] ignored text [This is second]"; printSubsInDelimiters(str);}} // This code is contributed by divyesh072019
<script> // Javascript program to implement // the above approach // Function to print strings present // between any pair of delimiters function printSubsInDelimiters(str) { // Stores the indices of let dels = []; for(let i = 0; i < str.length; i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.push(i); } // If closing delimiter // is encountered else if ((str[i] == ']') && (dels.length > 0)) { // Extract the position // of opening delimiter let pos = dels[dels.length - 1]; dels.pop(); // Length of substring let len = i - 1 - pos; // Extract the substring let ans; if(pos < len) { ans = str.substring(pos + 1, len + 1); } else{ ans = str.substring(pos + 1, len + pos + 1); } document.write(ans + "</br>"); } } } let str = "[This is first] ignored text [This is second]"; printSubsInDelimiters(str); </script>
This is first
This is second
Time Complexity: O(N)Auxiliary Space: O(N)
Space-Efficient Approach: The idea is to use Regular Expressions to solve this problem. Create a regular expression to extract the string between two delimiters as regex = “\\[(.*?)\\]” and match the given string with the Regular Expression. Print the subsequence formed.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to implement// the above approach#include <iostream>#include <regex>using namespace std; // Function to print Strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){ // Regex to extract the string // between two delimiters const regex pattern("\\[(.*?)\\]"); for(sregex_iterator it = sregex_iterator( str.begin(), str.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the // matching behavior here it is // for matches on 'string' objects smatch match; match = *it; cout << match.str(1) << endl; } return;} // Driver Codeint main(){ // Input String string str = "[This is first] ignored text [This is second]"; // Function Call printSubsInDelimiters(str); return 0;} // This code is contributed by yuvraj_chandra
// Java program to implement// the above approachimport java.util.regex.*; class GFG{ // Function to print Strings present// between any pair of delimiterspublic static void printSubsInDelimiters(String str){ // Regex to extract the string // between two delimiters String regex = "\\[(.*?)\\]"; // Compile the Regex. Pattern p = Pattern.compile(regex); // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Get the subsequence // using find() method while (m.find()) { System.out.println(m.group(1)); }} // Driver codepublic static void main(String args[]){ // Input String String str = "[This is first] ignored text [This is second]"; // Function Call printSubsInDelimiters(str);}}
# Python3 program to implement# the above approachimport re # Function to print Strings present# between any pair of delimitersdef printSubsInDelimiters(str): # Regex to extract the string # between two delimiters regex = "\\[(.*?)\\]" # Find match between given string # and regular expression # using re.findall() matches = re.findall(regex, str) # Print the matches for match in matches: print(match) # Driver code # Input Stringstr = "[This is first] ignored text [This is second]" # Function CallprintSubsInDelimiters(str) # This code is contributed by yuvraj_chandra
This is first
This is second
Time Complexity: O(N)Auxiliary Space: O(1)
divyesh072019
shikhasingrajput
ankthon
yuvraj_chandra
rameshtravel07
rkbhola5
gabaa406
regular-expression
substring
Technical Scripter 2020
Pattern Searching
Strings
Technical Scripter
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse the substrings of the given String according to the given Array of indices
Check if the given string is shuffled substring of another string
How to validate GUID (Globally Unique Identifier) using Regular Expression
How to check Aadhaar number is valid or not using Regular Expression
How to validate MAC address using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 162,
"s": 54,
"text": "Given a string str, the task is to extract the substrings present between two delimiters, i.e. ‘[‘ and ‘]’."
},
{
"code": null,
"e": 172,
"s": 162,
"text": "Examples:"
},
{
"code": null,
"e": 347,
"s": 172,
"text": "Input: str = “[This is a string to be extracted]”Output: This is a string to be extractedExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string."
},
{
"code": null,
"e": 527,
"s": 347,
"text": "Input: str= “[This is first] ignored text [This is second]”Output: This is firstThis is secondExplanation: The square brackets ‘[‘ and ‘]’ serve as delimiters in the given string."
},
{
"code": null,
"e": 774,
"s": 527,
"text": "Stack-based Approach: Iterate over the characters of the string and insert the index of every ‘[‘ encountered into the stack. For every ‘]’ encountered, simply pop the index stored at the top of the stack and print the substring lying in between."
},
{
"code": null,
"e": 824,
"s": 774,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 830,
"s": 824,
"text": "C++14"
},
{
"code": null,
"e": 835,
"s": 830,
"text": "Java"
},
{
"code": null,
"e": 843,
"s": 835,
"text": "Python3"
},
{
"code": null,
"e": 846,
"s": 843,
"text": "C#"
},
{
"code": null,
"e": 857,
"s": 846,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){ // Stores the indices of stack<int> dels; for (int i = 0; i < str.size(); i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.push(i); } // If closing delimiter // is encountered else if (str[i] == ']' && !dels.empty()) { // Extract the position // of opening delimiter int pos = dels.top(); dels.pop(); // Length of substring int len = i - 1 - pos; // Extract the substring string ans = str.substr( pos + 1, len); cout << ans << endl; } }} // Driver Codeint main(){ string str = \"[This is first] ignored text [This is second]\"; printSubsInDelimiters(str); return 0;}",
"e": 1862,
"s": 857,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to print Strings present// between any pair of delimitersstatic void printSubsInDelimiters(String str){ // Stores the indices of Stack<Integer> dels = new Stack<Integer>(); for(int i = 0; i < str.length(); i++) { // If opening delimiter // is encountered if (str.charAt(i) == '[') { dels.add(i); } // If closing delimiter // is encountered else if (str.charAt(i) == ']' && !dels.isEmpty()) { // Extract the position // of opening delimiter int pos = dels.peek(); dels.pop(); // Length of subString int len = i - 1 - pos; // Extract the subString String ans = str.substring( pos + 1, pos + 1 + len); System.out.print(ans + \"\\n\"); } }} // Driver Codepublic static void main(String[] args){ String str = \"[This is first] ignored text [This is second]\"; printSubsInDelimiters(str);}} // This code is contributed by shikhasingrajput",
"e": 3047,
"s": 1862,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Function to print strings present# between any pair of delimitersdef printSubsInDelimiters(string) : # Stores the indices dels = []; for i in range(len(string)): # If opening delimiter # is encountered if (string[i] == '[') : dels.append(i); # If closing delimiter # is encountered elif (string[i] == ']' and len(dels) != 0) : # Extract the position # of opening delimiter pos = dels[-1]; dels.pop(); # Length of substring length = i - 1 - pos; # Extract the substring ans = string[pos + 1 : pos + 1 + length]; print(ans); # Driver Codeif __name__ == \"__main__\" : string = \"[This is first] ignored text [This is second]\"; printSubsInDelimiters(string); # This code is contributed by AnkThon",
"e": 3987,
"s": 3047,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to print strings present// between any pair of delimitersstatic void printSubsInDelimiters(string str){ // Stores the indices of Stack dels = new Stack(); for(int i = 0; i < str.Length; i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.Push(i); } // If closing delimiter // is encountered else if (str[i] == ']' && dels.Count > 0) { // Extract the position // of opening delimiter int pos = (int)dels.Peek(); dels.Pop(); // Length of substring int len = i - 1 - pos; // Extract the substring string ans = str.Substring( pos + 1, len); Console.WriteLine(ans); } }} // Driver Codestatic void Main(){ string str = \"[This is first] ignored text [This is second]\"; printSubsInDelimiters(str);}} // This code is contributed by divyesh072019",
"e": 5123,
"s": 3987,
"text": null
},
{
"code": "<script> // Javascript program to implement // the above approach // Function to print strings present // between any pair of delimiters function printSubsInDelimiters(str) { // Stores the indices of let dels = []; for(let i = 0; i < str.length; i++) { // If opening delimiter // is encountered if (str[i] == '[') { dels.push(i); } // If closing delimiter // is encountered else if ((str[i] == ']') && (dels.length > 0)) { // Extract the position // of opening delimiter let pos = dels[dels.length - 1]; dels.pop(); // Length of substring let len = i - 1 - pos; // Extract the substring let ans; if(pos < len) { ans = str.substring(pos + 1, len + 1); } else{ ans = str.substring(pos + 1, len + pos + 1); } document.write(ans + \"</br>\"); } } } let str = \"[This is first] ignored text [This is second]\"; printSubsInDelimiters(str); </script>",
"e": 6506,
"s": 5123,
"text": null
},
{
"code": null,
"e": 6535,
"s": 6506,
"text": "This is first\nThis is second"
},
{
"code": null,
"e": 6580,
"s": 6537,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 6852,
"s": 6580,
"text": "Space-Efficient Approach: The idea is to use Regular Expressions to solve this problem. Create a regular expression to extract the string between two delimiters as regex = “\\\\[(.*?)\\\\]” and match the given string with the Regular Expression. Print the subsequence formed."
},
{
"code": null,
"e": 6903,
"s": 6852,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 6907,
"s": 6903,
"text": "C++"
},
{
"code": null,
"e": 6912,
"s": 6907,
"text": "Java"
},
{
"code": null,
"e": 6920,
"s": 6912,
"text": "Python3"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include <regex>using namespace std; // Function to print Strings present// between any pair of delimitersvoid printSubsInDelimiters(string str){ // Regex to extract the string // between two delimiters const regex pattern(\"\\\\[(.*?)\\\\]\"); for(sregex_iterator it = sregex_iterator( str.begin(), str.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the // matching behavior here it is // for matches on 'string' objects smatch match; match = *it; cout << match.str(1) << endl; } return;} // Driver Codeint main(){ // Input String string str = \"[This is first] ignored text [This is second]\"; // Function Call printSubsInDelimiters(str); return 0;} // This code is contributed by yuvraj_chandra",
"e": 7844,
"s": 6920,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.regex.*; class GFG{ // Function to print Strings present// between any pair of delimiterspublic static void printSubsInDelimiters(String str){ // Regex to extract the string // between two delimiters String regex = \"\\\\[(.*?)\\\\]\"; // Compile the Regex. Pattern p = Pattern.compile(regex); // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Get the subsequence // using find() method while (m.find()) { System.out.println(m.group(1)); }} // Driver codepublic static void main(String args[]){ // Input String String str = \"[This is first] ignored text [This is second]\"; // Function Call printSubsInDelimiters(str);}}",
"e": 8664,
"s": 7844,
"text": null
},
{
"code": "# Python3 program to implement# the above approachimport re # Function to print Strings present# between any pair of delimitersdef printSubsInDelimiters(str): # Regex to extract the string # between two delimiters regex = \"\\\\[(.*?)\\\\]\" # Find match between given string # and regular expression # using re.findall() matches = re.findall(regex, str) # Print the matches for match in matches: print(match) # Driver code # Input Stringstr = \"[This is first] ignored text [This is second]\" # Function CallprintSubsInDelimiters(str) # This code is contributed by yuvraj_chandra",
"e": 9274,
"s": 8664,
"text": null
},
{
"code": null,
"e": 9303,
"s": 9274,
"text": "This is first\nThis is second"
},
{
"code": null,
"e": 9348,
"s": 9305,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9364,
"s": 9350,
"text": "divyesh072019"
},
{
"code": null,
"e": 9381,
"s": 9364,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 9389,
"s": 9381,
"text": "ankthon"
},
{
"code": null,
"e": 9404,
"s": 9389,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 9419,
"s": 9404,
"text": "rameshtravel07"
},
{
"code": null,
"e": 9428,
"s": 9419,
"text": "rkbhola5"
},
{
"code": null,
"e": 9437,
"s": 9428,
"text": "gabaa406"
},
{
"code": null,
"e": 9456,
"s": 9437,
"text": "regular-expression"
},
{
"code": null,
"e": 9466,
"s": 9456,
"text": "substring"
},
{
"code": null,
"e": 9490,
"s": 9466,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9508,
"s": 9490,
"text": "Pattern Searching"
},
{
"code": null,
"e": 9516,
"s": 9508,
"text": "Strings"
},
{
"code": null,
"e": 9535,
"s": 9516,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9543,
"s": 9535,
"text": "Strings"
},
{
"code": null,
"e": 9561,
"s": 9543,
"text": "Pattern Searching"
},
{
"code": null,
"e": 9659,
"s": 9561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9742,
"s": 9659,
"text": "Reverse the substrings of the given String according to the given Array of indices"
},
{
"code": null,
"e": 9808,
"s": 9742,
"text": "Check if the given string is shuffled substring of another string"
},
{
"code": null,
"e": 9883,
"s": 9808,
"text": "How to validate GUID (Globally Unique Identifier) using Regular Expression"
},
{
"code": null,
"e": 9952,
"s": 9883,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 10005,
"s": 9952,
"text": "How to validate MAC address using Regular Expression"
},
{
"code": null,
"e": 10051,
"s": 10005,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10076,
"s": 10051,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10136,
"s": 10076,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10151,
"s": 10136,
"text": "C++ Data Types"
}
] |
Python | os.remove() method
|
29 May, 2019
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.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method. os.rmdir() can be used to remove directory.
Syntax: os.remove(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
# Python program to explain os.remove() method # importing os module import os # File namefile = 'file.txt' # File locationlocation = "/home/User/Documents" # Pathpath = os.path.join(location, file) # Remove the file# 'file.txt'os.remove(path)print("%s has been removed successfully" %file)
file.txt has been removed successfully
# Python program to explain os.remove() method # importing os module import os # Pathpath = "/home/User/Documents/ihritik" # Remove the specified# file pathos.remove(path)print("% s has been removed successfully" % file) # if the specified path # is a directory then # 'IsADirectoryError' error# will raised # Similarly if the specified# file path does not exists or # is invalid then corresponding# OSError will be raised
Traceback (most recent call last):
File "osremove.py", line 11, in
os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/ihritik'
# Python program to explain os.remove() method # importing os module import os # pathpath = '/home/User/Documents/ihritik' # Remove the specified # file pathtry: os.remove(path) print("% s removed successfully" % path)except OSError as error: print(error) print("File path can not be removed")
[Errno 21] Is a directory: '/home/User/Documents/ihritik'
File path can not be removed
Reference: https://docs.python.org/3/library/os.html
Python OS-path-module
python-os-module
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 271,
"s": 52,
"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 way of using operating system dependent functionality."
},
{
"code": null,
"e": 466,
"s": 271,
"text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system."
},
{
"code": null,
"e": 710,
"s": 466,
"text": "os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method. os.rmdir() can be used to remove directory."
},
{
"code": null,
"e": 752,
"s": 710,
"text": "Syntax: os.remove(path, *, dir_fd = None)"
},
{
"code": null,
"e": 1053,
"s": 752,
"text": "Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored."
},
{
"code": null,
"e": 1253,
"s": 1053,
"text": "Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter."
},
{
"code": null,
"e": 1305,
"s": 1253,
"text": "Return Type: This method does not return any value."
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # File namefile = 'file.txt' # File locationlocation = \"/home/User/Documents\" # Pathpath = os.path.join(location, file) # Remove the file# 'file.txt'os.remove(path)print(\"%s has been removed successfully\" %file)",
"e": 1604,
"s": 1305,
"text": null
},
{
"code": null,
"e": 1644,
"s": 1604,
"text": "file.txt has been removed successfully\n"
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # Pathpath = \"/home/User/Documents/ihritik\" # Remove the specified# file pathos.remove(path)print(\"% s has been removed successfully\" % file) # if the specified path # is a directory then # 'IsADirectoryError' error# will raised # Similarly if the specified# file path does not exists or # is invalid then corresponding# OSError will be raised",
"e": 2077,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2245,
"s": 2077,
"text": "Traceback (most recent call last):\n File \"osremove.py\", line 11, in \n os.remove(path)\nIsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/ihritik'\n"
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # pathpath = '/home/User/Documents/ihritik' # Remove the specified # file pathtry: os.remove(path) print(\"% s removed successfully\" % path)except OSError as error: print(error) print(\"File path can not be removed\")",
"e": 2557,
"s": 2245,
"text": null
},
{
"code": null,
"e": 2645,
"s": 2557,
"text": "[Errno 21] Is a directory: '/home/User/Documents/ihritik'\nFile path can not be removed\n"
},
{
"code": null,
"e": 2698,
"s": 2645,
"text": "Reference: https://docs.python.org/3/library/os.html"
},
{
"code": null,
"e": 2720,
"s": 2698,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 2737,
"s": 2720,
"text": "python-os-module"
},
{
"code": null,
"e": 2744,
"s": 2737,
"text": "Python"
},
{
"code": null,
"e": 2842,
"s": 2744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2860,
"s": 2842,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2902,
"s": 2860,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2924,
"s": 2902,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2959,
"s": 2924,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2985,
"s": 2959,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3017,
"s": 2985,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3046,
"s": 3017,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3073,
"s": 3046,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3103,
"s": 3073,
"text": "Iterate over a list in Python"
}
] |
Search Text in MongoDB
|
08 Mar, 2021
MongoDB provides a good technique that is text search. Using this technique we can find a piece of text or a specified word from the string fields. Or in other words, MongoDB allows you to perform a query operation to find the specified text from the string. In MongoDB, we can perform text search using text index and $text operator.
Text index: MongoDB proved text indexes that are used to find the specified text from the string content. Text indexes should be either a string or an array of string elements. When you perform a text search query always remember that your collection must contain a text index and a collection can only contain one text index but this single text index covers multiple fields. We can create a text index using createIndex() method.
Syntax:
db.collectionName.createIndex( { field: “text” } )
$text Operator: You can also search text index using the $text operator. This operator is used to perform text search operations on the collection with a text index. This operator tokenized each search string with whitespace and it treats most punctuations as delimiters except – and \”. After tokenizing the search string it performs logical OR operation on the tokens. If you want to sort the resultant documents then use the $meta query operator.
Syntax:
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
Using the following steps we can search text in MongoDB:
Step 1: First, we create a collection and add some documents to the collection:
In the following example, we are working with:
Database: gfg
Collection: content
Document: The content collection contains the three documents.
Step 2: Create index:
Now we create a string index on the name and pet field with the help of the createIndex() method. So we can search text over the name and line fields:
db.content.createIndex({name:"text",line:"text"})
Step 3: Search Text:
Now we are ready to search text. For example, we are going to search all the document which contain text love.
db.content.find({$text:{$search:"love"}})
Note: $text is a query operator that performs text searches on a collection with a text index.
One more example in which we are going to search all the document which contain dog text:
db.content.find({$text:{$search:"dog"}})
Instead of searching a single word you are also allowed to search for a phrase by wrapping the phrase in double quotes(“”). Generally, the phrase search performs OR operation in between the specified keywords. For example, the phrase is “I like Mango”, then phase search looks for all the documents that contain keywords either I, like, or Mango. And if you want to perform an exact phrase search then wrap the phase in between escaped double quotes(\”).
Syntax:
For Phrase search:
db.collectionName.find({$text:{$search:”Phrase”}})
For exact phrase search:
db.collectionName.find({$text:{$search:”\”Phrase”\”}})
Examples:
In the following examples, we are working with:
Database: gfg
Collection: content
Document: The content collection contains the three documents.
Find the phrase:
db.content.find({$text:{$search:"I love dogs"}})
Here, we search for the phrase “I love dogs”. So, in the result, we get all the documents that contain keywords I, love, or dogs.
Find the exact phrase:
db.content.find({$text:{$search:"\"I love dogs\""}})
Here, we search for the exact phrase by wrapping the phase in between escaped double quotes(\”).i.e., “\”I love dogs\””. So, in the result, we only get those documents that contain the specified exact phrase.
Exclusion of term means when you perform search operation and does not want to display the document that contains the specified term, so you can exclude the term by prefixing a search keyword with the minus sign(-). Using minus sign(-) you can exclude all the documents that contain exclude term. For example, you want to display all the documents that contain the keyword “Car” but not the “Cycle” keyword so you can use the following query:
dn.collectionName.find({$text:{$search:"Car -Cycle"}})
For Example:
In the following example, we are working with:
Database: gfg
Collection: content
Document: The content collection contains the three documents.
db.content.find({$text:{$search:"dog -cow"}})
Here, we only display those documents that contain dog not cow.
We can search text using the aggregation pipeline with the help of the $text query operator in the $match stage. But there are some restrictions for using the $text operator:
The first stage in the pipeline must be the $match stage that contains the $text operator.
Only once in the stage will a text operator occur.
The expression of the text operator cannot appear in expressions of $or or $not.
By default, the text search does not return matching documents in the order of the matched scores. If you want to sort in descending score, then use the $meta aggregation expression in the $sort stage.
Note: Text score is a score that is assigned to each document that holds the search term in the index field by the $text operator. The score reflects a document’s importance to a given text search query.
Example:
In the following example, we are working with:
Database: gfg
Collection: people
Document: The people collection contains the five documents.
Count the number of the document in which pet value is a cat:
db.people.aggregate([{$match:{$text:{$search:"Cat"}}},
{$group:{_id:null,total:{$sum:1}}}])
Count the number of the document in which pet value is a dog:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$group:{_id:null,total:{$sum:1}}}])
Return the Sorted result by using text score:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$sort:{score:{$meta:"textScore"}}},
{$project:{_id:0,name:1}}])
Here, we return the result(all the documents that contain the specified text,i.e., “Dog”) in the sorted form using textScore.
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB Cursor
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
Mongoose | update() Function
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 389,
"s": 54,
"text": "MongoDB provides a good technique that is text search. Using this technique we can find a piece of text or a specified word from the string fields. Or in other words, MongoDB allows you to perform a query operation to find the specified text from the string. In MongoDB, we can perform text search using text index and $text operator."
},
{
"code": null,
"e": 822,
"s": 389,
"text": "Text index: MongoDB proved text indexes that are used to find the specified text from the string content. Text indexes should be either a string or an array of string elements. When you perform a text search query always remember that your collection must contain a text index and a collection can only contain one text index but this single text index covers multiple fields. We can create a text index using createIndex() method. "
},
{
"code": null,
"e": 830,
"s": 822,
"text": "Syntax:"
},
{
"code": null,
"e": 881,
"s": 830,
"text": "db.collectionName.createIndex( { field: “text” } )"
},
{
"code": null,
"e": 1331,
"s": 881,
"text": "$text Operator: You can also search text index using the $text operator. This operator is used to perform text search operations on the collection with a text index. This operator tokenized each search string with whitespace and it treats most punctuations as delimiters except – and \\”. After tokenizing the search string it performs logical OR operation on the tokens. If you want to sort the resultant documents then use the $meta query operator."
},
{
"code": null,
"e": 1339,
"s": 1331,
"text": "Syntax:"
},
{
"code": null,
"e": 1346,
"s": 1339,
"text": "$text:"
},
{
"code": null,
"e": 1348,
"s": 1346,
"text": "{"
},
{
"code": null,
"e": 1372,
"s": 1348,
"text": " $search: <string>,"
},
{
"code": null,
"e": 1398,
"s": 1372,
"text": " $language: <string>,"
},
{
"code": null,
"e": 1430,
"s": 1398,
"text": " $caseSensitive: <boolean>,"
},
{
"code": null,
"e": 1466,
"s": 1430,
"text": " $diacriticSensitive: <boolean>"
},
{
"code": null,
"e": 1468,
"s": 1466,
"text": "}"
},
{
"code": null,
"e": 1525,
"s": 1468,
"text": "Using the following steps we can search text in MongoDB:"
},
{
"code": null,
"e": 1607,
"s": 1525,
"text": "Step 1: First, we create a collection and add some documents to the collection: "
},
{
"code": null,
"e": 1654,
"s": 1607,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 1668,
"s": 1654,
"text": "Database: gfg"
},
{
"code": null,
"e": 1688,
"s": 1668,
"text": "Collection: content"
},
{
"code": null,
"e": 1751,
"s": 1688,
"text": "Document: The content collection contains the three documents."
},
{
"code": null,
"e": 1773,
"s": 1751,
"text": "Step 2: Create index:"
},
{
"code": null,
"e": 1924,
"s": 1773,
"text": "Now we create a string index on the name and pet field with the help of the createIndex() method. So we can search text over the name and line fields:"
},
{
"code": null,
"e": 1974,
"s": 1924,
"text": "db.content.createIndex({name:\"text\",line:\"text\"})"
},
{
"code": null,
"e": 1995,
"s": 1974,
"text": "Step 3: Search Text:"
},
{
"code": null,
"e": 2106,
"s": 1995,
"text": "Now we are ready to search text. For example, we are going to search all the document which contain text love."
},
{
"code": null,
"e": 2150,
"s": 2106,
"text": "db.content.find({$text:{$search:\"love\"}}) "
},
{
"code": null,
"e": 2245,
"s": 2150,
"text": "Note: $text is a query operator that performs text searches on a collection with a text index."
},
{
"code": null,
"e": 2335,
"s": 2245,
"text": "One more example in which we are going to search all the document which contain dog text:"
},
{
"code": null,
"e": 2376,
"s": 2335,
"text": "db.content.find({$text:{$search:\"dog\"}})"
},
{
"code": null,
"e": 2831,
"s": 2376,
"text": "Instead of searching a single word you are also allowed to search for a phrase by wrapping the phrase in double quotes(“”). Generally, the phrase search performs OR operation in between the specified keywords. For example, the phrase is “I like Mango”, then phase search looks for all the documents that contain keywords either I, like, or Mango. And if you want to perform an exact phrase search then wrap the phase in between escaped double quotes(\\”)."
},
{
"code": null,
"e": 2839,
"s": 2831,
"text": "Syntax:"
},
{
"code": null,
"e": 2858,
"s": 2839,
"text": "For Phrase search:"
},
{
"code": null,
"e": 2909,
"s": 2858,
"text": "db.collectionName.find({$text:{$search:”Phrase”}})"
},
{
"code": null,
"e": 2934,
"s": 2909,
"text": "For exact phrase search:"
},
{
"code": null,
"e": 2989,
"s": 2934,
"text": "db.collectionName.find({$text:{$search:”\\”Phrase”\\”}})"
},
{
"code": null,
"e": 2999,
"s": 2989,
"text": "Examples:"
},
{
"code": null,
"e": 3047,
"s": 2999,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 3061,
"s": 3047,
"text": "Database: gfg"
},
{
"code": null,
"e": 3081,
"s": 3061,
"text": "Collection: content"
},
{
"code": null,
"e": 3144,
"s": 3081,
"text": "Document: The content collection contains the three documents."
},
{
"code": null,
"e": 3161,
"s": 3144,
"text": "Find the phrase:"
},
{
"code": null,
"e": 3210,
"s": 3161,
"text": "db.content.find({$text:{$search:\"I love dogs\"}})"
},
{
"code": null,
"e": 3340,
"s": 3210,
"text": "Here, we search for the phrase “I love dogs”. So, in the result, we get all the documents that contain keywords I, love, or dogs."
},
{
"code": null,
"e": 3363,
"s": 3340,
"text": "Find the exact phrase:"
},
{
"code": null,
"e": 3416,
"s": 3363,
"text": "db.content.find({$text:{$search:\"\\\"I love dogs\\\"\"}})"
},
{
"code": null,
"e": 3625,
"s": 3416,
"text": "Here, we search for the exact phrase by wrapping the phase in between escaped double quotes(\\”).i.e., “\\”I love dogs\\””. So, in the result, we only get those documents that contain the specified exact phrase."
},
{
"code": null,
"e": 4068,
"s": 3625,
"text": "Exclusion of term means when you perform search operation and does not want to display the document that contains the specified term, so you can exclude the term by prefixing a search keyword with the minus sign(-). Using minus sign(-) you can exclude all the documents that contain exclude term. For example, you want to display all the documents that contain the keyword “Car” but not the “Cycle” keyword so you can use the following query:"
},
{
"code": null,
"e": 4123,
"s": 4068,
"text": "dn.collectionName.find({$text:{$search:\"Car -Cycle\"}})"
},
{
"code": null,
"e": 4136,
"s": 4123,
"text": "For Example:"
},
{
"code": null,
"e": 4183,
"s": 4136,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 4197,
"s": 4183,
"text": "Database: gfg"
},
{
"code": null,
"e": 4217,
"s": 4197,
"text": "Collection: content"
},
{
"code": null,
"e": 4280,
"s": 4217,
"text": "Document: The content collection contains the three documents."
},
{
"code": null,
"e": 4326,
"s": 4280,
"text": "db.content.find({$text:{$search:\"dog -cow\"}})"
},
{
"code": null,
"e": 4390,
"s": 4326,
"text": "Here, we only display those documents that contain dog not cow."
},
{
"code": null,
"e": 4565,
"s": 4390,
"text": "We can search text using the aggregation pipeline with the help of the $text query operator in the $match stage. But there are some restrictions for using the $text operator:"
},
{
"code": null,
"e": 4656,
"s": 4565,
"text": "The first stage in the pipeline must be the $match stage that contains the $text operator."
},
{
"code": null,
"e": 4707,
"s": 4656,
"text": "Only once in the stage will a text operator occur."
},
{
"code": null,
"e": 4788,
"s": 4707,
"text": "The expression of the text operator cannot appear in expressions of $or or $not."
},
{
"code": null,
"e": 4990,
"s": 4788,
"text": "By default, the text search does not return matching documents in the order of the matched scores. If you want to sort in descending score, then use the $meta aggregation expression in the $sort stage."
},
{
"code": null,
"e": 5194,
"s": 4990,
"text": "Note: Text score is a score that is assigned to each document that holds the search term in the index field by the $text operator. The score reflects a document’s importance to a given text search query."
},
{
"code": null,
"e": 5203,
"s": 5194,
"text": "Example:"
},
{
"code": null,
"e": 5250,
"s": 5203,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 5264,
"s": 5250,
"text": "Database: gfg"
},
{
"code": null,
"e": 5283,
"s": 5264,
"text": "Collection: people"
},
{
"code": null,
"e": 5344,
"s": 5283,
"text": "Document: The people collection contains the five documents."
},
{
"code": null,
"e": 5406,
"s": 5344,
"text": "Count the number of the document in which pet value is a cat:"
},
{
"code": null,
"e": 5511,
"s": 5406,
"text": "db.people.aggregate([{$match:{$text:{$search:\"Cat\"}}},\n {$group:{_id:null,total:{$sum:1}}}])"
},
{
"code": null,
"e": 5573,
"s": 5511,
"text": "Count the number of the document in which pet value is a dog:"
},
{
"code": null,
"e": 5678,
"s": 5573,
"text": "db.people.aggregate([{$match:{$text:{$search:\"Dog\"}}},\n {$group:{_id:null,total:{$sum:1}}}])"
},
{
"code": null,
"e": 5724,
"s": 5678,
"text": "Return the Sorted result by using text score:"
},
{
"code": null,
"e": 5886,
"s": 5724,
"text": "db.people.aggregate([{$match:{$text:{$search:\"Dog\"}}},\n {$sort:{score:{$meta:\"textScore\"}}},\n {$project:{_id:0,name:1}}])"
},
{
"code": null,
"e": 6012,
"s": 5886,
"text": "Here, we return the result(all the documents that contain the specified text,i.e., “Dog”) in the sorted form using textScore."
},
{
"code": null,
"e": 6020,
"s": 6012,
"text": "MongoDB"
},
{
"code": null,
"e": 6027,
"s": 6020,
"text": "Picked"
},
{
"code": null,
"e": 6035,
"s": 6027,
"text": "MongoDB"
},
{
"code": null,
"e": 6133,
"s": 6035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6171,
"s": 6133,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 6196,
"s": 6171,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 6220,
"s": 6196,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 6247,
"s": 6220,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 6302,
"s": 6247,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 6318,
"s": 6302,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 6333,
"s": 6318,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 6360,
"s": 6333,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 6417,
"s": 6360,
"text": "MongoDB updateMany() Method - db.Collection.updateMany()"
}
] |
Handling NameError Exception in Python
|
29 Jan, 2022
Prerequisites: Python Exception Handling
There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :
1. Misspelled built-in functions:
In the below example code, the print statement is misspelled hence NameError will be raised.
Python3
geek = input()print(geek)
Output :
NameError: name 'print' is not defined
2. Using undefined variables:
When the below program is executed, NameError will be raised as the variable geek is never defined.
Python3
geeky = input()print(geek)
Output :
NameError: name 'geek' is not defined
3. Defining variable after usage:
In the following example, even though the variable geek is defined in the program, it is defined after its usage. Since Python interprets the code from top to bottom, this will raise NameError
Python3
print(geek)geek = "GeeksforGeeks"
Output :
NameError: name 'geek' is not defined
4. Incorrect usage of scope:
In the below example program, the variable geek is defined within the local scope of the assign function. Hence, it cannot be accessed globally. This raises NameError.
Python3
def assign(): geek = "GeeksforGeeks" assign()print(geek)
Output :
NameError: name 'geek' is not defined
To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.
Python3
def geek_message(): try: geek = "GeeksforGeeks" return geeksforgeeks except NameError: return "NameError occurred. Some variable isn't defined." print(geek_message())
Output :
NameError occurred. Some variable isn't defined.
saurabh1990aror
sumitgumber28
Python-exceptions
Python
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
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jan, 2022"
},
{
"code": null,
"e": 94,
"s": 53,
"text": "Prerequisites: Python Exception Handling"
},
{
"code": null,
"e": 323,
"s": 94,
"text": "There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :"
},
{
"code": null,
"e": 357,
"s": 323,
"text": "1. Misspelled built-in functions:"
},
{
"code": null,
"e": 450,
"s": 357,
"text": "In the below example code, the print statement is misspelled hence NameError will be raised."
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Python3"
},
{
"code": "geek = input()print(geek)",
"e": 484,
"s": 458,
"text": null
},
{
"code": null,
"e": 494,
"s": 484,
"text": "Output : "
},
{
"code": null,
"e": 533,
"s": 494,
"text": "NameError: name 'print' is not defined"
},
{
"code": null,
"e": 563,
"s": 533,
"text": "2. Using undefined variables:"
},
{
"code": null,
"e": 663,
"s": 563,
"text": "When the below program is executed, NameError will be raised as the variable geek is never defined."
},
{
"code": null,
"e": 671,
"s": 663,
"text": "Python3"
},
{
"code": "geeky = input()print(geek)",
"e": 698,
"s": 671,
"text": null
},
{
"code": null,
"e": 709,
"s": 698,
"text": " Output : "
},
{
"code": null,
"e": 747,
"s": 709,
"text": "NameError: name 'geek' is not defined"
},
{
"code": null,
"e": 781,
"s": 747,
"text": "3. Defining variable after usage:"
},
{
"code": null,
"e": 974,
"s": 781,
"text": "In the following example, even though the variable geek is defined in the program, it is defined after its usage. Since Python interprets the code from top to bottom, this will raise NameError"
},
{
"code": null,
"e": 982,
"s": 974,
"text": "Python3"
},
{
"code": "print(geek)geek = \"GeeksforGeeks\"",
"e": 1016,
"s": 982,
"text": null
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": " Output : "
},
{
"code": null,
"e": 1065,
"s": 1027,
"text": "NameError: name 'geek' is not defined"
},
{
"code": null,
"e": 1094,
"s": 1065,
"text": "4. Incorrect usage of scope:"
},
{
"code": null,
"e": 1262,
"s": 1094,
"text": "In the below example program, the variable geek is defined within the local scope of the assign function. Hence, it cannot be accessed globally. This raises NameError."
},
{
"code": null,
"e": 1270,
"s": 1262,
"text": "Python3"
},
{
"code": "def assign(): geek = \"GeeksforGeeks\" assign()print(geek)",
"e": 1330,
"s": 1270,
"text": null
},
{
"code": null,
"e": 1341,
"s": 1330,
"text": " Output : "
},
{
"code": null,
"e": 1379,
"s": 1341,
"text": "NameError: name 'geek' is not defined"
},
{
"code": null,
"e": 1605,
"s": 1379,
"text": "To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console."
},
{
"code": null,
"e": 1613,
"s": 1605,
"text": "Python3"
},
{
"code": "def geek_message(): try: geek = \"GeeksforGeeks\" return geeksforgeeks except NameError: return \"NameError occurred. Some variable isn't defined.\" print(geek_message())",
"e": 1807,
"s": 1613,
"text": null
},
{
"code": null,
"e": 1817,
"s": 1807,
"text": "Output : "
},
{
"code": null,
"e": 1866,
"s": 1817,
"text": "NameError occurred. Some variable isn't defined."
},
{
"code": null,
"e": 1882,
"s": 1866,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1896,
"s": 1882,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1914,
"s": 1896,
"text": "Python-exceptions"
},
{
"code": null,
"e": 1921,
"s": 1914,
"text": "Python"
},
{
"code": null,
"e": 2019,
"s": 1921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2051,
"s": 2019,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2078,
"s": 2051,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2099,
"s": 2078,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2130,
"s": 2099,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2186,
"s": 2130,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2209,
"s": 2186,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2251,
"s": 2209,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2293,
"s": 2251,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2332,
"s": 2293,
"text": "Python | datetime.timedelta() function"
}
] |
How to use Docker Default Bridge Networking?
|
05 Nov, 2020
Docker allows you to create dedicated channels between multiple Docker Containers to create a network of Containers that can share files and other resources with each other. This is called Docker Networking. You can create Docker Networks with various kinds of Network Drivers which include Bridge drivers, McVLAN drivers, etc. By default, if you do not mention a driver while creating a network, it automatically chooses the default bridge driver. Bridge drivers are single-host networking drivers and hence their scope is limited to local.
In this article, we are going to discuss how to create, manage, and use Docker Bridge Networks. For this, you would need a Linux based Host machine with access to Docker. Without any further ado, let’s dive deep into Docker Bridged Networking.
Every installation of Docker provides a pre-built default Bridge Network with Bridge driver scoped locally. You can verify the same using the network ls command.
sudo docker network ls
Bridge Driver always provides single-host networking hence, the scope is local.
Note that the Bridge Network we saw in the previous step is the default network for Docker Containers. If you don’t specify any other network, all new Containers will be joined to this default network. To connect an Ubuntu Container to the default bridge network, use this command.
sudo docker run -dt ubuntu
After you have created the Docker Container, check whether it is running or not.
sudo docker container ls
Since the Container is already running, we can now use the network inspect command to inspect the Docker default bridge network.
sudo docker network inspect bridge
You can see the details related to the Bridge Network in JSON format. You can also check the Containers associated with the network in the Container object.
To test the network connectivity, note down the IP address of the Container. In this example, the IP address is “172.17.0.2/16”.
We will ping this address from the Docker Host to check the connectivity.
ping 172.17.0.2
It shows that the host is able to ping the Docker Container in the network.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Fuzzy Logic | Introduction
Monolithic vs Microservices architecture
OpenCV - Overview
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 570,
"s": 28,
"text": "Docker allows you to create dedicated channels between multiple Docker Containers to create a network of Containers that can share files and other resources with each other. This is called Docker Networking. You can create Docker Networks with various kinds of Network Drivers which include Bridge drivers, McVLAN drivers, etc. By default, if you do not mention a driver while creating a network, it automatically chooses the default bridge driver. Bridge drivers are single-host networking drivers and hence their scope is limited to local."
},
{
"code": null,
"e": 814,
"s": 570,
"text": "In this article, we are going to discuss how to create, manage, and use Docker Bridge Networks. For this, you would need a Linux based Host machine with access to Docker. Without any further ado, let’s dive deep into Docker Bridged Networking."
},
{
"code": null,
"e": 976,
"s": 814,
"text": "Every installation of Docker provides a pre-built default Bridge Network with Bridge driver scoped locally. You can verify the same using the network ls command."
},
{
"code": null,
"e": 1001,
"s": 976,
"text": "sudo docker network ls\n\n"
},
{
"code": null,
"e": 1081,
"s": 1001,
"text": "Bridge Driver always provides single-host networking hence, the scope is local."
},
{
"code": null,
"e": 1363,
"s": 1081,
"text": "Note that the Bridge Network we saw in the previous step is the default network for Docker Containers. If you don’t specify any other network, all new Containers will be joined to this default network. To connect an Ubuntu Container to the default bridge network, use this command."
},
{
"code": null,
"e": 1393,
"s": 1363,
"text": "sudo docker run -dt ubuntu \n\n"
},
{
"code": null,
"e": 1474,
"s": 1393,
"text": "After you have created the Docker Container, check whether it is running or not."
},
{
"code": null,
"e": 1501,
"s": 1474,
"text": "sudo docker container ls\n\n"
},
{
"code": null,
"e": 1630,
"s": 1501,
"text": "Since the Container is already running, we can now use the network inspect command to inspect the Docker default bridge network."
},
{
"code": null,
"e": 1667,
"s": 1630,
"text": "sudo docker network inspect bridge\n\n"
},
{
"code": null,
"e": 1824,
"s": 1667,
"text": "You can see the details related to the Bridge Network in JSON format. You can also check the Containers associated with the network in the Container object."
},
{
"code": null,
"e": 1953,
"s": 1824,
"text": "To test the network connectivity, note down the IP address of the Container. In this example, the IP address is “172.17.0.2/16”."
},
{
"code": null,
"e": 2027,
"s": 1953,
"text": "We will ping this address from the Docker Host to check the connectivity."
},
{
"code": null,
"e": 2045,
"s": 2027,
"text": "ping 172.17.0.2\n\n"
},
{
"code": null,
"e": 2121,
"s": 2045,
"text": "It shows that the host is able to ping the Docker Container in the network."
},
{
"code": null,
"e": 2138,
"s": 2121,
"text": "Docker Container"
},
{
"code": null,
"e": 2144,
"s": 2138,
"text": "linux"
},
{
"code": null,
"e": 2170,
"s": 2144,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2268,
"s": 2170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2304,
"s": 2268,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2328,
"s": 2304,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2364,
"s": 2328,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2408,
"s": 2364,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2443,
"s": 2408,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2484,
"s": 2443,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 2532,
"s": 2484,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 2559,
"s": 2532,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 2600,
"s": 2559,
"text": "Monolithic vs Microservices architecture"
}
] |
Selenium - Multi Select Action
|
Sometimes we would be in a situation to select two or more items in a list box or text area. To understand the same, we would demonstrate multiple selection from the list using 'https://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'.
Let us say, we want to select 3 items from this list as shown below -
Let us see how to code for this functionality −
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
public class webdriverdemo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx");
//driver.manage().window().maximize();
driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click();
driver.findElement(By.id("ContentHolder_lbSelectionMode_DDD_L_LBI1T0")).click();
Thread.sleep(5000);
// Perform Multiple Select
Actions builder = new Actions(driver);
WebElement select = driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
List<WebElement> options = select.findElements(By.tagName("td"));
System.out.println(options.size());
Action multipleSelect =
builder.keyDown(Keys.CONTROL).click(options.get(2)).click(options.get(4)).click(options.get(6)).build();
multipleSelect.perform();
driver.close();
}
}
Upon executing the script, the items would be selected as displayed above and the size of the list box would also be printed in the console.
|
[
{
"code": null,
"e": 2264,
"s": 2009,
"text": "Sometimes we would be in a situation to select two or more items in a list box or text area. To understand the same, we would demonstrate multiple selection from the list using 'https://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'."
},
{
"code": null,
"e": 2334,
"s": 2264,
"text": "Let us say, we want to select 3 items from this list as shown below -"
},
{
"code": null,
"e": 2382,
"s": 2334,
"text": "Let us see how to code for this functionality −"
},
{
"code": null,
"e": 3690,
"s": 2382,
"text": "import java.util.List;\nimport java.util.concurrent.TimeUnit;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport org.openqa.selenium.interactions.Actions;\nimport org.openqa.selenium.interactions.Action;\n\npublic class webdriverdemo {\n\n public static void main(String[] args) throws InterruptedException {\n \n WebDriver driver = new FirefoxDriver();\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n\n driver.navigate().to(\"http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx\");\n\n //driver.manage().window().maximize();\n driver.findElement(By.id(\"ContentHolder_lbSelectionMode_I\")).click();\n driver.findElement(By.id(\"ContentHolder_lbSelectionMode_DDD_L_LBI1T0\")).click();\n Thread.sleep(5000);\n \n // Perform Multiple Select\n Actions builder = new Actions(driver);\n WebElement select = driver.findElement(By.id(\"ContentHolder_lbFeatures_LBT\"));\n List<WebElement> options = select.findElements(By.tagName(\"td\"));\n \n System.out.println(options.size());\n Action multipleSelect = \n builder.keyDown(Keys.CONTROL).click(options.get(2)).click(options.get(4)).click(options.get(6)).build();\n \n multipleSelect.perform();\n driver.close();\n }\n}"
}
] |
How to call a function when content of a div changes using jQuery ?
|
24 May, 2021
The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up.
.change(): This method will only trigger when some change occurs in the element or field. It accepts an optional function as an argument that will perform some kind of work.
Syntax:
$(selector).change(function())
selector: It will select an element on which we have to perform this task.
function(): It is an optional argument that will specify the function to run when the change event occurs for the selected elements.
Approach 1: In this approach, we are going to implement its execution without taking any parameter such as function.
First, create an input box with some value and onChange attribute.
Create a button and map it to the script where you have written the change method without any argument.
Explanation: When you click a button trigger change event of the input field occurs and pop-up window will appear and display whatever present in the input field.
Example 1:
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("input").change(); }); }); </script></head> <body> <p> <h1> Press enter to see the pop-up. which says whatever written in the input field </h1> </p> <p>Enter anything you wish to: <input value="GeeksForGeeks" onchange="alert(this.value)" type="text"></p> <button> Trigger change event for input field </button></body> </html>
Output:
Before click:
After click:
Approach 2: In this approach, we are going to implement its execution with the help of function as an argument in the change method.
Make an input field of text type.
Map input element to the change() method and write some text to show on function call.
Explanation: When you enter something in the input field and press enter then the change event will run and executes the function and show the message that is written in the function.
Example 2:
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("input").change(function(){ alert("Welcome geek you have changed something."); }); }); </script></head> <body> <input type="text"> <p><h1> Enter something and press enter to see the effect. <h1></p></body> </html>
Output:
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the value in an input text box using jQuery ?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
jQuery | parent() & parents() with Examples
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": 28,
"s": 0,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up."
},
{
"code": null,
"e": 442,
"s": 268,
"text": ".change(): This method will only trigger when some change occurs in the element or field. It accepts an optional function as an argument that will perform some kind of work."
},
{
"code": null,
"e": 450,
"s": 442,
"text": "Syntax:"
},
{
"code": null,
"e": 481,
"s": 450,
"text": "$(selector).change(function())"
},
{
"code": null,
"e": 556,
"s": 481,
"text": "selector: It will select an element on which we have to perform this task."
},
{
"code": null,
"e": 689,
"s": 556,
"text": "function(): It is an optional argument that will specify the function to run when the change event occurs for the selected elements."
},
{
"code": null,
"e": 806,
"s": 689,
"text": "Approach 1: In this approach, we are going to implement its execution without taking any parameter such as function."
},
{
"code": null,
"e": 873,
"s": 806,
"text": "First, create an input box with some value and onChange attribute."
},
{
"code": null,
"e": 977,
"s": 873,
"text": "Create a button and map it to the script where you have written the change method without any argument."
},
{
"code": null,
"e": 1140,
"s": 977,
"text": "Explanation: When you click a button trigger change event of the input field occurs and pop-up window will appear and display whatever present in the input field."
},
{
"code": null,
"e": 1152,
"s": 1140,
"text": "Example 1: "
},
{
"code": null,
"e": 1157,
"s": 1152,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function(){ $(\"button\").click(function(){ $(\"input\").change(); }); }); </script></head> <body> <p> <h1> Press enter to see the pop-up. which says whatever written in the input field </h1> </p> <p>Enter anything you wish to: <input value=\"GeeksForGeeks\" onchange=\"alert(this.value)\" type=\"text\"></p> <button> Trigger change event for input field </button></body> </html>",
"e": 1827,
"s": 1157,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "Output:"
},
{
"code": null,
"e": 1849,
"s": 1835,
"text": "Before click:"
},
{
"code": null,
"e": 1862,
"s": 1849,
"text": "After click:"
},
{
"code": null,
"e": 1995,
"s": 1862,
"text": "Approach 2: In this approach, we are going to implement its execution with the help of function as an argument in the change method."
},
{
"code": null,
"e": 2029,
"s": 1995,
"text": "Make an input field of text type."
},
{
"code": null,
"e": 2116,
"s": 2029,
"text": "Map input element to the change() method and write some text to show on function call."
},
{
"code": null,
"e": 2300,
"s": 2116,
"text": "Explanation: When you enter something in the input field and press enter then the change event will run and executes the function and show the message that is written in the function."
},
{
"code": null,
"e": 2311,
"s": 2300,
"text": "Example 2:"
},
{
"code": null,
"e": 2316,
"s": 2311,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function(){ $(\"input\").change(function(){ alert(\"Welcome geek you have changed something.\"); }); }); </script></head> <body> <input type=\"text\"> <p><h1> Enter something and press enter to see the effect. <h1></p></body> </html>",
"e": 2774,
"s": 2316,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2774,
"text": "Output:"
},
{
"code": null,
"e": 2797,
"s": 2782,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 2814,
"s": 2797,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 2821,
"s": 2814,
"text": "Picked"
},
{
"code": null,
"e": 2828,
"s": 2821,
"text": "JQuery"
},
{
"code": null,
"e": 2845,
"s": 2828,
"text": "Web Technologies"
},
{
"code": null,
"e": 2943,
"s": 2845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3000,
"s": 2943,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 3073,
"s": 3000,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 3096,
"s": 3073,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 3132,
"s": 3096,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 3176,
"s": 3132,
"text": "jQuery | parent() & parents() with Examples"
},
{
"code": null,
"e": 3238,
"s": 3176,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3271,
"s": 3238,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3332,
"s": 3271,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3382,
"s": 3332,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Flutter – Draggable Scrollable Sheet
|
16 Aug, 2021
In this tutorial, we are going to learn what the DraggableScrollableSheet widget is and how to implement it in Flutter.
What is Flutter
DraggableScrollableSheet
Project Setup
Project Code
Flutter is an open-source UI software development kit created by Google with which we can develop applications for Android, IOS, Desktop, and Web with a single codebase.
A DraggableScrollableSheet is a widget in Flutter that responds to drag gestures by resizing the scrollable.
In this tutorial, we are going to make an Animal Details app wherein the main screen will be a list of animals and we will create a DraggableScrollableSheet widget to display the features of animals. The app will be focused on the DraggableScrollableSheet widget.
Let’s get started by creating a new project. Enter the following command on Command Prompt / Terminal in your preferred directory or you can also use your existing project.
flutter create draggable_scrollable_sheet_tutorial
We don’t need any extra packages for this tutorial.
The Starting code is here and is in the main.dart file.
Dart
import 'dart:math';import 'dart:ui'; import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Container(), ), ); }}
We are going to use the Stack Widget to display the main screen in the background and the draggable Sheet widget in the front.
So, use Stack as the child of the Container.
Dart
Container( child: Stack( children: [], ),),
So let us create a separate ListView widget with some animal names. We will name it animalsList.
Dart
Widget animalsList() { return ListView( children: [], );}
Now we will create some ListTiles with names of animals. But here we are going to create a separate ListTile widget and we will name it animalListTile. We are going to do this for simplifying our code.
Dart
Widget animalListTile(int index, String animalName) { return ListTile( onTap: () { print(index); }, title: Text(animalName), );}
Here we are taking to parameters, first is the index of ListTile and the second is animalName. We are using the index to update the DraggableScrollableSheet. The animalName is for the name of the animal.
Now let us create our DraggableScrollableSheet. Create a separate widget and name it bottomDetailsSheet.
Dart
Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: , minChildSize: , maxChildSize: , builder: (BuildContext context, ScrollController scrollController) { return Container(); }, );}
Now here we have got so many new parameters. Let’s learn about them one by one.
initialChildSize: This field specifies the initial size of the bottom draggable sheet you want to appear on the fraction of the screen and takes a double value. Its default value is 0.5. Its value range from 0 – 1.0.
minChildSize: This field specifies the minimum size of the DraggableScrollableSheet widget that is when any user will scroll down to close the widget, the minimum height will appear. Its default value is 0.25 and ranges from 0 – 1.0. It also specifies the fraction of the screen to be occupied.
maxChildSize: This field specifies the maximum size of the DraggableScrollableSheet widget that is when any user will scroll up to open the widget, the maximum height will appear. Its default value is 1.0 and ranges from 0 – 1.0. It also specifies the fraction of the screen to be occupied.
builder: This function returns a widget. Here we will use a ListView and display the details of the animal tapped. By default, we will display the details of the first animal.
expand: This field specifies whether the widget should expand to fill the available space in its parent or not. The default value is true. We have not specified because we want it to be true.
Let us specify the first three fields.
Dart
initialChildSize: .2,minChildSize: .1,maxChildSize: .6,
Let us create variables for our app. You can copy from below. All variables are self-explanatory.
Dart
List<String> animalNames = ['Elephant', 'Tiger', 'Kangaroo'];List<String> animalFamily = ['Elephantidae', 'Panthera', 'Macropodidae'];List<String> animalLifeSpan = ['60-70', '8-10', '15-20'];List<String> animalWeight = ['2700-6000', '90-310', '47-66'];int selectedTile = 0;
Now let us design the builder function. Designing is your own choice and so you can either proceed by copying my design or your own. Here is the full design of DraggableScrollableSheet.
Dart
Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: .2, minChildSize: .1, maxChildSize: .6, builder: (BuildContext context, ScrollController scrollController) { return Container( color: Colors.lightGreen[100], child: ListView( controller: scrollController, children: [ ListTile( title: Text( "NAME", ), subtitle: Text( animalNames[selectedTile], ), ), ListTile( title: Text( "FAMILY", ), subtitle: Text( animalFamily[selectedTile], ), ), ListTile( title: Text( "LIFESPAN", ), subtitle: Text( animalLifeSpan[selectedTile], ), ), ListTile( title: Text( "WEIGHT", ), subtitle: Text( animalWeight[selectedTile], ), ), ], ), ); }, );}
Here we used the ScrollController scrollController to make our list scrollable.
If you run the app you will see as follows.
DraggableScrollableSheet
And now is the time for the animalList widget. We have already created our widget. Add the animalListTile widget as children of animalList.
Dart
Widget animalsList() { return ListView( children: [ animalListTile(0, animalNames[0]), animalListTile(1, animalNames[1]), animalListTile(2, animalNames[2]), ], );} Widget animalListTile(int index, String animalName) { return ListTile( onTap: () { print(index); }, title: Text(animalName), );}
Here instead of printing the index, we will change the selectedTile value. But we also need to design the active list tile so that we can distinguish which one is active. Also, we will tweak the design of the animalListTile. So here is the final design.
Dart
Widget animalListTile(int index, String animalName) { return Padding( padding: EdgeInsets.all(8.0), child: ListTile( onTap: () { setState(() { selectedTile = index; }); }, title: Text( animalName, style: TextStyle( color: Colors.brown, fontSize: 24.0, fontWeight: FontWeight.w600, ), ), tileColor: Colors.lightGreen[300], selected: index == selectedTile, selectedTileColor: Colors.lightGreen[600], ), );}
So our app is almost ready. Add the animalList in Stack widget’s children.
Dart
Stack( children: [ animalsList(), bottomDetailsSheet(), ],),
Now run the app.
Complete DraggableScrollableSheet App
We have successfully created our app. If you had any problems comment below. Also here is the full Code.
Dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'DraggableScrollableSheet GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { List<String> animalNames = ['Elephant', 'Tiger', 'Kangaroo']; List<String> animalFamily = ['Elephantidae', 'Panthera', 'Macropodidae']; List<String> animalLifeSpan = ['60-70', '8-10', '15-20']; List<String> animalWeight = ['2700-6000', '90-310', '47-66']; int selectedTile = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Container( child: Stack( children: [ animalsList(), bottomDetailsSheet(), ], ), ), ); } Widget animalsList() { return ListView( children: [ animalListTile(0, animalNames[0]), animalListTile(1, animalNames[1]), animalListTile(2, animalNames[2]), ], ); } Widget animalListTile(int index, String animalName) { return Padding( padding: EdgeInsets.all(8.0), child: ListTile( onTap: () { setState(() { selectedTile = index; }); }, title: Text( animalName, style: TextStyle( color: Colors.brown, fontSize: 24.0, fontWeight: FontWeight.w600, ), ), tileColor: Colors.lightGreen[300], selected: index == selectedTile, selectedTileColor: Colors.lightGreen[600], ), ); } Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: .2, minChildSize: .1, maxChildSize: .6, builder: (BuildContext context, ScrollController scrollController) { return Container( color: Colors.lightGreen[100], child: ListView( controller: scrollController, children: [ ListTile( title: Text( "NAME", ), subtitle: Text( animalNames[selectedTile], ), ), ListTile( title: Text( "FAMILY", ), subtitle: Text( animalFamily[selectedTile], ), ), ListTile( title: Text( "LIFESPAN", ), subtitle: Text( animalLifeSpan[selectedTile], ), ), ListTile( title: Text( "WEIGHT", ), subtitle: Text( animalWeight[selectedTile], ), ), ], ), ); }, ); }}
Hope you liked the tutorial. Thank you.
Flutter UI-components
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "In this tutorial, we are going to learn what the DraggableScrollableSheet widget is and how to implement it in Flutter."
},
{
"code": null,
"e": 164,
"s": 148,
"text": "What is Flutter"
},
{
"code": null,
"e": 189,
"s": 164,
"text": "DraggableScrollableSheet"
},
{
"code": null,
"e": 203,
"s": 189,
"text": "Project Setup"
},
{
"code": null,
"e": 216,
"s": 203,
"text": "Project Code"
},
{
"code": null,
"e": 386,
"s": 216,
"text": "Flutter is an open-source UI software development kit created by Google with which we can develop applications for Android, IOS, Desktop, and Web with a single codebase."
},
{
"code": null,
"e": 495,
"s": 386,
"text": "A DraggableScrollableSheet is a widget in Flutter that responds to drag gestures by resizing the scrollable."
},
{
"code": null,
"e": 759,
"s": 495,
"text": "In this tutorial, we are going to make an Animal Details app wherein the main screen will be a list of animals and we will create a DraggableScrollableSheet widget to display the features of animals. The app will be focused on the DraggableScrollableSheet widget."
},
{
"code": null,
"e": 933,
"s": 759,
"text": "Let’s get started by creating a new project. Enter the following command on Command Prompt / Terminal in your preferred directory or you can also use your existing project."
},
{
"code": null,
"e": 984,
"s": 933,
"text": "flutter create draggable_scrollable_sheet_tutorial"
},
{
"code": null,
"e": 1036,
"s": 984,
"text": "We don’t need any extra packages for this tutorial."
},
{
"code": null,
"e": 1092,
"s": 1036,
"text": "The Starting code is here and is in the main.dart file."
},
{
"code": null,
"e": 1097,
"s": 1092,
"text": "Dart"
},
{
"code": "import 'dart:math';import 'dart:ui'; import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Container(), ), ); }}",
"e": 1879,
"s": 1097,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1879,
"text": "We are going to use the Stack Widget to display the main screen in the background and the draggable Sheet widget in the front."
},
{
"code": null,
"e": 2051,
"s": 2006,
"text": "So, use Stack as the child of the Container."
},
{
"code": null,
"e": 2056,
"s": 2051,
"text": "Dart"
},
{
"code": "Container( child: Stack( children: [], ),),",
"e": 2105,
"s": 2056,
"text": null
},
{
"code": null,
"e": 2202,
"s": 2105,
"text": "So let us create a separate ListView widget with some animal names. We will name it animalsList."
},
{
"code": null,
"e": 2207,
"s": 2202,
"text": "Dart"
},
{
"code": "Widget animalsList() { return ListView( children: [], );}",
"e": 2270,
"s": 2207,
"text": null
},
{
"code": null,
"e": 2472,
"s": 2270,
"text": "Now we will create some ListTiles with names of animals. But here we are going to create a separate ListTile widget and we will name it animalListTile. We are going to do this for simplifying our code."
},
{
"code": null,
"e": 2477,
"s": 2472,
"text": "Dart"
},
{
"code": "Widget animalListTile(int index, String animalName) { return ListTile( onTap: () { print(index); }, title: Text(animalName), );}",
"e": 2622,
"s": 2477,
"text": null
},
{
"code": null,
"e": 2826,
"s": 2622,
"text": "Here we are taking to parameters, first is the index of ListTile and the second is animalName. We are using the index to update the DraggableScrollableSheet. The animalName is for the name of the animal."
},
{
"code": null,
"e": 2931,
"s": 2826,
"text": "Now let us create our DraggableScrollableSheet. Create a separate widget and name it bottomDetailsSheet."
},
{
"code": null,
"e": 2936,
"s": 2931,
"text": "Dart"
},
{
"code": "Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: , minChildSize: , maxChildSize: , builder: (BuildContext context, ScrollController scrollController) { return Container(); }, );}",
"e": 3169,
"s": 2936,
"text": null
},
{
"code": null,
"e": 3249,
"s": 3169,
"text": "Now here we have got so many new parameters. Let’s learn about them one by one."
},
{
"code": null,
"e": 3466,
"s": 3249,
"text": "initialChildSize: This field specifies the initial size of the bottom draggable sheet you want to appear on the fraction of the screen and takes a double value. Its default value is 0.5. Its value range from 0 – 1.0."
},
{
"code": null,
"e": 3761,
"s": 3466,
"text": "minChildSize: This field specifies the minimum size of the DraggableScrollableSheet widget that is when any user will scroll down to close the widget, the minimum height will appear. Its default value is 0.25 and ranges from 0 – 1.0. It also specifies the fraction of the screen to be occupied."
},
{
"code": null,
"e": 4052,
"s": 3761,
"text": "maxChildSize: This field specifies the maximum size of the DraggableScrollableSheet widget that is when any user will scroll up to open the widget, the maximum height will appear. Its default value is 1.0 and ranges from 0 – 1.0. It also specifies the fraction of the screen to be occupied."
},
{
"code": null,
"e": 4228,
"s": 4052,
"text": "builder: This function returns a widget. Here we will use a ListView and display the details of the animal tapped. By default, we will display the details of the first animal."
},
{
"code": null,
"e": 4420,
"s": 4228,
"text": "expand: This field specifies whether the widget should expand to fill the available space in its parent or not. The default value is true. We have not specified because we want it to be true."
},
{
"code": null,
"e": 4459,
"s": 4420,
"text": "Let us specify the first three fields."
},
{
"code": null,
"e": 4464,
"s": 4459,
"text": "Dart"
},
{
"code": "initialChildSize: .2,minChildSize: .1,maxChildSize: .6,",
"e": 4520,
"s": 4464,
"text": null
},
{
"code": null,
"e": 4619,
"s": 4520,
"text": "Let us create variables for our app. You can copy from below. All variables are self-explanatory. "
},
{
"code": null,
"e": 4624,
"s": 4619,
"text": "Dart"
},
{
"code": "List<String> animalNames = ['Elephant', 'Tiger', 'Kangaroo'];List<String> animalFamily = ['Elephantidae', 'Panthera', 'Macropodidae'];List<String> animalLifeSpan = ['60-70', '8-10', '15-20'];List<String> animalWeight = ['2700-6000', '90-310', '47-66'];int selectedTile = 0;",
"e": 4898,
"s": 4624,
"text": null
},
{
"code": null,
"e": 5084,
"s": 4898,
"text": "Now let us design the builder function. Designing is your own choice and so you can either proceed by copying my design or your own. Here is the full design of DraggableScrollableSheet."
},
{
"code": null,
"e": 5089,
"s": 5084,
"text": "Dart"
},
{
"code": "Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: .2, minChildSize: .1, maxChildSize: .6, builder: (BuildContext context, ScrollController scrollController) { return Container( color: Colors.lightGreen[100], child: ListView( controller: scrollController, children: [ ListTile( title: Text( \"NAME\", ), subtitle: Text( animalNames[selectedTile], ), ), ListTile( title: Text( \"FAMILY\", ), subtitle: Text( animalFamily[selectedTile], ), ), ListTile( title: Text( \"LIFESPAN\", ), subtitle: Text( animalLifeSpan[selectedTile], ), ), ListTile( title: Text( \"WEIGHT\", ), subtitle: Text( animalWeight[selectedTile], ), ), ], ), ); }, );}",
"e": 6239,
"s": 5089,
"text": null
},
{
"code": null,
"e": 6319,
"s": 6239,
"text": "Here we used the ScrollController scrollController to make our list scrollable."
},
{
"code": null,
"e": 6364,
"s": 6319,
"text": "If you run the app you will see as follows. "
},
{
"code": null,
"e": 6389,
"s": 6364,
"text": "DraggableScrollableSheet"
},
{
"code": null,
"e": 6529,
"s": 6389,
"text": "And now is the time for the animalList widget. We have already created our widget. Add the animalListTile widget as children of animalList."
},
{
"code": null,
"e": 6534,
"s": 6529,
"text": "Dart"
},
{
"code": "Widget animalsList() { return ListView( children: [ animalListTile(0, animalNames[0]), animalListTile(1, animalNames[1]), animalListTile(2, animalNames[2]), ], );} Widget animalListTile(int index, String animalName) { return ListTile( onTap: () { print(index); }, title: Text(animalName), );}",
"e": 6867,
"s": 6534,
"text": null
},
{
"code": null,
"e": 7121,
"s": 6867,
"text": "Here instead of printing the index, we will change the selectedTile value. But we also need to design the active list tile so that we can distinguish which one is active. Also, we will tweak the design of the animalListTile. So here is the final design."
},
{
"code": null,
"e": 7126,
"s": 7121,
"text": "Dart"
},
{
"code": "Widget animalListTile(int index, String animalName) { return Padding( padding: EdgeInsets.all(8.0), child: ListTile( onTap: () { setState(() { selectedTile = index; }); }, title: Text( animalName, style: TextStyle( color: Colors.brown, fontSize: 24.0, fontWeight: FontWeight.w600, ), ), tileColor: Colors.lightGreen[300], selected: index == selectedTile, selectedTileColor: Colors.lightGreen[600], ), );}",
"e": 7648,
"s": 7126,
"text": null
},
{
"code": null,
"e": 7723,
"s": 7648,
"text": "So our app is almost ready. Add the animalList in Stack widget’s children."
},
{
"code": null,
"e": 7728,
"s": 7723,
"text": "Dart"
},
{
"code": "Stack( children: [ animalsList(), bottomDetailsSheet(), ],),",
"e": 7797,
"s": 7728,
"text": null
},
{
"code": null,
"e": 7814,
"s": 7797,
"text": "Now run the app."
},
{
"code": null,
"e": 7852,
"s": 7814,
"text": "Complete DraggableScrollableSheet App"
},
{
"code": null,
"e": 7957,
"s": 7852,
"text": "We have successfully created our app. If you had any problems comment below. Also here is the full Code."
},
{
"code": null,
"e": 7962,
"s": 7957,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'DraggableScrollableSheet GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { List<String> animalNames = ['Elephant', 'Tiger', 'Kangaroo']; List<String> animalFamily = ['Elephantidae', 'Panthera', 'Macropodidae']; List<String> animalLifeSpan = ['60-70', '8-10', '15-20']; List<String> animalWeight = ['2700-6000', '90-310', '47-66']; int selectedTile = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), ), body: Container( child: Stack( children: [ animalsList(), bottomDetailsSheet(), ], ), ), ); } Widget animalsList() { return ListView( children: [ animalListTile(0, animalNames[0]), animalListTile(1, animalNames[1]), animalListTile(2, animalNames[2]), ], ); } Widget animalListTile(int index, String animalName) { return Padding( padding: EdgeInsets.all(8.0), child: ListTile( onTap: () { setState(() { selectedTile = index; }); }, title: Text( animalName, style: TextStyle( color: Colors.brown, fontSize: 24.0, fontWeight: FontWeight.w600, ), ), tileColor: Colors.lightGreen[300], selected: index == selectedTile, selectedTileColor: Colors.lightGreen[600], ), ); } Widget bottomDetailsSheet() { return DraggableScrollableSheet( initialChildSize: .2, minChildSize: .1, maxChildSize: .6, builder: (BuildContext context, ScrollController scrollController) { return Container( color: Colors.lightGreen[100], child: ListView( controller: scrollController, children: [ ListTile( title: Text( \"NAME\", ), subtitle: Text( animalNames[selectedTile], ), ), ListTile( title: Text( \"FAMILY\", ), subtitle: Text( animalFamily[selectedTile], ), ), ListTile( title: Text( \"LIFESPAN\", ), subtitle: Text( animalLifeSpan[selectedTile], ), ), ListTile( title: Text( \"WEIGHT\", ), subtitle: Text( animalWeight[selectedTile], ), ), ], ), ); }, ); }}",
"e": 11146,
"s": 7962,
"text": null
},
{
"code": null,
"e": 11186,
"s": 11146,
"text": "Hope you liked the tutorial. Thank you."
},
{
"code": null,
"e": 11208,
"s": 11186,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 11213,
"s": 11208,
"text": "Dart"
},
{
"code": null,
"e": 11221,
"s": 11213,
"text": "Flutter"
}
] |
Merge an array of size n into another array of size m+n
|
09 Jun, 2022
There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted. Input: array with m+n elements (mPlusN[]).
NA => Value is not filled/available in array mPlusN[]. There should be n such array blocks.Input: array with n elements (N[]).
Output: N[] merged into mPlusN[] (Modified mPlusN[])
Algorithm:
Let first array be mPlusN[] and other array be N[]
1) Move m elements of mPlusN[] to end.
2) Start from nth element of mPlusN[] and 0th
element of N[] and merge them into mPlusN[].
Below is the implementation of the above algorithm :
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Merge an array of// size n into another array of size m + n#include <bits/stdc++.h>using namespace std; /* Assuming -1 is filled for the places where element is not available */#define NA -1 /* Function to move m elements at the end of array mPlusN[] */void moveToEnd(int mPlusN[], int size){ int j = size - 1; for (int i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; }} /* Merges array N[] of size n into array mPlusN[] of size m+n*/int merge(int mPlusN[], int N[], int m, int n){ int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)||(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } }} /* Utility that prints out an array on a line */void printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl;} /* Driver code */int main(){ /* Initialize arrays */ int mPlusN[] = {2, 8, NA, NA, NA, 13, NA, 15, 20}; int N[] = {5, 7, 9, 25}; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m+n); return 0;}
// C program to Merge an array of// size n into another array of size m + n#include <stdio.h> /* Assuming -1 is filled for the places where element is not available */#define NA -1 /* Function to move m elements at the end of array mPlusN[] */void moveToEnd(int mPlusN[], int size){ int i = 0, j = size - 1; for (i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; }} /* Merges array N[] of size n into array mPlusN[] of size m+n*/int merge(int mPlusN[], int N[], int m, int n){ int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)|| (i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } }} /* Utility that prints out an array on a line */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n");} /* Driver code */int main(){ /* Initialize arrays */ int mPlusN[] = { 2, 8, NA, NA, NA, 13, NA, 15, 20 }; int N[] = { 5, 7, 9, 25 }; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m + n); return 0;}
// Java program to Merge an array of// size n into another array of size m + n class MergeArrays { /* Function to move m elements at the end of array * mPlusN[] */ void moveToEnd(int mPlusN[], int size) { int i, j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ void merge(int mPlusN[], int N[], int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(""); } // Driver Code public static void main(String[] args) { MergeArrays mergearray = new MergeArrays(); /* Initialize arrays */ int mPlusN[] = { 2, 8, -1, -1, -1, 13, -1, 15, 20 }; int N[] = { 5, 7, 9, 25 }; int n = N.length; int m = mPlusN.length - n; /*Move the m elements at the end of mPlusN*/ mergearray.moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ mergearray.merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ mergearray.printArray(mPlusN, m + n); }} // This code has been contributed by Mayank Jaiswal
# Python program to Merge an array of# size n into another array of size m + n NA = -1 # Function to move m elements# at the end of array mPlusN[] def moveToEnd(mPlusN, size): i = 0 j = size - 1 for i in range(size-1, -1, -1): if (mPlusN[i] != NA): mPlusN[j] = mPlusN[i] j -= 1 # Merges array N[]# of size n into array mPlusN[]# of size m+n def merge(mPlusN, N, m, n): i = n # Current index of i/p part of mPlusN[] j = 0 # Current index of N[] k = 0 # Current index of output mPlusN[] while (k < (m+n)): # Take an element from mPlusN[] if # a) value of the picked # element is smaller and we have # not reached end of it # b) We have reached end of N[] */ if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])): mPlusN[k] = mPlusN[i] k += 1 i += 1 else: # Otherwise take element from N[] mPlusN[k] = N[j] k += 1 j += 1 # Utility that prints# out an array on a line def printArray(arr, size): for i in range(size): print(arr[i], " ", end="") print() # Driver function to# test above functions # Initialize arraysmPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20]N = [5, 7, 9, 25]n = len(N) m = len(mPlusN) - n # Move the m elements# at the end of mPlusNmoveToEnd(mPlusN, m+n) # Merge N[] into mPlusN[]merge(mPlusN, N, m, n) # Print the resultant mPlusNprintArray(mPlusN, m+n) # This code is contributed# by Anant Agarwal.
// C# program to Merge an array of// size n into another array of size m + nusing System; class GFG { /* Function to move m elements at the end of array mPlusN[] */ public virtual void moveToEnd(int[] mPlusN, int size) { int i, j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ public virtual void merge(int[] mPlusN, int[] N, int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ public virtual void printArray(int[] arr, int size) { int i; for (i = 0; i < size; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(""); } // Driver Code public static void Main(string[] args) { GFG mergearray = new GFG(); /* Initialize arrays */ int[] mPlusN = new int[] { 2, 8, -1, -1, -1, 13, -1, 15, 20 }; int[] N = new int[] { 5, 7, 9, 25 }; int n = N.Length; int m = mPlusN.Length - n; /*Move the m elements at the end of mPlusN*/ mergearray.moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ mergearray.merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ mergearray.printArray(mPlusN, m + n); }} // This code is contributed by Shrikant13
<?php// PHP program to Merge an array// of size n into another array// of size m + n /* Assuming -1 is filled forthe places where element isnot available */$NA = -1; /* Function to move m elementsat the end of array mPlusN[] */function moveToEnd(&$mPlusN, $size){ global $NA; $j = $size - 1; for ($i = $size - 1; $i >= 0; $i--) if ($mPlusN[$i] != $NA) { $mPlusN[$j] = $mPlusN[$i]; $j--; }} /* Merges array N[] of size ninto array mPlusN[] of size m+n*/function merge(&$mPlusN, &$N, $m, $n){ $i = $n; /* Current index of i/p part of mPlusN[]*/ $j = 0; /* Current index of N[]*/ $k = 0; /* Current index of output mPlusN[]*/ while ($k < ($m + $n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if (($j == $n) || ($i < ($m + $n) && $mPlusN[$i] <= $N[$j])) { $mPlusN[$k] = $mPlusN[$i]; $k++; $i++; } else // Otherwise take element from N[] { $mPlusN[$k] = $N[$j]; $k++; $j++; }}} /* Utility that prints out an array on a line */function printArray(&$arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . " "; echo "\n";} // Driver Code /* Initialize arrays */$mPlusN = array(2, 8, $NA, $NA, $NA, 13, $NA, 15, 20);$N = array(5, 7, 9, 25); $n = sizeof($N);$m = sizeof($mPlusN) - $n; /* Move the m elements at the end of mPlusN*/moveToEnd($mPlusN, $m + $n); /* Merge N[] into mPlusN[] */merge($mPlusN, $N, $m, $n); /* Print the resultant mPlusN */printArray($mPlusN, $m+$n); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to Merge an array of// size n into another array of size m + n /* Function to move m elements at the end of array * mPlusN[] */ function moveToEnd(mPlusN,size) { let i = 0; let j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ function merge(mPlusN, N, m, n) { let i = n; /* Current index of i/p part of mPlusN[]*/ let j = 0; /* Current index of N[]*/ let k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ function printArray(arr,size) { let i = 0; for (i = 0; i < size; i++) { document.write(arr[i] + " "); } document.write("\n"); } // Driver Code /* Initialize arrays */ let mPlusN = [2, 8, -1, -1, -1, 13, -1, 15, 20]; let N = [ 5, 7, 9, 25] let n = N.length; let m = mPlusN.length - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m + n); // This code is contributed by avanitrachhadiya2155</script>
2 5 7 8 9 13 15 20 25
Time Complexity: O(m+n)
Auxiliary Space: O(1)
Please write comment if you find any bug in the above program or a better way to solve the same problem.
shrikanth13
ukasp
ShubhamMaurya3
rahulsharma9
avanitrachhadiya2155
codewithshinchan
Amazon
Brocade
Goldman Sachs
Juniper Networks
Linkedin
Microsoft
Quikr
Snapdeal
Synopsys
Zoho
Arrays
Zoho
Amazon
Microsoft
Snapdeal
Goldman Sachs
Linkedin
Brocade
Juniper Networks
Quikr
Synopsys
Arrays
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
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 317,
"s": 52,
"text": "There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted. Input: array with m+n elements (mPlusN[]). "
},
{
"code": null,
"e": 446,
"s": 317,
"text": "NA => Value is not filled/available in array mPlusN[]. There should be n such array blocks.Input: array with n elements (N[]). "
},
{
"code": null,
"e": 501,
"s": 446,
"text": "Output: N[] merged into mPlusN[] (Modified mPlusN[]) "
},
{
"code": null,
"e": 515,
"s": 503,
"text": "Algorithm: "
},
{
"code": null,
"e": 700,
"s": 515,
"text": "Let first array be mPlusN[] and other array be N[]\n1) Move m elements of mPlusN[] to end.\n2) Start from nth element of mPlusN[] and 0th \n element of N[] and merge them into mPlusN[]."
},
{
"code": null,
"e": 754,
"s": 700,
"text": "Below is the implementation of the above algorithm : "
},
{
"code": null,
"e": 758,
"s": 754,
"text": "C++"
},
{
"code": null,
"e": 760,
"s": 758,
"text": "C"
},
{
"code": null,
"e": 765,
"s": 760,
"text": "Java"
},
{
"code": null,
"e": 773,
"s": 765,
"text": "Python3"
},
{
"code": null,
"e": 776,
"s": 773,
"text": "C#"
},
{
"code": null,
"e": 780,
"s": 776,
"text": "PHP"
},
{
"code": null,
"e": 791,
"s": 780,
"text": "Javascript"
},
{
"code": "// C++ program to Merge an array of// size n into another array of size m + n#include <bits/stdc++.h>using namespace std; /* Assuming -1 is filled for the places where element is not available */#define NA -1 /* Function to move m elements at the end of array mPlusN[] */void moveToEnd(int mPlusN[], int size){ int j = size - 1; for (int i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; }} /* Merges array N[] of size n into array mPlusN[] of size m+n*/int merge(int mPlusN[], int N[], int m, int n){ int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)||(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } }} /* Utility that prints out an array on a line */void printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \"; cout << endl;} /* Driver code */int main(){ /* Initialize arrays */ int mPlusN[] = {2, 8, NA, NA, NA, 13, NA, 15, 20}; int N[] = {5, 7, 9, 25}; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m+n); return 0;}",
"e": 2508,
"s": 791,
"text": null
},
{
"code": "// C program to Merge an array of// size n into another array of size m + n#include <stdio.h> /* Assuming -1 is filled for the places where element is not available */#define NA -1 /* Function to move m elements at the end of array mPlusN[] */void moveToEnd(int mPlusN[], int size){ int i = 0, j = size - 1; for (i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; }} /* Merges array N[] of size n into array mPlusN[] of size m+n*/int merge(int mPlusN[], int N[], int m, int n){ int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)|| (i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } }} /* Utility that prints out an array on a line */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} /* Driver code */int main(){ /* Initialize arrays */ int mPlusN[] = { 2, 8, NA, NA, NA, 13, NA, 15, 20 }; int N[] = { 5, 7, 9, 25 }; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m + n); return 0;}",
"e": 4333,
"s": 2508,
"text": null
},
{
"code": "// Java program to Merge an array of// size n into another array of size m + n class MergeArrays { /* Function to move m elements at the end of array * mPlusN[] */ void moveToEnd(int mPlusN[], int size) { int i, j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ void merge(int mPlusN[], int N[], int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) System.out.print(arr[i] + \" \"); System.out.println(\"\"); } // Driver Code public static void main(String[] args) { MergeArrays mergearray = new MergeArrays(); /* Initialize arrays */ int mPlusN[] = { 2, 8, -1, -1, -1, 13, -1, 15, 20 }; int N[] = { 5, 7, 9, 25 }; int n = N.length; int m = mPlusN.length - n; /*Move the m elements at the end of mPlusN*/ mergearray.moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ mergearray.merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ mergearray.printArray(mPlusN, m + n); }} // This code has been contributed by Mayank Jaiswal",
"e": 6474,
"s": 4333,
"text": null
},
{
"code": "# Python program to Merge an array of# size n into another array of size m + n NA = -1 # Function to move m elements# at the end of array mPlusN[] def moveToEnd(mPlusN, size): i = 0 j = size - 1 for i in range(size-1, -1, -1): if (mPlusN[i] != NA): mPlusN[j] = mPlusN[i] j -= 1 # Merges array N[]# of size n into array mPlusN[]# of size m+n def merge(mPlusN, N, m, n): i = n # Current index of i/p part of mPlusN[] j = 0 # Current index of N[] k = 0 # Current index of output mPlusN[] while (k < (m+n)): # Take an element from mPlusN[] if # a) value of the picked # element is smaller and we have # not reached end of it # b) We have reached end of N[] */ if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])): mPlusN[k] = mPlusN[i] k += 1 i += 1 else: # Otherwise take element from N[] mPlusN[k] = N[j] k += 1 j += 1 # Utility that prints# out an array on a line def printArray(arr, size): for i in range(size): print(arr[i], \" \", end=\"\") print() # Driver function to# test above functions # Initialize arraysmPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20]N = [5, 7, 9, 25]n = len(N) m = len(mPlusN) - n # Move the m elements# at the end of mPlusNmoveToEnd(mPlusN, m+n) # Merge N[] into mPlusN[]merge(mPlusN, N, m, n) # Print the resultant mPlusNprintArray(mPlusN, m+n) # This code is contributed# by Anant Agarwal.",
"e": 7979,
"s": 6474,
"text": null
},
{
"code": "// C# program to Merge an array of// size n into another array of size m + nusing System; class GFG { /* Function to move m elements at the end of array mPlusN[] */ public virtual void moveToEnd(int[] mPlusN, int size) { int i, j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ public virtual void merge(int[] mPlusN, int[] N, int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ public virtual void printArray(int[] arr, int size) { int i; for (i = 0; i < size; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(\"\"); } // Driver Code public static void Main(string[] args) { GFG mergearray = new GFG(); /* Initialize arrays */ int[] mPlusN = new int[] { 2, 8, -1, -1, -1, 13, -1, 15, 20 }; int[] N = new int[] { 5, 7, 9, 25 }; int n = N.Length; int m = mPlusN.Length - n; /*Move the m elements at the end of mPlusN*/ mergearray.moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ mergearray.merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ mergearray.printArray(mPlusN, m + n); }} // This code is contributed by Shrikant13",
"e": 10293,
"s": 7979,
"text": null
},
{
"code": "<?php// PHP program to Merge an array// of size n into another array// of size m + n /* Assuming -1 is filled forthe places where element isnot available */$NA = -1; /* Function to move m elementsat the end of array mPlusN[] */function moveToEnd(&$mPlusN, $size){ global $NA; $j = $size - 1; for ($i = $size - 1; $i >= 0; $i--) if ($mPlusN[$i] != $NA) { $mPlusN[$j] = $mPlusN[$i]; $j--; }} /* Merges array N[] of size ninto array mPlusN[] of size m+n*/function merge(&$mPlusN, &$N, $m, $n){ $i = $n; /* Current index of i/p part of mPlusN[]*/ $j = 0; /* Current index of N[]*/ $k = 0; /* Current index of output mPlusN[]*/ while ($k < ($m + $n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if (($j == $n) || ($i < ($m + $n) && $mPlusN[$i] <= $N[$j])) { $mPlusN[$k] = $mPlusN[$i]; $k++; $i++; } else // Otherwise take element from N[] { $mPlusN[$k] = $N[$j]; $k++; $j++; }}} /* Utility that prints out an array on a line */function printArray(&$arr, $size){ for ($i = 0; $i < $size; $i++) echo $arr[$i] . \" \"; echo \"\\n\";} // Driver Code /* Initialize arrays */$mPlusN = array(2, 8, $NA, $NA, $NA, 13, $NA, 15, 20);$N = array(5, 7, 9, 25); $n = sizeof($N);$m = sizeof($mPlusN) - $n; /* Move the m elements at the end of mPlusN*/moveToEnd($mPlusN, $m + $n); /* Merge N[] into mPlusN[] */merge($mPlusN, $N, $m, $n); /* Print the resultant mPlusN */printArray($mPlusN, $m+$n); // This code is contributed// by ChitraNayal?>",
"e": 12112,
"s": 10293,
"text": null
},
{
"code": "<script>// Javascript program to Merge an array of// size n into another array of size m + n /* Function to move m elements at the end of array * mPlusN[] */ function moveToEnd(mPlusN,size) { let i = 0; let j = size - 1; for (i = size - 1; i >= 0; i--) { if (mPlusN[i] != -1) { mPlusN[j] = mPlusN[i]; j--; } } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ function merge(mPlusN, N, m, n) { let i = n; /* Current index of i/p part of mPlusN[]*/ let j = 0; /* Current index of N[]*/ let k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ function printArray(arr,size) { let i = 0; for (i = 0; i < size; i++) { document.write(arr[i] + \" \"); } document.write(\"\\n\"); } // Driver Code /* Initialize arrays */ let mPlusN = [2, 8, -1, -1, -1, 13, -1, 15, 20]; let N = [ 5, 7, 9, 25] let n = N.length; let m = mPlusN.length - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m + n); // This code is contributed by avanitrachhadiya2155</script>",
"e": 14154,
"s": 12112,
"text": null
},
{
"code": null,
"e": 14177,
"s": 14154,
"text": "2 5 7 8 9 13 15 20 25 "
},
{
"code": null,
"e": 14201,
"s": 14177,
"text": "Time Complexity: O(m+n)"
},
{
"code": null,
"e": 14223,
"s": 14201,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 14328,
"s": 14223,
"text": "Please write comment if you find any bug in the above program or a better way to solve the same problem."
},
{
"code": null,
"e": 14340,
"s": 14328,
"text": "shrikanth13"
},
{
"code": null,
"e": 14346,
"s": 14340,
"text": "ukasp"
},
{
"code": null,
"e": 14361,
"s": 14346,
"text": "ShubhamMaurya3"
},
{
"code": null,
"e": 14374,
"s": 14361,
"text": "rahulsharma9"
},
{
"code": null,
"e": 14395,
"s": 14374,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 14412,
"s": 14395,
"text": "codewithshinchan"
},
{
"code": null,
"e": 14419,
"s": 14412,
"text": "Amazon"
},
{
"code": null,
"e": 14427,
"s": 14419,
"text": "Brocade"
},
{
"code": null,
"e": 14441,
"s": 14427,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 14458,
"s": 14441,
"text": "Juniper Networks"
},
{
"code": null,
"e": 14467,
"s": 14458,
"text": "Linkedin"
},
{
"code": null,
"e": 14477,
"s": 14467,
"text": "Microsoft"
},
{
"code": null,
"e": 14483,
"s": 14477,
"text": "Quikr"
},
{
"code": null,
"e": 14492,
"s": 14483,
"text": "Snapdeal"
},
{
"code": null,
"e": 14501,
"s": 14492,
"text": "Synopsys"
},
{
"code": null,
"e": 14506,
"s": 14501,
"text": "Zoho"
},
{
"code": null,
"e": 14513,
"s": 14506,
"text": "Arrays"
},
{
"code": null,
"e": 14518,
"s": 14513,
"text": "Zoho"
},
{
"code": null,
"e": 14525,
"s": 14518,
"text": "Amazon"
},
{
"code": null,
"e": 14535,
"s": 14525,
"text": "Microsoft"
},
{
"code": null,
"e": 14544,
"s": 14535,
"text": "Snapdeal"
},
{
"code": null,
"e": 14558,
"s": 14544,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 14567,
"s": 14558,
"text": "Linkedin"
},
{
"code": null,
"e": 14575,
"s": 14567,
"text": "Brocade"
},
{
"code": null,
"e": 14592,
"s": 14575,
"text": "Juniper Networks"
},
{
"code": null,
"e": 14598,
"s": 14592,
"text": "Quikr"
},
{
"code": null,
"e": 14607,
"s": 14598,
"text": "Synopsys"
},
{
"code": null,
"e": 14614,
"s": 14607,
"text": "Arrays"
},
{
"code": null,
"e": 14712,
"s": 14614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14780,
"s": 14712,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14824,
"s": 14780,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 14856,
"s": 14824,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14904,
"s": 14856,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 14918,
"s": 14904,
"text": "Linear Search"
},
{
"code": null,
"e": 15003,
"s": 14918,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 15026,
"s": 15003,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 15082,
"s": 15026,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 15109,
"s": 15082,
"text": "Subset Sum Problem | DP-25"
}
] |
Bug Tracking System
|
13 Dec, 2020
What is Bug tracking system? A bug tracking system is software that keeps track of bugs that the user encountered in any software development or in any project.
The three main functionalities of the Bug Tracking system is:
Creating a new text file and writing the details entered by the user into the text file.Option to change the status of the bug.Report of specific bug file.
Creating a new text file and writing the details entered by the user into the text file.
Option to change the status of the bug.
Report of specific bug file.
Now will see what are functions involved
Driver Function: The idea is to keep a variable id that stores the id of the Bugs that are registered till now. There are mainly three options out of which user can select the functionality:
Create New BugChange Status of BugReport a BugExit
Create New Bug
Change Status of Bug
Report a Bug
Exit
Switch Statements are used to Switch into the functionalities as preferred by the user.
Create a New Bug: This function will ask the user for his name, and create a new text file as a name with the id number attached to it.
For Example:
If the user creating a bug file for the first time id which is initially 0 incremented by 1 and if the user enters name as bugfile then the file that our program will create will be named as bugfile1.txt
If the user creating a bug file for the 3rd time id incremented by 1 three times and if the user enters the name as bugfile again then the file that our program will create will be named as bugfile3.txt
After naming the file, Take the information from the user and add it to the text file with the time of creation attached to it
The information is taken by a user for a bug is:
Bug Filed by User.Bug TypeBug PriorityBug DescriptionBug Status
Bug Filed by User.
Bug Type
Bug Priority
Bug Description
Bug Status
Change Status of Bug: Take the information about the bug and change the status of the bug in the desired file. Also, update the Last Updated Time of the Bug.
Report a Bug: Take the information about the bug. Such as Bug file name and print the contents of the Bug.
Below is the implementation of the Bug Tracking System:
Diver Function
Create a Bug
Status of Bug
Report Bug
Complete Code
// C program for the Driver Function// of the Bug Tracking System #include <stdio.h> // Driver Codevoid main(){ printf("***************"); printf("BUG TRACKING SYSTEM"); printf("***************\n"); int number, i = 1; // Id initialised to 0 int id = 0; // while loop to run while (i != 0) { printf("\n1. FILE A NEW BUG\n"); printf("2. CHANGE THE STATUS OF THE BUG\n"); printf("3. GET BUG REPORT\n4. EXIT"); printf("\n\n ENTER YOUR CHOICE:"); scanf("%d", &number); // Using switch to go case by case switch (number) { case 1: id++; // Creating a New Bug filebug(id); break; case 2: // Change Status of Bug changestatus(); break; case 3: // Report the Bug report(); break; case 4: i = 0; break; default: printf("\ninvalid entry"); break; } }}
// C program for filing a bug// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to file the Bug into// the Bug Tracking Systemvoid filebug(int id){ printf("**********"); printf("FILING A BUG"); printf("***********\n"); // Current Time time_t CurrentTime; time(&CurrentTime); char name[20], bugtype[50]; char bugdescription[1000]; char bugpriority[30]; int bugstatus; FILE* ptr; // User name printf("Enter your name:\n"); scanf("%s", name); char ids[10]; itoa(id, ids, 10); strcat(name, ids); char ex[] = ".txt"; strcat(name, ex); // Filename of the Bug printf("Filename :%s\n", name); ptr = fopen(name, "w"); // Case when file cannot be created if (ptr == NULL) printf("cannot create file!!!\n"); fprintf(ptr, "DATE AND TIME : %s", ctime(&CurrentTime)); // ID in the Text File fprintf(ptr, "BUG ID : %d\n", id); // Adding New Line in Text File fprintf(ptr, "\n"); // Bug ID printf("BUG ID:%d\n", id); fprintf(ptr, "BUG FILED BY: %s\n", name); fprintf(ptr, "\n"); printf("Enter bug type:\n"); scanf(" %[^\n]", bugtype); // Bug Type fprintf(ptr, "TYPE OF BUG: %s", bugtype); fprintf(ptr, "\n"); // Bug Priority printf("Enter bug priority:\n"); scanf(" %[^\n]s", bugpriority); fprintf(ptr, "BUG PRIORITY: %s\n", bugpriority); fprintf(ptr, "\n"); // Bug Description printf("Enter the bug description:\n"); scanf(" %[^\n]s", bugdescription); fprintf(ptr, "BUG DESCRIPTION: %s\n", bugdescription); fprintf(ptr, "\n"); printf("Status of bug:\n"); printf("1. NOT YET ASSIGNED\n"); printf("2.IN PROCESS\n 3.FIXED\n"); printf("4.DELIVERED\n ENTER YOUR CHOICE:"); int j; scanf("%d", &j); // Date and time of Bug Creation fprintf(ptr, "DATE AND TIME: %s", ctime(&CurrentTime)); fprintf(ptr, "BUG STATUS:"); // Switching for the Status of the // Bug switch (j) { case 1: fprintf(ptr, "NOT YET ASSIGNED\n"); break; case 2: fprintf(ptr, "IN PROCESS\n"); break; case 3: fprintf(ptr, "FIXED\n"); break; case 4: fprintf(ptr, "DELIVERED\n"); break; default: printf("invalid choice\n"); break; } fclose(ptr);}
// C program for changing Status// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to Change the status// of the Bugvoid changestatus(){ printf("*************"); printf("Change status"); printf("**************\n"); // Current Time time_t CurrentTime; time(&CurrentTime); FILE* file; char name[50]; // Bug File name printf("Enter file name:\n"); scanf("%s", name); char ex[] = ".txt"; strcat(name, ex); // Opening the Bug in Append Mode file = fopen(name, "a"); printf("\n 1. NOT YET ASSIGNED\n"); printf(" 2.IN PROCESS\n 3.FIXED\n"); printf(" 4.DELIVERED\n ENTER YOUR CHOICE:"); // Change the Status int k; scanf("%d", &k); fprintf(file, "\n"); fprintf(file, "DATE AND TIME : %s", ctime(&CurrentTime)); fprintf(file, "BUG STATUS:"); // Changing the status on the // basis of the user input switch (k) { case 1: fprintf(file, "NOT YET ASSIGNED\n"); break; case 2: fprintf(file, "IN PROCESS\n"); break; case 3: fprintf(file, "FIXED\n"); break; case 4: fprintf(file, "DELIVERED\n"); break; default: printf("invalid choice\n"); break; } fclose(file);}
// C program for report a bug// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to report the Bug// in the Bug Tracking Systemvoid report(){ printf("**********"); printf("REPORT"); printf("**********\n"); FILE* fp; char name[50]; // Asking the Filename to report // the bug of the file printf("Enter file name:\n"); scanf("%s", name); char ex[] = ".txt"; strcat(name, ex); // Opening the file into the // Read mode fp = fopen(name, "r"); char ch; ch = getc(fp); // Character of the File while (ch != EOF) { printf("%c", ch); ch = getc(fp); } fclose(fp); getch();}
// C program for the// Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to file the Bug into// the Bug Tracking Systemvoid filebug(int id){ printf("**********"); printf("FILING A BUG"); printf("***********\n"); // Current Time time_t CurrentTime; time(&CurrentTime); char name[20], bugtype[50]; char bugdescription[1000]; char bugpriority[30]; int bugstatus; FILE* ptr; // User name printf("Enter your name:\n"); scanf("%s", name); char ids[10]; itoa(id, ids, 10); strcat(name, ids); char ex[] = ".txt"; strcat(name, ex); // Filename of the Bug printf("Filename :%s\n", name); ptr = fopen(name, "w"); // Case when file cannot be created if (ptr == NULL) printf("cannot create file!!!\n"); fprintf(ptr, "DATE AND TIME : %s", ctime(&CurrentTime)); // ID in the Text File fprintf(ptr, "BUG ID : %d\n", id); // Adding New Line in Text File fprintf(ptr, "\n"); // Bug ID printf("BUG ID:%d\n", id); fprintf(ptr, "BUG FILED BY: %s\n", name); fprintf(ptr, "\n"); printf("Enter bug type:\n"); scanf(" %[^\n]", bugtype); // Bug Type fprintf(ptr, "TYPE OF BUG: %s", bugtype); fprintf(ptr, "\n"); // Bug Priority printf("Enter bug priority:\n"); scanf(" %[^\n]s", bugpriority); fprintf(ptr, "BUG PRIORITY: %s\n", bugpriority); fprintf(ptr, "\n"); // Bug Description printf("Enter the bug description:\n"); scanf(" %[^\n]s", bugdescription); fprintf(ptr, "BUG DESCRIPTION: %s\n", bugdescription); fprintf(ptr, "\n"); printf("Status of bug:\n"); printf("1. NOT YET ASSIGNED\n"); printf("2.IN PROCESS\n 3.FIXED\n"); printf("4.DELIVERED\n ENTER YOUR CHOICE:"); int j; scanf("%d", &j); // Date and time of Bug Creation fprintf(ptr, "DATE AND TIME: %s", ctime(&CurrentTime)); fprintf(ptr, "BUG STATUS:"); // Switching for the Status of the // Bug switch (j) { case 1: fprintf(ptr, "NOT YET ASSIGNED\n"); break; case 2: fprintf(ptr, "IN PROCESS\n"); break; case 3: fprintf(ptr, "FIXED\n"); break; case 4: fprintf(ptr, "DELIVERED\n"); break; default: printf("invalid choice\n"); break; } fclose(ptr);} // Function to Change the status// of the Bugvoid changestatus(){ printf("*************"); printf("Change status"); printf("**************\n"); // Current Time time_t CurrentTime; time(&CurrentTime); FILE* file; char name[50]; // Bug File name printf("Enter file name:\n"); scanf("%s", name); char ex[] = ".txt"; strcat(name, ex); // Opening the Bug in Append Mode file = fopen(name, "a"); printf("\n 1. NOT YET ASSIGNED\n"); printf(" 2.IN PROCESS\n 3.FIXED\n"); printf(" 4.DELIVERED\n ENTER YOUR CHOICE:"); // Change the Status int k; scanf("%d", &k); fprintf(file, "\n"); fprintf(file, "DATE AND TIME : %s", ctime(&CurrentTime)); fprintf(file, "BUG STATUS:"); // Changing the status on the // basis of the user input switch (k) { case 1: fprintf(file, "NOT YET ASSIGNED\n"); break; case 2: fprintf(file, "IN PROCESS\n"); break; case 3: fprintf(file, "FIXED\n"); break; case 4: fprintf(file, "DELIVERED\n"); break; default: printf("invalid choice\n"); break; } fclose(file);} // Function to report the Bug// in the Bug Tracking Systemvoid report(){ printf("**********"); printf("REPORT"); printf("**********\n"); FILE* fp; char name[50]; // Asking the Filename to report // the bug of the file printf("Enter file name:\n"); scanf("%s", name); char ex[] = ".txt"; strcat(name, ex); // Opening the file into the // Read mode fp = fopen(name, "r"); char ch; ch = getc(fp); // Character of the File while (ch != EOF) { printf("%c", ch); ch = getc(fp); } fclose(fp); getch();} // Driver Codevoid main(){ printf("***************"); printf("BUG TRACKING SYSTEM"); printf("***************\n"); int number, i = 1; // Id initialised to 0 int id = 0; // while loop to run while (i != 0) { printf("\n1. FILE A NEW BUG\n"); printf("2. CHANGE THE STATUS OF THE BUG\n"); printf("3. GET BUG REPORT\n4. EXIT"); printf("\n\n ENTER YOUR CHOICE:"); scanf("%d", &number); // Using switch to go case by case switch (number) { case 1: id++; // Creating a New Bug filebug(id); break; case 2: // Change Status of Bug changestatus(); break; case 3: // Report the Bug report(); break; case 4: i = 0; break; default: printf("\ninvalid entry"); break; } }}
Output:
Driver Function:
Create a Bug:
Change Status & Report the Bug
Bug File:
gurukiranx
Technical Scripter 2020
C Language
C Programs
Project
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Dec, 2020"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "What is Bug tracking system? A bug tracking system is software that keeps track of bugs that the user encountered in any software development or in any project."
},
{
"code": null,
"e": 275,
"s": 213,
"text": "The three main functionalities of the Bug Tracking system is:"
},
{
"code": null,
"e": 431,
"s": 275,
"text": "Creating a new text file and writing the details entered by the user into the text file.Option to change the status of the bug.Report of specific bug file."
},
{
"code": null,
"e": 520,
"s": 431,
"text": "Creating a new text file and writing the details entered by the user into the text file."
},
{
"code": null,
"e": 560,
"s": 520,
"text": "Option to change the status of the bug."
},
{
"code": null,
"e": 589,
"s": 560,
"text": "Report of specific bug file."
},
{
"code": null,
"e": 630,
"s": 589,
"text": "Now will see what are functions involved"
},
{
"code": null,
"e": 821,
"s": 630,
"text": "Driver Function: The idea is to keep a variable id that stores the id of the Bugs that are registered till now. There are mainly three options out of which user can select the functionality:"
},
{
"code": null,
"e": 872,
"s": 821,
"text": "Create New BugChange Status of BugReport a BugExit"
},
{
"code": null,
"e": 887,
"s": 872,
"text": "Create New Bug"
},
{
"code": null,
"e": 908,
"s": 887,
"text": "Change Status of Bug"
},
{
"code": null,
"e": 921,
"s": 908,
"text": "Report a Bug"
},
{
"code": null,
"e": 926,
"s": 921,
"text": "Exit"
},
{
"code": null,
"e": 1014,
"s": 926,
"text": "Switch Statements are used to Switch into the functionalities as preferred by the user."
},
{
"code": null,
"e": 1150,
"s": 1014,
"text": "Create a New Bug: This function will ask the user for his name, and create a new text file as a name with the id number attached to it."
},
{
"code": null,
"e": 1163,
"s": 1150,
"text": "For Example:"
},
{
"code": null,
"e": 1368,
"s": 1163,
"text": "If the user creating a bug file for the first time id which is initially 0 incremented by 1 and if the user enters name as bugfile then the file that our program will create will be named as bugfile1.txt "
},
{
"code": null,
"e": 1571,
"s": 1368,
"text": "If the user creating a bug file for the 3rd time id incremented by 1 three times and if the user enters the name as bugfile again then the file that our program will create will be named as bugfile3.txt"
},
{
"code": null,
"e": 1699,
"s": 1571,
"text": "After naming the file, Take the information from the user and add it to the text file with the time of creation attached to it "
},
{
"code": null,
"e": 1748,
"s": 1699,
"text": "The information is taken by a user for a bug is:"
},
{
"code": null,
"e": 1812,
"s": 1748,
"text": "Bug Filed by User.Bug TypeBug PriorityBug DescriptionBug Status"
},
{
"code": null,
"e": 1831,
"s": 1812,
"text": "Bug Filed by User."
},
{
"code": null,
"e": 1840,
"s": 1831,
"text": "Bug Type"
},
{
"code": null,
"e": 1853,
"s": 1840,
"text": "Bug Priority"
},
{
"code": null,
"e": 1869,
"s": 1853,
"text": "Bug Description"
},
{
"code": null,
"e": 1880,
"s": 1869,
"text": "Bug Status"
},
{
"code": null,
"e": 2038,
"s": 1880,
"text": "Change Status of Bug: Take the information about the bug and change the status of the bug in the desired file. Also, update the Last Updated Time of the Bug."
},
{
"code": null,
"e": 2145,
"s": 2038,
"text": "Report a Bug: Take the information about the bug. Such as Bug file name and print the contents of the Bug."
},
{
"code": null,
"e": 2201,
"s": 2145,
"text": "Below is the implementation of the Bug Tracking System:"
},
{
"code": null,
"e": 2216,
"s": 2201,
"text": "Diver Function"
},
{
"code": null,
"e": 2229,
"s": 2216,
"text": "Create a Bug"
},
{
"code": null,
"e": 2243,
"s": 2229,
"text": "Status of Bug"
},
{
"code": null,
"e": 2254,
"s": 2243,
"text": "Report Bug"
},
{
"code": null,
"e": 2268,
"s": 2254,
"text": "Complete Code"
},
{
"code": "// C program for the Driver Function// of the Bug Tracking System #include <stdio.h> // Driver Codevoid main(){ printf(\"***************\"); printf(\"BUG TRACKING SYSTEM\"); printf(\"***************\\n\"); int number, i = 1; // Id initialised to 0 int id = 0; // while loop to run while (i != 0) { printf(\"\\n1. FILE A NEW BUG\\n\"); printf(\"2. CHANGE THE STATUS OF THE BUG\\n\"); printf(\"3. GET BUG REPORT\\n4. EXIT\"); printf(\"\\n\\n ENTER YOUR CHOICE:\"); scanf(\"%d\", &number); // Using switch to go case by case switch (number) { case 1: id++; // Creating a New Bug filebug(id); break; case 2: // Change Status of Bug changestatus(); break; case 3: // Report the Bug report(); break; case 4: i = 0; break; default: printf(\"\\ninvalid entry\"); break; } }}",
"e": 3289,
"s": 2268,
"text": null
},
{
"code": "// C program for filing a bug// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to file the Bug into// the Bug Tracking Systemvoid filebug(int id){ printf(\"**********\"); printf(\"FILING A BUG\"); printf(\"***********\\n\"); // Current Time time_t CurrentTime; time(&CurrentTime); char name[20], bugtype[50]; char bugdescription[1000]; char bugpriority[30]; int bugstatus; FILE* ptr; // User name printf(\"Enter your name:\\n\"); scanf(\"%s\", name); char ids[10]; itoa(id, ids, 10); strcat(name, ids); char ex[] = \".txt\"; strcat(name, ex); // Filename of the Bug printf(\"Filename :%s\\n\", name); ptr = fopen(name, \"w\"); // Case when file cannot be created if (ptr == NULL) printf(\"cannot create file!!!\\n\"); fprintf(ptr, \"DATE AND TIME : %s\", ctime(&CurrentTime)); // ID in the Text File fprintf(ptr, \"BUG ID : %d\\n\", id); // Adding New Line in Text File fprintf(ptr, \"\\n\"); // Bug ID printf(\"BUG ID:%d\\n\", id); fprintf(ptr, \"BUG FILED BY: %s\\n\", name); fprintf(ptr, \"\\n\"); printf(\"Enter bug type:\\n\"); scanf(\" %[^\\n]\", bugtype); // Bug Type fprintf(ptr, \"TYPE OF BUG: %s\", bugtype); fprintf(ptr, \"\\n\"); // Bug Priority printf(\"Enter bug priority:\\n\"); scanf(\" %[^\\n]s\", bugpriority); fprintf(ptr, \"BUG PRIORITY: %s\\n\", bugpriority); fprintf(ptr, \"\\n\"); // Bug Description printf(\"Enter the bug description:\\n\"); scanf(\" %[^\\n]s\", bugdescription); fprintf(ptr, \"BUG DESCRIPTION: %s\\n\", bugdescription); fprintf(ptr, \"\\n\"); printf(\"Status of bug:\\n\"); printf(\"1. NOT YET ASSIGNED\\n\"); printf(\"2.IN PROCESS\\n 3.FIXED\\n\"); printf(\"4.DELIVERED\\n ENTER YOUR CHOICE:\"); int j; scanf(\"%d\", &j); // Date and time of Bug Creation fprintf(ptr, \"DATE AND TIME: %s\", ctime(&CurrentTime)); fprintf(ptr, \"BUG STATUS:\"); // Switching for the Status of the // Bug switch (j) { case 1: fprintf(ptr, \"NOT YET ASSIGNED\\n\"); break; case 2: fprintf(ptr, \"IN PROCESS\\n\"); break; case 3: fprintf(ptr, \"FIXED\\n\"); break; case 4: fprintf(ptr, \"DELIVERED\\n\"); break; default: printf(\"invalid choice\\n\"); break; } fclose(ptr);}",
"e": 5731,
"s": 3289,
"text": null
},
{
"code": "// C program for changing Status// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to Change the status// of the Bugvoid changestatus(){ printf(\"*************\"); printf(\"Change status\"); printf(\"**************\\n\"); // Current Time time_t CurrentTime; time(&CurrentTime); FILE* file; char name[50]; // Bug File name printf(\"Enter file name:\\n\"); scanf(\"%s\", name); char ex[] = \".txt\"; strcat(name, ex); // Opening the Bug in Append Mode file = fopen(name, \"a\"); printf(\"\\n 1. NOT YET ASSIGNED\\n\"); printf(\" 2.IN PROCESS\\n 3.FIXED\\n\"); printf(\" 4.DELIVERED\\n ENTER YOUR CHOICE:\"); // Change the Status int k; scanf(\"%d\", &k); fprintf(file, \"\\n\"); fprintf(file, \"DATE AND TIME : %s\", ctime(&CurrentTime)); fprintf(file, \"BUG STATUS:\"); // Changing the status on the // basis of the user input switch (k) { case 1: fprintf(file, \"NOT YET ASSIGNED\\n\"); break; case 2: fprintf(file, \"IN PROCESS\\n\"); break; case 3: fprintf(file, \"FIXED\\n\"); break; case 4: fprintf(file, \"DELIVERED\\n\"); break; default: printf(\"invalid choice\\n\"); break; } fclose(file);}",
"e": 7050,
"s": 5731,
"text": null
},
{
"code": "// C program for report a bug// in Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to report the Bug// in the Bug Tracking Systemvoid report(){ printf(\"**********\"); printf(\"REPORT\"); printf(\"**********\\n\"); FILE* fp; char name[50]; // Asking the Filename to report // the bug of the file printf(\"Enter file name:\\n\"); scanf(\"%s\", name); char ex[] = \".txt\"; strcat(name, ex); // Opening the file into the // Read mode fp = fopen(name, \"r\"); char ch; ch = getc(fp); // Character of the File while (ch != EOF) { printf(\"%c\", ch); ch = getc(fp); } fclose(fp); getch();}",
"e": 7776,
"s": 7050,
"text": null
},
{
"code": "// C program for the// Bug Tracking System #include <conio.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h> // Function to file the Bug into// the Bug Tracking Systemvoid filebug(int id){ printf(\"**********\"); printf(\"FILING A BUG\"); printf(\"***********\\n\"); // Current Time time_t CurrentTime; time(&CurrentTime); char name[20], bugtype[50]; char bugdescription[1000]; char bugpriority[30]; int bugstatus; FILE* ptr; // User name printf(\"Enter your name:\\n\"); scanf(\"%s\", name); char ids[10]; itoa(id, ids, 10); strcat(name, ids); char ex[] = \".txt\"; strcat(name, ex); // Filename of the Bug printf(\"Filename :%s\\n\", name); ptr = fopen(name, \"w\"); // Case when file cannot be created if (ptr == NULL) printf(\"cannot create file!!!\\n\"); fprintf(ptr, \"DATE AND TIME : %s\", ctime(&CurrentTime)); // ID in the Text File fprintf(ptr, \"BUG ID : %d\\n\", id); // Adding New Line in Text File fprintf(ptr, \"\\n\"); // Bug ID printf(\"BUG ID:%d\\n\", id); fprintf(ptr, \"BUG FILED BY: %s\\n\", name); fprintf(ptr, \"\\n\"); printf(\"Enter bug type:\\n\"); scanf(\" %[^\\n]\", bugtype); // Bug Type fprintf(ptr, \"TYPE OF BUG: %s\", bugtype); fprintf(ptr, \"\\n\"); // Bug Priority printf(\"Enter bug priority:\\n\"); scanf(\" %[^\\n]s\", bugpriority); fprintf(ptr, \"BUG PRIORITY: %s\\n\", bugpriority); fprintf(ptr, \"\\n\"); // Bug Description printf(\"Enter the bug description:\\n\"); scanf(\" %[^\\n]s\", bugdescription); fprintf(ptr, \"BUG DESCRIPTION: %s\\n\", bugdescription); fprintf(ptr, \"\\n\"); printf(\"Status of bug:\\n\"); printf(\"1. NOT YET ASSIGNED\\n\"); printf(\"2.IN PROCESS\\n 3.FIXED\\n\"); printf(\"4.DELIVERED\\n ENTER YOUR CHOICE:\"); int j; scanf(\"%d\", &j); // Date and time of Bug Creation fprintf(ptr, \"DATE AND TIME: %s\", ctime(&CurrentTime)); fprintf(ptr, \"BUG STATUS:\"); // Switching for the Status of the // Bug switch (j) { case 1: fprintf(ptr, \"NOT YET ASSIGNED\\n\"); break; case 2: fprintf(ptr, \"IN PROCESS\\n\"); break; case 3: fprintf(ptr, \"FIXED\\n\"); break; case 4: fprintf(ptr, \"DELIVERED\\n\"); break; default: printf(\"invalid choice\\n\"); break; } fclose(ptr);} // Function to Change the status// of the Bugvoid changestatus(){ printf(\"*************\"); printf(\"Change status\"); printf(\"**************\\n\"); // Current Time time_t CurrentTime; time(&CurrentTime); FILE* file; char name[50]; // Bug File name printf(\"Enter file name:\\n\"); scanf(\"%s\", name); char ex[] = \".txt\"; strcat(name, ex); // Opening the Bug in Append Mode file = fopen(name, \"a\"); printf(\"\\n 1. NOT YET ASSIGNED\\n\"); printf(\" 2.IN PROCESS\\n 3.FIXED\\n\"); printf(\" 4.DELIVERED\\n ENTER YOUR CHOICE:\"); // Change the Status int k; scanf(\"%d\", &k); fprintf(file, \"\\n\"); fprintf(file, \"DATE AND TIME : %s\", ctime(&CurrentTime)); fprintf(file, \"BUG STATUS:\"); // Changing the status on the // basis of the user input switch (k) { case 1: fprintf(file, \"NOT YET ASSIGNED\\n\"); break; case 2: fprintf(file, \"IN PROCESS\\n\"); break; case 3: fprintf(file, \"FIXED\\n\"); break; case 4: fprintf(file, \"DELIVERED\\n\"); break; default: printf(\"invalid choice\\n\"); break; } fclose(file);} // Function to report the Bug// in the Bug Tracking Systemvoid report(){ printf(\"**********\"); printf(\"REPORT\"); printf(\"**********\\n\"); FILE* fp; char name[50]; // Asking the Filename to report // the bug of the file printf(\"Enter file name:\\n\"); scanf(\"%s\", name); char ex[] = \".txt\"; strcat(name, ex); // Opening the file into the // Read mode fp = fopen(name, \"r\"); char ch; ch = getc(fp); // Character of the File while (ch != EOF) { printf(\"%c\", ch); ch = getc(fp); } fclose(fp); getch();} // Driver Codevoid main(){ printf(\"***************\"); printf(\"BUG TRACKING SYSTEM\"); printf(\"***************\\n\"); int number, i = 1; // Id initialised to 0 int id = 0; // while loop to run while (i != 0) { printf(\"\\n1. FILE A NEW BUG\\n\"); printf(\"2. CHANGE THE STATUS OF THE BUG\\n\"); printf(\"3. GET BUG REPORT\\n4. EXIT\"); printf(\"\\n\\n ENTER YOUR CHOICE:\"); scanf(\"%d\", &number); // Using switch to go case by case switch (number) { case 1: id++; // Creating a New Bug filebug(id); break; case 2: // Change Status of Bug changestatus(); break; case 3: // Report the Bug report(); break; case 4: i = 0; break; default: printf(\"\\ninvalid entry\"); break; } }}",
"e": 12890,
"s": 7776,
"text": null
},
{
"code": null,
"e": 12901,
"s": 12893,
"text": "Output:"
},
{
"code": null,
"e": 12920,
"s": 12903,
"text": "Driver Function:"
},
{
"code": null,
"e": 12938,
"s": 12924,
"text": "Create a Bug:"
},
{
"code": null,
"e": 12973,
"s": 12942,
"text": "Change Status & Report the Bug"
},
{
"code": null,
"e": 12987,
"s": 12977,
"text": "Bug File:"
},
{
"code": null,
"e": 13002,
"s": 12991,
"text": "gurukiranx"
},
{
"code": null,
"e": 13026,
"s": 13002,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 13037,
"s": 13026,
"text": "C Language"
},
{
"code": null,
"e": 13048,
"s": 13037,
"text": "C Programs"
},
{
"code": null,
"e": 13056,
"s": 13048,
"text": "Project"
},
{
"code": null,
"e": 13075,
"s": 13056,
"text": "Technical Scripter"
},
{
"code": null,
"e": 13173,
"s": 13075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13221,
"s": 13173,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 13266,
"s": 13221,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 13287,
"s": 13266,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 13313,
"s": 13287,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 13351,
"s": 13313,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 13364,
"s": 13351,
"text": "Strings in C"
},
{
"code": null,
"e": 13405,
"s": 13364,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 13434,
"s": 13405,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 13472,
"s": 13434,
"text": "UDP Server-Client implementation in C"
}
] |
SymPy - Symbols
|
Symbol is the most important class in symPy library. As mentioned earlier, symbolic computations are done with symbols. SymPy variables are objects of Symbols class.
Symbol() function's argument is a string containing symbol which can be assigned to a variable.
>>> from sympy import Symbol
>>> x=Symbol('x')
>>> y=Symbol('y')
>>> expr=x**2+y**2
>>> expr
The above code snippet gives an output equivalent to the below expression −
x2+y2
A symbol may be of more than one alphabets.
>>> s=Symbol('side')
>>> s**3
The above code snippet gives an output equivalent to the below expression −
side3
SymPy also has a Symbols() function that can define multiple symbols at once. String contains names of variables separated by comma or space.
>>> from sympy import symbols
>>> x,y,z=symbols("x,y,z")
In SymPy's abc module, all Latin and Greek alphabets are defined as symbols. Hence, instead of instantiating Symbol object, this method is convenient.
>>> from sympy.abc import x,y,z
However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with more than one alphabets are not defined in abc module, for which you should use Symbol object as above. The abc module defines special names that can detect definitions in default SymPy namespace. clash1 contains single letters and clash2 has multi letter clashing symbols
>>> from sympy.abc import _clash1, _clash2
>>> _clash1
The output of the above snippet is as follows −
{'C': C, 'O': O, 'Q': Q, 'N': N, 'I': I, 'E': E, 'S': S}
>>> _clash2
The output of the above snippet is as follows −
{'beta': beta, 'zeta': zeta, 'gamma': gamma, 'pi': pi}
Indexed symbols can be defined using syntax similar to range() function. Ranges are indicated by a colon. Type of range is determined by the character to the right of the colon. If itr is a digit, all contiguous digits to the left are taken as the nonnegative starting value. All contiguous digits to the right are taken as 1 greater than the ending value.
>>> from sympy import symbols
>>> symbols('a:5')
The output of the above snippet is as follows −
(a0, a1, a2, a3, a4)
>>> symbols('mark(1:4)')
The output of the above snippet is as follows −
(mark1, mark2, mark3)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2185,
"s": 2019,
"text": "Symbol is the most important class in symPy library. As mentioned earlier, symbolic computations are done with symbols. SymPy variables are objects of Symbols class."
},
{
"code": null,
"e": 2281,
"s": 2185,
"text": "Symbol() function's argument is a string containing symbol which can be assigned to a variable."
},
{
"code": null,
"e": 2379,
"s": 2281,
"text": ">>> from sympy import Symbol \n>>> x=Symbol('x') \n>>> y=Symbol('y') \n>>> expr=x**2+y**2 \n>>> expr\n"
},
{
"code": null,
"e": 2455,
"s": 2379,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 2461,
"s": 2455,
"text": "x2+y2"
},
{
"code": null,
"e": 2505,
"s": 2461,
"text": "A symbol may be of more than one alphabets."
},
{
"code": null,
"e": 2537,
"s": 2505,
"text": ">>> s=Symbol('side') \n>>> s**3\n"
},
{
"code": null,
"e": 2613,
"s": 2537,
"text": "The above code snippet gives an output equivalent to the below expression −"
},
{
"code": null,
"e": 2619,
"s": 2613,
"text": "side3"
},
{
"code": null,
"e": 2761,
"s": 2619,
"text": "SymPy also has a Symbols() function that can define multiple symbols at once. String contains names of variables separated by comma or space."
},
{
"code": null,
"e": 2820,
"s": 2761,
"text": ">>> from sympy import symbols \n>>> x,y,z=symbols(\"x,y,z\")\n"
},
{
"code": null,
"e": 2971,
"s": 2820,
"text": "In SymPy's abc module, all Latin and Greek alphabets are defined as symbols. Hence, instead of instantiating Symbol object, this method is convenient."
},
{
"code": null,
"e": 3004,
"s": 2971,
"text": ">>> from sympy.abc import x,y,z\n"
},
{
"code": null,
"e": 3362,
"s": 3004,
"text": "However, the names C, O, S, I, N, E and Q are predefined symbols. Also, symbols with more than one alphabets are not defined in abc module, for which you should use Symbol object as above. The abc module defines special names that can detect definitions in default SymPy namespace. clash1 contains single letters and clash2 has multi letter clashing symbols"
},
{
"code": null,
"e": 3419,
"s": 3362,
"text": ">>> from sympy.abc import _clash1, _clash2 \n>>> _clash1\n"
},
{
"code": null,
"e": 3467,
"s": 3419,
"text": "The output of the above snippet is as follows −"
},
{
"code": null,
"e": 3524,
"s": 3467,
"text": "{'C': C, 'O': O, 'Q': Q, 'N': N, 'I': I, 'E': E, 'S': S}"
},
{
"code": null,
"e": 3537,
"s": 3524,
"text": ">>> _clash2\n"
},
{
"code": null,
"e": 3585,
"s": 3537,
"text": "The output of the above snippet is as follows −"
},
{
"code": null,
"e": 3640,
"s": 3585,
"text": "{'beta': beta, 'zeta': zeta, 'gamma': gamma, 'pi': pi}"
},
{
"code": null,
"e": 3997,
"s": 3640,
"text": "Indexed symbols can be defined using syntax similar to range() function. Ranges are indicated by a colon. Type of range is determined by the character to the right of the colon. If itr is a digit, all contiguous digits to the left are taken as the nonnegative starting value. All contiguous digits to the right are taken as 1 greater than the ending value."
},
{
"code": null,
"e": 4048,
"s": 3997,
"text": ">>> from sympy import symbols \n>>> symbols('a:5')\n"
},
{
"code": null,
"e": 4096,
"s": 4048,
"text": "The output of the above snippet is as follows −"
},
{
"code": null,
"e": 4117,
"s": 4096,
"text": "(a0, a1, a2, a3, a4)"
},
{
"code": null,
"e": 4143,
"s": 4117,
"text": ">>> symbols('mark(1:4)')\n"
},
{
"code": null,
"e": 4191,
"s": 4143,
"text": "The output of the above snippet is as follows −"
},
{
"code": null,
"e": 4213,
"s": 4191,
"text": "(mark1, mark2, mark3)"
},
{
"code": null,
"e": 4220,
"s": 4213,
"text": " Print"
},
{
"code": null,
"e": 4231,
"s": 4220,
"text": " Add Notes"
}
] |
isspace() function in C++
|
The isspace() function is a predefined function in ctype.h. It specifies whether the argument is a whitespace character or not. Some of the whitespace characters are space, horizontal tab, vertical tab etc.
A program that implements isspace() function by counting the number of spaces in a string is given as follows −
Live Demo
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
char str[] = "Coding is fun";
int i, count = 0;
for(i=0; str[i]!='\0';i++) {
if(isspace(str[i]))
count++;
}
cout<<"Number of spaces in the string are "<<count;
return 0;
}
The output of the above program is as follows −
Number of spaces in the string are 2
In the above program, first the string is defined. Then a for loop is used to check each of the characters in the string to see if they are a white space character. If they are, then count is incremented by 1. Finally, the value of count is displayed. This is displayed in the following code snippet −
char str[] = "Coding is fun";
int i, count = 0;
for(i=0; str[i]!='\0';i++) {
if(isspace(str[i]))
count++;
}
cout<<"Number of spaces in the string are "<<count;
This is another program to demonstrate the isspace() function. It specifies if the given character is a whitespace character or not. The program is given as follows −
Live Demo
#include <iostream>
#include <ctype.h>
using namespace std;
int main() {
char ch1 = 'A';
char ch2 = ' ';
if(isspace(ch1))
cout<<"ch1 is a space"<<endl;
else
cout<<"ch1 is not a space"<<endl;
if(isspace(ch2))
cout<<"ch2 is a space"<<endl;
else
cout<<"ch2 is not a space"<<endl;
return 0;
}
The output of the above program is as follows −
ch1 is not a space
ch2 is a space
In the above program, ch1 and ch2 are defined. Then isspace() is used to check if they are whitespace characters or not. The code snippet for this is given as follows −
char ch1 = 'A';
char ch2 = ' ';
if(isspace(ch1))
cout<<"ch1 is a space"<<endl;
else
cout<<"ch1 is not a space"<<endl;
if(isspace(ch2))
cout<<"ch2 is a space"<<endl;
else
cout<<"ch2 is not a space"<<endl;
|
[
{
"code": null,
"e": 1269,
"s": 1062,
"text": "The isspace() function is a predefined function in ctype.h. It specifies whether the argument is a whitespace character or not. Some of the whitespace characters are space, horizontal tab, vertical tab etc."
},
{
"code": null,
"e": 1381,
"s": 1269,
"text": "A program that implements isspace() function by counting the number of spaces in a string is given as follows −"
},
{
"code": null,
"e": 1392,
"s": 1381,
"text": " Live Demo"
},
{
"code": null,
"e": 1670,
"s": 1392,
"text": "#include <iostream>\n#include <ctype.h>\n\nusing namespace std;\nint main() {\n char str[] = \"Coding is fun\";\n int i, count = 0;\n\n for(i=0; str[i]!='\\0';i++) {\n if(isspace(str[i]))\n count++;\n }\n\n cout<<\"Number of spaces in the string are \"<<count;\n return 0;\n}"
},
{
"code": null,
"e": 1718,
"s": 1670,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1755,
"s": 1718,
"text": "Number of spaces in the string are 2"
},
{
"code": null,
"e": 2057,
"s": 1755,
"text": "In the above program, first the string is defined. Then a for loop is used to check each of the characters in the string to see if they are a white space character. If they are, then count is incremented by 1. Finally, the value of count is displayed. This is displayed in the following code snippet −"
},
{
"code": null,
"e": 2224,
"s": 2057,
"text": "char str[] = \"Coding is fun\";\nint i, count = 0;\n\nfor(i=0; str[i]!='\\0';i++) {\n if(isspace(str[i]))\n count++;\n}\ncout<<\"Number of spaces in the string are \"<<count;"
},
{
"code": null,
"e": 2391,
"s": 2224,
"text": "This is another program to demonstrate the isspace() function. It specifies if the given character is a whitespace character or not. The program is given as follows −"
},
{
"code": null,
"e": 2402,
"s": 2391,
"text": " Live Demo"
},
{
"code": null,
"e": 2731,
"s": 2402,
"text": "#include <iostream>\n#include <ctype.h>\n\nusing namespace std;\nint main() {\n char ch1 = 'A';\n char ch2 = ' ';\n if(isspace(ch1))\n cout<<\"ch1 is a space\"<<endl;\n\n else\n cout<<\"ch1 is not a space\"<<endl;\n \n if(isspace(ch2))\n cout<<\"ch2 is a space\"<<endl;\n\n else\n cout<<\"ch2 is not a space\"<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2779,
"s": 2731,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2813,
"s": 2779,
"text": "ch1 is not a space\nch2 is a space"
},
{
"code": null,
"e": 2982,
"s": 2813,
"text": "In the above program, ch1 and ch2 are defined. Then isspace() is used to check if they are whitespace characters or not. The code snippet for this is given as follows −"
},
{
"code": null,
"e": 3190,
"s": 2982,
"text": "char ch1 = 'A';\nchar ch2 = ' ';\n\nif(isspace(ch1))\ncout<<\"ch1 is a space\"<<endl;\n\nelse\ncout<<\"ch1 is not a space\"<<endl;\n\nif(isspace(ch2))\ncout<<\"ch2 is a space\"<<endl;\n\nelse\ncout<<\"ch2 is not a space\"<<endl;"
}
] |
Logical Operators on String in Java
|
Let us implement logical operators on String in Java −
Live Demo
import java.io.*;
public class Demo{
public static void main(String[] args){
int a = 45, b = 32, c = 87, d = 1;
System.out.println("The first variable is " + a);
System.out.println("The second variable is = " + b);
System.out.println("The third variable is = " + c);
if ((a > b) && (b == c)){
d = a + b + c;
System.out.println("The sum is " + d);
}
else
System.out.println("The conditions haven't been fulfilled");
}
}
The first variable is 45
The second variable is = 32
The third variable is = 87
The conditions haven't been fulfilled
A class named Demo contains the main function, where 4 variables are declared, and various logical
operators are implemented using these variables, and they are declared on the console.
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "Let us implement logical operators on String in Java −"
},
{
"code": null,
"e": 1128,
"s": 1117,
"text": " Live Demo"
},
{
"code": null,
"e": 1622,
"s": 1128,
"text": "import java.io.*;\npublic class Demo{\n public static void main(String[] args){\n int a = 45, b = 32, c = 87, d = 1;\n System.out.println(\"The first variable is \" + a);\n System.out.println(\"The second variable is = \" + b);\n System.out.println(\"The third variable is = \" + c);\n if ((a > b) && (b == c)){\n d = a + b + c;\n System.out.println(\"The sum is \" + d);\n }\n else\n System.out.println(\"The conditions haven't been fulfilled\");\n }\n}"
},
{
"code": null,
"e": 1740,
"s": 1622,
"text": "The first variable is 45\nThe second variable is = 32\nThe third variable is = 87\nThe conditions haven't been fulfilled"
},
{
"code": null,
"e": 1926,
"s": 1740,
"text": "A class named Demo contains the main function, where 4 variables are declared, and various logical\noperators are implemented using these variables, and they are declared on the console."
}
] |
Multiple linear regression with interactions. | Towards Data Science
|
We all had some sort of experience with linear regression. It’s one of the most used regression techniques used. Why? Because it is simple to explain and it is easy to implement. But what happens when you have more than one variable? How can you deal with this increased complexity and still use an easy to understand regression like this? And what happen if the system is even more complicated? Let’s imagine when you have an interaction between two variables.
Here is where multiple linear regression kicks in and we will see how to deal with interactions using some handy libraries in python. Finally we will try to deal with the same problem also with symbolic regression and we will enjoy the benefits that come with it!
If you want to have a refresh on linear regression there are plenty of resources available and I also wrote a brief introduction with coding. What about symbolic regression? In this article we will be using gplearn. See its documentation for more informations or, if you like, see my other article about how to use it with complex functions in python here.
We will explore two use cases of regression. In in the first case we will just have four variables (x1 to x4) which adds up plus some predetermined interactions: x1*x2, x3*x2 and x4*x2.
Note that in our dataset “out_df” we don’t have the interactions terms. What we will be doing will try to discover those relationships with our tools. This is how the variables look like when we plot them with seaborn, using x4 as hue (figure 1):
The y of the second case (figure 2) is given by:
y_true = x1+x2+x3+x4+ (x1*x2)*x2 - x3*x2 + x4*x2*x3*x2 + x1**2
Pretty complex sceneario!
The first step is to have a better understanding of the relationships so we will try our standard approach and fit a multiple linear regression to this dataset. We will be using statsmodels for that. In figure 3 we have the OLS regressions results.
import statsmodels.api as sm Xb = sm.add_constant(out_df[['x1','x2','x3','x4']])mod = sm.OLS(y_true, Xb)res = mod.fit()res.summary()
Ouch, this is clearly not the result we were hoping for. R2 is just 0.567 and moreover I am surprised to see that P value for x1 and x4 is incredibly high. We need some different strategy.
What we can do is to import a python library called PolynomialFeatures from sklearn which will generate polynomial and interaction features. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a2, ab, b2].
from sklearn.preprocessing import PolynomialFeaturesimport scipy.specialpoly = PolynomialFeatures(interaction_only=True)X_tr = poly.fit_transform(Xb)Xt = pd.concat([Xb,pd.DataFrame(X_tr,columns=poly.get_feature_names()).drop([‘1’,’x0',’x1',’x2',’x3',’x4'],1)],1)
With “interaction_only=True” only interaction features are produced: features that are products of at most degree distinct input features (so not x[1] ** 2, x[0] * x[2] ** 3, etc.). The default degree parameter is 2.
With the same code as before, but using Xt now, yields the results below.
mod = sm.OLS(y_true, Xt)res = mod.fit()res.summary()
Now R2 in Figure 4 is 1 which is perfect. Too perfect to be good? In fact there are a lot of interaction terms in the summary statistics. Some that we did not even be aware of. Our equation is of the kind of: y = x1+05*x2+2*x3+x4+ x1*x2 — x3*x2 + x4*x2 So our fit introduces interactions that we didn’t explicitly use in our function. Even if we remove those with high p-value (x1 x4), we are left with a complex scenario. This might be a problem for generalization. We can exploit genetic programming to give us some advice here.
With genetic programming we are basically telling the system to do its best to find relationships in our data in an analytical form. If you read the other tutorial some functions I will call here will be clearer. However what we basically want to do is to import SymbolicRegressor from gplearn.genetic and we will use sympy to pretty formatting our equations. Since we are at it, we will also import RandomForest and DecisionTree regressors to compare the results between all those tools later on. Below the code to get it working:
The converter dictionary is there to help us map the equation with its corrispondent python function to let simpy do its work. We also do train_test split of our data so that we will compare our predictions on the test data alone. We defined a function set in which we use standard functions from gplearn’s set. At the 40th generation the code stops and we see that R2 is almost 1, while the formula generated is now pretty easy to read.
If you compare it with the formula we actually used you will see that its a close match, refactoring our formula becomes:
y = -x3 (x2–2) + x2 (x1+x4+ 0.5)+x1+x4
All algorithms performed good on this work: here are the R2.
statsmodels OLS with polynomial features 1.0, random forest 0.9964436147653762, decision tree 0.9939005077996459, gplearn regression 0.9999946996993035
In this case the relationship is more complex as the interaction order is increased:
X = np.column_stack((x1, x2, x3, x4))y_true = x1+x2+x3+x4+ (x1*x2)*x2 - x3*x2 + x4*x2*x3*x2 + x1**2out_df['y'] = y_true
We do basically the same steps as in the first case, but here we already start with polynomial features:
poly = PolynomialFeatures(interaction_only=True)X_tr = poly.fit_transform(out_df.drop('y',1))Xt = pd.concat([out_df.drop('y',1),pd.DataFrame(X_tr,columns=poly.get_feature_names()).drop(['1','x0','x1','x2','x3'],1)],1)Xt = sm.add_constant(Xt)mod = sm.OLS(y_true, Xt)res = mod.fit()res.summary()
In this scenario our approach is not rewarding anymore. It is clear that we don’t have the correct predictors in our dataset. We could use polynomialfeatures to investigate higher orders of interactions but the dimensionality will likely increase too much and we will be left with no much more knowledge then before. Besides, if you had a real dataset and you did not know the formula of the target, would you increase the interactions order? I guess not!
In the code below we again fit and predict our dataset with decision tree and random forest algorithms but also employ gplearn.
X_train, X_test, y_train, y_test = train_test_split(out_df.drop('y',1), y, test_size=0.30, random_state=42)est_tree = DecisionTreeRegressor(max_depth=5)est_tree.fit(X_train, y_train)est_rf = RandomForestRegressor(n_estimators=100,max_depth=5)est_rf.fit(X_train, y_train)y_gp = est_gp.predict(X_test)score_gp = est_gp.score(X_test, y_test)y_tree = est_tree.predict(X_test)score_tree = est_tree.score(X_test, y_test)y_rf = est_rf.predict(X_test)score_rf = est_rf.score(X_test, y_test)y_sm = res.predict(Xt)est_gp.fit(X_train, y_train)print('R2:',est_gp.score(X_test,y_test))next_e = sympify((est_gp._program), locals=converter)next_e
The result is incredible: again after 40 generations we are left with an incredibly high R2 and even better a simple analytical equation.
The original formula is like this:
So we see that there are indeed differences on the terms which involves x1 and its interactions. While the terms which don’t depend on it are perfectly there. Neverthless, if compared with the polynomialfeatures approach, we’re dealing with a much less complicated formula here.
What is the error of the different systems? Well for gplearn it is incredibly low if compared with other. In figure 8 the error in the y-coordinate versus the actual y is reported. While the x axis is shared, you can notice how different the y axis become. The maximum error with GPlearn is around 4 while other methods can show spikes up to 1000.
In the first part of this article we saw how to deal with multiple linear regression in the presence of interactions. We used statsmodels OLS for multiple linear regression and sklearn polynomialfeatures to generate interactions. We then approached the same problem with a different class of algorithm, namely genetic programming, which is easy to import and implement and gives an analytical expression.
In the second part we saw that when things get messy, we are left with some uncertainty using standard tools, even those from traditional machine learning. However, this class of problems is easier to face with the use of gplearn. With this library we were given an analytical formula for our problem directly.
[1] statsmodels[2] sklearn polynomial features[3] gplearn
|
[
{
"code": null,
"e": 633,
"s": 171,
"text": "We all had some sort of experience with linear regression. It’s one of the most used regression techniques used. Why? Because it is simple to explain and it is easy to implement. But what happens when you have more than one variable? How can you deal with this increased complexity and still use an easy to understand regression like this? And what happen if the system is even more complicated? Let’s imagine when you have an interaction between two variables."
},
{
"code": null,
"e": 897,
"s": 633,
"text": "Here is where multiple linear regression kicks in and we will see how to deal with interactions using some handy libraries in python. Finally we will try to deal with the same problem also with symbolic regression and we will enjoy the benefits that come with it!"
},
{
"code": null,
"e": 1254,
"s": 897,
"text": "If you want to have a refresh on linear regression there are plenty of resources available and I also wrote a brief introduction with coding. What about symbolic regression? In this article we will be using gplearn. See its documentation for more informations or, if you like, see my other article about how to use it with complex functions in python here."
},
{
"code": null,
"e": 1440,
"s": 1254,
"text": "We will explore two use cases of regression. In in the first case we will just have four variables (x1 to x4) which adds up plus some predetermined interactions: x1*x2, x3*x2 and x4*x2."
},
{
"code": null,
"e": 1687,
"s": 1440,
"text": "Note that in our dataset “out_df” we don’t have the interactions terms. What we will be doing will try to discover those relationships with our tools. This is how the variables look like when we plot them with seaborn, using x4 as hue (figure 1):"
},
{
"code": null,
"e": 1736,
"s": 1687,
"text": "The y of the second case (figure 2) is given by:"
},
{
"code": null,
"e": 1799,
"s": 1736,
"text": "y_true = x1+x2+x3+x4+ (x1*x2)*x2 - x3*x2 + x4*x2*x3*x2 + x1**2"
},
{
"code": null,
"e": 1825,
"s": 1799,
"text": "Pretty complex sceneario!"
},
{
"code": null,
"e": 2074,
"s": 1825,
"text": "The first step is to have a better understanding of the relationships so we will try our standard approach and fit a multiple linear regression to this dataset. We will be using statsmodels for that. In figure 3 we have the OLS regressions results."
},
{
"code": null,
"e": 2207,
"s": 2074,
"text": "import statsmodels.api as sm Xb = sm.add_constant(out_df[['x1','x2','x3','x4']])mod = sm.OLS(y_true, Xb)res = mod.fit()res.summary()"
},
{
"code": null,
"e": 2396,
"s": 2207,
"text": "Ouch, this is clearly not the result we were hoping for. R2 is just 0.567 and moreover I am surprised to see that P value for x1 and x4 is incredibly high. We need some different strategy."
},
{
"code": null,
"e": 2672,
"s": 2396,
"text": "What we can do is to import a python library called PolynomialFeatures from sklearn which will generate polynomial and interaction features. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a2, ab, b2]."
},
{
"code": null,
"e": 2935,
"s": 2672,
"text": "from sklearn.preprocessing import PolynomialFeaturesimport scipy.specialpoly = PolynomialFeatures(interaction_only=True)X_tr = poly.fit_transform(Xb)Xt = pd.concat([Xb,pd.DataFrame(X_tr,columns=poly.get_feature_names()).drop([‘1’,’x0',’x1',’x2',’x3',’x4'],1)],1)"
},
{
"code": null,
"e": 3152,
"s": 2935,
"text": "With “interaction_only=True” only interaction features are produced: features that are products of at most degree distinct input features (so not x[1] ** 2, x[0] * x[2] ** 3, etc.). The default degree parameter is 2."
},
{
"code": null,
"e": 3226,
"s": 3152,
"text": "With the same code as before, but using Xt now, yields the results below."
},
{
"code": null,
"e": 3279,
"s": 3226,
"text": "mod = sm.OLS(y_true, Xt)res = mod.fit()res.summary()"
},
{
"code": null,
"e": 3810,
"s": 3279,
"text": "Now R2 in Figure 4 is 1 which is perfect. Too perfect to be good? In fact there are a lot of interaction terms in the summary statistics. Some that we did not even be aware of. Our equation is of the kind of: y = x1+05*x2+2*x3+x4+ x1*x2 — x3*x2 + x4*x2 So our fit introduces interactions that we didn’t explicitly use in our function. Even if we remove those with high p-value (x1 x4), we are left with a complex scenario. This might be a problem for generalization. We can exploit genetic programming to give us some advice here."
},
{
"code": null,
"e": 4342,
"s": 3810,
"text": "With genetic programming we are basically telling the system to do its best to find relationships in our data in an analytical form. If you read the other tutorial some functions I will call here will be clearer. However what we basically want to do is to import SymbolicRegressor from gplearn.genetic and we will use sympy to pretty formatting our equations. Since we are at it, we will also import RandomForest and DecisionTree regressors to compare the results between all those tools later on. Below the code to get it working:"
},
{
"code": null,
"e": 4780,
"s": 4342,
"text": "The converter dictionary is there to help us map the equation with its corrispondent python function to let simpy do its work. We also do train_test split of our data so that we will compare our predictions on the test data alone. We defined a function set in which we use standard functions from gplearn’s set. At the 40th generation the code stops and we see that R2 is almost 1, while the formula generated is now pretty easy to read."
},
{
"code": null,
"e": 4902,
"s": 4780,
"text": "If you compare it with the formula we actually used you will see that its a close match, refactoring our formula becomes:"
},
{
"code": null,
"e": 4941,
"s": 4902,
"text": "y = -x3 (x2–2) + x2 (x1+x4+ 0.5)+x1+x4"
},
{
"code": null,
"e": 5002,
"s": 4941,
"text": "All algorithms performed good on this work: here are the R2."
},
{
"code": null,
"e": 5154,
"s": 5002,
"text": "statsmodels OLS with polynomial features 1.0, random forest 0.9964436147653762, decision tree 0.9939005077996459, gplearn regression 0.9999946996993035"
},
{
"code": null,
"e": 5239,
"s": 5154,
"text": "In this case the relationship is more complex as the interaction order is increased:"
},
{
"code": null,
"e": 5359,
"s": 5239,
"text": "X = np.column_stack((x1, x2, x3, x4))y_true = x1+x2+x3+x4+ (x1*x2)*x2 - x3*x2 + x4*x2*x3*x2 + x1**2out_df['y'] = y_true"
},
{
"code": null,
"e": 5464,
"s": 5359,
"text": "We do basically the same steps as in the first case, but here we already start with polynomial features:"
},
{
"code": null,
"e": 5758,
"s": 5464,
"text": "poly = PolynomialFeatures(interaction_only=True)X_tr = poly.fit_transform(out_df.drop('y',1))Xt = pd.concat([out_df.drop('y',1),pd.DataFrame(X_tr,columns=poly.get_feature_names()).drop(['1','x0','x1','x2','x3'],1)],1)Xt = sm.add_constant(Xt)mod = sm.OLS(y_true, Xt)res = mod.fit()res.summary()"
},
{
"code": null,
"e": 6214,
"s": 5758,
"text": "In this scenario our approach is not rewarding anymore. It is clear that we don’t have the correct predictors in our dataset. We could use polynomialfeatures to investigate higher orders of interactions but the dimensionality will likely increase too much and we will be left with no much more knowledge then before. Besides, if you had a real dataset and you did not know the formula of the target, would you increase the interactions order? I guess not!"
},
{
"code": null,
"e": 6342,
"s": 6214,
"text": "In the code below we again fit and predict our dataset with decision tree and random forest algorithms but also employ gplearn."
},
{
"code": null,
"e": 6974,
"s": 6342,
"text": "X_train, X_test, y_train, y_test = train_test_split(out_df.drop('y',1), y, test_size=0.30, random_state=42)est_tree = DecisionTreeRegressor(max_depth=5)est_tree.fit(X_train, y_train)est_rf = RandomForestRegressor(n_estimators=100,max_depth=5)est_rf.fit(X_train, y_train)y_gp = est_gp.predict(X_test)score_gp = est_gp.score(X_test, y_test)y_tree = est_tree.predict(X_test)score_tree = est_tree.score(X_test, y_test)y_rf = est_rf.predict(X_test)score_rf = est_rf.score(X_test, y_test)y_sm = res.predict(Xt)est_gp.fit(X_train, y_train)print('R2:',est_gp.score(X_test,y_test))next_e = sympify((est_gp._program), locals=converter)next_e"
},
{
"code": null,
"e": 7112,
"s": 6974,
"text": "The result is incredible: again after 40 generations we are left with an incredibly high R2 and even better a simple analytical equation."
},
{
"code": null,
"e": 7147,
"s": 7112,
"text": "The original formula is like this:"
},
{
"code": null,
"e": 7426,
"s": 7147,
"text": "So we see that there are indeed differences on the terms which involves x1 and its interactions. While the terms which don’t depend on it are perfectly there. Neverthless, if compared with the polynomialfeatures approach, we’re dealing with a much less complicated formula here."
},
{
"code": null,
"e": 7774,
"s": 7426,
"text": "What is the error of the different systems? Well for gplearn it is incredibly low if compared with other. In figure 8 the error in the y-coordinate versus the actual y is reported. While the x axis is shared, you can notice how different the y axis become. The maximum error with GPlearn is around 4 while other methods can show spikes up to 1000."
},
{
"code": null,
"e": 8179,
"s": 7774,
"text": "In the first part of this article we saw how to deal with multiple linear regression in the presence of interactions. We used statsmodels OLS for multiple linear regression and sklearn polynomialfeatures to generate interactions. We then approached the same problem with a different class of algorithm, namely genetic programming, which is easy to import and implement and gives an analytical expression."
},
{
"code": null,
"e": 8490,
"s": 8179,
"text": "In the second part we saw that when things get messy, we are left with some uncertainty using standard tools, even those from traditional machine learning. However, this class of problems is easier to face with the use of gplearn. With this library we were given an analytical formula for our problem directly."
}
] |
How to iterate over a Java list?
|
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps −
Obtain an iterator to the start of the collection by calling the collection's iterator() method.Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.Within the loop, obtain each element by calling next().
Obtain an iterator to the start of the collection by calling the collection's iterator() method.
Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
Within the loop, obtain each element by calling next().
Live Demo
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorSample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("JavaFx");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
JavaFx
Java
WebGL
OpenCV
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Often, you will want to cycle through the elements in a collection. For example, you might want to display each element."
},
{
"code": null,
"e": 1322,
"s": 1183,
"text": "The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface."
},
{
"code": null,
"e": 1513,
"s": 1322,
"text": "Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements."
},
{
"code": null,
"e": 1809,
"s": 1513,
"text": "Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time."
},
{
"code": null,
"e": 1908,
"s": 1809,
"text": "In general, to use an iterator to cycle through the contents of a collection, follow these steps −"
},
{
"code": null,
"e": 2162,
"s": 1908,
"text": "Obtain an iterator to the start of the collection by calling the collection's iterator() method.Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.Within the loop, obtain each element by calling next()."
},
{
"code": null,
"e": 2259,
"s": 2162,
"text": "Obtain an iterator to the start of the collection by calling the collection's iterator() method."
},
{
"code": null,
"e": 2362,
"s": 2259,
"text": "Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true."
},
{
"code": null,
"e": 2418,
"s": 2362,
"text": "Within the loop, obtain each element by calling next()."
},
{
"code": null,
"e": 2429,
"s": 2418,
"text": " Live Demo"
},
{
"code": null,
"e": 2854,
"s": 2429,
"text": "import java.util.ArrayList;\nimport java.util.Iterator;\n\npublic class IteratorSample {\n public static void main(String[] args) {\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"JavaFx\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n Iterator iterator = list.iterator();\n while(iterator.hasNext()) {\n System.out.println(iterator.next());\n }\n }\n}"
},
{
"code": null,
"e": 2879,
"s": 2854,
"text": "JavaFx\nJava\nWebGL\nOpenCV"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.