title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Binomial Random Variables - GeeksforGeeks
30 Nov, 2021 In this post, we’ll discuss Binomial Random Variables.Prerequisite : Random Variables A specific type of discrete random variable that counts how often a particular event occurs in a fixed number of tries or trials. For a variable to be a binomial random variable, ALL of the following conditions must be met: There are a fixed number of trials (a fixed sample size).On each trial, the event of interest either occurs or does not.The probability of occurrence (or not) is the same on each trial.Trials are independent of one another. There are a fixed number of trials (a fixed sample size). On each trial, the event of interest either occurs or does not. The probability of occurrence (or not) is the same on each trial. Trials are independent of one another. Mathematical Notations n = number of trials p = probability of success in each trial k = number of success in n trials Now we try to find out the probability of k success in n trials.Here the probability of success in each trial is p independent of other trials. So we first choose k trials in which there will be a success and in rest n-k trials there will be a failure. Number of ways to do so is Since all n events are independent, hence the probability of k success in n trials is equivalent to multiplication of probability for each trial.Here its k success and n-k failures, So probability for each way to achieve k success and n-k failure is Hence final probability is (number of ways to achieve k success and n-k failures) * (probability for each way to achieve k success and n-k failure) Then Binomial Random Variable Probability is given by: Let X be a binomial random variable with the number of trials n and probability of success in each trial be p. Expected number of success is given by E[X] = np Variance of number of success is given by Var[X] = np(1-p) Example 1 : Consider a random experiment in which a biased coin (probability of head = 1/3) is thrown for 10 times. Find the probability that the number of heads appearing will be 5.Solution : Let X be binomial random variable with n = 10 and p = 1/3 P(X=5) = ? Here is the implementation for the same C++ Java Python3 C# PHP Javascript // C++ program to compute Binomial Probability#include <iostream>#include <cmath>using namespace std; // function to calculate nCr i.e., number of // ways to choose r out of n objectsint nCr(int n, int r){ // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer;} // function to calculate binomial r.v. probabilityfloat binomialProbability(int n, int k, float p){ return nCr(n, k) * pow(p, k) * pow(1 - p, n - k);} // Driver codeint main(){ int n = 10; int k = 5; float p = 1.0 / 3; float probability = binomialProbability(n, k, p); cout << "Probability of " << k; cout << " heads when a coin is tossed " << n; cout << " times where probability of each head is " << p << endl; cout << " is = " << probability << endl;} // Java program to compute Binomial Probability import java.util.*; class GFG{ // function to calculate nCr i.e., number of // ways to choose r out of n objects static int nCr(int n, int r) { // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial r.v. probability static float binomialProbability(int n, int k, float p) { return nCr(n, k) * (float)Math.pow(p, k) * (float)Math.pow(1 - p, n - k); } // Driver code public static void main(String[] args) { int n = 10; int k = 5; float p = (float)1.0 / 3; float probability = binomialProbability(n, k, p); System.out.print("Probability of " +k); System.out.print(" heads when a coin is tossed " +n); System.out.println(" times where probability of each head is " +p); System.out.println( " is = " + probability ); }} /* This code is contributed by Mr. Somesh Awasthi */ # Python3 program to compute Binomial # Probability # function to calculate nCr i.e.,# number of ways to choose r out# of n objectsdef nCr(n, r): # Since nCr is same as nC(n-r) # To decrease number of iterations if (r > n / 2): r = n - r; answer = 1; for i in range(1, r + 1): answer *= (n - r + i); answer /= i; return answer; # function to calculate binomial r.v.# probabilitydef binomialProbability(n, k, p): return (nCr(n, k) * pow(p, k) * pow(1 - p, n - k)); # Driver coden = 10;k = 5;p = 1.0 / 3; probability = binomialProbability(n, k, p); print("Probability of", k, "heads when a coin is tossed", end = " ");print(n, "times where probability of each head is", round(p, 6));print("is = ", round(probability, 6)); # This code is contributed by mits // C# program to compute Binomial// Probability.using System; class GFG { // function to calculate nCr // i.e., number of ways to // choose r out of n objects static int nCr(int n, int r) { // Since nCr is same as // nC(n-r) To decrease // number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial // r.v. probability static float binomialProbability( int n, int k, float p) { return nCr(n, k) * (float)Math.Pow(p, k) * (float)Math.Pow(1 - p, n - k); } // Driver code public static void Main() { int n = 10; int k = 5; float p = (float)1.0 / 3; float probability = binomialProbability(n, k, p); Console.Write("Probability of " + k); Console.Write(" heads when a coin " + "is tossed " + n); Console.Write(" times where " + "probability of each head is " + p); Console.Write( " is = " + probability ); }} // This code is contributed by nitin mittal. <?php// php program to compute Binomial // Probability // function to calculate nCr i.e.,// number of ways to choose r out// of n objectsfunction nCr($n, $r){ // Since nCr is same as nC(n-r) // To decrease number of iterations if ($r > $n / 2) $r = $n - $r; $answer = 1; for ($i = 1; $i <= $r; $i++) { $answer *= ($n - $r + $i); $answer /= $i; } return $answer;} // function to calculate binomial r.v.// probabilityfunction binomialProbability($n, $k, $p){ return nCr($n, $k) * pow($p, $k) * pow(1 - $p, $n - $k);} // Driver code $n = 10; $k = 5; $p = 1.0 / 3; $probability = binomialProbability($n, $k, $p); echo "Probability of " . $k; echo " heads when a coin is tossed " . $n; echo " times where probability of " . "each head is " . $p ; echo " is = " . $probability ; // This code is contributed by nitin mittal.?> <script> // Javascript program to compute Binomial Probability // function to calculate nCr i.e., number of // ways to choose r out of n objects function nCr(n, r) { // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; let answer = 1; for (let i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial r.v. probability function binomialProbability(n, k, p) { return nCr(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k); } // driver program let n = 10; let k = 5; let p = 1.0 / 3; let probability = binomialProbability(n, k, p); document.write("Probability of " +k); document.write(" heads when a coin is tossed " +n); document.write(" times where probability of each head is " +p); document.write( " is = " + probability ); // This code is contributed by code_hunt.</script> Output: Probability of 5 heads when a coin is tossed 10 times where probability of each head is 0.333333 is = 0.136565 Reference : stat200This article is contributed by Pratik Chhajer . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. nitin mittal Mithun Kumar Akanksha_Rai code_hunt Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Random Walk (Implementation in Python) Shuffle a given array using Fisher–Yates shuffle Algorithm Shuffle a deck of cards Shuffle or Randomize a list in Java K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
[ { "code": null, "e": 24327, "s": 24299, "text": "\n30 Nov, 2021" }, { "code": null, "e": 24639, "s": 24327, "text": "In this post, we’ll discuss Binomial Random Variables.Prerequisite : Random Variables A specific type of discrete random variable that counts how often a particular event occurs in a fixed number of tries or trials. For a variable to be a binomial random variable, ALL of the following conditions must be met: " }, { "code": null, "e": 24863, "s": 24639, "text": "There are a fixed number of trials (a fixed sample size).On each trial, the event of interest either occurs or does not.The probability of occurrence (or not) is the same on each trial.Trials are independent of one another." }, { "code": null, "e": 24921, "s": 24863, "text": "There are a fixed number of trials (a fixed sample size)." }, { "code": null, "e": 24985, "s": 24921, "text": "On each trial, the event of interest either occurs or does not." }, { "code": null, "e": 25051, "s": 24985, "text": "The probability of occurrence (or not) is the same on each trial." }, { "code": null, "e": 25090, "s": 25051, "text": "Trials are independent of one another." }, { "code": null, "e": 25115, "s": 25090, "text": "Mathematical Notations " }, { "code": null, "e": 25211, "s": 25115, "text": "n = number of trials\np = probability of success in each trial\nk = number of success in n trials" }, { "code": null, "e": 25493, "s": 25211, "text": "Now we try to find out the probability of k success in n trials.Here the probability of success in each trial is p independent of other trials. So we first choose k trials in which there will be a success and in rest n-k trials there will be a failure. Number of ways to do so is " }, { "code": null, "e": 25745, "s": 25493, "text": "Since all n events are independent, hence the probability of k success in n trials is equivalent to multiplication of probability for each trial.Here its k success and n-k failures, So probability for each way to achieve k success and n-k failure is " }, { "code": null, "e": 25774, "s": 25745, "text": "Hence final probability is " }, { "code": null, "e": 25898, "s": 25774, "text": "(number of ways to achieve k success\n and n-k failures)\n *\n(probability for each way to achieve k\n success and n-k failure)" }, { "code": null, "e": 25955, "s": 25898, "text": "Then Binomial Random Variable Probability is given by: " }, { "code": null, "e": 26107, "s": 25955, "text": "Let X be a binomial random variable with the number of trials n and probability of success in each trial be p. Expected number of success is given by " }, { "code": null, "e": 26117, "s": 26107, "text": "E[X] = np" }, { "code": null, "e": 26161, "s": 26117, "text": "Variance of number of success is given by " }, { "code": null, "e": 26178, "s": 26161, "text": "Var[X] = np(1-p)" }, { "code": null, "e": 26373, "s": 26178, "text": "Example 1 : Consider a random experiment in which a biased coin (probability of head = 1/3) is thrown for 10 times. Find the probability that the number of heads appearing will be 5.Solution : " }, { "code": null, "e": 26443, "s": 26373, "text": "Let X be binomial random variable \nwith n = 10 and p = 1/3\nP(X=5) = ?" }, { "code": null, "e": 26489, "s": 26447, "text": "Here is the implementation for the same " }, { "code": null, "e": 26493, "s": 26489, "text": "C++" }, { "code": null, "e": 26498, "s": 26493, "text": "Java" }, { "code": null, "e": 26506, "s": 26498, "text": "Python3" }, { "code": null, "e": 26509, "s": 26506, "text": "C#" }, { "code": null, "e": 26513, "s": 26509, "text": "PHP" }, { "code": null, "e": 26524, "s": 26513, "text": "Javascript" }, { "code": "// C++ program to compute Binomial Probability#include <iostream>#include <cmath>using namespace std; // function to calculate nCr i.e., number of // ways to choose r out of n objectsint nCr(int n, int r){ // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer;} // function to calculate binomial r.v. probabilityfloat binomialProbability(int n, int k, float p){ return nCr(n, k) * pow(p, k) * pow(1 - p, n - k);} // Driver codeint main(){ int n = 10; int k = 5; float p = 1.0 / 3; float probability = binomialProbability(n, k, p); cout << \"Probability of \" << k; cout << \" heads when a coin is tossed \" << n; cout << \" times where probability of each head is \" << p << endl; cout << \" is = \" << probability << endl;}", "e": 27477, "s": 26524, "text": null }, { "code": "// Java program to compute Binomial Probability import java.util.*; class GFG{ // function to calculate nCr i.e., number of // ways to choose r out of n objects static int nCr(int n, int r) { // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial r.v. probability static float binomialProbability(int n, int k, float p) { return nCr(n, k) * (float)Math.pow(p, k) * (float)Math.pow(1 - p, n - k); } // Driver code public static void main(String[] args) { int n = 10; int k = 5; float p = (float)1.0 / 3; float probability = binomialProbability(n, k, p); System.out.print(\"Probability of \" +k); System.out.print(\" heads when a coin is tossed \" +n); System.out.println(\" times where probability of each head is \" +p); System.out.println( \" is = \" + probability ); }} /* This code is contributed by Mr. Somesh Awasthi */", "e": 28721, "s": 27477, "text": null }, { "code": "# Python3 program to compute Binomial # Probability # function to calculate nCr i.e.,# number of ways to choose r out# of n objectsdef nCr(n, r): # Since nCr is same as nC(n-r) # To decrease number of iterations if (r > n / 2): r = n - r; answer = 1; for i in range(1, r + 1): answer *= (n - r + i); answer /= i; return answer; # function to calculate binomial r.v.# probabilitydef binomialProbability(n, k, p): return (nCr(n, k) * pow(p, k) * pow(1 - p, n - k)); # Driver coden = 10;k = 5;p = 1.0 / 3; probability = binomialProbability(n, k, p); print(\"Probability of\", k, \"heads when a coin is tossed\", end = \" \");print(n, \"times where probability of each head is\", round(p, 6));print(\"is = \", round(probability, 6)); # This code is contributed by mits", "e": 29604, "s": 28721, "text": null }, { "code": "// C# program to compute Binomial// Probability.using System; class GFG { // function to calculate nCr // i.e., number of ways to // choose r out of n objects static int nCr(int n, int r) { // Since nCr is same as // nC(n-r) To decrease // number of iterations if (r > n / 2) r = n - r; int answer = 1; for (int i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial // r.v. probability static float binomialProbability( int n, int k, float p) { return nCr(n, k) * (float)Math.Pow(p, k) * (float)Math.Pow(1 - p, n - k); } // Driver code public static void Main() { int n = 10; int k = 5; float p = (float)1.0 / 3; float probability = binomialProbability(n, k, p); Console.Write(\"Probability of \" + k); Console.Write(\" heads when a coin \" + \"is tossed \" + n); Console.Write(\" times where \" + \"probability of each head is \" + p); Console.Write( \" is = \" + probability ); }} // This code is contributed by nitin mittal.", "e": 31070, "s": 29604, "text": null }, { "code": "<?php// php program to compute Binomial // Probability // function to calculate nCr i.e.,// number of ways to choose r out// of n objectsfunction nCr($n, $r){ // Since nCr is same as nC(n-r) // To decrease number of iterations if ($r > $n / 2) $r = $n - $r; $answer = 1; for ($i = 1; $i <= $r; $i++) { $answer *= ($n - $r + $i); $answer /= $i; } return $answer;} // function to calculate binomial r.v.// probabilityfunction binomialProbability($n, $k, $p){ return nCr($n, $k) * pow($p, $k) * pow(1 - $p, $n - $k);} // Driver code $n = 10; $k = 5; $p = 1.0 / 3; $probability = binomialProbability($n, $k, $p); echo \"Probability of \" . $k; echo \" heads when a coin is tossed \" . $n; echo \" times where probability of \" . \"each head is \" . $p ; echo \" is = \" . $probability ; // This code is contributed by nitin mittal.?>", "e": 32055, "s": 31070, "text": null }, { "code": "<script> // Javascript program to compute Binomial Probability // function to calculate nCr i.e., number of // ways to choose r out of n objects function nCr(n, r) { // Since nCr is same as nC(n-r) // To decrease number of iterations if (r > n / 2) r = n - r; let answer = 1; for (let i = 1; i <= r; i++) { answer *= (n - r + i); answer /= i; } return answer; } // function to calculate binomial r.v. probability function binomialProbability(n, k, p) { return nCr(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k); } // driver program let n = 10; let k = 5; let p = 1.0 / 3; let probability = binomialProbability(n, k, p); document.write(\"Probability of \" +k); document.write(\" heads when a coin is tossed \" +n); document.write(\" times where probability of each head is \" +p); document.write( \" is = \" + probability ); // This code is contributed by code_hunt.</script>", "e": 33175, "s": 32055, "text": null }, { "code": null, "e": 33185, "s": 33175, "text": "Output: " }, { "code": null, "e": 33297, "s": 33185, "text": "Probability of 5 heads when a coin is tossed 10 times where probability of each head is 0.333333\n is = 0.136565" }, { "code": null, "e": 33740, "s": 33297, "text": "Reference : stat200This article is contributed by Pratik Chhajer . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. " }, { "code": null, "e": 33753, "s": 33740, "text": "nitin mittal" }, { "code": null, "e": 33766, "s": 33753, "text": "Mithun Kumar" }, { "code": null, "e": 33779, "s": 33766, "text": "Akanksha_Rai" }, { "code": null, "e": 33789, "s": 33779, "text": "code_hunt" }, { "code": null, "e": 33802, "s": 33789, "text": "Mathematical" }, { "code": null, "e": 33813, "s": 33802, "text": "Randomized" }, { "code": null, "e": 33826, "s": 33813, "text": "Mathematical" }, { "code": null, "e": 33924, "s": 33826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33933, "s": 33924, "text": "Comments" }, { "code": null, "e": 33946, "s": 33933, "text": "Old Comments" }, { "code": null, "e": 33991, "s": 33946, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 34023, "s": 33991, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34067, "s": 34023, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34101, "s": 34067, "text": "Program to add two binary strings" }, { "code": null, "e": 34134, "s": 34101, "text": "Program to multiply two matrices" }, { "code": null, "e": 34173, "s": 34134, "text": "Random Walk (Implementation in Python)" }, { "code": null, "e": 34232, "s": 34173, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 34256, "s": 34232, "text": "Shuffle a deck of cards" }, { "code": null, "e": 34292, "s": 34256, "text": "Shuffle or Randomize a list in Java" } ]
Count all possible paths from top left to bottom right of a mXn matrix in C++
In this tutorial, we will be discussing a program to find the number of possible paths from top left to bottom right of a mXn matrix. For this we will be provided with a mXn matrix. Our task is to find all the possible paths from top left to bottom right of the given matrix. #include <iostream> using namespace std; //returning count of possible paths int count_paths(int m, int n){ if (m == 1 || n == 1) return 1; return count_paths(m - 1, n) + count_paths(m, n - 1); } int main(){ cout << count_paths(3, 3); return 0; } 6
[ { "code": null, "e": 1196, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the number of possible paths from top left to bottom right of a mXn matrix." }, { "code": null, "e": 1338, "s": 1196, "text": "For this we will be provided with a mXn matrix. Our task is to find all the possible paths from top left to bottom right of the given matrix." }, { "code": null, "e": 1603, "s": 1338, "text": "#include <iostream>\nusing namespace std;\n//returning count of possible paths\nint count_paths(int m, int n){\n if (m == 1 || n == 1)\n return 1;\n return count_paths(m - 1, n) + count_paths(m, n - 1);\n}\nint main(){\n cout << count_paths(3, 3);\n return 0;\n}" }, { "code": null, "e": 1605, "s": 1603, "text": "6" } ]
A beginner’s guide to dimensionality reduction in Machine Learning | by Judy T Raj | Towards Data Science
This is my first article on medium. Here, I’ll be giving a quick overview of what dimensionality reduction is, why we need it and how to do it. Dimensionality reduction is simply, the process of reducing the dimension of your feature set. Your feature set could be a dataset with a hundred columns (i.e features) or it could be an array of points that make up a large sphere in the three-dimensional space. Dimensionality reduction is bringing the number of columns down to say, twenty or converting the sphere to a circle in the two-dimensional space. That is all well and good but why should we care? Why would we drop 80 columns off our dataset when we could straight up feed it to our machine learning algorithm and let it do the rest? We care because the curse of dimensionality demands that we do. The curse of dimensionality refers to all the problems that arise when working with data in the higher dimensions, that did not exist in the lower dimensions. As the number of features increase, the number of samples also increases proportionally. The more features we have, the more number of samples we will need to have all combinations of feature values well represented in our sample. As the number of features increases, the model becomes more complex. The more the number of features, the more the chances of overfitting. A machine learning model that is trained on a large number of features, gets increasingly dependent on the data it was trained on and in turn overfitted, resulting in poor performance on real data, beating the purpose. Avoiding overfitting is a major motivation for performing dimensionality reduction. The fewer features our training data has, the lesser assumptions our model makes and the simpler it will be. But that is not all and dimensionality reduction has a lot more advantages to offer, like Less misleading data means model accuracy improves.Less dimensions mean less computing. Less data means that algorithms train faster.Less data means less storage space required.Less dimensions allow usage of algorithms unfit for a large number of dimensionsRemoves redundant features and noise. Less misleading data means model accuracy improves. Less dimensions mean less computing. Less data means that algorithms train faster. Less data means less storage space required. Less dimensions allow usage of algorithms unfit for a large number of dimensions Removes redundant features and noise. Dimensionality reduction could be done by both feature selection methods as well as feature engineering methods. Feature selection is the process of identifying and selecting relevant features for your sample. Feature engineering is manually generating new features from existing features, by applying some transformation or performing some operation on them. Feature selection can be done either manually or programmatically. For example, consider you are trying to build a model which predicts people’s weights and you have collected a large corpus of data which describes each person quite thoroughly. If you had a column that described the color of each person’s clothing, would that be much help in predicting their weight? I think we can safely agree it won’t be. This is something we can drop without further ado. What about a column that described their heights? That’s a definite yes. We can make these simple manual feature selections and reduce the dimensionality when the relevance or irrelevance of certain features are obvious or common knowledge. And when its not glaringly obvious, there are a lot of tools we could employ to aid our feature selection. Heatmaps that show the correlation between features is a good idea.So is just visualising the relationship between the features and the target variable by plotting each feature against the target variable. Heatmaps that show the correlation between features is a good idea. So is just visualising the relationship between the features and the target variable by plotting each feature against the target variable. Now let us look at a few programmatic methods for feature selection from the popular machine learning library sci-kit learn, namely, Variance Threshold andUnivariate selection. Variance Threshold and Univariate selection. Variance Threshold is a baseline approach to feature selection. As the name suggests, it drops all features where the variance along the column does not exceed a threshold value. The premise is that a feature which doesn’t vary much within itself, has very little predictive power. >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]>>> selector = VarianceThreshold()>>> selector.fit_transform(X)array([[2, 0], [1, 4], [1, 1]]) Univariate Feature Selection uses statistical tests to select features. Univariate describes a type of data which consists of observations on only a single characteristic or attribute. Univariate feature selection examines each feature individually to determine the strength of the relationship of the feature with the response variable. Some examples of statistical tests that can be used to evaluate feature relevance are Pearson Correlation, Maximal information coefficient, Distance correlation, ANOVA and Chi-square. Chi-square is used to find the relationship between categorical variables and Anova is preferred when the variables are continuous. Scikit-learn exposes feature selection routines likes SelectKBest, SelectPercentile or GenericUnivariateSelect as objects that implement a transform method based on the score of anova or chi2 or mutual information. Sklearn offers f_regression and mutual_info_regression as the scoring functions for regression and f_classif and mutual_info_classif for classification. F-Test checks for and only captures linear relationships between features and labels. A highly correlated feature is given higher score and less correlated features are given lower score. Correlation is highly deceptive as it doesn’t capture strong non-linear relationships. On the other hand, mutual information methods can capture any kind of statistical dependency, but being nonparametric, they require more samples for accurate estimation. Feature selection is the simplest of dimensionality reduction methods. We will look at a few feature engineering methods for dimensionality reduction later. The most common and well known dimensionality reduction methods are the ones that apply linear transformations, like PCA (Principal Component Analysis) : Popularly used for dimensionality reduction in continuous data, PCA rotates and projects data along the direction of increasing variance. The features with the maximum variance are the principal components.Factor Analysis : a technique that is used to reduce a large number of variables into fewer numbers of factors. The values of observed data are expressed as functions of a number of possible causes in order to find which are the most important. The observations are assumed to be caused by a linear transformation of lower dimensional latent factors and added Gaussian noise.LDA (Linear Discriminant Analysis): projects data in a way that the class separability is maximised. Examples from same class are put closely together by the projection. Examples from different classes are placed far apart by the projection PCA (Principal Component Analysis) : Popularly used for dimensionality reduction in continuous data, PCA rotates and projects data along the direction of increasing variance. The features with the maximum variance are the principal components. Factor Analysis : a technique that is used to reduce a large number of variables into fewer numbers of factors. The values of observed data are expressed as functions of a number of possible causes in order to find which are the most important. The observations are assumed to be caused by a linear transformation of lower dimensional latent factors and added Gaussian noise. LDA (Linear Discriminant Analysis): projects data in a way that the class separability is maximised. Examples from same class are put closely together by the projection. Examples from different classes are placed far apart by the projection Non-linear transformation methods or manifold learning methods are used when the data doesn’t lie on a linear subspace. It is based on the manifold hypothesis which says that in a high dimensional structure, most relevant information is concentrated in small number of low dimensional manifolds. If a linear subspace is a flat sheet of paper, then a rolled up sheet of paper is a simple example of a nonlinear manifold. Informally, this is called a Swiss roll, a canonical problem in the field of non-linear dimensionality reduction. Some popular manifold learning methods are, Multi-dimensional scaling (MDS) : A technique used for analyzing similarity or dissimilarity of data as distances in a geometric spaces. Projects data to a lower dimension such that data points that are close to each other (in terms if Euclidean distance) in the higher dimension are close in the lower dimension as well.Isometric Feature Mapping (Isomap) : Projects data to a lower dimension while preserving the geodesic distance (rather than Euclidean distance as in MDS). Geodesic distance is the shortest distance between two points on a curve.Locally Linear Embedding (LLE): Recovers global non-linear structure from linear fits. Each local patch of the manifold can be written as a linear, weighted sum of its neighbours given enough data.Hessian Eigenmapping (HLLE): Projects data to a lower dimension while preserving the local neighbourhood like LLE but uses the Hessian operator to better achieve this result and hence the name.Spectral Embedding (Laplacian Eigenmaps): Uses spectral techniques to perform dimensionality reduction by mapping nearby inputs to nearby outputs. It preserves locality rather than local linearityt-distributed Stochastic Neighbor Embedding (t-SNE): Computes the probability that pairs of data points in the high-dimensional space are related and then chooses a low-dimensional embedding which produce a similar distribution. Multi-dimensional scaling (MDS) : A technique used for analyzing similarity or dissimilarity of data as distances in a geometric spaces. Projects data to a lower dimension such that data points that are close to each other (in terms if Euclidean distance) in the higher dimension are close in the lower dimension as well. Isometric Feature Mapping (Isomap) : Projects data to a lower dimension while preserving the geodesic distance (rather than Euclidean distance as in MDS). Geodesic distance is the shortest distance between two points on a curve. Locally Linear Embedding (LLE): Recovers global non-linear structure from linear fits. Each local patch of the manifold can be written as a linear, weighted sum of its neighbours given enough data. Hessian Eigenmapping (HLLE): Projects data to a lower dimension while preserving the local neighbourhood like LLE but uses the Hessian operator to better achieve this result and hence the name. Spectral Embedding (Laplacian Eigenmaps): Uses spectral techniques to perform dimensionality reduction by mapping nearby inputs to nearby outputs. It preserves locality rather than local linearity t-distributed Stochastic Neighbor Embedding (t-SNE): Computes the probability that pairs of data points in the high-dimensional space are related and then chooses a low-dimensional embedding which produce a similar distribution. Another popular dimensionality reduction method that gives spectacular results are auto-encoders, a type of artificial neural network that aims to copy their inputs to their outputs. They compress the input into a latent-space representation, and then reconstructs the output from this representation. An autoencoder is composed of two parts : Encoder: compresses the input into a latent-space representation.Decoder: reconstruct the input from the latent space representation. Encoder: compresses the input into a latent-space representation. Decoder: reconstruct the input from the latent space representation. In subsequent posts, let us look more deeply into linear and non-linear dimensionality reduction methods.
[ { "code": null, "e": 316, "s": 172, "text": "This is my first article on medium. Here, I’ll be giving a quick overview of what dimensionality reduction is, why we need it and how to do it." }, { "code": null, "e": 725, "s": 316, "text": "Dimensionality reduction is simply, the process of reducing the dimension of your feature set. Your feature set could be a dataset with a hundred columns (i.e features) or it could be an array of points that make up a large sphere in the three-dimensional space. Dimensionality reduction is bringing the number of columns down to say, twenty or converting the sphere to a circle in the two-dimensional space." }, { "code": null, "e": 912, "s": 725, "text": "That is all well and good but why should we care? Why would we drop 80 columns off our dataset when we could straight up feed it to our machine learning algorithm and let it do the rest?" }, { "code": null, "e": 1135, "s": 912, "text": "We care because the curse of dimensionality demands that we do. The curse of dimensionality refers to all the problems that arise when working with data in the higher dimensions, that did not exist in the lower dimensions." }, { "code": null, "e": 1366, "s": 1135, "text": "As the number of features increase, the number of samples also increases proportionally. The more features we have, the more number of samples we will need to have all combinations of feature values well represented in our sample." }, { "code": null, "e": 1724, "s": 1366, "text": "As the number of features increases, the model becomes more complex. The more the number of features, the more the chances of overfitting. A machine learning model that is trained on a large number of features, gets increasingly dependent on the data it was trained on and in turn overfitted, resulting in poor performance on real data, beating the purpose." }, { "code": null, "e": 2007, "s": 1724, "text": "Avoiding overfitting is a major motivation for performing dimensionality reduction. The fewer features our training data has, the lesser assumptions our model makes and the simpler it will be. But that is not all and dimensionality reduction has a lot more advantages to offer, like" }, { "code": null, "e": 2302, "s": 2007, "text": "Less misleading data means model accuracy improves.Less dimensions mean less computing. Less data means that algorithms train faster.Less data means less storage space required.Less dimensions allow usage of algorithms unfit for a large number of dimensionsRemoves redundant features and noise." }, { "code": null, "e": 2354, "s": 2302, "text": "Less misleading data means model accuracy improves." }, { "code": null, "e": 2437, "s": 2354, "text": "Less dimensions mean less computing. Less data means that algorithms train faster." }, { "code": null, "e": 2482, "s": 2437, "text": "Less data means less storage space required." }, { "code": null, "e": 2563, "s": 2482, "text": "Less dimensions allow usage of algorithms unfit for a large number of dimensions" }, { "code": null, "e": 2601, "s": 2563, "text": "Removes redundant features and noise." }, { "code": null, "e": 2714, "s": 2601, "text": "Dimensionality reduction could be done by both feature selection methods as well as feature engineering methods." }, { "code": null, "e": 2961, "s": 2714, "text": "Feature selection is the process of identifying and selecting relevant features for your sample. Feature engineering is manually generating new features from existing features, by applying some transformation or performing some operation on them." }, { "code": null, "e": 3770, "s": 2961, "text": "Feature selection can be done either manually or programmatically. For example, consider you are trying to build a model which predicts people’s weights and you have collected a large corpus of data which describes each person quite thoroughly. If you had a column that described the color of each person’s clothing, would that be much help in predicting their weight? I think we can safely agree it won’t be. This is something we can drop without further ado. What about a column that described their heights? That’s a definite yes. We can make these simple manual feature selections and reduce the dimensionality when the relevance or irrelevance of certain features are obvious or common knowledge. And when its not glaringly obvious, there are a lot of tools we could employ to aid our feature selection." }, { "code": null, "e": 3976, "s": 3770, "text": "Heatmaps that show the correlation between features is a good idea.So is just visualising the relationship between the features and the target variable by plotting each feature against the target variable." }, { "code": null, "e": 4044, "s": 3976, "text": "Heatmaps that show the correlation between features is a good idea." }, { "code": null, "e": 4183, "s": 4044, "text": "So is just visualising the relationship between the features and the target variable by plotting each feature against the target variable." }, { "code": null, "e": 4316, "s": 4183, "text": "Now let us look at a few programmatic methods for feature selection from the popular machine learning library sci-kit learn, namely," }, { "code": null, "e": 4360, "s": 4316, "text": "Variance Threshold andUnivariate selection." }, { "code": null, "e": 4383, "s": 4360, "text": "Variance Threshold and" }, { "code": null, "e": 4405, "s": 4383, "text": "Univariate selection." }, { "code": null, "e": 4687, "s": 4405, "text": "Variance Threshold is a baseline approach to feature selection. As the name suggests, it drops all features where the variance along the column does not exceed a threshold value. The premise is that a feature which doesn’t vary much within itself, has very little predictive power." }, { "code": null, "e": 4844, "s": 4687, "text": ">>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]>>> selector = VarianceThreshold()>>> selector.fit_transform(X)array([[2, 0], [1, 4], [1, 1]])" }, { "code": null, "e": 5498, "s": 4844, "text": "Univariate Feature Selection uses statistical tests to select features. Univariate describes a type of data which consists of observations on only a single characteristic or attribute. Univariate feature selection examines each feature individually to determine the strength of the relationship of the feature with the response variable. Some examples of statistical tests that can be used to evaluate feature relevance are Pearson Correlation, Maximal information coefficient, Distance correlation, ANOVA and Chi-square. Chi-square is used to find the relationship between categorical variables and Anova is preferred when the variables are continuous." }, { "code": null, "e": 6311, "s": 5498, "text": "Scikit-learn exposes feature selection routines likes SelectKBest, SelectPercentile or GenericUnivariateSelect as objects that implement a transform method based on the score of anova or chi2 or mutual information. Sklearn offers f_regression and mutual_info_regression as the scoring functions for regression and f_classif and mutual_info_classif for classification. F-Test checks for and only captures linear relationships between features and labels. A highly correlated feature is given higher score and less correlated features are given lower score. Correlation is highly deceptive as it doesn’t capture strong non-linear relationships. On the other hand, mutual information methods can capture any kind of statistical dependency, but being nonparametric, they require more samples for accurate estimation." }, { "code": null, "e": 6468, "s": 6311, "text": "Feature selection is the simplest of dimensionality reduction methods. We will look at a few feature engineering methods for dimensionality reduction later." }, { "code": null, "e": 6585, "s": 6468, "text": "The most common and well known dimensionality reduction methods are the ones that apply linear transformations, like" }, { "code": null, "e": 7444, "s": 6585, "text": "PCA (Principal Component Analysis) : Popularly used for dimensionality reduction in continuous data, PCA rotates and projects data along the direction of increasing variance. The features with the maximum variance are the principal components.Factor Analysis : a technique that is used to reduce a large number of variables into fewer numbers of factors. The values of observed data are expressed as functions of a number of possible causes in order to find which are the most important. The observations are assumed to be caused by a linear transformation of lower dimensional latent factors and added Gaussian noise.LDA (Linear Discriminant Analysis): projects data in a way that the class separability is maximised. Examples from same class are put closely together by the projection. Examples from different classes are placed far apart by the projection" }, { "code": null, "e": 7688, "s": 7444, "text": "PCA (Principal Component Analysis) : Popularly used for dimensionality reduction in continuous data, PCA rotates and projects data along the direction of increasing variance. The features with the maximum variance are the principal components." }, { "code": null, "e": 8064, "s": 7688, "text": "Factor Analysis : a technique that is used to reduce a large number of variables into fewer numbers of factors. The values of observed data are expressed as functions of a number of possible causes in order to find which are the most important. The observations are assumed to be caused by a linear transformation of lower dimensional latent factors and added Gaussian noise." }, { "code": null, "e": 8305, "s": 8064, "text": "LDA (Linear Discriminant Analysis): projects data in a way that the class separability is maximised. Examples from same class are put closely together by the projection. Examples from different classes are placed far apart by the projection" }, { "code": null, "e": 8883, "s": 8305, "text": "Non-linear transformation methods or manifold learning methods are used when the data doesn’t lie on a linear subspace. It is based on the manifold hypothesis which says that in a high dimensional structure, most relevant information is concentrated in small number of low dimensional manifolds. If a linear subspace is a flat sheet of paper, then a rolled up sheet of paper is a simple example of a nonlinear manifold. Informally, this is called a Swiss roll, a canonical problem in the field of non-linear dimensionality reduction. Some popular manifold learning methods are," }, { "code": null, "e": 10247, "s": 8883, "text": "Multi-dimensional scaling (MDS) : A technique used for analyzing similarity or dissimilarity of data as distances in a geometric spaces. Projects data to a lower dimension such that data points that are close to each other (in terms if Euclidean distance) in the higher dimension are close in the lower dimension as well.Isometric Feature Mapping (Isomap) : Projects data to a lower dimension while preserving the geodesic distance (rather than Euclidean distance as in MDS). Geodesic distance is the shortest distance between two points on a curve.Locally Linear Embedding (LLE): Recovers global non-linear structure from linear fits. Each local patch of the manifold can be written as a linear, weighted sum of its neighbours given enough data.Hessian Eigenmapping (HLLE): Projects data to a lower dimension while preserving the local neighbourhood like LLE but uses the Hessian operator to better achieve this result and hence the name.Spectral Embedding (Laplacian Eigenmaps): Uses spectral techniques to perform dimensionality reduction by mapping nearby inputs to nearby outputs. It preserves locality rather than local linearityt-distributed Stochastic Neighbor Embedding (t-SNE): Computes the probability that pairs of data points in the high-dimensional space are related and then chooses a low-dimensional embedding which produce a similar distribution." }, { "code": null, "e": 10569, "s": 10247, "text": "Multi-dimensional scaling (MDS) : A technique used for analyzing similarity or dissimilarity of data as distances in a geometric spaces. Projects data to a lower dimension such that data points that are close to each other (in terms if Euclidean distance) in the higher dimension are close in the lower dimension as well." }, { "code": null, "e": 10798, "s": 10569, "text": "Isometric Feature Mapping (Isomap) : Projects data to a lower dimension while preserving the geodesic distance (rather than Euclidean distance as in MDS). Geodesic distance is the shortest distance between two points on a curve." }, { "code": null, "e": 10996, "s": 10798, "text": "Locally Linear Embedding (LLE): Recovers global non-linear structure from linear fits. Each local patch of the manifold can be written as a linear, weighted sum of its neighbours given enough data." }, { "code": null, "e": 11190, "s": 10996, "text": "Hessian Eigenmapping (HLLE): Projects data to a lower dimension while preserving the local neighbourhood like LLE but uses the Hessian operator to better achieve this result and hence the name." }, { "code": null, "e": 11387, "s": 11190, "text": "Spectral Embedding (Laplacian Eigenmaps): Uses spectral techniques to perform dimensionality reduction by mapping nearby inputs to nearby outputs. It preserves locality rather than local linearity" }, { "code": null, "e": 11616, "s": 11387, "text": "t-distributed Stochastic Neighbor Embedding (t-SNE): Computes the probability that pairs of data points in the high-dimensional space are related and then chooses a low-dimensional embedding which produce a similar distribution." }, { "code": null, "e": 11960, "s": 11616, "text": "Another popular dimensionality reduction method that gives spectacular results are auto-encoders, a type of artificial neural network that aims to copy their inputs to their outputs. They compress the input into a latent-space representation, and then reconstructs the output from this representation. An autoencoder is composed of two parts :" }, { "code": null, "e": 12094, "s": 11960, "text": "Encoder: compresses the input into a latent-space representation.Decoder: reconstruct the input from the latent space representation." }, { "code": null, "e": 12160, "s": 12094, "text": "Encoder: compresses the input into a latent-space representation." }, { "code": null, "e": 12229, "s": 12160, "text": "Decoder: reconstruct the input from the latent space representation." } ]
Angular 8 - Form Validation
Form validation is an important part of web application. It is used to validate whether the user input is in correct format or not. Let’s perform simple required field validation in angular. Open command prompt and go to reactive-form-app. cd /go/to/reactive-form-app Replace the below code in test.component.ts file. import { Component, OnInit } from '@angular/core'; //import validator and FormBuilder import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { //Create FormGroup requiredForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm(); } //Create required field validator for name myForm() { this.requiredForm = this.fb.group({ name: ['', Validators.required ] }); } ngOnInit() { } } Here, We have used form builder to handle all the validation. Constructor is used to create a form with the validation rules. Add the below code inside test.component.html file. <div> <h2> Required Field validation </h2> <form [formGroup]="requiredForm" novalidate> <div class="form-group"> <label class="center-block">Name: <input class="form-control" formControlName="name"> </label> </div> <div *ngIf="requiredForm.controls['name'].invalid && requiredForm.controls['name'].touched" class="alert alert-danger"> <div *ngIf="requiredForm.controls['name'].errors.required"> Name is required. </div> </div> </form> <p>Form value: {{ requiredForm.value | json }}</p> <p>Form status: {{ requiredForm.status | json }}</p> </div> Here, requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm. requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm. Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message. Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message. Finally, start your application (if not done already) using the below command − ng serve Now run your application and put focus on text box. Then, it will use show Name is required as shown below − If you enter text in the textbox, then it is validated and the output is shown below − PatternValidator is used to validate regex pattern. Let’s perform simple email validation. Open command prompt and to reactive-form-app. cd /go/to/reactive-form-app Replace below code in test.component.ts file − import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { requiredForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm(); } myForm() { this.requiredForm = this.fb.group({ email: ['', [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")] ] }); } ngOnInit() { } } Here, Added email pattern validator inside the Validator. Update below code in test.component.html file − <div> <h2> Pattern validation </h2> <form [formGroup]="requiredForm" novalidate> <div class="form-group"> <label class="center-block">Email: <input class="form-control" formControlName="email"> </label> </div> <div *ngIf="requiredForm.controls['email'].invalid && requiredForm.controls['email'].touched" class="alert alert-danger"> <div *ngIf="requiredForm.controls['email'].errors.required"> Email is required. </div> </div> </form> <p>Form value: {{ requiredForm.value | json }}</p> <p>Form status: {{ requiredForm.status | json }}</p> </div> Here, we have created the email control and called email validator. Run your application and you could see the below result − Similarly, you can try yourself to perform other types of validators. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2388, "text": "Form validation is an important part of web application. It is used to validate whether the user input is in correct format or not." }, { "code": null, "e": 2579, "s": 2520, "text": "Let’s perform simple required field validation in angular." }, { "code": null, "e": 2628, "s": 2579, "text": "Open command prompt and go to reactive-form-app." }, { "code": null, "e": 2656, "s": 2628, "text": "cd /go/to/reactive-form-app" }, { "code": null, "e": 2706, "s": 2656, "text": "Replace the below code in test.component.ts file." }, { "code": null, "e": 3347, "s": 2706, "text": "import { Component, OnInit } from '@angular/core';\n\n//import validator and FormBuilder\nimport { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\n\nexport class TestComponent implements OnInit {\n //Create FormGroup\n requiredForm: FormGroup;\n constructor(private fb: FormBuilder) {\n this.myForm();\n }\n\n //Create required field validator for name\n myForm() {\n this.requiredForm = this.fb.group({\n name: ['', Validators.required ]\n });\n }\n ngOnInit()\n {\n\n }\n}" }, { "code": null, "e": 3353, "s": 3347, "text": "Here," }, { "code": null, "e": 3473, "s": 3353, "text": "We have used form builder to handle all the validation. Constructor is used to create a form with the validation rules." }, { "code": null, "e": 3525, "s": 3473, "text": "Add the below code inside test.component.html file." }, { "code": null, "e": 4199, "s": 3525, "text": "<div>\n <h2>\n Required Field validation\n </h2>\n <form [formGroup]=\"requiredForm\" novalidate>\n <div class=\"form-group\">\n <label class=\"center-block\">Name:\n <input class=\"form-control\" formControlName=\"name\">\n </label>\n </div>\n <div *ngIf=\"requiredForm.controls['name'].invalid && requiredForm.controls['name'].touched\" class=\"alert alert-danger\">\n <div *ngIf=\"requiredForm.controls['name'].errors.required\">\n Name is required.\n </div>\n </div>\n </form>\n <p>Form value: {{ requiredForm.value | json }}</p>\n <p>Form status: {{ requiredForm.status | json }}</p>\n </div>" }, { "code": null, "e": 4205, "s": 4199, "text": "Here," }, { "code": null, "e": 4323, "s": 4205, "text": "requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm." }, { "code": null, "e": 4441, "s": 4323, "text": "requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm." }, { "code": null, "e": 4581, "s": 4441, "text": "Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message." }, { "code": null, "e": 4721, "s": 4581, "text": "Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message." }, { "code": null, "e": 4801, "s": 4721, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 4810, "s": 4801, "text": "ng serve" }, { "code": null, "e": 4919, "s": 4810, "text": "Now run your application and put focus on text box. Then, it will use show Name is required as shown below −" }, { "code": null, "e": 5006, "s": 4919, "text": "If you enter text in the textbox, then it is validated and the output is shown below −" }, { "code": null, "e": 5097, "s": 5006, "text": "PatternValidator is used to validate regex pattern. Let’s perform simple email validation." }, { "code": null, "e": 5143, "s": 5097, "text": "Open command prompt and to reactive-form-app." }, { "code": null, "e": 5171, "s": 5143, "text": "cd /go/to/reactive-form-app" }, { "code": null, "e": 5218, "s": 5171, "text": "Replace below code in test.component.ts file −" }, { "code": null, "e": 5835, "s": 5218, "text": "import { Component, OnInit } from '@angular/core';\n\nimport { FormGroup, FormControl, Validators, FormBuilder } from \n'@angular/forms';\n\n@Component({\n selector: 'app-test',\n templateUrl: './test.component.html',\n styleUrls: ['./test.component.css']\n})\n\nexport class TestComponent implements OnInit {\n requiredForm: FormGroup;\n constructor(private fb: FormBuilder) {\n this.myForm();\n }\n\n myForm() {\n this.requiredForm = this.fb.group({\n email: ['', [Validators.required, \n Validators.pattern(\"^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$\")] ]\n });\n }\n\n ngOnInit()\n {\n\n }\n}" }, { "code": null, "e": 5841, "s": 5835, "text": "Here," }, { "code": null, "e": 5893, "s": 5841, "text": "Added email pattern validator inside the Validator." }, { "code": null, "e": 5941, "s": 5893, "text": "Update below code in test.component.html file −" }, { "code": null, "e": 6556, "s": 5941, "text": "<div>\n <h2>\n Pattern validation\n </h2>\n <form [formGroup]=\"requiredForm\" novalidate>\n <div class=\"form-group\">\n <label class=\"center-block\">Email:\n <input class=\"form-control\" formControlName=\"email\">\n </label>\n </div>\n <div *ngIf=\"requiredForm.controls['email'].invalid && requiredForm.controls['email'].touched\" class=\"alert alert-danger\">\n <div *ngIf=\"requiredForm.controls['email'].errors.required\">\n Email is required.\n </div>\n </div>\n </form>\n <p>Form value: {{ requiredForm.value | json }}</p>\n <p>Form status: {{ requiredForm.status | json }}</p>\n</div>" }, { "code": null, "e": 6624, "s": 6556, "text": "Here, we have created the email control and called email validator." }, { "code": null, "e": 6682, "s": 6624, "text": "Run your application and you could see the below result −" }, { "code": null, "e": 6752, "s": 6682, "text": "Similarly, you can try yourself to perform other types of validators." }, { "code": null, "e": 6787, "s": 6752, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6801, "s": 6787, "text": " Anadi Sharma" }, { "code": null, "e": 6836, "s": 6801, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6850, "s": 6836, "text": " Anadi Sharma" }, { "code": null, "e": 6885, "s": 6850, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6905, "s": 6885, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6940, "s": 6905, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6957, "s": 6940, "text": " Frahaan Hussain" }, { "code": null, "e": 6990, "s": 6957, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7002, "s": 6990, "text": " Senol Atac" }, { "code": null, "e": 7037, "s": 7002, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7049, "s": 7037, "text": " Senol Atac" }, { "code": null, "e": 7056, "s": 7049, "text": " Print" }, { "code": null, "e": 7067, "s": 7056, "text": " Add Notes" } ]
Creating an environment with Airflow and DBT on AWS (part 2) | by Arthur Chaves | Towards Data Science
In part 1 of this article, we launched an EC2 instance, installed some OS requirements and then Airflow. Now, we are going to install DBT. But first let’s make some settings to simplify some things. Until now, we were connecting to the EC2 instance using the default user, ec2-user. Then we switched to the user Airflow, the owner of our installations. We can simplify the connection step, allowing the connection with the airflow user directly. To do this, first go to VSCode, connect to the EC2 instance and switch to the airflow user. Now, we need to create a directory to store the ssh authorized keys, copy the file with them (the file allows the connection using the .pem file generated when we launched the instance) and adjust some permissions. Here are the commands. $ mkdir ~/.ssh$ sudo cp /home/ec2-user/.ssh/authorized_keys ~/.ssh/authorized_keys$ sudo chown airflow:airflow ~/.ssh/authorized_keys$ sudo chmod 700 ~/.ssh$ sudo chmod 600 ~/.ssh/authorized_keys In VSCode, press F1, type SSH and choose “Add new SSH host”. Now, use the same command we used in part 1, but changing the user. ssh -i airflow_server.pem airflow@myinstancehost Follow the same instructions of part1 to adjust the path for the .pem file in the SSH configuration file, choose a name for the new connection and then save the file. After that, press F1 again, choose Connect to host and choose the new connection. Now you’re connected to the instance with the airflow user. Whenever you need to stop the instance and connect again, you could consider just use this connection, with this user. To start Airflow as we did in part 1, we could just run the airflow commands (webserver and scheduler). But we would have to open two terminals and leave them opened on VSCode. We could just use nohup to detach the command from the terminal. A even better option is to run these services as daemons. This can make easier not only to start/stop the services, but to automatically start the services along with the instance. To do this we will use the files available in Airflow github, with some adjusts. First, create a file in /etc/sysconfig, named airflow: $ sudo vi /etc/sysconfig/airflow And the content: AIRFLOW_CONFIG=/home/airflow/airflow/airflow.cfgLD_LIBRARY_PATH=/usr/local/lib This defines two environment variables which will be used when running Airflow commands, with the path for the airflow configuration file and for the directory with the correct version of sqlite. Now, create a file in /usr/lib/systemd/system named airflow-webserver.service: $ sudo vi /usr/lib/systemd/system/airflow-webserver.service And the content as below. Notice that I am passing the port, even though I am using the default, 8080. If you intend to have other application running in the same server using the 8080 port, you can change to use another one: [Unit]Description=Airflow webserver daemonAfter=network.target postgresql.service mysql.service redis.service rabbitmq-server.serviceWants=postgresql.service mysql.service redis.service rabbitmq-server.service[Service]PIDFile=/run/airflow/webserver.pidEnvironmentFile=/etc/sysconfig/airflowUser=airflowGroup=airflowType=simpleExecStart=/usr/bin/bash -c 'source /home/airflow/.venv/airflow/bin/activate; airflow webserver -p 8080 --pid /run/airflow/webserver.pid'ExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s TERM $MAINPIDRestart=on-failureRestartSec=5sPrivateTmp=true[Install]WantedBy=multi-user.target Create another file in the same directory, named airflow-scheduler.service: $ sudo vi /usr/lib/systemd/system/airflow-scheduler.service And the content: [Unit]Description=Airflow scheduler daemonAfter=network.target postgresql.service mysql.service redis.service rabbitmq-server.serviceWants=postgresql.service mysql.service redis.service rabbitmq-server.service[Service]PIDFile=/run/airflow/webserver.pidEnvironmentFile=/etc/sysconfig/airflowUser=airflowGroup=airflowType=simpleExecStart=/usr/bin/bash -c 'source /home/airflow/.venv/airflow/bin/activate; airflow scheduler --pid /run/airflow/webserver.pid'KillMode=processRestart=alwaysRestartSec=5s[Install]WantedBy=multi-user.target Finally, create a file /usr/lib/tmpfiles.d/airflow.conf, with: $ sudo vi /usr/lib/tmpfiles.d/airflow.conf And the content below: D /run/airflow 0755 airflow airflow Now create one directory, owned by airflow: $ sudo mkdir /run/airflow$ sudo chown -R airflow:airflow /run/airflow Ok, now the two services, Scheduler and Webserver, are able to run as daemons. To make them start automatically, just run these commands: $ sudo systemctl enable airflow-webserver.service$ sudo systemctl enable airflow-scheduler.service If you still haven’t started Airflow since you started your instance, now you can do this just by running: $ sudo systemctl start airflow-webserver.service$ sudo systemctl start airflow-scheduler.service To check the status of the services, you can run the commands $ sudo systemctl status airflow-webserver.service$ sudo systemctl status airflow-scheduler.service The result we expect is the status “active (running)” on green. If you ever have something different, showing the service is not running, you can check the output of the services with the commands (the 100 is the number of lines I want to show, you can change it): $ journalctl -u airflow-webserver -n 100$ journalctl -u airflow-scheduler -n 100 Now, it’s time to install DBT. Since we are going to use Airflow to orchestrate DBT jobs and want to make a simple and cheap configuration, we will install it on the same server. If you follow the part 1 of this article, you already installed all the OS requirements. Now we just need to install the Python packages. First, activate the python environment we created: $ source ~/.venv/airflow/bin/activate Now, install these two packages required to install DBT $ pip3 install pyicu-binary pyicu Finally, we can now install dbt, with the command: $ pip3 install dbt After a few seconds, you will have the successful message. If, during the installation of dbt, you have some message of failure informing something about .h files not found, it’s probably because gcc package is looking only for the /usr/include folder. If this happens, run the following command to create symbolic links to the headers in the folder where gcc is trying to find them: $ sudo ln -sv /usr/include/python2.7/* /usr/include/ You can then check if everything worked, by using: $ dbt --version The command will show the version of dbt and its plugins. DBT is a tool to run on a Data Warehouse. Altough it is compatible with Redshift, it is also with Postgres. To avoid some unexpected billing with Redshift (due do free tier period expired or cluster configured with resources/time above the free tier), which could be really expensive, we are going to use Postgres, on RDS. You can choose to use Redshift, just pay atention to the configurations we are going to make and you’ll probably manage to switch when needed. Also remember to use the port 5439, instead of 5432. First, go to the AWS Management Console and access the RDS page. Select create database. In the configuration page, select the ‘Standard create’, choose ‘PostgreSQL’, and you can keep the 12.5-R1 version. Choose the Free tier template, to make easier to configure this database. Choose any name to your instance, the master username and some password. In the “Public access” option, that you need to choose ‘Yes’, so you can connect from your network. You don’t need to change any of the other options in this page, so just click on ‘Create database’. You will be redirected to the list of databases. Select the one you just created. Wait some minutes until you see the status is ‘Available’. Click on the name of the database, to enter in the configuration page. In the ‘Connectivity and security’ tab, click on the link in ‘VPC security groups’. You will open the security group rules to the database. In the bottom of the page, there are some tabs. Select inbound rules, and then ‘Edit inbound rules’. Click on ‘Add rule’. In the type, choose ‘PostgreSQL’, and in source, use the private IP of your EC2 instance. Then, click on ‘Save rules’. If you can’t find this IP, you just have to open the EC2 page on a new tab, select your instance, and copy the IP in “Private IPv4 addresses”. Now, connect to your new database (I suggest to use DBeaver, but you’re free to choose you own tool). Within the default database, postgres, create two schemas, one named ‘data_warehouse’ and the other named ‘data_lake’. If you rather, you can also create a specific database to do this, but I’ll keep simple, and use the postgres database. Also, create a table on your database and add some data. Just run this on DBeaver: create table data_lake.user (name varchar(256), birth_date DATE, email varchar(256));insert into data_lake.user values('Ted Mosby', '1978-07-04', '[email protected]'),('Robin Scherbatsky', '1980-12-04', '[email protected]'),('Barney Stinson', '1976-11-02', '[email protected]'),('Marshall Eriksen', '1978-03-16', '[email protected]'),('Lily Aldrin', '1979-09-22', '[email protected]'); The first thing we need to configure is the profiles file. In this file, we put the information to connect to our Data Warehouse, so when we have different bases and schemas, here is where we are going to add them. The default path to store this file is in a hidden folder named .dbt. You can also change the permissions to avoid unauthorized access to this file, cause for now, we are going to keep the password in this file. So, to create the directory and the file: $ mkdir ~/.dbt$ vi ~/.dbt/profiles.yml And add the information to connect to your database, switching to your own information when it is the case: dw_dev: target: data_warehouse outputs: data_warehouse: type: postgres host: your-db-host user: postgres pass: postgres port: 5432 dbname: postgres schema: data_warehouse threads: 4 keepalives_idle: 0 Now, we need to create the dbt_project file. This file contains the information about the project. Let’s also create a folder to keep the files we are going to use with DBT: $ mkdir ~/dbt$ cd ~/dbt$ vi ~/dbt/dbt_project.yml In DBT page, you can find an example of this file. For now, we are going to add just some properties. After you advance in your usage of DBT, you can add other properties. So, add the following to this file: name: 'project_dbt_airflow'config-version: 2version: 1.0profile: dw_devsource-paths: ['source']data-paths: ['data']test-paths: ['test']analysis-paths: ['analysis']macro-paths: ['macro']snapshot-paths: ['snapshots']models: +materialized: table +enabled: true Now, create the folder to store the models (the .sql files). As you can see in the content of the previous file, we could also have other directories (for tests, macros etc.), but we are not going to use them for now. Also, create a file to run our first model on DBT: $ mkdir ~/dbt/source$ vi ~/dbt/source/user.sql And add just this one line: select * from data_lake.user Now, we are ready to run dbt for the first time. Go to the dbt project folder and run the dbt command: $ cd ~/dbt$ dbt run What DBT just did now was to run the query and then create a model (in this case, a table) with the result of the query. If you have an architecture in which you can access the source data from the data warehouse connection (like a data lake on s3, accessed by a data warehouse on Redshift with Spectrum), you can just run your models querying your source like this. If that is not the case, you would first have to move the data from your source to your data warehouse (as it is specified on the DBT documentation, it works only with the T of ETL). But you can always add some step on Airflow to do this as part of your pipeline. Anyway, you can check the data in your data warehouse on DBeaver, using: select * from data_warehouse.user; Now, we have installed DBT and Airflow on our instance. In the next parts, we are going to integrate them, using Airflow to orchestrate DBT jobs, and also use DBT Cloud, to check other option of integration. Part 1: Launching an instance and installing AirflowPart 2: Installing DBT and some settings to make the work easierPart 3: Using DBT Cloud and integrating Airflow with DBT https://www.getdbt.com/https://airflow.apache.org/https://github.com/apache/airflow/tree/master/scripts/systemdhttps://docs.getdbt.com/reference/dbt_project.yml Sources that helped me with the bases of most what I did here:https://www.datascienceacademy.com.brhttps://docs.getdbt.com/docs/introduction
[ { "code": null, "e": 371, "s": 172, "text": "In part 1 of this article, we launched an EC2 instance, installed some OS requirements and then Airflow. Now, we are going to install DBT. But first let’s make some settings to simplify some things." }, { "code": null, "e": 948, "s": 371, "text": "Until now, we were connecting to the EC2 instance using the default user, ec2-user. Then we switched to the user Airflow, the owner of our installations. We can simplify the connection step, allowing the connection with the airflow user directly. To do this, first go to VSCode, connect to the EC2 instance and switch to the airflow user. Now, we need to create a directory to store the ssh authorized keys, copy the file with them (the file allows the connection using the .pem file generated when we launched the instance) and adjust some permissions. Here are the commands." }, { "code": null, "e": 1144, "s": 948, "text": "$ mkdir ~/.ssh$ sudo cp /home/ec2-user/.ssh/authorized_keys ~/.ssh/authorized_keys$ sudo chown airflow:airflow ~/.ssh/authorized_keys$ sudo chmod 700 ~/.ssh$ sudo chmod 600 ~/.ssh/authorized_keys" }, { "code": null, "e": 1273, "s": 1144, "text": "In VSCode, press F1, type SSH and choose “Add new SSH host”. Now, use the same command we used in part 1, but changing the user." }, { "code": null, "e": 1322, "s": 1273, "text": "ssh -i airflow_server.pem airflow@myinstancehost" }, { "code": null, "e": 1489, "s": 1322, "text": "Follow the same instructions of part1 to adjust the path for the .pem file in the SSH configuration file, choose a name for the new connection and then save the file." }, { "code": null, "e": 1750, "s": 1489, "text": "After that, press F1 again, choose Connect to host and choose the new connection. Now you’re connected to the instance with the airflow user. Whenever you need to stop the instance and connect again, you could consider just use this connection, with this user." }, { "code": null, "e": 2173, "s": 1750, "text": "To start Airflow as we did in part 1, we could just run the airflow commands (webserver and scheduler). But we would have to open two terminals and leave them opened on VSCode. We could just use nohup to detach the command from the terminal. A even better option is to run these services as daemons. This can make easier not only to start/stop the services, but to automatically start the services along with the instance." }, { "code": null, "e": 2254, "s": 2173, "text": "To do this we will use the files available in Airflow github, with some adjusts." }, { "code": null, "e": 2309, "s": 2254, "text": "First, create a file in /etc/sysconfig, named airflow:" }, { "code": null, "e": 2342, "s": 2309, "text": "$ sudo vi /etc/sysconfig/airflow" }, { "code": null, "e": 2359, "s": 2342, "text": "And the content:" }, { "code": null, "e": 2438, "s": 2359, "text": "AIRFLOW_CONFIG=/home/airflow/airflow/airflow.cfgLD_LIBRARY_PATH=/usr/local/lib" }, { "code": null, "e": 2634, "s": 2438, "text": "This defines two environment variables which will be used when running Airflow commands, with the path for the airflow configuration file and for the directory with the correct version of sqlite." }, { "code": null, "e": 2713, "s": 2634, "text": "Now, create a file in /usr/lib/systemd/system named airflow-webserver.service:" }, { "code": null, "e": 2773, "s": 2713, "text": "$ sudo vi /usr/lib/systemd/system/airflow-webserver.service" }, { "code": null, "e": 2999, "s": 2773, "text": "And the content as below. Notice that I am passing the port, even though I am using the default, 8080. If you intend to have other application running in the same server using the 8080 port, you can change to use another one:" }, { "code": null, "e": 3614, "s": 2999, "text": "[Unit]Description=Airflow webserver daemonAfter=network.target postgresql.service mysql.service redis.service rabbitmq-server.serviceWants=postgresql.service mysql.service redis.service rabbitmq-server.service[Service]PIDFile=/run/airflow/webserver.pidEnvironmentFile=/etc/sysconfig/airflowUser=airflowGroup=airflowType=simpleExecStart=/usr/bin/bash -c 'source /home/airflow/.venv/airflow/bin/activate; airflow webserver -p 8080 --pid /run/airflow/webserver.pid'ExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s TERM $MAINPIDRestart=on-failureRestartSec=5sPrivateTmp=true[Install]WantedBy=multi-user.target" }, { "code": null, "e": 3690, "s": 3614, "text": "Create another file in the same directory, named airflow-scheduler.service:" }, { "code": null, "e": 3750, "s": 3690, "text": "$ sudo vi /usr/lib/systemd/system/airflow-scheduler.service" }, { "code": null, "e": 3767, "s": 3750, "text": "And the content:" }, { "code": null, "e": 4300, "s": 3767, "text": "[Unit]Description=Airflow scheduler daemonAfter=network.target postgresql.service mysql.service redis.service rabbitmq-server.serviceWants=postgresql.service mysql.service redis.service rabbitmq-server.service[Service]PIDFile=/run/airflow/webserver.pidEnvironmentFile=/etc/sysconfig/airflowUser=airflowGroup=airflowType=simpleExecStart=/usr/bin/bash -c 'source /home/airflow/.venv/airflow/bin/activate; airflow scheduler --pid /run/airflow/webserver.pid'KillMode=processRestart=alwaysRestartSec=5s[Install]WantedBy=multi-user.target" }, { "code": null, "e": 4363, "s": 4300, "text": "Finally, create a file /usr/lib/tmpfiles.d/airflow.conf, with:" }, { "code": null, "e": 4406, "s": 4363, "text": "$ sudo vi /usr/lib/tmpfiles.d/airflow.conf" }, { "code": null, "e": 4429, "s": 4406, "text": "And the content below:" }, { "code": null, "e": 4465, "s": 4429, "text": "D /run/airflow 0755 airflow airflow" }, { "code": null, "e": 4509, "s": 4465, "text": "Now create one directory, owned by airflow:" }, { "code": null, "e": 4579, "s": 4509, "text": "$ sudo mkdir /run/airflow$ sudo chown -R airflow:airflow /run/airflow" }, { "code": null, "e": 4717, "s": 4579, "text": "Ok, now the two services, Scheduler and Webserver, are able to run as daemons. To make them start automatically, just run these commands:" }, { "code": null, "e": 4816, "s": 4717, "text": "$ sudo systemctl enable airflow-webserver.service$ sudo systemctl enable airflow-scheduler.service" }, { "code": null, "e": 4923, "s": 4816, "text": "If you still haven’t started Airflow since you started your instance, now you can do this just by running:" }, { "code": null, "e": 5020, "s": 4923, "text": "$ sudo systemctl start airflow-webserver.service$ sudo systemctl start airflow-scheduler.service" }, { "code": null, "e": 5082, "s": 5020, "text": "To check the status of the services, you can run the commands" }, { "code": null, "e": 5181, "s": 5082, "text": "$ sudo systemctl status airflow-webserver.service$ sudo systemctl status airflow-scheduler.service" }, { "code": null, "e": 5446, "s": 5181, "text": "The result we expect is the status “active (running)” on green. If you ever have something different, showing the service is not running, you can check the output of the services with the commands (the 100 is the number of lines I want to show, you can change it):" }, { "code": null, "e": 5527, "s": 5446, "text": "$ journalctl -u airflow-webserver -n 100$ journalctl -u airflow-scheduler -n 100" }, { "code": null, "e": 5706, "s": 5527, "text": "Now, it’s time to install DBT. Since we are going to use Airflow to orchestrate DBT jobs and want to make a simple and cheap configuration, we will install it on the same server." }, { "code": null, "e": 5895, "s": 5706, "text": "If you follow the part 1 of this article, you already installed all the OS requirements. Now we just need to install the Python packages. First, activate the python environment we created:" }, { "code": null, "e": 5933, "s": 5895, "text": "$ source ~/.venv/airflow/bin/activate" }, { "code": null, "e": 5989, "s": 5933, "text": "Now, install these two packages required to install DBT" }, { "code": null, "e": 6023, "s": 5989, "text": "$ pip3 install pyicu-binary pyicu" }, { "code": null, "e": 6074, "s": 6023, "text": "Finally, we can now install dbt, with the command:" }, { "code": null, "e": 6093, "s": 6074, "text": "$ pip3 install dbt" }, { "code": null, "e": 6477, "s": 6093, "text": "After a few seconds, you will have the successful message. If, during the installation of dbt, you have some message of failure informing something about .h files not found, it’s probably because gcc package is looking only for the /usr/include folder. If this happens, run the following command to create symbolic links to the headers in the folder where gcc is trying to find them:" }, { "code": null, "e": 6530, "s": 6477, "text": "$ sudo ln -sv /usr/include/python2.7/* /usr/include/" }, { "code": null, "e": 6581, "s": 6530, "text": "You can then check if everything worked, by using:" }, { "code": null, "e": 6597, "s": 6581, "text": "$ dbt --version" }, { "code": null, "e": 6655, "s": 6597, "text": "The command will show the version of dbt and its plugins." }, { "code": null, "e": 7174, "s": 6655, "text": "DBT is a tool to run on a Data Warehouse. Altough it is compatible with Redshift, it is also with Postgres. To avoid some unexpected billing with Redshift (due do free tier period expired or cluster configured with resources/time above the free tier), which could be really expensive, we are going to use Postgres, on RDS. You can choose to use Redshift, just pay atention to the configurations we are going to make and you’ll probably manage to switch when needed. Also remember to use the port 5439, instead of 5432." }, { "code": null, "e": 7379, "s": 7174, "text": "First, go to the AWS Management Console and access the RDS page. Select create database. In the configuration page, select the ‘Standard create’, choose ‘PostgreSQL’, and you can keep the 12.5-R1 version." }, { "code": null, "e": 7526, "s": 7379, "text": "Choose the Free tier template, to make easier to configure this database. Choose any name to your instance, the master username and some password." }, { "code": null, "e": 7626, "s": 7526, "text": "In the “Public access” option, that you need to choose ‘Yes’, so you can connect from your network." }, { "code": null, "e": 7726, "s": 7626, "text": "You don’t need to change any of the other options in this page, so just click on ‘Create database’." }, { "code": null, "e": 7867, "s": 7726, "text": "You will be redirected to the list of databases. Select the one you just created. Wait some minutes until you see the status is ‘Available’." }, { "code": null, "e": 8022, "s": 7867, "text": "Click on the name of the database, to enter in the configuration page. In the ‘Connectivity and security’ tab, click on the link in ‘VPC security groups’." }, { "code": null, "e": 8179, "s": 8022, "text": "You will open the security group rules to the database. In the bottom of the page, there are some tabs. Select inbound rules, and then ‘Edit inbound rules’." }, { "code": null, "e": 8462, "s": 8179, "text": "Click on ‘Add rule’. In the type, choose ‘PostgreSQL’, and in source, use the private IP of your EC2 instance. Then, click on ‘Save rules’. If you can’t find this IP, you just have to open the EC2 page on a new tab, select your instance, and copy the IP in “Private IPv4 addresses”." }, { "code": null, "e": 8564, "s": 8462, "text": "Now, connect to your new database (I suggest to use DBeaver, but you’re free to choose you own tool)." }, { "code": null, "e": 8803, "s": 8564, "text": "Within the default database, postgres, create two schemas, one named ‘data_warehouse’ and the other named ‘data_lake’. If you rather, you can also create a specific database to do this, but I’ll keep simple, and use the postgres database." }, { "code": null, "e": 8886, "s": 8803, "text": "Also, create a table on your database and add some data. Just run this on DBeaver:" }, { "code": null, "e": 9286, "s": 8886, "text": "create table data_lake.user (name varchar(256), birth_date DATE, email varchar(256));insert into data_lake.user values('Ted Mosby', '1978-07-04', '[email protected]'),('Robin Scherbatsky', '1980-12-04', '[email protected]'),('Barney Stinson', '1976-11-02', '[email protected]'),('Marshall Eriksen', '1978-03-16', '[email protected]'),('Lily Aldrin', '1979-09-22', '[email protected]');" }, { "code": null, "e": 9755, "s": 9286, "text": "The first thing we need to configure is the profiles file. In this file, we put the information to connect to our Data Warehouse, so when we have different bases and schemas, here is where we are going to add them. The default path to store this file is in a hidden folder named .dbt. You can also change the permissions to avoid unauthorized access to this file, cause for now, we are going to keep the password in this file. So, to create the directory and the file:" }, { "code": null, "e": 9794, "s": 9755, "text": "$ mkdir ~/.dbt$ vi ~/.dbt/profiles.yml" }, { "code": null, "e": 9902, "s": 9794, "text": "And add the information to connect to your database, switching to your own information when it is the case:" }, { "code": null, "e": 10153, "s": 9902, "text": "dw_dev: target: data_warehouse outputs: data_warehouse: type: postgres host: your-db-host user: postgres pass: postgres port: 5432 dbname: postgres schema: data_warehouse threads: 4 keepalives_idle: 0" }, { "code": null, "e": 10327, "s": 10153, "text": "Now, we need to create the dbt_project file. This file contains the information about the project. Let’s also create a folder to keep the files we are going to use with DBT:" }, { "code": null, "e": 10377, "s": 10327, "text": "$ mkdir ~/dbt$ cd ~/dbt$ vi ~/dbt/dbt_project.yml" }, { "code": null, "e": 10585, "s": 10377, "text": "In DBT page, you can find an example of this file. For now, we are going to add just some properties. After you advance in your usage of DBT, you can add other properties. So, add the following to this file:" }, { "code": null, "e": 10849, "s": 10585, "text": "name: 'project_dbt_airflow'config-version: 2version: 1.0profile: dw_devsource-paths: ['source']data-paths: ['data']test-paths: ['test']analysis-paths: ['analysis']macro-paths: ['macro']snapshot-paths: ['snapshots']models: +materialized: table +enabled: true" }, { "code": null, "e": 11118, "s": 10849, "text": "Now, create the folder to store the models (the .sql files). As you can see in the content of the previous file, we could also have other directories (for tests, macros etc.), but we are not going to use them for now. Also, create a file to run our first model on DBT:" }, { "code": null, "e": 11165, "s": 11118, "text": "$ mkdir ~/dbt/source$ vi ~/dbt/source/user.sql" }, { "code": null, "e": 11193, "s": 11165, "text": "And add just this one line:" }, { "code": null, "e": 11222, "s": 11193, "text": "select * from data_lake.user" }, { "code": null, "e": 11325, "s": 11222, "text": "Now, we are ready to run dbt for the first time. Go to the dbt project folder and run the dbt command:" }, { "code": null, "e": 11345, "s": 11325, "text": "$ cd ~/dbt$ dbt run" }, { "code": null, "e": 11976, "s": 11345, "text": "What DBT just did now was to run the query and then create a model (in this case, a table) with the result of the query. If you have an architecture in which you can access the source data from the data warehouse connection (like a data lake on s3, accessed by a data warehouse on Redshift with Spectrum), you can just run your models querying your source like this. If that is not the case, you would first have to move the data from your source to your data warehouse (as it is specified on the DBT documentation, it works only with the T of ETL). But you can always add some step on Airflow to do this as part of your pipeline." }, { "code": null, "e": 12049, "s": 11976, "text": "Anyway, you can check the data in your data warehouse on DBeaver, using:" }, { "code": null, "e": 12084, "s": 12049, "text": "select * from data_warehouse.user;" }, { "code": null, "e": 12292, "s": 12084, "text": "Now, we have installed DBT and Airflow on our instance. In the next parts, we are going to integrate them, using Airflow to orchestrate DBT jobs, and also use DBT Cloud, to check other option of integration." }, { "code": null, "e": 12465, "s": 12292, "text": "Part 1: Launching an instance and installing AirflowPart 2: Installing DBT and some settings to make the work easierPart 3: Using DBT Cloud and integrating Airflow with DBT" }, { "code": null, "e": 12626, "s": 12465, "text": "https://www.getdbt.com/https://airflow.apache.org/https://github.com/apache/airflow/tree/master/scripts/systemdhttps://docs.getdbt.com/reference/dbt_project.yml" } ]
How to Convert Index to Column in Pandas Dataframe? - GeeksforGeeks
01 Jul, 2020 Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. By default, each row of the dataframe has an index value. The rows in the dataframe are assigned index values from 0 to the (number of rows – 1) in a sequentially order with each row having one index value. There are many ways to convert an index to a column in a pandas dataframe. Let’s create a dataframe. Python3 # importing the pandas library as pdimport pandas as pd # Creating the dataframe dfdf = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf Output: Method 1: The simplest method is to create a new column and pass the indexes of each row into that column by using the Dataframe.index function. Python3 import pandas as pd df = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf['index'] = df.indexdf Output: Method 2: We can also use the Dataframe.reset_index function to convert the index as a column. The inplace parameter reflects the change in the dataframe to stay permanent. Python3 import pandas as pd df = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf.reset_index(level=0, inplace=True)df Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON? Convert integer to string in Python
[ { "code": null, "e": 26141, "s": 26113, "text": "\n01 Jul, 2020" }, { "code": null, "e": 26472, "s": 26141, "text": "Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. " }, { "code": null, "e": 26780, "s": 26472, "text": "By default, each row of the dataframe has an index value. The rows in the dataframe are assigned index values from 0 to the (number of rows – 1) in a sequentially order with each row having one index value. There are many ways to convert an index to a column in a pandas dataframe. Let’s create a dataframe." }, { "code": null, "e": 26788, "s": 26780, "text": "Python3" }, { "code": "# importing the pandas library as pdimport pandas as pd # Creating the dataframe dfdf = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf", "e": 27230, "s": 26788, "text": null }, { "code": null, "e": 27238, "s": 27230, "text": "Output:" }, { "code": null, "e": 27383, "s": 27238, "text": "Method 1: The simplest method is to create a new column and pass the indexes of each row into that column by using the Dataframe.index function." }, { "code": null, "e": 27391, "s": 27383, "text": "Python3" }, { "code": "import pandas as pd df = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf['index'] = df.indexdf", "e": 27792, "s": 27391, "text": null }, { "code": null, "e": 27800, "s": 27792, "text": "Output:" }, { "code": null, "e": 27973, "s": 27800, "text": "Method 2: We can also use the Dataframe.reset_index function to convert the index as a column. The inplace parameter reflects the change in the dataframe to stay permanent." }, { "code": null, "e": 27981, "s": 27973, "text": "Python3" }, { "code": "import pandas as pd df = pd.DataFrame({'Roll Number': ['20CSE29', '20CSE49', '20CSE36', '20CSE44'], 'Name': ['Amelia', 'Sam', 'Dean', 'Jessica'], 'Marks In Percentage': [97, 90, 70, 82], 'Grade': ['A', 'A', 'C', 'B'], 'Subject': ['Physics', 'Physics', 'Physics', 'Physics']}) # Printing the dataframedf.reset_index(level=0, inplace=True)df", "e": 28397, "s": 27981, "text": null }, { "code": null, "e": 28405, "s": 28397, "text": "Output:" }, { "code": null, "e": 28429, "s": 28405, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28443, "s": 28429, "text": "Python-pandas" }, { "code": null, "e": 28450, "s": 28443, "text": "Python" }, { "code": null, "e": 28548, "s": 28450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28566, "s": 28548, "text": "Python Dictionary" }, { "code": null, "e": 28598, "s": 28566, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28620, "s": 28598, "text": "Enumerate() in Python" }, { "code": null, "e": 28662, "s": 28620, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28691, "s": 28662, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28735, "s": 28691, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28772, "s": 28735, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28814, "s": 28772, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28856, "s": 28814, "text": "How To Convert Python Dictionary To JSON?" } ]
How to add a number to a current value in MySQL (multiple times at the same time)?
You can use UPDATE command for this. The syntax is as follows update yourTableName set yourColumnName =yourColumnName +yourIntegerValue where <yourCondition>; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table addANumberToCurrentValueDemo -> ( -> Game_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Game_Score int -> ); Query OK, 0 rows affected (0.67 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1090); Query OK, 1 row affected (0.30 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(204); Query OK, 1 row affected (0.12 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(510); Query OK, 1 row affected (0.14 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(7890); Query OK, 1 row affected (0.14 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(8999); Query OK, 1 row affected (0.11 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1093859); Query OK, 1 row affected (0.11 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(157596); Query OK, 1 row affected (0.11 sec) mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(4857567); Query OK, 1 row affected (0.28 sec) Now you can display all records from the table using select statement. The query is as follows − mysql> select *from addANumberToCurrentValueDemo; The following is the output +---------+------------+ | Game_Id | Game_Score | +---------+------------+ | 1 | 1090 | | 2 | 204 | | 3 | 510 | | 4 | 7890 | | 5 | 9290 | | 6 | 1093859 | | 7 | 157596 | | 8 | 4857567 | +---------+------------+ 8 rows in set (0.05 sec) Here is the query to add a number to a current value in MySQL mysql> update addANumberToCurrentValueDemo set Game_Score=Game_Score+11 where Game_Id=5; Query OK, 1 row affected (0.15 sec) Rows matched: 1 Changed: 1 Warnings: 0 Now check the table records once again to verify the column Game_Score has been updated from 8999 to 9010. The query is as follows − mysql> select *from addANumberToCurrentValueDemo; The following is the output +---------+------------+ | Game_Id | Game_Score | +---------+------------+ | 1 | 1090 | | 2 | 204 | | 3 | 510 | | 4 | 7890 | | 5 | 9301 | | 6 | 1093859 | | 7 | 157596 | | 8 | 4857567 | +---------+------------+ 8 rows in set (0.00 sec)
[ { "code": null, "e": 1099, "s": 1062, "text": "You can use UPDATE command for this." }, { "code": null, "e": 1124, "s": 1099, "text": "The syntax is as follows" }, { "code": null, "e": 1221, "s": 1124, "text": "update yourTableName set yourColumnName =yourColumnName +yourIntegerValue where <yourCondition>;" }, { "code": null, "e": 1318, "s": 1221, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1497, "s": 1318, "text": "mysql> create table addANumberToCurrentValueDemo\n -> (\n -> Game_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Game_Score int\n -> );\nQuery OK, 0 rows affected (0.67 sec)" }, { "code": null, "e": 1590, "s": 1497, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2476, "s": 1590, "text": "mysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1090);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(204);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(510);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(7890);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(8999);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(1093859);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(157596);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into addANumberToCurrentValueDemo(Game_Score) values(4857567);\nQuery OK, 1 row affected (0.28 sec)" }, { "code": null, "e": 2547, "s": 2476, "text": "Now you can display all records from the table using select statement." }, { "code": null, "e": 2573, "s": 2547, "text": "The query is as follows −" }, { "code": null, "e": 2623, "s": 2573, "text": "mysql> select *from addANumberToCurrentValueDemo;" }, { "code": null, "e": 2651, "s": 2623, "text": "The following is the output" }, { "code": null, "e": 2976, "s": 2651, "text": "+---------+------------+\n| Game_Id | Game_Score |\n+---------+------------+\n| 1 | 1090 |\n| 2 | 204 |\n| 3 | 510 |\n| 4 | 7890 |\n| 5 | 9290 |\n| 6 | 1093859 |\n| 7 | 157596 |\n| 8 | 4857567 |\n+---------+------------+\n8 rows in set (0.05 sec)" }, { "code": null, "e": 3038, "s": 2976, "text": "Here is the query to add a number to a current value in MySQL" }, { "code": null, "e": 3202, "s": 3038, "text": "mysql> update addANumberToCurrentValueDemo set Game_Score=Game_Score+11 where Game_Id=5;\nQuery OK, 1 row affected (0.15 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 3309, "s": 3202, "text": "Now check the table records once again to verify the column Game_Score has been updated from 8999 to 9010." }, { "code": null, "e": 3335, "s": 3309, "text": "The query is as follows −" }, { "code": null, "e": 3385, "s": 3335, "text": "mysql> select *from addANumberToCurrentValueDemo;" }, { "code": null, "e": 3413, "s": 3385, "text": "The following is the output" }, { "code": null, "e": 3738, "s": 3413, "text": "+---------+------------+\n| Game_Id | Game_Score |\n+---------+------------+\n| 1 | 1090 |\n| 2 | 204 |\n| 3 | 510 |\n| 4 | 7890 |\n| 5 | 9301 |\n| 6 | 1093859 |\n| 7 | 157596 |\n| 8 | 4857567 |\n+---------+------------+\n8 rows in set (0.00 sec)" } ]
Python program to input a comma separated string - GeeksforGeeks
23 Jan, 2020 Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways: Using List comprehension and split() Using map() and split() Method 1: Using List comprehension and split() split() function helps in getting multiple inputs from the user. It breaks the given input by the specified separator. If the separator is not provided then any white space is used as a separator. Generally, users use a split() method to split a Python string but one can also use it in taking multiple inputs. Example: # Python program to take a comma# separated string as input # Taking input when the numbers # of input are known and storing# in different variables # Taking 2 inputsa, b = [int(x) for x in input("Enter two values\n").split(', ')]print("\nThe value of a is {} and b is {}".format(a, b)) # Taking 3 inputsa, b, c = [int(x) for x in input("Enter three values\n").split(', ')]print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c)) # Taking multiple inputsL = [int(x) for x in input("Enter multiple values\n").split(', ')]print("\nThe values of input are", L) Output: Enter two values 1, 2 The value of a is 1 and b is 2 Enter three values 1, 2, 3 The value of a is 1, b is 2 and c is 3 Enter multiple values 1, 22, 34, 6, 88, 2 The values of input are [1, 22, 34, 6, 88, 2] Method 2: Using map() and split() map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.) # Python program to take a comma# separated string as input # Taking input when the numbers # of input are known and storing# in different variables # Taking 2 inputsa, b = map(int, input("Enter two values\n").split(', '))print("\nThe value of a is {} and b is {}".format(a, b)) # Taking 3 inputsa, b, c = map(int, input("Enter three values\n").split(', '))print("\nThe value of a is {}, b is {} and c is {}".format(a, b, c)) # Taking multiple inputsL = list(map(int, input("Enter multiple values\n").split(', ')))print("\nThe values of input are", L) Output: Enter two values 1, 2 The value of a is 1 and b is 2 Enter three values 1, 2, 3 The value of a is 1, b is 2 and c is 3 Enter multiple values 1, 2, 3, 4 The values of input are [1, 2, 3, 4] python-input-output Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26550, "s": 26522, "text": "\n23 Jan, 2020" }, { "code": null, "e": 26724, "s": 26550, "text": "Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways:" }, { "code": null, "e": 26761, "s": 26724, "text": "Using List comprehension and split()" }, { "code": null, "e": 26785, "s": 26761, "text": "Using map() and split()" }, { "code": null, "e": 26832, "s": 26785, "text": "Method 1: Using List comprehension and split()" }, { "code": null, "e": 27143, "s": 26832, "text": "split() function helps in getting multiple inputs from the user. It breaks the given input by the specified separator. If the separator is not provided then any white space is used as a separator. Generally, users use a split() method to split a Python string but one can also use it in taking multiple inputs." }, { "code": null, "e": 27152, "s": 27143, "text": "Example:" }, { "code": "# Python program to take a comma# separated string as input # Taking input when the numbers # of input are known and storing# in different variables # Taking 2 inputsa, b = [int(x) for x in input(\"Enter two values\\n\").split(', ')]print(\"\\nThe value of a is {} and b is {}\".format(a, b)) # Taking 3 inputsa, b, c = [int(x) for x in input(\"Enter three values\\n\").split(', ')]print(\"\\nThe value of a is {}, b is {} and c is {}\".format(a, b, c)) # Taking multiple inputsL = [int(x) for x in input(\"Enter multiple values\\n\").split(', ')]print(\"\\nThe values of input are\", L) ", "e": 27729, "s": 27152, "text": null }, { "code": null, "e": 27737, "s": 27729, "text": "Output:" }, { "code": null, "e": 27948, "s": 27737, "text": "Enter two values\n1, 2\n\nThe value of a is 1 and b is 2\nEnter three values\n1, 2, 3\n\nThe value of a is 1, b is 2 and c is 3\nEnter multiple values\n1, 22, 34, 6, 88, 2\n\nThe values of input are [1, 22, 34, 6, 88, 2]\n" }, { "code": null, "e": 27982, "s": 27948, "text": "Method 2: Using map() and split()" }, { "code": null, "e": 28113, "s": 27982, "text": "map() function returns a list of the results after applying the given function to each item of a given iterable (list, tuple etc.)" }, { "code": "# Python program to take a comma# separated string as input # Taking input when the numbers # of input are known and storing# in different variables # Taking 2 inputsa, b = map(int, input(\"Enter two values\\n\").split(', '))print(\"\\nThe value of a is {} and b is {}\".format(a, b)) # Taking 3 inputsa, b, c = map(int, input(\"Enter three values\\n\").split(', '))print(\"\\nThe value of a is {}, b is {} and c is {}\".format(a, b, c)) # Taking multiple inputsL = list(map(int, input(\"Enter multiple values\\n\").split(', ')))print(\"\\nThe values of input are\", L)", "e": 28671, "s": 28113, "text": null }, { "code": null, "e": 28679, "s": 28671, "text": "Output:" }, { "code": null, "e": 28872, "s": 28679, "text": "Enter two values\n1, 2\n\nThe value of a is 1 and b is 2\nEnter three values\n1, 2, 3\n\nThe value of a is 1, b is 2 and c is 3\nEnter multiple values\n1, 2, 3, 4\n\nThe values of input are [1, 2, 3, 4]\n" }, { "code": null, "e": 28892, "s": 28872, "text": "python-input-output" }, { "code": null, "e": 28899, "s": 28892, "text": "Python" }, { "code": null, "e": 28915, "s": 28899, "text": "Python Programs" }, { "code": null, "e": 29013, "s": 28915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29031, "s": 29013, "text": "Python Dictionary" }, { "code": null, "e": 29066, "s": 29031, "text": "Read a file line by line in Python" }, { "code": null, "e": 29098, "s": 29066, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29120, "s": 29098, "text": "Enumerate() in Python" }, { "code": null, "e": 29162, "s": 29120, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29205, "s": 29162, "text": "Python program to convert a list to string" }, { "code": null, "e": 29227, "s": 29205, "text": "Defaultdict in Python" }, { "code": null, "e": 29266, "s": 29227, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29312, "s": 29266, "text": "Python | Split string into list of characters" } ]
Construct Binary Tree from given Parent Array representation | Iterative Approach - GeeksforGeeks
02 Jun, 2021 Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.Examples: Input: parent[] = {1, 5, 5, 2, 2, -1, 3} Output: Inorder Traversal of constructed tree 0 1 5 6 3 2 4 5 / \ 1 2 / / \ 0 3 4 / 6 Index of -1 is 5. So 5 is root. 5 is present at indexes 1 and 2. So 1 and 2 are children of 5. 1 is present at index 0, so 0 is child of 1. 2 is present at indexes 3 and 4. So 3 and 4 are children of 2. 3 is present at index 6, so 6 is child of 3. Input: parent[] = {-1, 0, 0, 1, 1, 3, 5} Output: Inorder Traversal of constructed tree 6 5 3 1 4 0 2 0 / \ 1 2 / \ 3 4 / 5 / 6 Approach: Recursive approach to this problem is discussed here. Following is the iterative approach: 1. Create a map with key as the array index and its value as the node for that index. 2. Start traversing the given parent array. 3. For all elements of the given array: (a) Search the map for the current index. (i) If the current index does not exist in the map: .. Create a node for the current index .. Map the newly created node with its key by m[i]=node (ii) If the key exists in the map: .. it means that the node is already created .. Do nothing (b) If the parent of the current index is -1, it implies it is the root of the tree .. Make root=m[i] Else search for the parent in the map (i) If the parent does not exist: .. Create the parent node. .. Assign the current node as its left child .. Map the parent node(as in Step 3.(a).(i)) (ii) If the parent exists: .. If the left child of the parent does not exist -> Assign the node as its left child .. Else (i.e. right child of the parent does not exist) -> Assign the node as its right child This approach works even when the nodes are not given in order.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create new NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Utility function to perform// inorder traversal of the treevoid inorder(Node* root){ if (root != NULL) { inorder(root->left); cout << root->key << " "; inorder(root->right); }} // Function to construct a Binary Tree from parent arrayNode* createTree(int parent[], int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node map<int, Node*> m; Node *root, *temp; int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.find(i) == m.end()) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m[i] = temp; } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m[i]; // Current node is not root and parent // of that node is not created yet else if (m.find(parent[i]) == m.end()) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp->left = m[i]; // Entry of parent in map m[parent[i]] = temp; } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (!m[parent[i]]->left) m[parent[i]]->left = m[i]; // Right child of the parent doesn't exist else m[parent[i]]->right = m[i]; } } return root;} // Driver codeint main(){ int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = sizeof parent / sizeof parent[0]; Node* root = createTree(parent, n); cout << "Inorder Traversal of constructed tree\n"; inorder(root); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // A tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create new Nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Utility function to perform// inorder traversal of the treestatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print( root.key + " "); inorder(root.right); }} // Function to construct a Binary Tree from parent arraystatic Node createTree(int parent[], int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node HashMap<Integer, Node> m=new HashMap<>(); Node root=new Node(), temp=new Node(); int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.get(i) == null) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.put(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m.get(i); // Current node is not root and parent // of that node is not created yet else if (m.get(parent[i]) == null) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m.get(i); // Entry of parent in map m.put(parent[i],temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m.get(parent[i]).left == null) m.get(parent[i]).left = m.get(i); // Right child of the parent doesn't exist else m.get(parent[i]).right = m.get(i); } } return root;} // Driver codepublic static void main(String args[]){ int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = parent.length; Node root = createTree(parent, n); System.out.print( "Inorder Traversal of constructed tree\n"); inorder(root); }} // This code is contributed by Arnab Kundu # Python implementation of the approach # A tree nodeclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility function to create new Nodedef newNode(key: int) -> Node: temp = Node() temp.key = key temp.left = None temp.right = None return temp # Utility function to perform# inorder traversal of the treedef inorder(root: Node): if root is not None: inorder(root.left) print(root.key, end=" ") inorder(root.right) # Function to construct a Binary Tree from parent arraydef createTree(parent: list, n: int) -> Node: # A map to keep track of all the nodes created. # Key: node value; Value: Pointer to that Node m = dict() root = Node() # Iterate for all elements of the parent array. for i in range(n): # Node i does not exist in the map if i not in m: # Create a new node for the current index temp = newNode(i) # Entry of the node in the map with # key as i and value as temp m[i] = temp # If parent is -1 # Current node i is the root # So mark it as the root of the tree if parent[i] == -1: root = m[i] # Current node is not root and parent # of that node is not created yet elif parent[i] not in m: # Create the parent temp = newNode(parent[i]) # Assign the node as the # left child of the parent temp.left = m[i] # Entry of parent in map m[parent[i]] = temp # Current node is not root and parent # of that node is already created else: # Left child of the parent doesn't exist if m[parent[i]].left is None: m[parent[i]].left = m[i] # Right child of the parent doesn't exist else: m[parent[i]].right = m[i] return root # Driver Codeif __name__ == "__main__": parent = [-1, 0, 0, 1, 1, 3, 5] n = len(parent) root = createTree(parent, n) print("Inorder Traversal of constructed tree") inorder(root) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // A tree nodeclass Node{ public int key; public Node left, right;}; // Utility function to create new Nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Utility function to perform// inorder traversal of the treestatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write( root.key + " "); inorder(root.right); }} // Function to construct a Binary Tree from parent arraystatic Node createTree(int []parent, int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node Dictionary<int, Node> m = new Dictionary<int, Node>(); Node root = new Node(), temp = new Node(); int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (!m.ContainsKey(i)) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.Add(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m[i]; // Current node is not root and parent // of that node is not created yet else if (!m.ContainsKey(parent[i])) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m[i]; // Entry of parent in map m.Add(parent[i], temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m[parent[i]].left == null) m[parent[i]].left = m[i]; // Right child of the parent doesn't exist else m[parent[i]].right = m[i]; } } return root;} // Driver codepublic static void Main(String []args){ int []parent = { -1, 0, 0, 1, 1, 3, 5 }; int n = parent.Length; Node root = createTree(parent, n); Console.Write("Inorder Traversal of constructed tree\n"); inorder(root);}} // This code is contributed by Rajput-Ji <script>// javascript implementation of the approach // A tree nodeclass Node { constructor(val) { this.key = val; this.left = null; this.right = null; }} // Utility function to create new Node function newNode(key) {var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Utility function to perform // inorder traversal of the tree function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + " "); inorder(root.right); } } // Function to construct a Binary Tree from parent array function createTree(parent , n) { // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node var m = new Map();var root = new Node(), temp = new Node(); var i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.get(i) == null) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.set(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m.get(i); // Current node is not root and parent // of that node is not created yet else if (m.get(parent[i]) == null) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m.get(i); // Entry of parent in map m.set(parent[i], temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m.get(parent[i]).left == null) m.get(parent[i]).left = m.get(i); // Right child of the parent doesn't exist else m.get(parent[i]).right = m.get(i); } } return root; } // Driver code var parent = [ -1, 0, 0, 1, 1, 3, 5 ]; var n = parent.length;var root = createTree(parent, n); document.write("Inorder Traversal of constructed tree<br/>"); inorder(root); // This code contributed by umadevi9616</script> Inorder Traversal of constructed tree 6 5 3 1 4 0 2 andrew1234 Rajput-Ji sanjeev2552 Akanksha_Rai umadevi9616 Binary Tree Constructive Algorithms Marketing Arrays Tree Arrays Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Find duplicates in O(n) time and O(1) extra space | Set 1 Reversal algorithm for array rotation Next Greater Element Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24822, "s": 24794, "text": "\n02 Jun, 2021" }, { "code": null, "e": 25185, "s": 24822, "text": "Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.Examples: " }, { "code": null, "e": 25808, "s": 25185, "text": "Input: parent[] = {1, 5, 5, 2, 2, -1, 3}\nOutput:\nInorder Traversal of constructed tree\n0 1 5 6 3 2 4\n 5\n / \\\n 1 2\n / / \\\n 0 3 4\n /\n 6 \nIndex of -1 is 5. So 5 is root. \n5 is present at indexes 1 and 2. So 1 and 2 are\nchildren of 5. \n1 is present at index 0, so 0 is child of 1.\n2 is present at indexes 3 and 4. So 3 and 4 are\nchildren of 2. \n3 is present at index 6, so 6 is child of 3.\n\nInput: parent[] = {-1, 0, 0, 1, 1, 3, 5}\nOutput:\nInorder Traversal of constructed tree\n6 5 3 1 4 0 2\n 0\n / \\\n 1 2\n / \\\n 3 4\n /\n 5 \n /\n6" }, { "code": null, "e": 25913, "s": 25810, "text": "Approach: Recursive approach to this problem is discussed here. Following is the iterative approach: " }, { "code": null, "e": 27054, "s": 25913, "text": "1. Create a map with key as the array index and its \n value as the node for that index.\n2. Start traversing the given parent array.\n3. For all elements of the given array:\n (a) Search the map for the current index.\n (i) If the current index does not exist in the map:\n .. Create a node for the current index\n .. Map the newly created node with its key by m[i]=node\n (ii) If the key exists in the map:\n .. it means that the node is already created\n .. Do nothing\n (b) If the parent of the current index is -1, it implies it is\n the root of the tree\n .. Make root=m[i]\n Else search for the parent in the map\n (i) If the parent does not exist:\n .. Create the parent node.\n .. Assign the current node as its left child \n .. Map the parent node(as in Step 3.(a).(i))\n (ii) If the parent exists:\n .. If the left child of the parent does not exist\n -> Assign the node as its left child\n .. Else (i.e. right child of the parent does not exist)\n -> Assign the node as its right child" }, { "code": null, "e": 27170, "s": 27054, "text": "This approach works even when the nodes are not given in order.Below is the implementation of the above approach: " }, { "code": null, "e": 27174, "s": 27170, "text": "C++" }, { "code": null, "e": 27179, "s": 27174, "text": "Java" }, { "code": null, "e": 27187, "s": 27179, "text": "Python3" }, { "code": null, "e": 27190, "s": 27187, "text": "C#" }, { "code": null, "e": 27201, "s": 27190, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create new NodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Utility function to perform// inorder traversal of the treevoid inorder(Node* root){ if (root != NULL) { inorder(root->left); cout << root->key << \" \"; inorder(root->right); }} // Function to construct a Binary Tree from parent arrayNode* createTree(int parent[], int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node map<int, Node*> m; Node *root, *temp; int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.find(i) == m.end()) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m[i] = temp; } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m[i]; // Current node is not root and parent // of that node is not created yet else if (m.find(parent[i]) == m.end()) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp->left = m[i]; // Entry of parent in map m[parent[i]] = temp; } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (!m[parent[i]]->left) m[parent[i]]->left = m[i]; // Right child of the parent doesn't exist else m[parent[i]]->right = m[i]; } } return root;} // Driver codeint main(){ int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = sizeof parent / sizeof parent[0]; Node* root = createTree(parent, n); cout << \"Inorder Traversal of constructed tree\\n\"; inorder(root); return 0;}", "e": 29522, "s": 27201, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // A tree nodestatic class Node{ int key; Node left, right;}; // Utility function to create new Nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Utility function to perform// inorder traversal of the treestatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print( root.key + \" \"); inorder(root.right); }} // Function to construct a Binary Tree from parent arraystatic Node createTree(int parent[], int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node HashMap<Integer, Node> m=new HashMap<>(); Node root=new Node(), temp=new Node(); int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.get(i) == null) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.put(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m.get(i); // Current node is not root and parent // of that node is not created yet else if (m.get(parent[i]) == null) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m.get(i); // Entry of parent in map m.put(parent[i],temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m.get(parent[i]).left == null) m.get(parent[i]).left = m.get(i); // Right child of the parent doesn't exist else m.get(parent[i]).right = m.get(i); } } return root;} // Driver codepublic static void main(String args[]){ int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = parent.length; Node root = createTree(parent, n); System.out.print( \"Inorder Traversal of constructed tree\\n\"); inorder(root); }} // This code is contributed by Arnab Kundu", "e": 32001, "s": 29522, "text": null }, { "code": "# Python implementation of the approach # A tree nodeclass Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility function to create new Nodedef newNode(key: int) -> Node: temp = Node() temp.key = key temp.left = None temp.right = None return temp # Utility function to perform# inorder traversal of the treedef inorder(root: Node): if root is not None: inorder(root.left) print(root.key, end=\" \") inorder(root.right) # Function to construct a Binary Tree from parent arraydef createTree(parent: list, n: int) -> Node: # A map to keep track of all the nodes created. # Key: node value; Value: Pointer to that Node m = dict() root = Node() # Iterate for all elements of the parent array. for i in range(n): # Node i does not exist in the map if i not in m: # Create a new node for the current index temp = newNode(i) # Entry of the node in the map with # key as i and value as temp m[i] = temp # If parent is -1 # Current node i is the root # So mark it as the root of the tree if parent[i] == -1: root = m[i] # Current node is not root and parent # of that node is not created yet elif parent[i] not in m: # Create the parent temp = newNode(parent[i]) # Assign the node as the # left child of the parent temp.left = m[i] # Entry of parent in map m[parent[i]] = temp # Current node is not root and parent # of that node is already created else: # Left child of the parent doesn't exist if m[parent[i]].left is None: m[parent[i]].left = m[i] # Right child of the parent doesn't exist else: m[parent[i]].right = m[i] return root # Driver Codeif __name__ == \"__main__\": parent = [-1, 0, 0, 1, 1, 3, 5] n = len(parent) root = createTree(parent, n) print(\"Inorder Traversal of constructed tree\") inorder(root) # This code is contributed by# sanjeev2552", "e": 34190, "s": 32001, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // A tree nodeclass Node{ public int key; public Node left, right;}; // Utility function to create new Nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Utility function to perform// inorder traversal of the treestatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write( root.key + \" \"); inorder(root.right); }} // Function to construct a Binary Tree from parent arraystatic Node createTree(int []parent, int n){ // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node Dictionary<int, Node> m = new Dictionary<int, Node>(); Node root = new Node(), temp = new Node(); int i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (!m.ContainsKey(i)) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.Add(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m[i]; // Current node is not root and parent // of that node is not created yet else if (!m.ContainsKey(parent[i])) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m[i]; // Entry of parent in map m.Add(parent[i], temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m[parent[i]].left == null) m[parent[i]].left = m[i]; // Right child of the parent doesn't exist else m[parent[i]].right = m[i]; } } return root;} // Driver codepublic static void Main(String []args){ int []parent = { -1, 0, 0, 1, 1, 3, 5 }; int n = parent.Length; Node root = createTree(parent, n); Console.Write(\"Inorder Traversal of constructed tree\\n\"); inorder(root);}} // This code is contributed by Rajput-Ji", "e": 36683, "s": 34190, "text": null }, { "code": "<script>// javascript implementation of the approach // A tree nodeclass Node { constructor(val) { this.key = val; this.left = null; this.right = null; }} // Utility function to create new Node function newNode(key) {var temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp); } // Utility function to perform // inorder traversal of the tree function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + \" \"); inorder(root.right); } } // Function to construct a Binary Tree from parent array function createTree(parent , n) { // A map to keep track of all the nodes created. // Key: node value; Value: Pointer to that Node var m = new Map();var root = new Node(), temp = new Node(); var i; // Iterate for all elements of the parent array. for (i = 0; i < n; i++) { // Node i does not exist in the map if (m.get(i) == null) { // Create a new node for the current index temp = newNode(i); // Entry of the node in the map with // key as i and value as temp m.set(i, temp); } // If parent is -1 // Current node i is the root // So mark it as the root of the tree if (parent[i] == -1) root = m.get(i); // Current node is not root and parent // of that node is not created yet else if (m.get(parent[i]) == null) { // Create the parent temp = newNode(parent[i]); // Assign the node as the // left child of the parent temp.left = m.get(i); // Entry of parent in map m.set(parent[i], temp); } // Current node is not root and parent // of that node is already created else { // Left child of the parent doesn't exist if (m.get(parent[i]).left == null) m.get(parent[i]).left = m.get(i); // Right child of the parent doesn't exist else m.get(parent[i]).right = m.get(i); } } return root; } // Driver code var parent = [ -1, 0, 0, 1, 1, 3, 5 ]; var n = parent.length;var root = createTree(parent, n); document.write(\"Inorder Traversal of constructed tree<br/>\"); inorder(root); // This code contributed by umadevi9616</script>", "e": 39347, "s": 36683, "text": null }, { "code": null, "e": 39399, "s": 39347, "text": "Inorder Traversal of constructed tree\n6 5 3 1 4 0 2" }, { "code": null, "e": 39412, "s": 39401, "text": "andrew1234" }, { "code": null, "e": 39422, "s": 39412, "text": "Rajput-Ji" }, { "code": null, "e": 39434, "s": 39422, "text": "sanjeev2552" }, { "code": null, "e": 39447, "s": 39434, "text": "Akanksha_Rai" }, { "code": null, "e": 39459, "s": 39447, "text": "umadevi9616" }, { "code": null, "e": 39471, "s": 39459, "text": "Binary Tree" }, { "code": null, "e": 39495, "s": 39471, "text": "Constructive Algorithms" }, { "code": null, "e": 39505, "s": 39495, "text": "Marketing" }, { "code": null, "e": 39512, "s": 39505, "text": "Arrays" }, { "code": null, "e": 39517, "s": 39512, "text": "Tree" }, { "code": null, "e": 39524, "s": 39517, "text": "Arrays" }, { "code": null, "e": 39529, "s": 39524, "text": "Tree" }, { "code": null, "e": 39627, "s": 39529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39636, "s": 39627, "text": "Comments" }, { "code": null, "e": 39649, "s": 39636, "text": "Old Comments" }, { "code": null, "e": 39674, "s": 39649, "text": "Window Sliding Technique" }, { "code": null, "e": 39723, "s": 39674, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 39781, "s": 39723, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 39819, "s": 39781, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39840, "s": 39819, "text": "Next Greater Element" }, { "code": null, "e": 39890, "s": 39840, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 39925, "s": 39890, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 39959, "s": 39925, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 39988, "s": 39959, "text": "AVL Tree | Set 1 (Insertion)" } ]
Build your own barcode and QRcode scanner using python | by Pruthvi Hingu | Towards Data Science
Let’s create a program that scans the QR codes and Barcodes from an image. For this program, we need three packages, which are OpenCV, NumPy, and pyzbar. Most of the python programmers are familiar with OpenCV and Numpy libraries. OpenCV is an open-source computer vision and machine learning library. It is a useful library for image processing. We are using this library in our project for processing each frame from a video captured by a device. We are using Numpy here because pyzbar works with OpenCV / numpy ndarrays. Whereas, pyzbar library is used to read barcodes and QR codes from a given image. It supports EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5, and QR Code. So, this is a small introduction to our project and libraries. Install the required libraries using the following commands. For OpenCV pip install opencv-python For pyzbar pip install pyzbar For Numpy pip install numpy Import all the required libraries for our program. import cv2import numpy as npfrom pyzbar.pyzbar import decode Capture the video from the device camera. Now, let’s create a decoder function that decodes barcode and QR code from a given image. This function takes an image, then identifies the QRcode and barcode from the image, and decodes the value of it. Here barcode is a list of barcode and QRcode objects recognized by the decode function. Each object contains rect, polygon, data, type, etc attributes. rect and polygon attributes give the position of barcode and QRcode. Check the final program below. Let’s check the output. You can download the source code from Github. github.com Thanks for reading this piece. Hope to see you again in the next article! Please connect with me through LinkedIn:
[ { "code": null, "e": 994, "s": 172, "text": "Let’s create a program that scans the QR codes and Barcodes from an image. For this program, we need three packages, which are OpenCV, NumPy, and pyzbar. Most of the python programmers are familiar with OpenCV and Numpy libraries. OpenCV is an open-source computer vision and machine learning library. It is a useful library for image processing. We are using this library in our project for processing each frame from a video captured by a device. We are using Numpy here because pyzbar works with OpenCV / numpy ndarrays. Whereas, pyzbar library is used to read barcodes and QR codes from a given image. It supports EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5, and QR Code. So, this is a small introduction to our project and libraries. Install the required libraries using the following commands." }, { "code": null, "e": 1005, "s": 994, "text": "For OpenCV" }, { "code": null, "e": 1031, "s": 1005, "text": "pip install opencv-python" }, { "code": null, "e": 1042, "s": 1031, "text": "For pyzbar" }, { "code": null, "e": 1061, "s": 1042, "text": "pip install pyzbar" }, { "code": null, "e": 1071, "s": 1061, "text": "For Numpy" }, { "code": null, "e": 1089, "s": 1071, "text": "pip install numpy" }, { "code": null, "e": 1140, "s": 1089, "text": "Import all the required libraries for our program." }, { "code": null, "e": 1201, "s": 1140, "text": "import cv2import numpy as npfrom pyzbar.pyzbar import decode" }, { "code": null, "e": 1243, "s": 1201, "text": "Capture the video from the device camera." }, { "code": null, "e": 1333, "s": 1243, "text": "Now, let’s create a decoder function that decodes barcode and QR code from a given image." }, { "code": null, "e": 1668, "s": 1333, "text": "This function takes an image, then identifies the QRcode and barcode from the image, and decodes the value of it. Here barcode is a list of barcode and QRcode objects recognized by the decode function. Each object contains rect, polygon, data, type, etc attributes. rect and polygon attributes give the position of barcode and QRcode." }, { "code": null, "e": 1699, "s": 1668, "text": "Check the final program below." }, { "code": null, "e": 1723, "s": 1699, "text": "Let’s check the output." }, { "code": null, "e": 1769, "s": 1723, "text": "You can download the source code from Github." }, { "code": null, "e": 1780, "s": 1769, "text": "github.com" } ]
How to send email using Node.js ? - GeeksforGeeks
11 Sep, 2021 Electronic Mail is a widely used method to transfer/exchange messages among people. We generally send the email with any software or application like Gmail, outlook, thunderbird mail, and yahoo, etc. We can also code the basic concept of these applications in a node.js app by using any third-party library which can interact with the networking systems and send an email. Nodemailer: There are various modules available for sending emails but the nodemailer is the most popular one and it provides us simple procedure and functionality to send mail. Features of Nodemailer: It supports various features like adding HTML in the mail, Unicode characters, sending attachments with the text, etc. It uses the simple mail transfer protocol (SMTP). Below is the step-by-step approach to be followed to integrate this module into our application. Step 1: Module Installation: Write the command in the terminal to install nodemailer and then import at the top of your nodejs application. npm install nodemailer Now we are ready to import this into our application. const nodemailer = require('nodemailer'); Step 2: Create Transporter Object: There exists a createTransport method in nodemailer which accepts an object with some configurations and finally returns a transporter object. This object will be required later to send emails. const transporter = nodemailer.createTransport(transport[, defaults]); Here we are using Gmail as a service just for sample purposes, Although nodemailer can be easily integrated with any other mail service. In Gmail, we can either make our account less secure or we can use the Oauth2 security authentication unless normally google will not allow sending any mail via node.js. Less Secure Account: Visit this link to make your account less secure, after doing this we can create our working transporter object just with the username and password of your Gmail account. app.js const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD }}); Using Oauth2: According to official docs here we need to provide client id, client secret, refresh token, and an access token along with the username and password. Follow the step-by-step approach to get these configurations from the google cloud console. 1. Open Google Cloud Console: In this step, we will get our client id and client secret. Visit the google cloud console website and register/sign in yourself. Then proceed to API & Services section from the leftmost navigation bar. Now check out the dashboard and create a project. After this, visit the Oauth consent screen to register about your application in this step make sure to select user type external and add some/one Test Users. After this step, go to the credentials section and click on Create credentials and then choose Oauth2 ClientID and choose application type as a web application, also make sure to add redirect URI as OAuth playground (copy link from here). Finally, you’ll be successful to get your client_id and client_secret. 2. Open the Oauth2 Playground: Here we will get our refresh token and access token. Visit the OAuth2 playground, Click on the oauth2.0 configuration icon from the right and then check the use your own credentials checkbox and provide the same client id and secret you’ve got from the cloud console. Now select the Gmail API for authorization. Click on Authorize API and then authorize it by the same Gmail id you have been filled as a test user in the credentials section of the last step. Finally, click on the exchange authorization code for tokens and this will provide a refresh token and access token. Note: We suggest you open these gifs in a separate tab and follow both approaches separately and don’t skip at any span this would save you from a lot of confusion, Also don’t try to copy this client id and client secret, etc. it will not going to work. app.js const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD, clientId: secure_configuration.CLIENT_ID, clientSecret: secure_configuration.CLIENT_SECRET, refreshToken: secure_configuration.REFRESH_TOKEN }}); With this our transporter object is ready and now we can send our emails. Step 3: Configure eMail: Before sending the mail we have to create some message configurations like what to send where to send etc. It is super easy to create these configurations there are several key-value pairs, from which you can provide the required ones along with some other values to the predefined key. Sending a simple text to one email: Javascript const mailConfigurations = { // It should be a string of sender email from: '[email protected]', // Comma Separated list of mails to: '[email protected]', // Subject of Email subject: 'Sending Email using Node.js', // This would be the text of email body text: 'Hi! There, You know I am using the' + ' NodeJS Code along with NodeMailer ' + 'to send this email.'}; Output: If we send the email with these configurations, something like this will be sent to the receiver. Although our code is currently incomplete, here we are just showing you how this message configuration will look like when the code will be completed. Sending to Multiple emails: We can concatenate more emails with a comma as a separator. Javascript const mailConfigurations = { from: '[email protected]', to: '[email protected], [email protected]', subject: 'Sending Email using Node.js', text: 'Hi! There, You know I am using the NodeJS Code' + ' along with NodeMailer to send this email.'}; Sending some HTML content: Just replace the Plain text with HTML and provide it to html key. Javascript const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', html: "<h2>Hi! There</h2> <h5> This HTML content is being send by NodeJS along with NodeMailer.</h5>"}; Output: Sending some Attachments, Nodemailer is so flexible while sending attachments, you can send any type of file which is being accepted by email service. Javascript const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', text:'Attachments can also be sent using nodemailer', attachments: [ { // utf-8 string as an attachment filename: 'text.txt', content: 'Hello, GeeksforGeeks Learner!' }, { // filename and content type is derived from path path: '/home/mrtwinklesharma/Programming/document.docx' }, { path: '/home/mrtwinklesharma/Videos/Sample.mp4' }, { // use URL as an attachment filename: 'license.txt', path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE' } ]}; Output: Not only these but nodemailer have a lot of possibilities for message configurations you can check them all from here. Step 4: Send eMail: Use any one of the above approaches to proceed with the transporter object, and then choose any one email configurations to send mail.There exists a sendMail method in the transporter object which accepts email configurations and a callback function that will be executed either when mail has been sent or due to an error. transporter.sendMail(mailConfigurations[, callback]); Javascript transporter.sendMail(mailConfigurations, function(error, info){ if (error) throw Error(error); console.log('Email Sent Successfully'); console.log(info);}); You can pick any options from the step 2 and 3. After providing it to the sendMail method you will be successfully able to send an email with node.js. Explanation: Here we have imported the nodemailer module in the beginning and then used the Oauth2 type of authentication, later there is the most basic message configuration which is being used. Finally, the sendMail method is sending the mail to receivers provided in message configuration.Note:- The secure module being imported has nothing to do with this nodemailer, I have just used it to secure my credentials. app.js const nodemailer = require('nodemailer');const secure_configuration = require('./secure'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD, clientId: secure_configuration.CLIENT_ID, clientSecret: secure_configuration.CLIENT_SECRET, refreshToken: secure_configuration.REFRESH_TOKEN }}); const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', text: 'Hi! There, You know I am using the NodeJS ' + 'Code along with NodeMailer to send this email.'}; transporter.sendMail(mailConfigurations, function(error, info){ if (error) throw Error(error); console.log('Email Sent Successfully'); console.log(info);}); Output: Run this code snippet with node command and this will be the output in the console and Gmail inbox. Blogathon-2021 Node.js-Methods NodeJS-Questions Picked Blogathon Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? How to Create a Table With Multiple Foreign Keys in SQL? How to pass data into table from a form using React Components SQL - Multiple Column Ordering Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method How to update NPM ?
[ { "code": null, "e": 24709, "s": 24681, "text": "\n11 Sep, 2021" }, { "code": null, "e": 25082, "s": 24709, "text": "Electronic Mail is a widely used method to transfer/exchange messages among people. We generally send the email with any software or application like Gmail, outlook, thunderbird mail, and yahoo, etc. We can also code the basic concept of these applications in a node.js app by using any third-party library which can interact with the networking systems and send an email." }, { "code": null, "e": 25261, "s": 25082, "text": "Nodemailer: There are various modules available for sending emails but the nodemailer is the most popular one and it provides us simple procedure and functionality to send mail. " }, { "code": null, "e": 25285, "s": 25261, "text": "Features of Nodemailer:" }, { "code": null, "e": 25404, "s": 25285, "text": "It supports various features like adding HTML in the mail, Unicode characters, sending attachments with the text, etc." }, { "code": null, "e": 25551, "s": 25404, "text": "It uses the simple mail transfer protocol (SMTP). Below is the step-by-step approach to be followed to integrate this module into our application." }, { "code": null, "e": 25691, "s": 25551, "text": "Step 1: Module Installation: Write the command in the terminal to install nodemailer and then import at the top of your nodejs application." }, { "code": null, "e": 25714, "s": 25691, "text": "npm install nodemailer" }, { "code": null, "e": 25769, "s": 25714, "text": "Now we are ready to import this into our application. " }, { "code": null, "e": 25811, "s": 25769, "text": "const nodemailer = require('nodemailer');" }, { "code": null, "e": 26041, "s": 25811, "text": "Step 2: Create Transporter Object: There exists a createTransport method in nodemailer which accepts an object with some configurations and finally returns a transporter object. This object will be required later to send emails. " }, { "code": null, "e": 26112, "s": 26041, "text": "const transporter = nodemailer.createTransport(transport[, defaults]);" }, { "code": null, "e": 26419, "s": 26112, "text": "Here we are using Gmail as a service just for sample purposes, Although nodemailer can be easily integrated with any other mail service. In Gmail, we can either make our account less secure or we can use the Oauth2 security authentication unless normally google will not allow sending any mail via node.js." }, { "code": null, "e": 26612, "s": 26419, "text": "Less Secure Account: Visit this link to make your account less secure, after doing this we can create our working transporter object just with the username and password of your Gmail account. " }, { "code": null, "e": 26619, "s": 26612, "text": "app.js" }, { "code": "const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD }});", "e": 26830, "s": 26619, "text": null }, { "code": null, "e": 27087, "s": 26830, "text": "Using Oauth2: According to official docs here we need to provide client id, client secret, refresh token, and an access token along with the username and password. Follow the step-by-step approach to get these configurations from the google cloud console. " }, { "code": null, "e": 27838, "s": 27087, "text": "1. Open Google Cloud Console: In this step, we will get our client id and client secret. Visit the google cloud console website and register/sign in yourself. Then proceed to API & Services section from the leftmost navigation bar. Now check out the dashboard and create a project. After this, visit the Oauth consent screen to register about your application in this step make sure to select user type external and add some/one Test Users. After this step, go to the credentials section and click on Create credentials and then choose Oauth2 ClientID and choose application type as a web application, also make sure to add redirect URI as OAuth playground (copy link from here). Finally, you’ll be successful to get your client_id and client_secret." }, { "code": null, "e": 28445, "s": 27838, "text": "2. Open the Oauth2 Playground: Here we will get our refresh token and access token. Visit the OAuth2 playground, Click on the oauth2.0 configuration icon from the right and then check the use your own credentials checkbox and provide the same client id and secret you’ve got from the cloud console. Now select the Gmail API for authorization. Click on Authorize API and then authorize it by the same Gmail id you have been filled as a test user in the credentials section of the last step. Finally, click on the exchange authorization code for tokens and this will provide a refresh token and access token." }, { "code": null, "e": 28699, "s": 28445, "text": "Note: We suggest you open these gifs in a separate tab and follow both approaches separately and don’t skip at any span this would save you from a lot of confusion, Also don’t try to copy this client id and client secret, etc. it will not going to work." }, { "code": null, "e": 28706, "s": 28699, "text": "app.js" }, { "code": "const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD, clientId: secure_configuration.CLIENT_ID, clientSecret: secure_configuration.CLIENT_SECRET, refreshToken: secure_configuration.REFRESH_TOKEN }});", "e": 29087, "s": 28706, "text": null }, { "code": null, "e": 29162, "s": 29087, "text": "With this our transporter object is ready and now we can send our emails. " }, { "code": null, "e": 29474, "s": 29162, "text": "Step 3: Configure eMail: Before sending the mail we have to create some message configurations like what to send where to send etc. It is super easy to create these configurations there are several key-value pairs, from which you can provide the required ones along with some other values to the predefined key." }, { "code": null, "e": 29510, "s": 29474, "text": "Sending a simple text to one email:" }, { "code": null, "e": 29521, "s": 29510, "text": "Javascript" }, { "code": "const mailConfigurations = { // It should be a string of sender email from: '[email protected]', // Comma Separated list of mails to: '[email protected]', // Subject of Email subject: 'Sending Email using Node.js', // This would be the text of email body text: 'Hi! There, You know I am using the' + ' NodeJS Code along with NodeMailer ' + 'to send this email.'};", "e": 29948, "s": 29521, "text": null }, { "code": null, "e": 30205, "s": 29948, "text": "Output: If we send the email with these configurations, something like this will be sent to the receiver. Although our code is currently incomplete, here we are just showing you how this message configuration will look like when the code will be completed." }, { "code": null, "e": 30293, "s": 30205, "text": "Sending to Multiple emails: We can concatenate more emails with a comma as a separator." }, { "code": null, "e": 30304, "s": 30293, "text": "Javascript" }, { "code": "const mailConfigurations = { from: '[email protected]', to: '[email protected], [email protected]', subject: 'Sending Email using Node.js', text: 'Hi! There, You know I am using the NodeJS Code' + ' along with NodeMailer to send this email.'};", "e": 30589, "s": 30304, "text": null }, { "code": null, "e": 30682, "s": 30589, "text": "Sending some HTML content: Just replace the Plain text with HTML and provide it to html key." }, { "code": null, "e": 30693, "s": 30682, "text": "Javascript" }, { "code": "const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', html: \"<h2>Hi! There</h2> <h5> This HTML content is being send by NodeJS along with NodeMailer.</h5>\"};", "e": 30940, "s": 30693, "text": null }, { "code": null, "e": 30948, "s": 30940, "text": "Output:" }, { "code": null, "e": 31099, "s": 30948, "text": "Sending some Attachments, Nodemailer is so flexible while sending attachments, you can send any type of file which is being accepted by email service." }, { "code": null, "e": 31110, "s": 31099, "text": "Javascript" }, { "code": "const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', text:'Attachments can also be sent using nodemailer', attachments: [ { // utf-8 string as an attachment filename: 'text.txt', content: 'Hello, GeeksforGeeks Learner!' }, { // filename and content type is derived from path path: '/home/mrtwinklesharma/Programming/document.docx' }, { path: '/home/mrtwinklesharma/Videos/Sample.mp4' }, { // use URL as an attachment filename: 'license.txt', path: 'https://raw.github.com/nodemailer/nodemailer/master/LICENSE' } ]};", "e": 31759, "s": 31110, "text": null }, { "code": null, "e": 31767, "s": 31759, "text": "Output:" }, { "code": null, "e": 31886, "s": 31767, "text": "Not only these but nodemailer have a lot of possibilities for message configurations you can check them all from here." }, { "code": null, "e": 32231, "s": 31886, "text": "Step 4: Send eMail: Use any one of the above approaches to proceed with the transporter object, and then choose any one email configurations to send mail.There exists a sendMail method in the transporter object which accepts email configurations and a callback function that will be executed either when mail has been sent or due to an error. " }, { "code": null, "e": 32285, "s": 32231, "text": "transporter.sendMail(mailConfigurations[, callback]);" }, { "code": null, "e": 32296, "s": 32285, "text": "Javascript" }, { "code": "transporter.sendMail(mailConfigurations, function(error, info){ if (error) throw Error(error); console.log('Email Sent Successfully'); console.log(info);});", "e": 32465, "s": 32296, "text": null }, { "code": null, "e": 32616, "s": 32465, "text": "You can pick any options from the step 2 and 3. After providing it to the sendMail method you will be successfully able to send an email with node.js." }, { "code": null, "e": 33035, "s": 32616, "text": "Explanation: Here we have imported the nodemailer module in the beginning and then used the Oauth2 type of authentication, later there is the most basic message configuration which is being used. Finally, the sendMail method is sending the mail to receivers provided in message configuration.Note:- The secure module being imported has nothing to do with this nodemailer, I have just used it to secure my credentials. " }, { "code": null, "e": 33042, "s": 33035, "text": "app.js" }, { "code": "const nodemailer = require('nodemailer');const secure_configuration = require('./secure'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: secure_configuration.EMAIL_USERNAME, pass: secure_configuration.PASSWORD, clientId: secure_configuration.CLIENT_ID, clientSecret: secure_configuration.CLIENT_SECRET, refreshToken: secure_configuration.REFRESH_TOKEN }}); const mailConfigurations = { from: '[email protected]', to: '[email protected]', subject: 'Sending Email using Node.js', text: 'Hi! There, You know I am using the NodeJS ' + 'Code along with NodeMailer to send this email.'}; transporter.sendMail(mailConfigurations, function(error, info){ if (error) throw Error(error); console.log('Email Sent Successfully'); console.log(info);});", "e": 33899, "s": 33042, "text": null }, { "code": null, "e": 34007, "s": 33899, "text": "Output: Run this code snippet with node command and this will be the output in the console and Gmail inbox." }, { "code": null, "e": 34022, "s": 34007, "text": "Blogathon-2021" }, { "code": null, "e": 34038, "s": 34022, "text": "Node.js-Methods" }, { "code": null, "e": 34055, "s": 34038, "text": "NodeJS-Questions" }, { "code": null, "e": 34062, "s": 34055, "text": "Picked" }, { "code": null, "e": 34072, "s": 34062, "text": "Blogathon" }, { "code": null, "e": 34080, "s": 34072, "text": "Node.js" }, { "code": null, "e": 34097, "s": 34080, "text": "Web Technologies" }, { "code": null, "e": 34195, "s": 34097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34204, "s": 34195, "text": "Comments" }, { "code": null, "e": 34217, "s": 34204, "text": "Old Comments" }, { "code": null, "e": 34258, "s": 34217, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 34293, "s": 34258, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 34350, "s": 34293, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 34413, "s": 34350, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 34444, "s": 34413, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 34477, "s": 34444, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34525, "s": 34477, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34558, "s": 34525, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 34587, "s": 34558, "text": "Node.js fs.readFile() Method" } ]
Java program to reverse a string using recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. You can reverse a string using the recursive function as shown in the following program. Live Demo public class StringReverse { public String reverseString(String str){ if(str.isEmpty()){ return str; } else { return reverseString(str.substring(1))+str.charAt(0); } } public static void main(String[] args) { StringReverse obj = new StringReverse(); String result = obj.reverseString("Tutorialspoint"); System.out.println(result); } } tniopslairotuT
[ { "code": null, "e": 1365, "s": 1062, "text": "Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. You can reverse a string using the recursive function as shown in the following program." }, { "code": null, "e": 1375, "s": 1365, "text": "Live Demo" }, { "code": null, "e": 1780, "s": 1375, "text": "public class StringReverse {\n public String reverseString(String str){\n \n if(str.isEmpty()){\n return str;\n } else {\n return reverseString(str.substring(1))+str.charAt(0);\n }\n }\n public static void main(String[] args) {\n StringReverse obj = new StringReverse();\n String result = obj.reverseString(\"Tutorialspoint\");\n System.out.println(result);\n }\n}" }, { "code": null, "e": 1795, "s": 1780, "text": "tniopslairotuT" } ]
What Explainable AI fails to explain (and how we fix that) | by Alvin Wan | Towards Data Science
Don’t take it from me. Take it from IEEE Fellow Cuntai Guan, who recognizes “many machine decisions are still poorly understood”. Most papers even suggest a rigid dichotomy between accuracy and interpretability. Explainable AI (XAI) attempts to bridge this divide, but as we explain below, XAI justifies decisions without interpreting the model directly. This means practitioners in applications such as finance and medicine are forced into a dilemma: pick an un-interpretable, accurate model or an inaccurate, interpretable model. Defining explainability or interpretability for computer vision is challenging: What does it even mean to explain a classification for high-dimensional inputs like images? As we discuss below, two popular definitions involve saliency maps and decision trees, but both approaches have their weaknesses. Many XAI methods produce heatmaps known as saliency maps, which highlight important input pixels that influence the prediction. However, saliency maps focus on the input and neglect to explain how the model makes decisions. For more on saliency maps, see these saliency tutorials and Github repositories. To illustrate why saliency maps do not fully explain how the model predicts, here is an example: Below, the saliency maps are identical, but the predictions differ. Why? Even though both saliency maps highlight the correct object, one prediction is incorrect. How? Answering this could help us improve the model, but as shown below, saliency maps fail to explain the model’s decision process. Another approach is to replace neural networks with interpretable models. Before deep learning, decision trees were the gold standard for accuracy and interpretability. Below, we illustrate the interpretability of decision trees, which works by breaking up each prediction into a sequence of decisions. For accuracy, however, decision trees lag behind neural networks by up to 40% accuracy on image classification datasets2. Neural-network-and-decision-tree hybrids also underperform, failing to match neural networks on even the dataset CIFAR10, which features tiny 32x32 images like the one below. As we show in our paper (Sec 5.2), this accuracy gap damages interpretability: high-accuracy, interpretable models are needed to explain high-accuracy neural networks. We challenge this false dichotomy by building models that are both interpretable and accurate. Our key insight is to combine neural networks with decision trees, preserving high-level interpretability while using neural networks for low-level decisions, as shown below. We call these models Neural-Backed Decision Trees (NBDTs) and show they can match neural network accuracy while preserving the interpretability of a decision tree. NBDTs are as interpretable as decision trees. Unlike neural networks today, NBDTs can output intermediate decisions for a prediction. For example, given an image, a neural network may output Dog. However, an NBDT can output both Dog and Animal, Chordate, Carnivore (below). NBDTs achieve neural network accuracy. Unlike any other decision-tree-based method, NBDTs match neural network accuracy (< 1% difference) on 3 image classification datasets3. NBDTs also achieve accuracy within 2% of neural networks on ImageNet, one of the largest image classification datasets with 1.2 million 224x224 images. Furthermore, NBDTs set new state-of-the-art accuracies for interpretable models. The NBDT’s ImageNet accuracy of 75.30% outperforms the best competing decision-tree-based method by a whole ~14%. To contextualize this accuracy gain: A similar gain of ~14% for non-interpretable neural networks took 3 years of research4. The most insightful justifications are for objects the model has never seen before. For example, consider an NBDT (below), and run inference on a Zebra. Although this model has never seen Zebra, the intermediate decisions shown below are correct — Zebras are both Animals and Ungulates (hoofed animal). The ability to see justification for individual predictions is quintessential for unseen objects. Furthermore, we find that with NBDTs, interpretability improves with accuracy. This is contrary to the dichotomy in the introduction: NBDTs not only have both accuracy and interpretability; they also make both accuracy and interpretability the same objective. For example, the lower-accuracy ResNet6 hierarchy (left) makes less sense, grouping Frog, Cat, and Airplane together. This is “less sensible,” as it is difficult to find an obvious visual feature shared by all three classes. By contrast, the higher-accuracy WideResNet hierarchy (right) makes more sense, cleanly separating Animal from Vehicle — thus, the higher accuracy, the more interpretable the NBDT. With low-dimensional tabular data, decision rules in a decision tree are simple to interpret e.g., if the dish contains a bun, then pick the right child, as shown below. However, decision rules are not as straightforward for inputs like high-dimensional images. As we qualitatively find in the paper (Sec 5.3), the model’s decision rules are based not only on object type but also on context, shape, and color. To interpret decision rules quantitatively, we leverage an existing hierarchy of nouns called WordNet7; with this hierarchy, we can find the most specific shared meaning between classes. For example, given the classes Cat and Dog, WordNet would provide Mammal. In our paper (Sec 5.2) and pictured below, we quantitatively verify these WordNet hypotheses. Note that in small datasets with 10 classes i.e., CIFAR10, we can find WordNet hypotheses for all nodes. However, in large datasets with 1000 classes i.e., ImageNet, we can only find WordNet hypotheses for a subset of nodes. Interested in trying out an NBDT, now? Without installing anything, you can view more example outputs online and even try out our web demo. Alternatively, use our command-line utility to run inference (Install with pip install nbdt). Below, we run inference on a picture of a cat. nbdt https://images.pexels.com/photos/126407/pexels-photo-126407.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=32 # this can also be a path to local image This outputs both the class prediction and all the intermediate decisions. Prediction: cat // Decisions: animal (99.47%), chordate (99.20%), carnivore (99.42%), cat (99.86%) You can load a pretrained NBDT in just a few lines of Python as well. Use the following to get started. We support several neural networks and datasets. from nbdt.model import HardNBDTfrom nbdt.models import wrn28_10_cifar10model = wrn28_10_cifar10()model = HardNBDT( pretrained=True, dataset='CIFAR10', arch='wrn28_10_cifar10', model=model) For reference, see the script for the command-line tool we ran above; only ~20 lines are directly involved in transforming the input and running inference. For more instructions on getting started and examples, see our Github repository. The training and inference process for a Neural-Backed Decision Tree can be broken down into four steps. Construct a hierarchy for the decision tree. This hierarchy determines which sets of classes the NBDT must decide between. We refer to this hierarchy as an Induced Hierarchy.This hierarchy yields a particular loss function, that we call the Tree Supervision Loss5. Train the original neural network, without any modifications, using this new loss.Start inference by passing the sample through the neural network backbone. The backbone is all neural network layers before the final fully-connected layer.Finish inference by running the final fully-connected layer as a sequence of decision rules, which we call Embedded Decision Rules. These decisions culminate in the final prediction. Construct a hierarchy for the decision tree. This hierarchy determines which sets of classes the NBDT must decide between. We refer to this hierarchy as an Induced Hierarchy. This hierarchy yields a particular loss function, that we call the Tree Supervision Loss5. Train the original neural network, without any modifications, using this new loss. Start inference by passing the sample through the neural network backbone. The backbone is all neural network layers before the final fully-connected layer. Finish inference by running the final fully-connected layer as a sequence of decision rules, which we call Embedded Decision Rules. These decisions culminate in the final prediction. For more detail, see our paper (Sec 3). Explainable AI does not fully explain how the neural network reaches a prediction: Existing methods explain the image’s impact on model predictions but do not explain the decision process. Decision trees address this, but unfortunately, images7 are kryptonite for decision tree accuracy. We thus combine neural networks and decision trees. Unlike predecessors that arrived at the same hybrid design, our neural-backed decision trees (NBDTs) simultaneously address the failures (1) of neural networks to provide justification and (2) of decision trees to attain high accuracy. This primes a new category of accurate, interpretable NBDTs for applications like medicine and finance. To get started, see the project page. By Alvin Wan, *Lisa Dunlap, *Daniel Ho, Jihan Yin, Scott Lee, Henry Jin, Suzanne Petryk, Sarah Adel Bargal, Joseph E. Gonzalez where * denotes equal contribution [0] Designed by author Alvin Wan. Footnote exists to clarify we have rights to use this graphic. [1] There are two types of saliency maps: one is white-box, where the method has access to the model and its parameters. One popular white-box method is Grad-CAM, which uses both gradients and class activation maps to visualize attention. You can learn more from the paper, “Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization” http://openaccess.thecvf.com/content_ICCV_2017/papers/Selvaraju_Grad-CAM_Visual_Explanations_ICCV_2017_paper.pdf. The other type of saliency map is black-box, where the model does not have access to the model parameters. RISE is one such saliency method. RISE masks random portions of the input image and passes this image through the model — the mask that damages accuracy the most is the most “important” portion. You can learn more from the paper “RISE: Randomized Input Sampling for Explanation of Black-box Models”, http://bmvc2018.org/contents/papers/1064.pdf. [2] This 40% gap between decision tree and neural network accuracy shows up on TinyImageNet200. [3] The three datasets in particular are CIFAR10, CIFAR100, TinyImageNet200. [4] This ImageNet accuracy gain is significant: for non-interpretable neural networks, a similar 14% gain on ImageNet took 3 years of research. To make this comparison, we examine a similar accuracy gain which took 3 years, from AlexNet in 2013 (63.3%) to Inception V3 (78.8%). The NBDT improves on previously state-of-the-art results by ~14% at around the same range, from NofE (61.29%) to our NBDTs (75.30%). There are other factors at play, however: One obvious one is that compute and deep learning libraries were not as readily available in 2013. A fairer comparison may to be use the latest the latest 14%-gain on ImageNet. The latest 14% gain took 5 years, starting from VGG-19 in 2015 (74.5%) and leading up to FixEfficientNet-L2 in 2020 (88.5%). However, this technically isn’t comparable either since large gains are harder at higher accuracies. Despite this lack of perfectly comparable benchmark progress, we just took the minimum of the two ranges in time, to try and illustrate how large of a gap 14% is. [6] ResNet10 achieves 4% lower accuracy than WideResNet28x10 on CIFAR10. [7] WordNet is a lexical hierarchy of various words. A large majority of words are nouns, but other parts of speech are included as well. For more information, see the official website. [8] To understand the basic idea for a Tree Supervision Loss: Horse is just one class. However, it is also an Ungulate and an Animal. (See the figure in “Justifications for Individual Predictions”.) At the root node, the Horse sample thus needs to be passed to the child node Animal. Furthermore, the node Animal needs to pass the sample to Ungulate. Finally, the node Ungulate must pass the sample to Horse. Train each node to predict the correct child node. We call the loss that enforces this the Tree Supervision Loss. [9] In general, decision trees perform best with low-dimensional data. Images are the antithesis of this best-case scenario, being extremely high-dimensional.
[ { "code": null, "e": 384, "s": 172, "text": "Don’t take it from me. Take it from IEEE Fellow Cuntai Guan, who recognizes “many machine decisions are still poorly understood”. Most papers even suggest a rigid dichotomy between accuracy and interpretability." }, { "code": null, "e": 704, "s": 384, "text": "Explainable AI (XAI) attempts to bridge this divide, but as we explain below, XAI justifies decisions without interpreting the model directly. This means practitioners in applications such as finance and medicine are forced into a dilemma: pick an un-interpretable, accurate model or an inaccurate, interpretable model." }, { "code": null, "e": 1006, "s": 704, "text": "Defining explainability or interpretability for computer vision is challenging: What does it even mean to explain a classification for high-dimensional inputs like images? As we discuss below, two popular definitions involve saliency maps and decision trees, but both approaches have their weaknesses." }, { "code": null, "e": 1230, "s": 1006, "text": "Many XAI methods produce heatmaps known as saliency maps, which highlight important input pixels that influence the prediction. However, saliency maps focus on the input and neglect to explain how the model makes decisions." }, { "code": null, "e": 1311, "s": 1230, "text": "For more on saliency maps, see these saliency tutorials and Github repositories." }, { "code": null, "e": 1704, "s": 1311, "text": "To illustrate why saliency maps do not fully explain how the model predicts, here is an example: Below, the saliency maps are identical, but the predictions differ. Why? Even though both saliency maps highlight the correct object, one prediction is incorrect. How? Answering this could help us improve the model, but as shown below, saliency maps fail to explain the model’s decision process." }, { "code": null, "e": 2007, "s": 1704, "text": "Another approach is to replace neural networks with interpretable models. Before deep learning, decision trees were the gold standard for accuracy and interpretability. Below, we illustrate the interpretability of decision trees, which works by breaking up each prediction into a sequence of decisions." }, { "code": null, "e": 2304, "s": 2007, "text": "For accuracy, however, decision trees lag behind neural networks by up to 40% accuracy on image classification datasets2. Neural-network-and-decision-tree hybrids also underperform, failing to match neural networks on even the dataset CIFAR10, which features tiny 32x32 images like the one below." }, { "code": null, "e": 2472, "s": 2304, "text": "As we show in our paper (Sec 5.2), this accuracy gap damages interpretability: high-accuracy, interpretable models are needed to explain high-accuracy neural networks." }, { "code": null, "e": 2906, "s": 2472, "text": "We challenge this false dichotomy by building models that are both interpretable and accurate. Our key insight is to combine neural networks with decision trees, preserving high-level interpretability while using neural networks for low-level decisions, as shown below. We call these models Neural-Backed Decision Trees (NBDTs) and show they can match neural network accuracy while preserving the interpretability of a decision tree." }, { "code": null, "e": 3180, "s": 2906, "text": "NBDTs are as interpretable as decision trees. Unlike neural networks today, NBDTs can output intermediate decisions for a prediction. For example, given an image, a neural network may output Dog. However, an NBDT can output both Dog and Animal, Chordate, Carnivore (below)." }, { "code": null, "e": 3507, "s": 3180, "text": "NBDTs achieve neural network accuracy. Unlike any other decision-tree-based method, NBDTs match neural network accuracy (< 1% difference) on 3 image classification datasets3. NBDTs also achieve accuracy within 2% of neural networks on ImageNet, one of the largest image classification datasets with 1.2 million 224x224 images." }, { "code": null, "e": 3827, "s": 3507, "text": "Furthermore, NBDTs set new state-of-the-art accuracies for interpretable models. The NBDT’s ImageNet accuracy of 75.30% outperforms the best competing decision-tree-based method by a whole ~14%. To contextualize this accuracy gain: A similar gain of ~14% for non-interpretable neural networks took 3 years of research4." }, { "code": null, "e": 4228, "s": 3827, "text": "The most insightful justifications are for objects the model has never seen before. For example, consider an NBDT (below), and run inference on a Zebra. Although this model has never seen Zebra, the intermediate decisions shown below are correct — Zebras are both Animals and Ungulates (hoofed animal). The ability to see justification for individual predictions is quintessential for unseen objects." }, { "code": null, "e": 4488, "s": 4228, "text": "Furthermore, we find that with NBDTs, interpretability improves with accuracy. This is contrary to the dichotomy in the introduction: NBDTs not only have both accuracy and interpretability; they also make both accuracy and interpretability the same objective." }, { "code": null, "e": 4894, "s": 4488, "text": "For example, the lower-accuracy ResNet6 hierarchy (left) makes less sense, grouping Frog, Cat, and Airplane together. This is “less sensible,” as it is difficult to find an obvious visual feature shared by all three classes. By contrast, the higher-accuracy WideResNet hierarchy (right) makes more sense, cleanly separating Animal from Vehicle — thus, the higher accuracy, the more interpretable the NBDT." }, { "code": null, "e": 5156, "s": 4894, "text": "With low-dimensional tabular data, decision rules in a decision tree are simple to interpret e.g., if the dish contains a bun, then pick the right child, as shown below. However, decision rules are not as straightforward for inputs like high-dimensional images." }, { "code": null, "e": 5305, "s": 5156, "text": "As we qualitatively find in the paper (Sec 5.3), the model’s decision rules are based not only on object type but also on context, shape, and color." }, { "code": null, "e": 5660, "s": 5305, "text": "To interpret decision rules quantitatively, we leverage an existing hierarchy of nouns called WordNet7; with this hierarchy, we can find the most specific shared meaning between classes. For example, given the classes Cat and Dog, WordNet would provide Mammal. In our paper (Sec 5.2) and pictured below, we quantitatively verify these WordNet hypotheses." }, { "code": null, "e": 5885, "s": 5660, "text": "Note that in small datasets with 10 classes i.e., CIFAR10, we can find WordNet hypotheses for all nodes. However, in large datasets with 1000 classes i.e., ImageNet, we can only find WordNet hypotheses for a subset of nodes." }, { "code": null, "e": 6166, "s": 5885, "text": "Interested in trying out an NBDT, now? Without installing anything, you can view more example outputs online and even try out our web demo. Alternatively, use our command-line utility to run inference (Install with pip install nbdt). Below, we run inference on a picture of a cat." }, { "code": null, "e": 6315, "s": 6166, "text": "nbdt https://images.pexels.com/photos/126407/pexels-photo-126407.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=32 # this can also be a path to local image" }, { "code": null, "e": 6390, "s": 6315, "text": "This outputs both the class prediction and all the intermediate decisions." }, { "code": null, "e": 6489, "s": 6390, "text": "Prediction: cat // Decisions: animal (99.47%), chordate (99.20%), carnivore (99.42%), cat (99.86%)" }, { "code": null, "e": 6642, "s": 6489, "text": "You can load a pretrained NBDT in just a few lines of Python as well. Use the following to get started. We support several neural networks and datasets." }, { "code": null, "e": 6843, "s": 6642, "text": "from nbdt.model import HardNBDTfrom nbdt.models import wrn28_10_cifar10model = wrn28_10_cifar10()model = HardNBDT( pretrained=True, dataset='CIFAR10', arch='wrn28_10_cifar10', model=model)" }, { "code": null, "e": 7081, "s": 6843, "text": "For reference, see the script for the command-line tool we ran above; only ~20 lines are directly involved in transforming the input and running inference. For more instructions on getting started and examples, see our Github repository." }, { "code": null, "e": 7186, "s": 7081, "text": "The training and inference process for a Neural-Backed Decision Tree can be broken down into four steps." }, { "code": null, "e": 7872, "s": 7186, "text": "Construct a hierarchy for the decision tree. This hierarchy determines which sets of classes the NBDT must decide between. We refer to this hierarchy as an Induced Hierarchy.This hierarchy yields a particular loss function, that we call the Tree Supervision Loss5. Train the original neural network, without any modifications, using this new loss.Start inference by passing the sample through the neural network backbone. The backbone is all neural network layers before the final fully-connected layer.Finish inference by running the final fully-connected layer as a sequence of decision rules, which we call Embedded Decision Rules. These decisions culminate in the final prediction." }, { "code": null, "e": 8047, "s": 7872, "text": "Construct a hierarchy for the decision tree. This hierarchy determines which sets of classes the NBDT must decide between. We refer to this hierarchy as an Induced Hierarchy." }, { "code": null, "e": 8221, "s": 8047, "text": "This hierarchy yields a particular loss function, that we call the Tree Supervision Loss5. Train the original neural network, without any modifications, using this new loss." }, { "code": null, "e": 8378, "s": 8221, "text": "Start inference by passing the sample through the neural network backbone. The backbone is all neural network layers before the final fully-connected layer." }, { "code": null, "e": 8561, "s": 8378, "text": "Finish inference by running the final fully-connected layer as a sequence of decision rules, which we call Embedded Decision Rules. These decisions culminate in the final prediction." }, { "code": null, "e": 8601, "s": 8561, "text": "For more detail, see our paper (Sec 3)." }, { "code": null, "e": 8889, "s": 8601, "text": "Explainable AI does not fully explain how the neural network reaches a prediction: Existing methods explain the image’s impact on model predictions but do not explain the decision process. Decision trees address this, but unfortunately, images7 are kryptonite for decision tree accuracy." }, { "code": null, "e": 9319, "s": 8889, "text": "We thus combine neural networks and decision trees. Unlike predecessors that arrived at the same hybrid design, our neural-backed decision trees (NBDTs) simultaneously address the failures (1) of neural networks to provide justification and (2) of decision trees to attain high accuracy. This primes a new category of accurate, interpretable NBDTs for applications like medicine and finance. To get started, see the project page." }, { "code": null, "e": 9446, "s": 9319, "text": "By Alvin Wan, *Lisa Dunlap, *Daniel Ho, Jihan Yin, Scott Lee, Henry Jin, Suzanne Petryk, Sarah Adel Bargal, Joseph E. Gonzalez" }, { "code": null, "e": 9481, "s": 9446, "text": "where * denotes equal contribution" }, { "code": null, "e": 9578, "s": 9481, "text": "[0] Designed by author Alvin Wan. Footnote exists to clarify we have rights to use this graphic." }, { "code": null, "e": 10502, "s": 9578, "text": "[1] There are two types of saliency maps: one is white-box, where the method has access to the model and its parameters. One popular white-box method is Grad-CAM, which uses both gradients and class activation maps to visualize attention. You can learn more from the paper, “Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization” http://openaccess.thecvf.com/content_ICCV_2017/papers/Selvaraju_Grad-CAM_Visual_Explanations_ICCV_2017_paper.pdf. The other type of saliency map is black-box, where the model does not have access to the model parameters. RISE is one such saliency method. RISE masks random portions of the input image and passes this image through the model — the mask that damages accuracy the most is the most “important” portion. You can learn more from the paper “RISE: Randomized Input Sampling for Explanation of Black-box Models”, http://bmvc2018.org/contents/papers/1064.pdf." }, { "code": null, "e": 10598, "s": 10502, "text": "[2] This 40% gap between decision tree and neural network accuracy shows up on TinyImageNet200." }, { "code": null, "e": 10675, "s": 10598, "text": "[3] The three datasets in particular are CIFAR10, CIFAR100, TinyImageNet200." }, { "code": null, "e": 11694, "s": 10675, "text": "[4] This ImageNet accuracy gain is significant: for non-interpretable neural networks, a similar 14% gain on ImageNet took 3 years of research. To make this comparison, we examine a similar accuracy gain which took 3 years, from AlexNet in 2013 (63.3%) to Inception V3 (78.8%). The NBDT improves on previously state-of-the-art results by ~14% at around the same range, from NofE (61.29%) to our NBDTs (75.30%). There are other factors at play, however: One obvious one is that compute and deep learning libraries were not as readily available in 2013. A fairer comparison may to be use the latest the latest 14%-gain on ImageNet. The latest 14% gain took 5 years, starting from VGG-19 in 2015 (74.5%) and leading up to FixEfficientNet-L2 in 2020 (88.5%). However, this technically isn’t comparable either since large gains are harder at higher accuracies. Despite this lack of perfectly comparable benchmark progress, we just took the minimum of the two ranges in time, to try and illustrate how large of a gap 14% is." }, { "code": null, "e": 11767, "s": 11694, "text": "[6] ResNet10 achieves 4% lower accuracy than WideResNet28x10 on CIFAR10." }, { "code": null, "e": 11953, "s": 11767, "text": "[7] WordNet is a lexical hierarchy of various words. A large majority of words are nouns, but other parts of speech are included as well. For more information, see the official website." }, { "code": null, "e": 12476, "s": 11953, "text": "[8] To understand the basic idea for a Tree Supervision Loss: Horse is just one class. However, it is also an Ungulate and an Animal. (See the figure in “Justifications for Individual Predictions”.) At the root node, the Horse sample thus needs to be passed to the child node Animal. Furthermore, the node Animal needs to pass the sample to Ungulate. Finally, the node Ungulate must pass the sample to Horse. Train each node to predict the correct child node. We call the loss that enforces this the Tree Supervision Loss." } ]
How to select a date less than the current date with MySQL?
Let us first create a table − mysql> create table DemoTable1877 ( DueDate datetime ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1877 values('2019-12-10'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1877 values('2019-12-05'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1877 values('2019-12-07'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1877 values('2019-12-09'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1877; This will produce the following output − +---------------------+ | DueDate | +---------------------+ | 2019-12-10 00:00:00 | | 2019-12-05 00:00:00 | | 2019-12-07 00:00:00 | | 2019-12-09 00:00:00 | +---------------------+ 4 rows in set (0.00 sec) The current date is as follows − mysql> select curdate(); +------------+ | curdate() | +------------+ | 2019-12-08 | +------------+ 1 row in set (0.00 sec) Here is the query to select a date less than the current one − mysql> select * from DemoTable1877 where DueDate < now(); This will produce the following output − +---------------------+ | DueDate | +---------------------+ | 2019-12-05 00:00:00 | | 2019-12-07 00:00:00 | +---------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1194, "s": 1092, "text": "mysql> create table DemoTable1877\n (\n DueDate datetime\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1250, "s": 1194, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1614, "s": 1250, "text": "mysql> insert into DemoTable1877 values('2019-12-10');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1877 values('2019-12-05');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1877 values('2019-12-07');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1877 values('2019-12-09');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1674, "s": 1614, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1710, "s": 1674, "text": "mysql> select * from DemoTable1877;" }, { "code": null, "e": 1751, "s": 1710, "text": "This will produce the following output −" }, { "code": null, "e": 1968, "s": 1751, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-12-10 00:00:00 |\n| 2019-12-05 00:00:00 |\n| 2019-12-07 00:00:00 |\n| 2019-12-09 00:00:00 |\n+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2001, "s": 1968, "text": "The current date is as follows −" }, { "code": null, "e": 2125, "s": 2001, "text": "mysql> select curdate();\n+------------+\n| curdate() |\n+------------+\n| 2019-12-08 |\n+------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2188, "s": 2125, "text": "Here is the query to select a date less than the current one −" }, { "code": null, "e": 2246, "s": 2188, "text": "mysql> select * from DemoTable1877 where DueDate < now();" }, { "code": null, "e": 2287, "s": 2246, "text": "This will produce the following output −" }, { "code": null, "e": 2456, "s": 2287, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-12-05 00:00:00 |\n| 2019-12-07 00:00:00 |\n+---------------------+\n2 rows in set (0.00 sec)" } ]
What do you mean by buffer in C language?
A temporary storage area is called buffer. All input output (I/O) devices contain I/O buffer. When we try to pass more than the required number of values as input then, the remaining values will automatically hold in the input buffer. This buffer data automatically go to the next input functionality, if it is exists. We have to clear the buffer before the next input is taken in. Following is the C program for buffer − #include<stdio.h> void main(){ int a,b; printf("\n Enter a value: "); scanf("%d",&a); printf("\n Enter b value: "); scanf("%d",&b); printf("\n a+b=%d ",a+b); getch(); } When the above program is executed, it produces the following result − Enter a value: 1 Enter b value: 2 a+b=3 Again, run the program. This time, we try to enter values in a and not in b. Enter a value: 1 2 3 Enter b value: a+b=3 Even though we didn’t enter b value, it takes the previously stored value, which is present in buffer already. In the implementation, when we need to remove standard input buffer data then go for flushall() or fflush() function. flushall() − It is a predefined function present in stdio.h. by using flushall we can remove the data from I/O buffer. flushall() − It is a predefined function present in stdio.h. by using flushall we can remove the data from I/O buffer. fflush() − It is a predefined function in "stdio.h" header file which is used to clear either input or output buffer memory. fflush() − It is a predefined function in "stdio.h" header file which is used to clear either input or output buffer memory. fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement. fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement. fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement. fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement.
[ { "code": null, "e": 1156, "s": 1062, "text": "A temporary storage area is called buffer. All input output (I/O) devices contain I/O buffer." }, { "code": null, "e": 1381, "s": 1156, "text": "When we try to pass more than the required number of values as input then, the remaining values will automatically hold in the input buffer. This buffer data automatically go to the next input functionality, if it is exists." }, { "code": null, "e": 1444, "s": 1381, "text": "We have to clear the buffer before the next input is taken in." }, { "code": null, "e": 1484, "s": 1444, "text": "Following is the C program for buffer −" }, { "code": null, "e": 1674, "s": 1484, "text": "#include<stdio.h>\nvoid main(){\n int a,b;\n printf(\"\\n Enter a value: \");\n scanf(\"%d\",&a);\n printf(\"\\n Enter b value: \");\n scanf(\"%d\",&b);\n printf(\"\\n a+b=%d \",a+b);\n getch();\n}" }, { "code": null, "e": 1745, "s": 1674, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 1785, "s": 1745, "text": "Enter a value: 1\nEnter b value: 2\na+b=3" }, { "code": null, "e": 1862, "s": 1785, "text": "Again, run the program. This time, we try to enter values in a and not in b." }, { "code": null, "e": 1904, "s": 1862, "text": "Enter a value: 1 2 3\nEnter b value: a+b=3" }, { "code": null, "e": 2015, "s": 1904, "text": "Even though we didn’t enter b value, it takes the previously stored value, which is present in buffer already." }, { "code": null, "e": 2133, "s": 2015, "text": "In the implementation, when we need to remove standard input buffer data then go for flushall() or fflush() function." }, { "code": null, "e": 2252, "s": 2133, "text": "flushall() − It is a predefined function present in stdio.h. by using flushall we can remove the data from I/O buffer." }, { "code": null, "e": 2371, "s": 2252, "text": "flushall() − It is a predefined function present in stdio.h. by using flushall we can remove the data from I/O buffer." }, { "code": null, "e": 2496, "s": 2371, "text": "fflush() − It is a predefined function in \"stdio.h\" header file which is used to clear either input or output buffer memory." }, { "code": null, "e": 2621, "s": 2496, "text": "fflush() − It is a predefined function in \"stdio.h\" header file which is used to clear either input or output buffer memory." }, { "code": null, "e": 2739, "s": 2621, "text": "fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement." }, { "code": null, "e": 2857, "s": 2739, "text": "fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement." }, { "code": null, "e": 2974, "s": 2857, "text": "fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement." }, { "code": null, "e": 3091, "s": 2974, "text": "fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement." } ]
How to Read Data Files on S3 from Amazon SageMaker | by Mikhail Klassen | Towards Data Science
Amazon SageMaker is a powerful, cloud-hosted Jupyter Notebook service offered by Amazon Web Services (AWS). It’s used to create, train, and deploy machine learning models, but it’s also great for doing exploratory data analysis and prototyping. While it may not be quite as beginner-friendly as some alternatives, such as Google CoLab or Kaggle Kernels, there are some good reasons why you may want to be doing data science work within Amazon SageMaker. Let’s discuss a few. Machine learning models must be trained on data. If you’re working with private data, then special care must be taken when accessing this data for model training. Downloading the entire data set to your laptop may be against your company’s policy or may be simply imprudent. Imagine having your laptop lost or stolen, knowing that it contains sensitive data. As a side note, this another reason why you should use always disk encryption. The data being hosted in the cloud may also be too large to fit on your personal computer’s disk, so it’s easier just to keep it hosted in the cloud and accessed directly. Working in the cloud means you can access powerful compute instances. AWS or your preferred cloud services provider will usually allow you select and configure your compute instances. Perhaps you need high CPU or high memory — more than what you have available on your personal machine. Or perhaps you need to train your models on GPUs. Cloud providers have a host of different instance types on offer. How to deploy ML models directly from SageMaker is a topic for another article, but AWS gives you this option. You won’t need to build a complex deployment architecture. SageMaker will spin off a managed compute instance hosting a Dockerized version of your trained ML model behind an API for performing inference tasks. Now let’s move on to the main topic of this article. I will show you how to load data saved as files in an S3 bucket using Python. The example data are pickled Python dictionaries that I’d like to load into my SageMaker notebook. The process for loading other data types (such as CSV or JSON) would be similar, but may require additional libraries. You will need to know the name of the S3 bucket. Files are indicated in S3 buckets as “keys”, but semantically I find it easier just to think in terms of files and folders. Let’s define the location of our files: bucket = 'my-bucket'subfolder = '' SageMaker and S3 are separate services offered by AWS, and for one service to perform actions on another service requires that the appropriate permissions are set. Thankfully, it’s expected that SageMaker users will be reading files from S3, so the standard permissions are fine. Still, you’ll need to import the necessary execution role, which isn’t hard. from sagemaker import get_execution_rolerole = get_execution_role() The boto3 Python library is designed to help users perform actions on AWS programmatically. It will facilitate the connection between the SageMaker notebook at the S3 bucket. The code below lists all of the files contained within a specific subfolder on an S3 bucket. This is useful for checking what files exist. You may adapt this code to create a list object in Python if you will be iterating over many files. The pickle library in Python is useful for saving Python data structures to a file so that you can load them later. In the example below, I want to load a Python dictionary and assign it to the data variable. This requires using boto3 to get the specific file object (the pickle) on S3 that I want to load. Notice how in the example the boto3 client returns a response that contains a data stream. We must read the data stream with the pickle library into the data object. This behavior is a bit different compared to how you would use pickle to load a local file. Since this is something I always forget how to do right, I’ve compiled the steps into this tutorial so that others might benefit. There are times you may want to download a file from S3 programmatically. Perhaps you want to download files to your local machine or to storage attached to your SageMaker instance. To do this, the code is a bit different: I have focussed on Amazon SageMaker in this article, but if you have the boto3 SDK set up correctly on your local machine, you can also read or download files from S3 there. Since much of my own data science work is done via SageMaker, where you need to remember to set the correct access permissions, I wanted to provide a resource for others (and my future self). Obviously SageMaker is not the only game in town. There are a variety of different cloud-hosted data science notebook environments on offer today, a huge leap forward from five years ago (2015) when I was completing my Ph.D. One consideration that I did not mention is cost: SageMaker is not free, but is billed by usage. Remember to shut down your notebook instances when you’re finished.
[ { "code": null, "e": 417, "s": 172, "text": "Amazon SageMaker is a powerful, cloud-hosted Jupyter Notebook service offered by Amazon Web Services (AWS). It’s used to create, train, and deploy machine learning models, but it’s also great for doing exploratory data analysis and prototyping." }, { "code": null, "e": 626, "s": 417, "text": "While it may not be quite as beginner-friendly as some alternatives, such as Google CoLab or Kaggle Kernels, there are some good reasons why you may want to be doing data science work within Amazon SageMaker." }, { "code": null, "e": 647, "s": 626, "text": "Let’s discuss a few." }, { "code": null, "e": 1085, "s": 647, "text": "Machine learning models must be trained on data. If you’re working with private data, then special care must be taken when accessing this data for model training. Downloading the entire data set to your laptop may be against your company’s policy or may be simply imprudent. Imagine having your laptop lost or stolen, knowing that it contains sensitive data. As a side note, this another reason why you should use always disk encryption." }, { "code": null, "e": 1257, "s": 1085, "text": "The data being hosted in the cloud may also be too large to fit on your personal computer’s disk, so it’s easier just to keep it hosted in the cloud and accessed directly." }, { "code": null, "e": 1660, "s": 1257, "text": "Working in the cloud means you can access powerful compute instances. AWS or your preferred cloud services provider will usually allow you select and configure your compute instances. Perhaps you need high CPU or high memory — more than what you have available on your personal machine. Or perhaps you need to train your models on GPUs. Cloud providers have a host of different instance types on offer." }, { "code": null, "e": 1981, "s": 1660, "text": "How to deploy ML models directly from SageMaker is a topic for another article, but AWS gives you this option. You won’t need to build a complex deployment architecture. SageMaker will spin off a managed compute instance hosting a Dockerized version of your trained ML model behind an API for performing inference tasks." }, { "code": null, "e": 2211, "s": 1981, "text": "Now let’s move on to the main topic of this article. I will show you how to load data saved as files in an S3 bucket using Python. The example data are pickled Python dictionaries that I’d like to load into my SageMaker notebook." }, { "code": null, "e": 2330, "s": 2211, "text": "The process for loading other data types (such as CSV or JSON) would be similar, but may require additional libraries." }, { "code": null, "e": 2503, "s": 2330, "text": "You will need to know the name of the S3 bucket. Files are indicated in S3 buckets as “keys”, but semantically I find it easier just to think in terms of files and folders." }, { "code": null, "e": 2543, "s": 2503, "text": "Let’s define the location of our files:" }, { "code": null, "e": 2578, "s": 2543, "text": "bucket = 'my-bucket'subfolder = ''" }, { "code": null, "e": 2858, "s": 2578, "text": "SageMaker and S3 are separate services offered by AWS, and for one service to perform actions on another service requires that the appropriate permissions are set. Thankfully, it’s expected that SageMaker users will be reading files from S3, so the standard permissions are fine." }, { "code": null, "e": 2935, "s": 2858, "text": "Still, you’ll need to import the necessary execution role, which isn’t hard." }, { "code": null, "e": 3003, "s": 2935, "text": "from sagemaker import get_execution_rolerole = get_execution_role()" }, { "code": null, "e": 3178, "s": 3003, "text": "The boto3 Python library is designed to help users perform actions on AWS programmatically. It will facilitate the connection between the SageMaker notebook at the S3 bucket." }, { "code": null, "e": 3317, "s": 3178, "text": "The code below lists all of the files contained within a specific subfolder on an S3 bucket. This is useful for checking what files exist." }, { "code": null, "e": 3417, "s": 3317, "text": "You may adapt this code to create a list object in Python if you will be iterating over many files." }, { "code": null, "e": 3533, "s": 3417, "text": "The pickle library in Python is useful for saving Python data structures to a file so that you can load them later." }, { "code": null, "e": 3626, "s": 3533, "text": "In the example below, I want to load a Python dictionary and assign it to the data variable." }, { "code": null, "e": 3890, "s": 3626, "text": "This requires using boto3 to get the specific file object (the pickle) on S3 that I want to load. Notice how in the example the boto3 client returns a response that contains a data stream. We must read the data stream with the pickle library into the data object." }, { "code": null, "e": 3982, "s": 3890, "text": "This behavior is a bit different compared to how you would use pickle to load a local file." }, { "code": null, "e": 4112, "s": 3982, "text": "Since this is something I always forget how to do right, I’ve compiled the steps into this tutorial so that others might benefit." }, { "code": null, "e": 4294, "s": 4112, "text": "There are times you may want to download a file from S3 programmatically. Perhaps you want to download files to your local machine or to storage attached to your SageMaker instance." }, { "code": null, "e": 4335, "s": 4294, "text": "To do this, the code is a bit different:" }, { "code": null, "e": 4701, "s": 4335, "text": "I have focussed on Amazon SageMaker in this article, but if you have the boto3 SDK set up correctly on your local machine, you can also read or download files from S3 there. Since much of my own data science work is done via SageMaker, where you need to remember to set the correct access permissions, I wanted to provide a resource for others (and my future self)." }, { "code": null, "e": 4926, "s": 4701, "text": "Obviously SageMaker is not the only game in town. There are a variety of different cloud-hosted data science notebook environments on offer today, a huge leap forward from five years ago (2015) when I was completing my Ph.D." } ]
Can Selenium interact with an existing browser session?
We can interact with an existing browser session. This is performed by using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method. This is generally used for debugging purposes when we have a large number of steps in a test and we do not want to repeat the same steps. First of all we shall launch the browser and enter some text in the below edit box. import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Capabilities; import org.openqa.selenium.By; import java.util.Map; import java.util.concurrent.TimeUnit; public class ConnectExistingSession{ public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //get browser capabilities in key value pairs Capabilities c = driver.getCapabilities(); Map<String, Object> m = c.asMap(); m.forEach((key, value) −> { System.out.println("Key is: " + key + " Value is: " + value); }); //set implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); //identify element WebElement l = driver.findElement(By.id("gsc−i−id1")); l.sendKeys("Selenium"); } } We shall note the parameter {debuggerAddress=localhost:61861} obtained from the Console output to be added to the ChromeOptions object. Browser window − Now, let us connect to the same browser session and perform some operations to it. We should not use browser close or quit methods while connecting to an existing session. Code Modifications done to connect to the existing session. import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.Capabilities; import org.openqa.selenium.By; import java.util.Map; import java.util.concurrent.TimeUnit; public class ConnectExistingSession{ public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //object of ChromeOptions class ChromeOptions o = new ChromeOptions(); //setting debuggerAddress value o.setExperimentalOption("debuggerAddress", "localhost:61861"); //add options to browser capabilities Capabilities c = driver.getCapabilities(o); Map<String, Object> m = c.asMap(); m.forEach((key, value) −> { System.out.println("Key is: " + key + " Value is: " + value); }); //set implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //identify element WebElement l = driver.findElement(By.id("gsc−i−id1")); //remove existing data in edit box l.clear(); l.sendKeys("Tutorialspoint"); String s = l.getAttribute("value"); System.out.println("Attribute value: " + s); } } Browser Window −
[ { "code": null, "e": 1284, "s": 1062, "text": "We can interact with an existing browser session. This is performed by using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method." }, { "code": null, "e": 1506, "s": 1284, "text": "This is generally used for debugging purposes when we have a large number of steps in a test and we do not want to repeat the same steps. First of all we shall launch the browser and enter some text in the below edit box." }, { "code": null, "e": 2585, "s": 1506, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.By;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\npublic class ConnectExistingSession{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //get browser capabilities in key value pairs\n Capabilities c = driver.getCapabilities();\n Map<String, Object> m = c.asMap();\n m.forEach((key, value) −> {\n System.out.println(\"Key is: \" + key + \" Value is: \" + value);\n });\n //set implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n //identify element\n WebElement l = driver.findElement(By.id(\"gsc−i−id1\"));\n l.sendKeys(\"Selenium\");\n }\n}" }, { "code": null, "e": 2721, "s": 2585, "text": "We shall note the parameter {debuggerAddress=localhost:61861} obtained from the Console output to be added to the ChromeOptions object." }, { "code": null, "e": 2738, "s": 2721, "text": "Browser window −" }, { "code": null, "e": 2910, "s": 2738, "text": "Now, let us connect to the same browser session and perform some operations to it. We should not use browser close or quit methods while connecting to an existing session." }, { "code": null, "e": 2970, "s": 2910, "text": "Code Modifications done to connect to the existing session." }, { "code": null, "e": 4362, "s": 2970, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.By;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\npublic class ConnectExistingSession{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //object of ChromeOptions class\n ChromeOptions o = new ChromeOptions();\n //setting debuggerAddress value\n o.setExperimentalOption(\"debuggerAddress\", \"localhost:61861\");\n //add options to browser capabilities\n Capabilities c = driver.getCapabilities(o);\n Map<String, Object> m = c.asMap();\n m.forEach((key, value) −> {\n System.out.println(\"Key is: \" + key + \" Value is: \" + value);\n });\n //set implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //identify element\n WebElement l = driver.findElement(By.id(\"gsc−i−id1\"));\n //remove existing data in edit box\n l.clear();\n l.sendKeys(\"Tutorialspoint\");\n String s = l.getAttribute(\"value\");\n System.out.println(\"Attribute value: \" + s);\n }\n}" }, { "code": null, "e": 4379, "s": 4362, "text": "Browser Window −" } ]
Processing and visualizing multiple categorical variables with Python — NBA’s schedule challenges | by JP Hwang | Towards Data Science
Today, I would like to discuss various ways to process, visualise and review categorical variables. Processing and visualising data when there are multiple categorical variables can be tricky. You might have seen criss-crossing line plots with multiple colours and marker shapes, or maybe it was a grid of subplots. These solutions can work (and work well), but they are far from the only types of plots available for this particular task, and today we’ll explore some of the other ways to do so. As to the data, we will use basketball (NBA) win/loss data. More specifically, we will look at three key externalities that is said to affect basketball outcomes; home court advantage, travel, and rest days. As ever, while this article utilises about basketball data, it is first and foremost a data analysis and visualisation article. So the basketball-specific discussion is kept at a relative minimum, and prior basketball/NBA knowledge is not necessary (although it is both appreciated and encouraged 😉). I include the code and data in my GitLab repo here, (in the nba_travel_impact directory ) and you should be able to easily follow along by downloading/cloning the repo if you wish. I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky. (Please find me on twitter and let me know if you would prefer more guidance.) You’ll need pandas and plotly. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]. You can use any graphics packages, obviously, but I personally prefer the simplicity and power you get with Plotly. Each NBA regular season runs between October and April. (The 2019–20 season runs between October 22 and April 15, for instance.) In that time, each team plays 82 games, which averages out to be only about 2.15 days per game. It’s barely a day of rest between games. Not only that, NBA stadiums are located all across the US and Toronto like so. Having to play half of their games away from home to balance the schedule, teams must commute between them like we catch the metro. In fact, NBA teams travel roughly between 60,000 and 85,000 km/year (37,000–53,000 miles/year), and their flights put together look something like this: (My article on visualising travel data, and an interactive, html version of the map) And the result of all of this is that travel, the venue of play and rest are huge parts of NBA schedules. Each team plays half of the 82 games at home, and the other half away. Even many of the home games would not always involve must rest — it might involve travel to come back overnight, and they might even leave again shortly for the next game. For us mere mortals who would have to go through commercial flights, this would be a nightmare. However, modern NBA players fly in private team jets, and their health and well being is so well-managed that it is not a given that travel would impact them significantly. Let’s find out. Before we can analyse the impact of rest, play and home advantage, we need to collect or load our data. For convenience I use last season’s, but (you could use this season’s, or multiple seasons’ worth also. Although you can simply load the data which I’ve pre-processed (skip to where I load box_df if you would prefer to do this), if you are interested — this is how I compiled the data: I obtained the schedule data from basketball-reference.com, and you can simply load the data as follows from my repo: schedule_df = pd.read_csv('srcdata/2019_nba_schedule.csv', index_col=0) The data includes game tip-off time in EST (est_time), so I create a column for date. schedule_df = schedule_df.assign(game_date=schedule_df.est_time.dt.date) Then, game_dates = schedule_df.game_date.unique() obtains a list of unique game dates, after which the basketball_reference_web_scraper package is used to download our data for each date. You’ll need to install it with pip if you are to try this code. What I am doing here is downloading the data, marking each game as a home game, or an away game, and saving the dataframe. In any case, let’s load a file that I prepared earlier for consistency: box_df = pd.read_csv('srcdata/2019_nba_team_box_scores.csv', index_col=0) Take a look at box_df, and you’ll see that it contains 2460 rows, which matches up with 30 teams’ 82 games, as each row shows a team’s box score. I’ve processed the data here to include boolean columns for whether the team was playing at home, whether they had travelled, and whether they won (win). I also created a categorised variable for the number of rest days (rest_cats), with anything longer than 2 getting grouped together, including opening day. For our first visualisations, let’s take a look at how many games fall into each categories for rest days, and travel. I’ll skip the home/away splits, which are 50:50. import plotly.express as px# How many games in each category?temp_grp_df = box_df.groupby('rest_cats').count().reset_index(drop=False)fig = px.bar(temp_grp_df, y='rest_cats', x='outcome', orientation='h')fig.show() # How many games in each category? Rest days & travel.temp_grp_df = box_df.groupby(['rest_cats', 'travelled']).count().reset_index(drop=False)temp_grp_df = temp_grp_df.assign(travelled=temp_grp_df.travelled.astype(str))fig = px.bar(temp_grp_df, y='rest_cats', x='outcome', orientation='h', color='travelled', barmode='group')fig.show() That’s simple enough, and categorical variables can be concisely represented here as grouped bars. As to the outputs, there are a couple of observations to be made — the NBA schedule is such that the majority of games have 1 day of rest, and there are not many back-to-back (0 days’ rest) games. When there are, they appear to be largely home games (as in, no travel is involved), which is good for the teams. Now, let’s we take a look at the impact of rest, and travel on wins.The code to do that is largely the same as previous, except for now creating a WIN% column for each group, which becomes our dependent variable. travel_cats = ['rest_cats', 'travelled']travel_grp_df = box_df.groupby(travel_cats).sum()travel_grp_df = travel_grp_df.assign(games=box_df.groupby(travel_cats)['minutes_played'].count())travel_grp_df['WIN%'] = travel_grp_df.win/travel_grp_df.games * 100travel_grp_df.reset_index(drop=False, inplace=True)travel_grp_df = travel_grp_df.assign(travelled=travel_grp_df.travelled.astype(str))fig = px.bar(travel_grp_df, y='rest_cats', x='WIN%', orientation='h', color='travelled', barmode='group')fig.show() The trend is as expected — travelling is bad for wins, and more rest is better. But, interestingly — teams that had travelled (red) is winning almost half of its games when given 2+ days of rest! Now, adding further complexity to these charts is where the analysis starts to get challenging. We have three categorical variables that we are trying to analyse for, and we need to choose how to visualise them all, while also indicating the dependent variables (win %, for example). With a bar graph, one option is to use subplots as mentioned: travel_cats = ['home', 'rest_cats', 'travelled']...fig = px.bar(travel_grp_df, y='rest_cats', x='WIN%', facet_col='home', orientation='h', color='travelled', barmode='group') This is fine, but it is still missing quite a bit of information that would be useful to us. For instance, it doesn’t show us how these categorical variables overlap, or interact. Also, subplots do not lend themselves to easy comparisons along an axis. Instead, let’s explore a parallel categories chart. Since they’re somewhat unusual, let’s plot one and then discuss what they contain. Luckily, it’s relatively easy to plot parallel category plots with Plotly. In fact, Plotly Express simply takes as argument the original box score dataframe and compiles the data based on categories which we pass on. Take a look at this simple example, with binary categories for home and travelled. # PARALLEL CATEGORIES - THREE CATEGORIES AND WIN %box_df = box_df.assign(win_num=box_df.win.astype(int))travel_cats = ['home', 'travelled']fig = px.parallel_categories(box_df, dimensions=travel_cats, color='win_num') You may not have seen many parallel categories charts before. They can look complicated, but they are quite simple once you get the hang of them. Each vertical column represents a category, and each band shows a permutation of categorical variables along each column. The chart above represents two categorical variables, and I have also separated them based on the outcome (win or loss), representing three variables. Here, it shows that there were 329 games (band) where the team was at home (left column), had travelled before the game (right column), and resulted in a win (colour). The nature of the charts is that, each added category adds to complexity of the chart, potentially exponentially. Take a look below at the same chart, with categories added for the length of rest days. Plotted below is an example showing two highlighted paths as an illustration. The top, dark, path shows the number of games lost where the team was away (home==false), travelled to get to the game (travel==true), and had 2 days or more of rest (rest_cats == 2+ Days). The lower, yellow, path shows numbers of games of the same criteria, but where the team won the game. (Here is an interactive version of this for you to try & have a play.) Once we are used to the format, exploring multi-dimensional categorical relationships through parallel categories chart can be quite refreshing. Here, each vertical bar shows the overall winning percentages, and simply following thicker lines reveal where strong co-occurrences lie. For instance, let’s take a look at games where the team was playing with no rest, and had travelled. This screenshot highlights records from perspectives fo teams who played away from home. It is already clear that the losses far outweigh the wins. The away team wins only about 32% of these games (out of 237). On the other hand, flipping that around, a home team on no rest & travel day wins 69% of 83 games (I will leave that as an exercise — have a look for yourself here). I find parallel category plots quite useful, especially for data exploration. This chart for instance I found quite useful and visually striking also (I prepared it for this article). This chart shows all of Klay Thompson’s shots, by shot location, and who the assist came from. While it initially looks complicated, look at how easy it is to spot the dominant combinations of categories. Parallel category plots make it easy to spot trends and co-occurrences as shown here. Admittedly, while parallel categories charts can be great for some cases, it has its limitations. In my experience, it can require some work by the reader to understand what is going on, and it can be visually confronting and intimidating for many. Another great, possibly more simple, way to visualise this type of data is treemaps. Treemaps Treemaps are a fantastic way to explore hierarchical, categorised data sets. Just take a look at this example, and see how easy it is to understand. Although treemaps are typically used to evaluate the impact of hierarchical data structures, it is also a good tool for multivariate cases such as this one. We can produce treemaps here conveniently showing sizes of each group, and variations in winning percentages as we drill down deeper and deeper into each category. Because treemaps require a hierarchy, we explore by plotting two different treemaps here: In the first, the hierarchy is based on home/away, travelled/not, and days of rest. In the second, the hierarchy is changed to be based on home/away, days of rest and travelled/not. The treemap layout does a great job in showing differences in sample sizes for each subset, as well as changes in percentages by colours. In both plots, it is clear that a much bigger impact on win percentages generally come from the amount of rest, and simply being home or away, rather than from whether they travelled at all. Take a look at the top graph, in the second tier of boxes (labelled travelled / stayed) for home games. The overall win / loss percentages for games where the home team returned home (i.e. travelled) before the game is very similar to where they did not travel. In the second graph, the overall winning percentages for days of rest are drastically different for all boxes, for instance away games with 0 days of rest being the worst (as we saw earlier in the parallel categories graph). Let’s just explore one more point, and wrap up today’s analysis. We’ve to date looked at this data from one team’s perspective (except for home/away stats, which is complementary). What happens if the opponents’ rest data is also ? I’ve got another dataset for just this reason — where the opponents’ rest days are added into opp_rest_cats column. box_df = pd.read_csv('srcdata/2019_nba_team_box_scores_2.csv', index_col=0)travel_cats = ['home', 'rest_cats', 'opp_rest_cats']travel_grp_df = box_df.groupby(travel_cats).sum()travel_grp_df = travel_grp_df.assign(games=box_df.groupby(travel_cats)['minutes_played'].count())travel_grp_df.reset_index(drop=False, inplace=True)chart_cats = ['home_str', 'rest_cats', 'opp_rest_cats']home_away = pd.Series(['Home ' * i for i in travel_grp_df.home.values]) + pd.Series(['Away ' * (1-i) for i in travel_grp_df.home.values])travel_grp_df['home_str'] = home_awaytravel_grp_df['rest_cats'] = travel_grp_df['rest_cats'] + "' Rest"travel_grp_df['opp_rest_cats'] = 'Opponent: <BR>' + travel_grp_df['opp_rest_cats'] + "'<BR>Rest"travel_grp_df['WIN%'] = travel_grp_df.win/travel_grp_df.games * 100fig = px.treemap( travel_grp_df, path=['home_str', 'rest_cats', 'opp_rest_cats'], values='games', color='WIN%', color_continuous_midpoint=50, color_continuous_scale=px.colors.diverging.Portland)fig.show() Look at that! The best and the worst win/loss percentages happen when the rest disparity is the greatest. Have a look at the ‘away’ stats on the left, where our teams have 0 days’ rest, and the opponents have 2+ days, and the opposite, where our teams have 2+ days of rest and the opponents have 0 days of rest. They represent the extreme opposites. The pattern persists throughout, where rest disparity is a huge factor in win percentages. Even when the home team is on a back-to-back, they on average crush the other back-to-back team, showing the value of home cooking. About the most neutral setup appears to be having the home team on a back-to-back, and the away team on extended rest. Isn’t that interesting!? As it turns out, travel turns out to be relatively a small factor, and the largest factors in win/loss percentages are rest differential, and being home/away. This was easily made discoverable through these treemaps. All in all, I hope the above demonstrated some useful examples and techniques for drilling into datasets where there are multiple categorical variables. In my opinion, parallel category plots and treemaps are useful tools in doing so, and potentially underutilised ones. Treemaps are effective in visualising data in terms of drilldowns and changes in a property as data was subdivided, whereas parallel category plots were excellent for identifying cooccurrences, and flow of data points. Try these out for yourself with your own data sets, and I would love to hear more about them. If you liked this, pls to say 👋 / follow on twitter, or follow here for updates. I also wrote this article about mapping NBA travel data using Plotly, if you haven’t read it before: medium.com And also this article about my favourite data visualisation books. towardsdatascience.com Thanks and see you next time!
[ { "code": null, "e": 365, "s": 172, "text": "Today, I would like to discuss various ways to process, visualise and review categorical variables. Processing and visualising data when there are multiple categorical variables can be tricky." }, { "code": null, "e": 669, "s": 365, "text": "You might have seen criss-crossing line plots with multiple colours and marker shapes, or maybe it was a grid of subplots. These solutions can work (and work well), but they are far from the only types of plots available for this particular task, and today we’ll explore some of the other ways to do so." }, { "code": null, "e": 877, "s": 669, "text": "As to the data, we will use basketball (NBA) win/loss data. More specifically, we will look at three key externalities that is said to affect basketball outcomes; home court advantage, travel, and rest days." }, { "code": null, "e": 1178, "s": 877, "text": "As ever, while this article utilises about basketball data, it is first and foremost a data analysis and visualisation article. So the basketball-specific discussion is kept at a relative minimum, and prior basketball/NBA knowledge is not necessary (although it is both appreciated and encouraged 😉)." }, { "code": null, "e": 1359, "s": 1178, "text": "I include the code and data in my GitLab repo here, (in the nba_travel_impact directory ) and you should be able to easily follow along by downloading/cloning the repo if you wish." }, { "code": null, "e": 1546, "s": 1359, "text": "I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky. (Please find me on twitter and let me know if you would prefer more guidance.)" }, { "code": null, "e": 1662, "s": 1546, "text": "You’ll need pandas and plotly. Install each (in your virtual environment) with a simple pip install [PACKAGE_NAME]." }, { "code": null, "e": 1778, "s": 1662, "text": "You can use any graphics packages, obviously, but I personally prefer the simplicity and power you get with Plotly." }, { "code": null, "e": 2044, "s": 1778, "text": "Each NBA regular season runs between October and April. (The 2019–20 season runs between October 22 and April 15, for instance.) In that time, each team plays 82 games, which averages out to be only about 2.15 days per game. It’s barely a day of rest between games." }, { "code": null, "e": 2255, "s": 2044, "text": "Not only that, NBA stadiums are located all across the US and Toronto like so. Having to play half of their games away from home to balance the schedule, teams must commute between them like we catch the metro." }, { "code": null, "e": 2408, "s": 2255, "text": "In fact, NBA teams travel roughly between 60,000 and 85,000 km/year (37,000–53,000 miles/year), and their flights put together look something like this:" }, { "code": null, "e": 2493, "s": 2408, "text": "(My article on visualising travel data, and an interactive, html version of the map)" }, { "code": null, "e": 2599, "s": 2493, "text": "And the result of all of this is that travel, the venue of play and rest are huge parts of NBA schedules." }, { "code": null, "e": 2842, "s": 2599, "text": "Each team plays half of the 82 games at home, and the other half away. Even many of the home games would not always involve must rest — it might involve travel to come back overnight, and they might even leave again shortly for the next game." }, { "code": null, "e": 3127, "s": 2842, "text": "For us mere mortals who would have to go through commercial flights, this would be a nightmare. However, modern NBA players fly in private team jets, and their health and well being is so well-managed that it is not a given that travel would impact them significantly. Let’s find out." }, { "code": null, "e": 3335, "s": 3127, "text": "Before we can analyse the impact of rest, play and home advantage, we need to collect or load our data. For convenience I use last season’s, but (you could use this season’s, or multiple seasons’ worth also." }, { "code": null, "e": 3517, "s": 3335, "text": "Although you can simply load the data which I’ve pre-processed (skip to where I load box_df if you would prefer to do this), if you are interested — this is how I compiled the data:" }, { "code": null, "e": 3635, "s": 3517, "text": "I obtained the schedule data from basketball-reference.com, and you can simply load the data as follows from my repo:" }, { "code": null, "e": 3707, "s": 3635, "text": "schedule_df = pd.read_csv('srcdata/2019_nba_schedule.csv', index_col=0)" }, { "code": null, "e": 3793, "s": 3707, "text": "The data includes game tip-off time in EST (est_time), so I create a column for date." }, { "code": null, "e": 3866, "s": 3793, "text": "schedule_df = schedule_df.assign(game_date=schedule_df.est_time.dt.date)" }, { "code": null, "e": 4118, "s": 3866, "text": "Then, game_dates = schedule_df.game_date.unique() obtains a list of unique game dates, after which the basketball_reference_web_scraper package is used to download our data for each date. You’ll need to install it with pip if you are to try this code." }, { "code": null, "e": 4241, "s": 4118, "text": "What I am doing here is downloading the data, marking each game as a home game, or an away game, and saving the dataframe." }, { "code": null, "e": 4313, "s": 4241, "text": "In any case, let’s load a file that I prepared earlier for consistency:" }, { "code": null, "e": 4387, "s": 4313, "text": "box_df = pd.read_csv('srcdata/2019_nba_team_box_scores.csv', index_col=0)" }, { "code": null, "e": 4533, "s": 4387, "text": "Take a look at box_df, and you’ll see that it contains 2460 rows, which matches up with 30 teams’ 82 games, as each row shows a team’s box score." }, { "code": null, "e": 4843, "s": 4533, "text": "I’ve processed the data here to include boolean columns for whether the team was playing at home, whether they had travelled, and whether they won (win). I also created a categorised variable for the number of rest days (rest_cats), with anything longer than 2 getting grouped together, including opening day." }, { "code": null, "e": 5011, "s": 4843, "text": "For our first visualisations, let’s take a look at how many games fall into each categories for rest days, and travel. I’ll skip the home/away splits, which are 50:50." }, { "code": null, "e": 5226, "s": 5011, "text": "import plotly.express as px# How many games in each category?temp_grp_df = box_df.groupby('rest_cats').count().reset_index(drop=False)fig = px.bar(temp_grp_df, y='rest_cats', x='outcome', orientation='h')fig.show()" }, { "code": null, "e": 5562, "s": 5226, "text": "# How many games in each category? Rest days & travel.temp_grp_df = box_df.groupby(['rest_cats', 'travelled']).count().reset_index(drop=False)temp_grp_df = temp_grp_df.assign(travelled=temp_grp_df.travelled.astype(str))fig = px.bar(temp_grp_df, y='rest_cats', x='outcome', orientation='h', color='travelled', barmode='group')fig.show()" }, { "code": null, "e": 5661, "s": 5562, "text": "That’s simple enough, and categorical variables can be concisely represented here as grouped bars." }, { "code": null, "e": 5858, "s": 5661, "text": "As to the outputs, there are a couple of observations to be made — the NBA schedule is such that the majority of games have 1 day of rest, and there are not many back-to-back (0 days’ rest) games." }, { "code": null, "e": 5972, "s": 5858, "text": "When there are, they appear to be largely home games (as in, no travel is involved), which is good for the teams." }, { "code": null, "e": 6185, "s": 5972, "text": "Now, let’s we take a look at the impact of rest, and travel on wins.The code to do that is largely the same as previous, except for now creating a WIN% column for each group, which becomes our dependent variable." }, { "code": null, "e": 6688, "s": 6185, "text": "travel_cats = ['rest_cats', 'travelled']travel_grp_df = box_df.groupby(travel_cats).sum()travel_grp_df = travel_grp_df.assign(games=box_df.groupby(travel_cats)['minutes_played'].count())travel_grp_df['WIN%'] = travel_grp_df.win/travel_grp_df.games * 100travel_grp_df.reset_index(drop=False, inplace=True)travel_grp_df = travel_grp_df.assign(travelled=travel_grp_df.travelled.astype(str))fig = px.bar(travel_grp_df, y='rest_cats', x='WIN%', orientation='h', color='travelled', barmode='group')fig.show()" }, { "code": null, "e": 6884, "s": 6688, "text": "The trend is as expected — travelling is bad for wins, and more rest is better. But, interestingly — teams that had travelled (red) is winning almost half of its games when given 2+ days of rest!" }, { "code": null, "e": 6980, "s": 6884, "text": "Now, adding further complexity to these charts is where the analysis starts to get challenging." }, { "code": null, "e": 7230, "s": 6980, "text": "We have three categorical variables that we are trying to analyse for, and we need to choose how to visualise them all, while also indicating the dependent variables (win %, for example). With a bar graph, one option is to use subplots as mentioned:" }, { "code": null, "e": 7405, "s": 7230, "text": "travel_cats = ['home', 'rest_cats', 'travelled']...fig = px.bar(travel_grp_df, y='rest_cats', x='WIN%', facet_col='home', orientation='h', color='travelled', barmode='group')" }, { "code": null, "e": 7658, "s": 7405, "text": "This is fine, but it is still missing quite a bit of information that would be useful to us. For instance, it doesn’t show us how these categorical variables overlap, or interact. Also, subplots do not lend themselves to easy comparisons along an axis." }, { "code": null, "e": 7710, "s": 7658, "text": "Instead, let’s explore a parallel categories chart." }, { "code": null, "e": 8010, "s": 7710, "text": "Since they’re somewhat unusual, let’s plot one and then discuss what they contain. Luckily, it’s relatively easy to plot parallel category plots with Plotly. In fact, Plotly Express simply takes as argument the original box score dataframe and compiles the data based on categories which we pass on." }, { "code": null, "e": 8093, "s": 8010, "text": "Take a look at this simple example, with binary categories for home and travelled." }, { "code": null, "e": 8310, "s": 8093, "text": "# PARALLEL CATEGORIES - THREE CATEGORIES AND WIN %box_df = box_df.assign(win_num=box_df.win.astype(int))travel_cats = ['home', 'travelled']fig = px.parallel_categories(box_df, dimensions=travel_cats, color='win_num')" }, { "code": null, "e": 8456, "s": 8310, "text": "You may not have seen many parallel categories charts before. They can look complicated, but they are quite simple once you get the hang of them." }, { "code": null, "e": 8729, "s": 8456, "text": "Each vertical column represents a category, and each band shows a permutation of categorical variables along each column. The chart above represents two categorical variables, and I have also separated them based on the outcome (win or loss), representing three variables." }, { "code": null, "e": 8897, "s": 8729, "text": "Here, it shows that there were 329 games (band) where the team was at home (left column), had travelled before the game (right column), and resulted in a win (colour)." }, { "code": null, "e": 9099, "s": 8897, "text": "The nature of the charts is that, each added category adds to complexity of the chart, potentially exponentially. Take a look below at the same chart, with categories added for the length of rest days." }, { "code": null, "e": 9177, "s": 9099, "text": "Plotted below is an example showing two highlighted paths as an illustration." }, { "code": null, "e": 9367, "s": 9177, "text": "The top, dark, path shows the number of games lost where the team was away (home==false), travelled to get to the game (travel==true), and had 2 days or more of rest (rest_cats == 2+ Days)." }, { "code": null, "e": 9469, "s": 9367, "text": "The lower, yellow, path shows numbers of games of the same criteria, but where the team won the game." }, { "code": null, "e": 9540, "s": 9469, "text": "(Here is an interactive version of this for you to try & have a play.)" }, { "code": null, "e": 9823, "s": 9540, "text": "Once we are used to the format, exploring multi-dimensional categorical relationships through parallel categories chart can be quite refreshing. Here, each vertical bar shows the overall winning percentages, and simply following thicker lines reveal where strong co-occurrences lie." }, { "code": null, "e": 10013, "s": 9823, "text": "For instance, let’s take a look at games where the team was playing with no rest, and had travelled. This screenshot highlights records from perspectives fo teams who played away from home." }, { "code": null, "e": 10135, "s": 10013, "text": "It is already clear that the losses far outweigh the wins. The away team wins only about 32% of these games (out of 237)." }, { "code": null, "e": 10301, "s": 10135, "text": "On the other hand, flipping that around, a home team on no rest & travel day wins 69% of 83 games (I will leave that as an exercise — have a look for yourself here)." }, { "code": null, "e": 10485, "s": 10301, "text": "I find parallel category plots quite useful, especially for data exploration. This chart for instance I found quite useful and visually striking also (I prepared it for this article)." }, { "code": null, "e": 10776, "s": 10485, "text": "This chart shows all of Klay Thompson’s shots, by shot location, and who the assist came from. While it initially looks complicated, look at how easy it is to spot the dominant combinations of categories. Parallel category plots make it easy to spot trends and co-occurrences as shown here." }, { "code": null, "e": 11025, "s": 10776, "text": "Admittedly, while parallel categories charts can be great for some cases, it has its limitations. In my experience, it can require some work by the reader to understand what is going on, and it can be visually confronting and intimidating for many." }, { "code": null, "e": 11110, "s": 11025, "text": "Another great, possibly more simple, way to visualise this type of data is treemaps." }, { "code": null, "e": 11119, "s": 11110, "text": "Treemaps" }, { "code": null, "e": 11268, "s": 11119, "text": "Treemaps are a fantastic way to explore hierarchical, categorised data sets. Just take a look at this example, and see how easy it is to understand." }, { "code": null, "e": 11425, "s": 11268, "text": "Although treemaps are typically used to evaluate the impact of hierarchical data structures, it is also a good tool for multivariate cases such as this one." }, { "code": null, "e": 11589, "s": 11425, "text": "We can produce treemaps here conveniently showing sizes of each group, and variations in winning percentages as we drill down deeper and deeper into each category." }, { "code": null, "e": 11679, "s": 11589, "text": "Because treemaps require a hierarchy, we explore by plotting two different treemaps here:" }, { "code": null, "e": 11763, "s": 11679, "text": "In the first, the hierarchy is based on home/away, travelled/not, and days of rest." }, { "code": null, "e": 11861, "s": 11763, "text": "In the second, the hierarchy is changed to be based on home/away, days of rest and travelled/not." }, { "code": null, "e": 11999, "s": 11861, "text": "The treemap layout does a great job in showing differences in sample sizes for each subset, as well as changes in percentages by colours." }, { "code": null, "e": 12190, "s": 11999, "text": "In both plots, it is clear that a much bigger impact on win percentages generally come from the amount of rest, and simply being home or away, rather than from whether they travelled at all." }, { "code": null, "e": 12452, "s": 12190, "text": "Take a look at the top graph, in the second tier of boxes (labelled travelled / stayed) for home games. The overall win / loss percentages for games where the home team returned home (i.e. travelled) before the game is very similar to where they did not travel." }, { "code": null, "e": 12677, "s": 12452, "text": "In the second graph, the overall winning percentages for days of rest are drastically different for all boxes, for instance away games with 0 days of rest being the worst (as we saw earlier in the parallel categories graph)." }, { "code": null, "e": 12909, "s": 12677, "text": "Let’s just explore one more point, and wrap up today’s analysis. We’ve to date looked at this data from one team’s perspective (except for home/away stats, which is complementary). What happens if the opponents’ rest data is also ?" }, { "code": null, "e": 13025, "s": 12909, "text": "I’ve got another dataset for just this reason — where the opponents’ rest days are added into opp_rest_cats column." }, { "code": null, "e": 14015, "s": 13025, "text": "box_df = pd.read_csv('srcdata/2019_nba_team_box_scores_2.csv', index_col=0)travel_cats = ['home', 'rest_cats', 'opp_rest_cats']travel_grp_df = box_df.groupby(travel_cats).sum()travel_grp_df = travel_grp_df.assign(games=box_df.groupby(travel_cats)['minutes_played'].count())travel_grp_df.reset_index(drop=False, inplace=True)chart_cats = ['home_str', 'rest_cats', 'opp_rest_cats']home_away = pd.Series(['Home ' * i for i in travel_grp_df.home.values]) + pd.Series(['Away ' * (1-i) for i in travel_grp_df.home.values])travel_grp_df['home_str'] = home_awaytravel_grp_df['rest_cats'] = travel_grp_df['rest_cats'] + \"' Rest\"travel_grp_df['opp_rest_cats'] = 'Opponent: <BR>' + travel_grp_df['opp_rest_cats'] + \"'<BR>Rest\"travel_grp_df['WIN%'] = travel_grp_df.win/travel_grp_df.games * 100fig = px.treemap( travel_grp_df, path=['home_str', 'rest_cats', 'opp_rest_cats'], values='games', color='WIN%', color_continuous_midpoint=50, color_continuous_scale=px.colors.diverging.Portland)fig.show()" }, { "code": null, "e": 14121, "s": 14015, "text": "Look at that! The best and the worst win/loss percentages happen when the rest disparity is the greatest." }, { "code": null, "e": 14456, "s": 14121, "text": "Have a look at the ‘away’ stats on the left, where our teams have 0 days’ rest, and the opponents have 2+ days, and the opposite, where our teams have 2+ days of rest and the opponents have 0 days of rest. They represent the extreme opposites. The pattern persists throughout, where rest disparity is a huge factor in win percentages." }, { "code": null, "e": 14707, "s": 14456, "text": "Even when the home team is on a back-to-back, they on average crush the other back-to-back team, showing the value of home cooking. About the most neutral setup appears to be having the home team on a back-to-back, and the away team on extended rest." }, { "code": null, "e": 14949, "s": 14707, "text": "Isn’t that interesting!? As it turns out, travel turns out to be relatively a small factor, and the largest factors in win/loss percentages are rest differential, and being home/away. This was easily made discoverable through these treemaps." }, { "code": null, "e": 15102, "s": 14949, "text": "All in all, I hope the above demonstrated some useful examples and techniques for drilling into datasets where there are multiple categorical variables." }, { "code": null, "e": 15220, "s": 15102, "text": "In my opinion, parallel category plots and treemaps are useful tools in doing so, and potentially underutilised ones." }, { "code": null, "e": 15533, "s": 15220, "text": "Treemaps are effective in visualising data in terms of drilldowns and changes in a property as data was subdivided, whereas parallel category plots were excellent for identifying cooccurrences, and flow of data points. Try these out for yourself with your own data sets, and I would love to hear more about them." }, { "code": null, "e": 15715, "s": 15533, "text": "If you liked this, pls to say 👋 / follow on twitter, or follow here for updates. I also wrote this article about mapping NBA travel data using Plotly, if you haven’t read it before:" }, { "code": null, "e": 15726, "s": 15715, "text": "medium.com" }, { "code": null, "e": 15793, "s": 15726, "text": "And also this article about my favourite data visualisation books." }, { "code": null, "e": 15816, "s": 15793, "text": "towardsdatascience.com" } ]
Garbage collection(GC) in JavaScript?
garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. The general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem. The main concept that garbage collection algorithms rely on is the concept of reference. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly). let a = [] function addToA() { let x = {name: "John"} a.push(x) } console.log(a[0]) {name: "John"} Note that x is not in scope anymore but is still accessible using a. This means that it needs to stay in memory until its reference is not there anymore. If we pop it from the array, it won't be needed anymore and can be garbage collected. Garbage collectors work using following algorithms − 1. Reference-counting garbage collection − An object is said to be "garbage", or collectible if there are zero references pointing to it. This is used in older browsers. But this causes a problem with circular referencing objects as they cannot be collected(There is always a reference to them from the other object. ) 2. Mark-and-sweep algorithm − This algorithm reduces the definition of "an object is no longer needed" to "an object is unreachable". This algorithm assumes the knowledge of a set of objects called roots. In JavaScript, the root is the global object. Periodically, the GC starts from these roots, find all objects that are referenced from these roots, recursively. Starting from the roots, the GC will thus find all reachable objects and collect all non-reachable objects. You can read more about GC in javascript athttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
[ { "code": null, "e": 1475, "s": 1062, "text": "garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. The general problem of automatically finding whether some memory \"is not needed anymore\" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem." }, { "code": null, "e": 1725, "s": 1475, "text": "The main concept that garbage collection algorithms rely on is the concept of reference. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly)." }, { "code": null, "e": 1815, "s": 1725, "text": "let a = []\nfunction addToA() {\n let x = {name: \"John\"}\n a.push(x)\n}\nconsole.log(a[0])" }, { "code": null, "e": 1830, "s": 1815, "text": "{name: \"John\"}" }, { "code": null, "e": 2070, "s": 1830, "text": "Note that x is not in scope anymore but is still accessible using a. This means that it needs to stay in memory until its reference is not there anymore. If we pop it from the array, it won't be needed anymore and can be garbage collected." }, { "code": null, "e": 2123, "s": 2070, "text": "Garbage collectors work using following algorithms −" }, { "code": null, "e": 2442, "s": 2123, "text": "1. Reference-counting garbage collection − An object is said to be \"garbage\", or collectible if there are zero references pointing to it. This is used in older browsers. But this causes a problem with circular referencing objects as they cannot be collected(There is always a reference to them from the other object. )" }, { "code": null, "e": 2915, "s": 2442, "text": "2. Mark-and-sweep algorithm − This algorithm reduces the definition of \"an object is no longer needed\" to \"an object is unreachable\". This algorithm assumes the knowledge of a set of objects called roots. In JavaScript, the root is the global object. Periodically, the GC starts from these roots, find all objects that are referenced from these roots, recursively. Starting from the roots, the GC will thus find all reachable objects and collect all non-reachable objects." }, { "code": null, "e": 3032, "s": 2915, "text": "You can read more about GC in javascript athttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management" } ]
5 Reasons “Logistic Regression” should be the first thing you learn when becoming a Data Scientist | by Dima Shulga | Towards Data Science
I started my way in the Data Science world a few years back. I was a Software Engineer back then and I started to learn online first (before starting my Master’s degree). I remember that as I searched for online resources I saw only names of learning algorithms — Linear Regression, Support Vector Machine, Decision Tree, Random Forest, Neural Networks and so on. It was very hard to understand where I should start. Today I know that the most important thing to learn to become a Data Scientist is the pipeline, i.e, the process of getting and processing data, understanding the data, building the model, evaluating the results (both of the model and the data processing phase) and deployment. So as a TL;DR for this post: Learn Logistic Regression first to become familiar with the pipeline and not being overwhelmed with fancy algorithms. You can read more about my experience of moving from Software Engineering into Data Science in this post. So here’s my 5 reasons why today I think that we should start with Logistic Regression first to become a Data Scientist. This is only my opinion of course, for other people it might be easier to do things in a different way. Because the learning algorithm is just a part of the pipeline As I said in the beginning, the Data Science work is not just model building. It includes these steps: You can see that “Modeling” is one part of this repetitive process. When building a data product, it is a good practice to build your whole pipeline first, keep it simple as possible, understand what exactly you’re trying to achieve, how can you measure yourself and what is your baseline. After that, you can do fancy Machine Learning and be able to know if you’re getting better. By the way, Logistic Regression (or any ML algorithm) may be used not only in the “Modeling” part but also in “Data Understanding” and “Data Preparation”, imputing is one example for this. Because you’ll better understand Machine Learning I think that the first question people ask themselves when reading this post title is why “Logistic” and not “Linear” regression. And the truth is that it doesn’t matter. This question alone brings to notion 2 types of supervised learning algorithms — Classification (Logistic Regression) and Regression (Linear Regression). When you build your pipeline with Logistic or Linear Regression you’re becoming familiar with most of the Machine Learning concepts while keeping things simple. Concepts like Supervised and Unsupervised Learning, Classification vs Regression, Linear vs Non-Linear problems and many more. Also you’re getting an idea about how to prepare your data, what challenges might be there (like imputing and feature selection), how do you measure your model, should you use “Accuracy”, “Precision-Recall”, “ROC AUC”? or maybe “Mean Squared Error” and “Pearson Correlation”?. All those concepts are the most important part of the Data Science process. After you’re familiar with them, you’ll be able to replace your simple model with much more complex one onces you’ve mastered them. Because “Logistic Regression” is (sometimes) enough Logistic regression is a very powerful algorithm, even for very complex problems it may do a good job. Take MNIST for example, you can achieve 95% accuracy using Logistic Regression only, it’s not a great result, but its more than good enough to make sure you pipeline works. Actually, with the right representation of the features, it can do a fantastic job. When dealing with non-linear problems, we sometimes try to represent the original data in a way that may be explained linearly. Here’s a small example of this idea: We want to perform a simple classification task on the following data: X1 x2 | Y==================-2 0 1 2 0 1-1 0 0 1 0 0 If we plot this data, we’ll be able to see that there is no single line that can separate it: plt.scatter([-2, 2], [0, 0 ], c='b')plt.scatter([-1, 1], [0, 0 ], c='r') In this case, Logistic Regression without doing something with the data won’t help us, but if we drop our x2 feature and use x12 instead, it will look like this: X1 x1^2 | Y==================-2 4 1 2 4 1-1 1 0 1 1 0 Now, there is a simple line that can separate the data. Of course, this toy example is nothing like real life, and in real life, it will be very hard to tell how exactly you need to change your data so a linear classier will help you, but, if you invest some time in feature engineering and feature selection your Logistic Regression might do a very good job. Because it is an important tool in Statistics Linear Regression is good not only for prediction, once you have a fitted Linear Regression model you can learn things about relationships between the depended and the independent variables, or in more “ML” language, you can learn the relations between your features and you target value. Consider a simple example where we have data about house pricing, we have a bunch of features and the actual price. We fit a Linear Regression model and get good results. We can look at the actual weights the model learned for each feature, and if those are significant, we can say that some feature is more important than others, moreover, we can say that the house size, for example, responsible for 50% of the change in the house price and increase in 1 square meter will lead to increase in 10K in house price. Linear Regression is a powerful tool to learn relationships from data and statisticians use it quite often. Because its a great start to learning Neural Networks For me, studying Logistic regression first helped a lot when I started to learn Neural Networks. You can think of each neuron in the network as a Logistic Regression, it has the input, the weights, the bias you do a dot product to all of that, then apply some non linear function. Moreover, the final layer of a neural network is a simple linear model (most of the time). Take a look at this very basic neural network: Let’s look closer at the “output layer”, you can see that this is a simple linear (or logistic) regression, we have the input (hidden layer 2), we have the weighs, we do a dot product and then add a non linear function (depends on the task). A nice way to think about neural networks is dividing the NN into two parts, the representation part, and the classification/regression part: The first part (on the left) is trying to learn a good representation of the data that will help the second part (on the right) to perform a linear classification/regression. You can read more about that idea in this great post. Conclusion There’s a lot to know if you want to become a Data Scientist, and at first glance, it looks like the learning algorithms are the most important part. The reality is that the learning algorithms are very complicated in most cases and require a lot of time and effort to understand, but are only a small part of the Data Science pipeline.
[ { "code": null, "e": 1014, "s": 172, "text": "I started my way in the Data Science world a few years back. I was a Software Engineer back then and I started to learn online first (before starting my Master’s degree). I remember that as I searched for online resources I saw only names of learning algorithms — Linear Regression, Support Vector Machine, Decision Tree, Random Forest, Neural Networks and so on. It was very hard to understand where I should start. Today I know that the most important thing to learn to become a Data Scientist is the pipeline, i.e, the process of getting and processing data, understanding the data, building the model, evaluating the results (both of the model and the data processing phase) and deployment. So as a TL;DR for this post: Learn Logistic Regression first to become familiar with the pipeline and not being overwhelmed with fancy algorithms." }, { "code": null, "e": 1120, "s": 1014, "text": "You can read more about my experience of moving from Software Engineering into Data Science in this post." }, { "code": null, "e": 1345, "s": 1120, "text": "So here’s my 5 reasons why today I think that we should start with Logistic Regression first to become a Data Scientist. This is only my opinion of course, for other people it might be easier to do things in a different way." }, { "code": null, "e": 1407, "s": 1345, "text": "Because the learning algorithm is just a part of the pipeline" }, { "code": null, "e": 1510, "s": 1407, "text": "As I said in the beginning, the Data Science work is not just model building. It includes these steps:" }, { "code": null, "e": 1892, "s": 1510, "text": "You can see that “Modeling” is one part of this repetitive process. When building a data product, it is a good practice to build your whole pipeline first, keep it simple as possible, understand what exactly you’re trying to achieve, how can you measure yourself and what is your baseline. After that, you can do fancy Machine Learning and be able to know if you’re getting better." }, { "code": null, "e": 2081, "s": 1892, "text": "By the way, Logistic Regression (or any ML algorithm) may be used not only in the “Modeling” part but also in “Data Understanding” and “Data Preparation”, imputing is one example for this." }, { "code": null, "e": 2131, "s": 2081, "text": "Because you’ll better understand Machine Learning" }, { "code": null, "e": 3229, "s": 2131, "text": "I think that the first question people ask themselves when reading this post title is why “Logistic” and not “Linear” regression. And the truth is that it doesn’t matter. This question alone brings to notion 2 types of supervised learning algorithms — Classification (Logistic Regression) and Regression (Linear Regression). When you build your pipeline with Logistic or Linear Regression you’re becoming familiar with most of the Machine Learning concepts while keeping things simple. Concepts like Supervised and Unsupervised Learning, Classification vs Regression, Linear vs Non-Linear problems and many more. Also you’re getting an idea about how to prepare your data, what challenges might be there (like imputing and feature selection), how do you measure your model, should you use “Accuracy”, “Precision-Recall”, “ROC AUC”? or maybe “Mean Squared Error” and “Pearson Correlation”?. All those concepts are the most important part of the Data Science process. After you’re familiar with them, you’ll be able to replace your simple model with much more complex one onces you’ve mastered them." }, { "code": null, "e": 3281, "s": 3229, "text": "Because “Logistic Regression” is (sometimes) enough" }, { "code": null, "e": 3877, "s": 3281, "text": "Logistic regression is a very powerful algorithm, even for very complex problems it may do a good job. Take MNIST for example, you can achieve 95% accuracy using Logistic Regression only, it’s not a great result, but its more than good enough to make sure you pipeline works. Actually, with the right representation of the features, it can do a fantastic job. When dealing with non-linear problems, we sometimes try to represent the original data in a way that may be explained linearly. Here’s a small example of this idea: We want to perform a simple classification task on the following data:" }, { "code": null, "e": 3976, "s": 3877, "text": "X1 x2 | Y==================-2 0 1 2 0 1-1 0 0 1 0 0" }, { "code": null, "e": 4070, "s": 3976, "text": "If we plot this data, we’ll be able to see that there is no single line that can separate it:" }, { "code": null, "e": 4143, "s": 4070, "text": "plt.scatter([-2, 2], [0, 0 ], c='b')plt.scatter([-1, 1], [0, 0 ], c='r')" }, { "code": null, "e": 4305, "s": 4143, "text": "In this case, Logistic Regression without doing something with the data won’t help us, but if we drop our x2 feature and use x12 instead, it will look like this:" }, { "code": null, "e": 4400, "s": 4305, "text": "X1 x1^2 | Y==================-2 4 1 2 4 1-1 1 0 1 1 0" }, { "code": null, "e": 4760, "s": 4400, "text": "Now, there is a simple line that can separate the data. Of course, this toy example is nothing like real life, and in real life, it will be very hard to tell how exactly you need to change your data so a linear classier will help you, but, if you invest some time in feature engineering and feature selection your Logistic Regression might do a very good job." }, { "code": null, "e": 4806, "s": 4760, "text": "Because it is an important tool in Statistics" }, { "code": null, "e": 5718, "s": 4806, "text": "Linear Regression is good not only for prediction, once you have a fitted Linear Regression model you can learn things about relationships between the depended and the independent variables, or in more “ML” language, you can learn the relations between your features and you target value. Consider a simple example where we have data about house pricing, we have a bunch of features and the actual price. We fit a Linear Regression model and get good results. We can look at the actual weights the model learned for each feature, and if those are significant, we can say that some feature is more important than others, moreover, we can say that the house size, for example, responsible for 50% of the change in the house price and increase in 1 square meter will lead to increase in 10K in house price. Linear Regression is a powerful tool to learn relationships from data and statisticians use it quite often." }, { "code": null, "e": 5772, "s": 5718, "text": "Because its a great start to learning Neural Networks" }, { "code": null, "e": 6191, "s": 5772, "text": "For me, studying Logistic regression first helped a lot when I started to learn Neural Networks. You can think of each neuron in the network as a Logistic Regression, it has the input, the weights, the bias you do a dot product to all of that, then apply some non linear function. Moreover, the final layer of a neural network is a simple linear model (most of the time). Take a look at this very basic neural network:" }, { "code": null, "e": 6575, "s": 6191, "text": "Let’s look closer at the “output layer”, you can see that this is a simple linear (or logistic) regression, we have the input (hidden layer 2), we have the weighs, we do a dot product and then add a non linear function (depends on the task). A nice way to think about neural networks is dividing the NN into two parts, the representation part, and the classification/regression part:" }, { "code": null, "e": 6804, "s": 6575, "text": "The first part (on the left) is trying to learn a good representation of the data that will help the second part (on the right) to perform a linear classification/regression. You can read more about that idea in this great post." }, { "code": null, "e": 6815, "s": 6804, "text": "Conclusion" } ]
Highcharts - Basic Pie Chart
Following is an example of a basic pie chart. We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. An example of a basic pie chart is given below. Let us now see the additional configurations/steps taken. Configure the series type to be pie based. series.type decides the series type for the chart. Here, the default value is "line". var series = { type: 'pie' }; highcharts_pie_basic.htm <html> <head> <title>Highcharts Tutorial</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src = "https://code.highcharts.com/highcharts.js"></script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div> <script language = "JavaScript"> $(document).ready(function() { var chart = { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }; var title = { text: 'Browser market shares at a specific website, 2014' }; var tooltip = { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }; var plotOptions = { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}%</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor)|| 'black' } } } }; var series = [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }]; var json = {}; json.chart = chart; json.title = title; json.tooltip = tooltip; json.series = series; json.plotOptions = plotOptions; $('#container').highcharts(json); }); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2063, "s": 2017, "text": "Following is an example of a basic pie chart." }, { "code": null, "e": 2167, "s": 2063, "text": "We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter." }, { "code": null, "e": 2215, "s": 2167, "text": "An example of a basic pie chart is given below." }, { "code": null, "e": 2273, "s": 2215, "text": "Let us now see the additional configurations/steps taken." }, { "code": null, "e": 2402, "s": 2273, "text": "Configure the series type to be pie based. series.type decides the series type for the chart. Here, the default value is \"line\"." }, { "code": null, "e": 2435, "s": 2402, "text": "var series = {\n type: 'pie'\n};" }, { "code": null, "e": 2460, "s": 2435, "text": "highcharts_pie_basic.htm" }, { "code": null, "e": 4660, "s": 2460, "text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() {\n var chart = {\n plotBackgroundColor: null,\n plotBorderWidth: null,\n plotShadow: false\n };\n var title = {\n text: 'Browser market shares at a specific website, 2014' \n };\n var tooltip = {\n pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'\n };\n var plotOptions = {\n pie: {\n allowPointSelect: true,\n cursor: 'pointer',\n \n dataLabels: {\n enabled: true,\n format: '<b>{point.name}%</b>: {point.percentage:.1f} %',\n style: {\n color: (Highcharts.theme && Highcharts.theme.contrastTextColor)||\n 'black'\n }\n }\n }\n };\n var series = [{\n type: 'pie',\n name: 'Browser share',\n data: [\n ['Firefox', 45.0],\n ['IE', 26.8],\n {\n name: 'Chrome',\n y: 12.8,\n sliced: true,\n selected: true\n },\n \n ['Safari', 8.5],\n ['Opera', 6.2],\n ['Others', 0.7]\n ]\n }];\n var json = {}; \n json.chart = chart; \n json.title = title; \n json.tooltip = tooltip; \n json.series = series;\n json.plotOptions = plotOptions;\n $('#container').highcharts(json); \n });\n </script>\n </body>\n \n</html>" }, { "code": null, "e": 4679, "s": 4660, "text": "Verify the result." }, { "code": null, "e": 4686, "s": 4679, "text": " Print" }, { "code": null, "e": 4697, "s": 4686, "text": " Add Notes" } ]
Python Number atan2() Method
Python number method atan2() returns atan(y / x), in radians. Following is the syntax for atan2() method − atan2(y, x) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. y − This must be a numeric value. y − This must be a numeric value. x − This must be a numeric value. x − This must be a numeric value. This method returns atan(y / x), in radians. The following example shows the usage of atan2() method. #!/usr/bin/python import math print "atan2(-0.50,-0.50) : ", math.atan2(-0.50,-0.50) print "atan2(0.50,0.50) : ", math.atan2(0.50,0.50) print "atan2(5,5) : ", math.atan2(5,5) print "atan2(-10,10) : ", math.atan2(-10,10) print "atan2(10,20) : ", math.atan2(10,20) When we run above program, it produces following result − atan2(-0.50,-0.50) : -2.35619449019 atan2(0.50,0.50) : 0.785398163397 atan2(5,5) : 0.785398163397 atan2(-10,10) : -0.785398163397 atan2(10,20) : 0.463647609001 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": 2307, "s": 2244, "text": "Python number method atan2() returns atan(y / x), in radians." }, { "code": null, "e": 2352, "s": 2307, "text": "Following is the syntax for atan2() method −" }, { "code": null, "e": 2365, "s": 2352, "text": "atan2(y, x)\n" }, { "code": null, "e": 2512, "s": 2365, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2546, "s": 2512, "text": "y − This must be a numeric value." }, { "code": null, "e": 2580, "s": 2546, "text": "y − This must be a numeric value." }, { "code": null, "e": 2614, "s": 2580, "text": "x − This must be a numeric value." }, { "code": null, "e": 2648, "s": 2614, "text": "x − This must be a numeric value." }, { "code": null, "e": 2693, "s": 2648, "text": "This method returns atan(y / x), in radians." }, { "code": null, "e": 2750, "s": 2693, "text": "The following example shows the usage of atan2() method." }, { "code": null, "e": 3019, "s": 2750, "text": "#!/usr/bin/python\nimport math\n\nprint \"atan2(-0.50,-0.50) : \", math.atan2(-0.50,-0.50)\nprint \"atan2(0.50,0.50) : \", math.atan2(0.50,0.50)\nprint \"atan2(5,5) : \", math.atan2(5,5)\nprint \"atan2(-10,10) : \", math.atan2(-10,10)\nprint \"atan2(10,20) : \", math.atan2(10,20)" }, { "code": null, "e": 3077, "s": 3019, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3243, "s": 3077, "text": "atan2(-0.50,-0.50) : -2.35619449019\natan2(0.50,0.50) : 0.785398163397\natan2(5,5) : 0.785398163397\natan2(-10,10) : -0.785398163397\natan2(10,20) : 0.463647609001\n" }, { "code": null, "e": 3280, "s": 3243, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3296, "s": 3280, "text": " Malhar Lathkar" }, { "code": null, "e": 3329, "s": 3296, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3348, "s": 3329, "text": " Arnab Chakraborty" }, { "code": null, "e": 3383, "s": 3348, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3405, "s": 3383, "text": " In28Minutes Official" }, { "code": null, "e": 3439, "s": 3405, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3467, "s": 3439, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3502, "s": 3467, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3516, "s": 3502, "text": " Lets Kode It" }, { "code": null, "e": 3549, "s": 3516, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3566, "s": 3549, "text": " Abhilash Nelson" }, { "code": null, "e": 3573, "s": 3566, "text": " Print" }, { "code": null, "e": 3584, "s": 3573, "text": " Add Notes" } ]
RxJS - Join Operator merge
This operator will take in the input observable and will emit all the values from the observable and emit one single output observable. merge(observable:array[]): Observable observable − The input will be an array of Observable. It will return an observable with a single value as output. import { of, merge } from 'rxjs'; import { concat } from 'rxjs/operators'; let list1 = of(2, 3, 4, 5, 6); let list2 = of(4, 9, 16, 25, 36) let final_val = merge(list1, list2); final_val.subscribe(x => console.log(x)); 51 Lectures 4 hours Daniel Stern Print Add Notes Bookmark this page
[ { "code": null, "e": 1960, "s": 1824, "text": "This operator will take in the input observable and will emit all the values from the observable and emit one single output observable." }, { "code": null, "e": 1999, "s": 1960, "text": "merge(observable:array[]): Observable\n" }, { "code": null, "e": 2054, "s": 1999, "text": "observable − The input will be an array of Observable." }, { "code": null, "e": 2114, "s": 2054, "text": "It will return an observable with a single value as output." }, { "code": null, "e": 2333, "s": 2114, "text": "import { of, merge } from 'rxjs';\nimport { concat } from 'rxjs/operators';\n\nlet list1 = of(2, 3, 4, 5, 6);\nlet list2 = of(4, 9, 16, 25, 36)\nlet final_val = merge(list1, list2);\nfinal_val.subscribe(x => console.log(x));" }, { "code": null, "e": 2366, "s": 2333, "text": "\n 51 Lectures \n 4 hours \n" }, { "code": null, "e": 2380, "s": 2366, "text": " Daniel Stern" }, { "code": null, "e": 2387, "s": 2380, "text": " Print" }, { "code": null, "e": 2398, "s": 2387, "text": " Add Notes" } ]
C Program For Searching An Element In A Linked List - GeeksforGeeks
27 Dec, 2021 Write a function that searches a given key ‘x’ in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 14, then the function should return true.Iterative Solution: 1) Initialize a node pointer, current = head. 2) Do following while current is not NULL a) current->key is equal to the key being searched return true. b) current = current->next 3) Return false Following is iterative implementation of above algorithm to search a given key. C // Iterative C program to search an // element in linked list#include<stdio.h>#include<stdlib.h>#include<stdbool.h> // Link list node struct Node{ int key; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_key){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the key new_node->key = new_key; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Checks whether the value x is present// in linked list bool search(struct Node* head, int x){ // Initialize current struct Node* current = head; while (current != NULL) { if (current->key == x) return true; current = current->next; } return false;} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; int x = 21; // Use push() to construct list // 14->21->11->30->10 push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); search(head, 21)? printf("Yes") : printf("No"); return 0;} Output: Yes Recursive Solution: bool search(head, x) 1) If head is NULL, return false. 2) If head's key is same as x, return true; 3) Else return search(head->next, x) Following is the recursive implementation of the above algorithm to search a given key. C // Recursive C program to search an // element in linked list#include<stdio.h>#include<stdlib.h>#include<stdbool.h>// Link list nodestruct Node{ int key; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_key){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the key new_node->key = new_key; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Checks whether the value x is present// in linked listbool search(struct Node* head, int x){ // Base case if (head == NULL) return false; // If key is present in current // node, return true if (head->key == x) return true; // Recur for remaining list return search(head->next, x);} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; int x = 21; // Use push() to construct list // 14->21->11->30->10 push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); search(head, 21)? printf("Yes") : printf("No"); return 0;} Output: Yes Please refer complete article on Search an element in a Linked List (Iterative and Recursive) for more details! Linked Lists C Language C Programs Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 24286, "s": 24258, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24448, "s": 24286, "text": "Write a function that searches a given key ‘x’ in a given singly linked list. The function should return true if x is present in linked list and false otherwise." }, { "code": null, "e": 24479, "s": 24448, "text": "bool search(Node *head, int x)" }, { "code": null, "e": 24685, "s": 24479, "text": "For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then function should return false. If key to be searched is 14, then the function should return true.Iterative Solution: " }, { "code": null, "e": 24889, "s": 24685, "text": "1) Initialize a node pointer, current = head.\n2) Do following while current is not NULL\n a) current->key is equal to the key being searched return true.\n b) current = current->next\n3) Return false " }, { "code": null, "e": 24969, "s": 24889, "text": "Following is iterative implementation of above algorithm to search a given key." }, { "code": null, "e": 24971, "s": 24969, "text": "C" }, { "code": "// Iterative C program to search an // element in linked list#include<stdio.h>#include<stdlib.h>#include<stdbool.h> // Link list node struct Node{ int key; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_key){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the key new_node->key = new_key; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Checks whether the value x is present// in linked list bool search(struct Node* head, int x){ // Initialize current struct Node* current = head; while (current != NULL) { if (current->key == x) return true; current = current->next; } return false;} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; int x = 21; // Use push() to construct list // 14->21->11->30->10 push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); search(head, 21)? printf(\"Yes\") : printf(\"No\"); return 0;}", "e": 26276, "s": 24971, "text": null }, { "code": null, "e": 26285, "s": 26276, "text": "Output: " }, { "code": null, "e": 26289, "s": 26285, "text": "Yes" }, { "code": null, "e": 26309, "s": 26289, "text": "Recursive Solution:" }, { "code": null, "e": 26446, "s": 26309, "text": "bool search(head, x)\n1) If head is NULL, return false.\n2) If head's key is same as x, return true;\n3) Else return search(head->next, x) " }, { "code": null, "e": 26534, "s": 26446, "text": "Following is the recursive implementation of the above algorithm to search a given key." }, { "code": null, "e": 26536, "s": 26534, "text": "C" }, { "code": "// Recursive C program to search an // element in linked list#include<stdio.h>#include<stdlib.h>#include<stdbool.h>// Link list nodestruct Node{ int key; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_key){ // Allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // Put in the key new_node->key = new_key; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Checks whether the value x is present// in linked listbool search(struct Node* head, int x){ // Base case if (head == NULL) return false; // If key is present in current // node, return true if (head->key == x) return true; // Recur for remaining list return search(head->next, x);} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; int x = 21; // Use push() to construct list // 14->21->11->30->10 push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); search(head, 21)? printf(\"Yes\") : printf(\"No\"); return 0;}", "e": 27869, "s": 26536, "text": null }, { "code": null, "e": 27877, "s": 27869, "text": "Output:" }, { "code": null, "e": 27881, "s": 27877, "text": "Yes" }, { "code": null, "e": 27993, "s": 27881, "text": "Please refer complete article on Search an element in a Linked List (Iterative and Recursive) for more details!" }, { "code": null, "e": 28006, "s": 27993, "text": "Linked Lists" }, { "code": null, "e": 28017, "s": 28006, "text": "C Language" }, { "code": null, "e": 28028, "s": 28017, "text": "C Programs" }, { "code": null, "e": 28040, "s": 28028, "text": "Linked List" }, { "code": null, "e": 28052, "s": 28040, "text": "Linked List" }, { "code": null, "e": 28150, "s": 28052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28188, "s": 28150, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28208, "s": 28188, "text": "Multithreading in C" }, { "code": null, "e": 28234, "s": 28208, "text": "Exception Handling in C++" }, { "code": null, "e": 28256, "s": 28234, "text": "'this' pointer in C++" }, { "code": null, "e": 28297, "s": 28256, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28310, "s": 28297, "text": "Strings in C" }, { "code": null, "e": 28351, "s": 28310, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28392, "s": 28351, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28430, "s": 28392, "text": "UDP Server-Client implementation in C" } ]
Bridge Design Pattern - GeeksforGeeks
22 Nov, 2021 The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. There are 2 parts in Bridge design pattern : AbstractionImplementation Abstraction Implementation This is a design mechanism that encapsulates an implementation class inside of an interface class. The bridge pattern allows the Abstraction and the Implementation to be developed independently and the client code can access only the Abstraction part without being concerned about the Implementation part. The abstraction is an interface or abstract class and the implementer is also an interface or abstract class. The abstraction contains a reference to the implementer. Children of the abstraction are referred to as refined abstractions, and children of the implementer are concrete implementers. Since we can change the reference to the implementer in the abstraction, we are able to change the abstraction’s implementer at run-time. Changes to the implementer do not affect client code. It increases the loose coupling between class abstraction and it’s implementation. UML Diagram of Bridge Design Pattern Elements of Bridge Design Pattern Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer. Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors. Implementer – It defines the interface for implementation classes. This interface does not need to correspond directly to the abstraction interface and can be very different. Abstraction imp provides an implementation in terms of operations provided by the Implementer interface. Concrete Implementation – Implements the above implementer by providing the concrete implementation. Lets see an Example of Bridge Design Pattern : Java // Java code to demonstrate// bridge design pattern // abstraction in bridge patternabstract class Vehicle { protected Workshop workShop1; protected Workshop workShop2; protected Vehicle(Workshop workShop1, Workshop workShop2) { this.workShop1 = workShop1; this.workShop2 = workShop2; } abstract public void manufacture();} // Refine abstraction 1 in bridge patternclass Car extends Vehicle { public Car(Workshop workShop1, Workshop workShop2) { super(workShop1, workShop2); } @Override public void manufacture() { System.out.print("Car "); workShop1.work(); workShop2.work(); }} // Refine abstraction 2 in bridge patternclass Bike extends Vehicle { public Bike(Workshop workShop1, Workshop workShop2) { super(workShop1, workShop2); } @Override public void manufacture() { System.out.print("Bike "); workShop1.work(); workShop2.work(); }} // Implementor for bridge patterninterface Workshop{ abstract public void work();} // Concrete implementation 1 for bridge patternclass Produce implements Workshop { @Override public void work() { System.out.print("Produced"); }} // Concrete implementation 2 for bridge patternclass Assemble implements Workshop { @Override public void work() { System.out.print(" And"); System.out.println(" Assembled."); }} // Demonstration of bridge design patternclass BridgePattern { public static void main(String[] args) { Vehicle vehicle1 = new Car(new Produce(), new Assemble()); vehicle1.manufacture(); Vehicle vehicle2 = new Bike(new Produce(), new Assemble()); vehicle2.manufacture(); }} Output : Car Produced And Assembled. Bike Produced And Assembled. Here we’re producing and assembling the two different vehicles using Bridge design pattern. When we need bridge design pattern The Bridge pattern is an application of the old advice, “prefer composition over inheritance”. It becomes handy when you must subclass different times in ways that are orthogonal with one another.For Example, the above example can also be done something like this : Without Bridge Design Pattern But the above solution has a problem. If you want to change the Bus class, then you may end up changing ProduceBus and AssembleBus as well and if the change is workshop specific then you may need to change the Bike class as well. With Bridge Design Pattern You can solve the above problem by decoupling the Vehicle and Workshop interfaces in the below manner. Advantages Bridge pattern decouple an abstraction from its implementation so that the two can vary independently.It is used mainly for implementing platform independence features.It adds one more method level redirection to achieve the objective.Publish abstraction interface in a separate inheritance hierarchy, and put the implementation in its own inheritance hierarchy.Use bridge pattern to run-time binding of the implementation.Use bridge pattern to map orthogonal class hierarchiesBridge is designed up-front to let the abstraction and the implementation vary independently. Bridge pattern decouple an abstraction from its implementation so that the two can vary independently. It is used mainly for implementing platform independence features. It adds one more method level redirection to achieve the objective. Publish abstraction interface in a separate inheritance hierarchy, and put the implementation in its own inheritance hierarchy. Use bridge pattern to run-time binding of the implementation. Use bridge pattern to map orthogonal class hierarchies Bridge is designed up-front to let the abstraction and the implementation vary independently. Further Read: Bridge Method in Python This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. sunny94 Nistelrooy srnathan711 Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Command Pattern Strategy Pattern | Set 1 (Introduction) Template Method Design Pattern State Design Pattern Difference between Sequence Diagram and Activity Diagram Visitor design pattern Iterator Pattern Observer Pattern | Set 2 (Implementation) Difference between Sequence diagram and Collaboration diagram Difference Between Architectural Style, Architectural Patterns and Design Patterns
[ { "code": null, "e": 24596, "s": 24568, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24722, "s": 24596, "text": "The Bridge design pattern allows you to separate the abstraction from the implementation. It is a structural design pattern. " }, { "code": null, "e": 24768, "s": 24722, "text": "There are 2 parts in Bridge design pattern : " }, { "code": null, "e": 24794, "s": 24768, "text": "AbstractionImplementation" }, { "code": null, "e": 24806, "s": 24794, "text": "Abstraction" }, { "code": null, "e": 24821, "s": 24806, "text": "Implementation" }, { "code": null, "e": 24922, "s": 24821, "text": "This is a design mechanism that encapsulates an implementation class inside of an interface class. " }, { "code": null, "e": 25129, "s": 24922, "text": "The bridge pattern allows the Abstraction and the Implementation to be developed independently and the client code can access only the Abstraction part without being concerned about the Implementation part." }, { "code": null, "e": 25239, "s": 25129, "text": "The abstraction is an interface or abstract class and the implementer is also an interface or abstract class." }, { "code": null, "e": 25616, "s": 25239, "text": "The abstraction contains a reference to the implementer. Children of the abstraction are referred to as refined abstractions, and children of the implementer are concrete implementers. Since we can change the reference to the implementer in the abstraction, we are able to change the abstraction’s implementer at run-time. Changes to the implementer do not affect client code." }, { "code": null, "e": 25699, "s": 25616, "text": "It increases the loose coupling between class abstraction and it’s implementation." }, { "code": null, "e": 25736, "s": 25699, "text": "UML Diagram of Bridge Design Pattern" }, { "code": null, "e": 25771, "s": 25736, "text": "Elements of Bridge Design Pattern " }, { "code": null, "e": 25882, "s": 25771, "text": "Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to the implementer." }, { "code": null, "e": 26011, "s": 25882, "text": "Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors." }, { "code": null, "e": 26291, "s": 26011, "text": "Implementer – It defines the interface for implementation classes. This interface does not need to correspond directly to the abstraction interface and can be very different. Abstraction imp provides an implementation in terms of operations provided by the Implementer interface." }, { "code": null, "e": 26392, "s": 26291, "text": "Concrete Implementation – Implements the above implementer by providing the concrete implementation." }, { "code": null, "e": 26441, "s": 26392, "text": "Lets see an Example of Bridge Design Pattern : " }, { "code": null, "e": 26446, "s": 26441, "text": "Java" }, { "code": "// Java code to demonstrate// bridge design pattern // abstraction in bridge patternabstract class Vehicle { protected Workshop workShop1; protected Workshop workShop2; protected Vehicle(Workshop workShop1, Workshop workShop2) { this.workShop1 = workShop1; this.workShop2 = workShop2; } abstract public void manufacture();} // Refine abstraction 1 in bridge patternclass Car extends Vehicle { public Car(Workshop workShop1, Workshop workShop2) { super(workShop1, workShop2); } @Override public void manufacture() { System.out.print(\"Car \"); workShop1.work(); workShop2.work(); }} // Refine abstraction 2 in bridge patternclass Bike extends Vehicle { public Bike(Workshop workShop1, Workshop workShop2) { super(workShop1, workShop2); } @Override public void manufacture() { System.out.print(\"Bike \"); workShop1.work(); workShop2.work(); }} // Implementor for bridge patterninterface Workshop{ abstract public void work();} // Concrete implementation 1 for bridge patternclass Produce implements Workshop { @Override public void work() { System.out.print(\"Produced\"); }} // Concrete implementation 2 for bridge patternclass Assemble implements Workshop { @Override public void work() { System.out.print(\" And\"); System.out.println(\" Assembled.\"); }} // Demonstration of bridge design patternclass BridgePattern { public static void main(String[] args) { Vehicle vehicle1 = new Car(new Produce(), new Assemble()); vehicle1.manufacture(); Vehicle vehicle2 = new Bike(new Produce(), new Assemble()); vehicle2.manufacture(); }}", "e": 28187, "s": 26446, "text": null }, { "code": null, "e": 28197, "s": 28187, "text": "Output : " }, { "code": null, "e": 28254, "s": 28197, "text": "Car Produced And Assembled.\nBike Produced And Assembled." }, { "code": null, "e": 28347, "s": 28254, "text": "Here we’re producing and assembling the two different vehicles using Bridge design pattern. " }, { "code": null, "e": 28382, "s": 28347, "text": "When we need bridge design pattern" }, { "code": null, "e": 28649, "s": 28382, "text": "The Bridge pattern is an application of the old advice, “prefer composition over inheritance”. It becomes handy when you must subclass different times in ways that are orthogonal with one another.For Example, the above example can also be done something like this : " }, { "code": null, "e": 28680, "s": 28649, "text": "Without Bridge Design Pattern " }, { "code": null, "e": 28910, "s": 28680, "text": "But the above solution has a problem. If you want to change the Bus class, then you may end up changing ProduceBus and AssembleBus as well and if the change is workshop specific then you may need to change the Bike class as well." }, { "code": null, "e": 28937, "s": 28910, "text": "With Bridge Design Pattern" }, { "code": null, "e": 29040, "s": 28937, "text": "You can solve the above problem by decoupling the Vehicle and Workshop interfaces in the below manner." }, { "code": null, "e": 29052, "s": 29040, "text": "Advantages " }, { "code": null, "e": 29623, "s": 29052, "text": "Bridge pattern decouple an abstraction from its implementation so that the two can vary independently.It is used mainly for implementing platform independence features.It adds one more method level redirection to achieve the objective.Publish abstraction interface in a separate inheritance hierarchy, and put the implementation in its own inheritance hierarchy.Use bridge pattern to run-time binding of the implementation.Use bridge pattern to map orthogonal class hierarchiesBridge is designed up-front to let the abstraction and the implementation vary independently." }, { "code": null, "e": 29726, "s": 29623, "text": "Bridge pattern decouple an abstraction from its implementation so that the two can vary independently." }, { "code": null, "e": 29793, "s": 29726, "text": "It is used mainly for implementing platform independence features." }, { "code": null, "e": 29861, "s": 29793, "text": "It adds one more method level redirection to achieve the objective." }, { "code": null, "e": 29989, "s": 29861, "text": "Publish abstraction interface in a separate inheritance hierarchy, and put the implementation in its own inheritance hierarchy." }, { "code": null, "e": 30051, "s": 29989, "text": "Use bridge pattern to run-time binding of the implementation." }, { "code": null, "e": 30106, "s": 30051, "text": "Use bridge pattern to map orthogonal class hierarchies" }, { "code": null, "e": 30200, "s": 30106, "text": "Bridge is designed up-front to let the abstraction and the implementation vary independently." }, { "code": null, "e": 30238, "s": 30200, "text": "Further Read: Bridge Method in Python" }, { "code": null, "e": 30658, "s": 30238, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. " }, { "code": null, "e": 30666, "s": 30658, "text": "sunny94" }, { "code": null, "e": 30677, "s": 30666, "text": "Nistelrooy" }, { "code": null, "e": 30689, "s": 30677, "text": "srnathan711" }, { "code": null, "e": 30704, "s": 30689, "text": "Design Pattern" }, { "code": null, "e": 30802, "s": 30704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30818, "s": 30802, "text": "Command Pattern" }, { "code": null, "e": 30858, "s": 30818, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 30889, "s": 30858, "text": "Template Method Design Pattern" }, { "code": null, "e": 30910, "s": 30889, "text": "State Design Pattern" }, { "code": null, "e": 30967, "s": 30910, "text": "Difference between Sequence Diagram and Activity Diagram" }, { "code": null, "e": 30990, "s": 30967, "text": "Visitor design pattern" }, { "code": null, "e": 31007, "s": 30990, "text": "Iterator Pattern" }, { "code": null, "e": 31049, "s": 31007, "text": "Observer Pattern | Set 2 (Implementation)" }, { "code": null, "e": 31111, "s": 31049, "text": "Difference between Sequence diagram and Collaboration diagram" } ]
Generators in Python - GeeksforGeeks
31 Mar, 2020 Prerequisites: Yield Keyword and Iterators There are two terms involved when we discuss generators. Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.# A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)Output :1 2 3Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).# A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())Output :1 2 3 Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.# A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)Output :1 2 3 # A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value) Output : 1 2 3 Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).# A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())Output :1 2 3 # A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next()) Output : 1 2 3 So a generator function returns an generator object that is iterable, i.e., can be used as an Iterators . As another example, below is a generator for Fibonacci Numbers. # A simple generator for Fibonacci Numbersdef fib(limit): # Initialize first two Fibonacci Numbers a, b = 0, 1 # One by one yield next Fibonacci Number while a < limit: yield a a, b = b, a + b # Create a generator objectx = fib(5) # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())print(x.next())print(x.next()) # Iterating over the generator object using for# in loop.print("\nUsing for in loop")for i in fib(5): print(i) Output : 0 1 1 2 3 Using for in loop 0 1 1 2 3 Applications : Suppose we to create a stream of Fibonacci numbers, adopting the generator approach makes it trivial; we just have to call next(x) to get the next Fibonacci number without bothering about where or when the stream of numbers ends.A more practical type of stream processing is handling large data files such as log files. Generators provide a space efficient method for such data processing as only parts of the file are handled at one given point in time. We can also use Iterators for these purposes, but Generator provides a quick way (We don’t need to write __next__ and __iter__ methods here). Refer below link for more advanced applications of generators in Python.http://www.dabeaz.com/finalgenerator/ This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above fridayda13 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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()
[ { "code": null, "e": 41552, "s": 41524, "text": "\n31 Mar, 2020" }, { "code": null, "e": 41595, "s": 41552, "text": "Prerequisites: Yield Keyword and Iterators" }, { "code": null, "e": 41652, "s": 41595, "text": "There are two terms involved when we discuss generators." }, { "code": null, "e": 42784, "s": 41652, "text": "Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.# A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)Output :1\n2\n3Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).# A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())Output :1\n2\n3" }, { "code": null, "e": 43344, "s": 42784, "text": "Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.# A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)Output :1\n2\n3" }, { "code": "# A generator function that yields 1 for first time,# 2 second time and 3 third timedef simpleGeneratorFun(): yield 1 yield 2 yield 3 # Driver code to check above generator functionfor value in simpleGeneratorFun(): print(value)", "e": 43624, "s": 43344, "text": null }, { "code": null, "e": 43633, "s": 43624, "text": "Output :" }, { "code": null, "e": 43639, "s": 43633, "text": "1\n2\n3" }, { "code": null, "e": 44212, "s": 43639, "text": "Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).# A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())Output :1\n2\n3" }, { "code": "# A Python program to demonstrate use of # generator object with next() # A generator functiondef simpleGeneratorFun(): yield 1 yield 2 yield 3 # x is a generator objectx = simpleGeneratorFun() # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())", "e": 44540, "s": 44212, "text": null }, { "code": null, "e": 44549, "s": 44540, "text": "Output :" }, { "code": null, "e": 44555, "s": 44549, "text": "1\n2\n3" }, { "code": null, "e": 44661, "s": 44555, "text": "So a generator function returns an generator object that is iterable, i.e., can be used as an Iterators ." }, { "code": null, "e": 44725, "s": 44661, "text": "As another example, below is a generator for Fibonacci Numbers." }, { "code": "# A simple generator for Fibonacci Numbersdef fib(limit): # Initialize first two Fibonacci Numbers a, b = 0, 1 # One by one yield next Fibonacci Number while a < limit: yield a a, b = b, a + b # Create a generator objectx = fib(5) # Iterating over the generator object using nextprint(x.next()) # In Python 3, __next__()print(x.next())print(x.next())print(x.next())print(x.next()) # Iterating over the generator object using for# in loop.print(\"\\nUsing for in loop\")for i in fib(5): print(i)", "e": 45259, "s": 44725, "text": null }, { "code": null, "e": 45268, "s": 45259, "text": "Output :" }, { "code": null, "e": 45307, "s": 45268, "text": "0\n1\n1\n2\n3\n\nUsing for in loop\n0\n1\n1\n2\n3" }, { "code": null, "e": 45919, "s": 45307, "text": "Applications : Suppose we to create a stream of Fibonacci numbers, adopting the generator approach makes it trivial; we just have to call next(x) to get the next Fibonacci number without bothering about where or when the stream of numbers ends.A more practical type of stream processing is handling large data files such as log files. Generators provide a space efficient method for such data processing as only parts of the file are handled at one given point in time. We can also use Iterators for these purposes, but Generator provides a quick way (We don’t need to write __next__ and __iter__ methods here)." }, { "code": null, "e": 46029, "s": 45919, "text": "Refer below link for more advanced applications of generators in Python.http://www.dabeaz.com/finalgenerator/" }, { "code": null, "e": 46204, "s": 46029, "text": "This article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 46215, "s": 46204, "text": "fridayda13" }, { "code": null, "e": 46222, "s": 46215, "text": "Python" }, { "code": null, "e": 46320, "s": 46222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46348, "s": 46320, "text": "Read JSON file using Python" }, { "code": null, "e": 46398, "s": 46348, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 46420, "s": 46398, "text": "Python map() function" }, { "code": null, "e": 46464, "s": 46420, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 46499, "s": 46464, "text": "Read a file line by line in Python" }, { "code": null, "e": 46521, "s": 46499, "text": "Enumerate() in Python" }, { "code": null, "e": 46553, "s": 46521, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 46583, "s": 46553, "text": "Iterate over a list in Python" }, { "code": null, "e": 46625, "s": 46583, "text": "Different ways to create Pandas Dataframe" } ]
Conversational AI: Design & Build a Contextual Assistant- Part 2 | by Mady Mantha | Towards Data Science
In the first part of this series, we introduced the different maturity levels of conversational AI and started building a travel assistant using Rasa. In this post, we’ll look at structuring happy and unhappy conversation paths, various machine learning policies and configurations to improve your dialogue model, and use a transfer learning based language model to generate natural conversations. Rasa recently released version 1.0 in which they combined Core and NLU into a single package. We’ll be using Rasa 1.0 in this article. Since the primary purpose of the assistant, let’s name it Coop, is to book awesome vacations, Coop requires key pieces of information from the user in order to do so. For the purpose of this article, let’s assume Coop only needs the number of people, the holiday destination, and the start and end dates of said vacation. In the next iteration, we want to extract more information from the user with regards to their interests, budget, age, itinerary restrictions, and anything else we need to create curated travel experiences for them. Armed with this initial set of knowledge, let’s take a look at how we can enable Coop to gather this information through a natural conversation with the user. Rasa uses slots to hold user provided information, among other things. Slots, which are essentially key-value pairs, can be used to influence conversations with a user. The value of a slot can be set in several ways — through NLU, interactive cards, and actions. Rasa defines this as slot filling. Slots are defined in the “domain.yml” file. Each slot is given a name, type, and an optional initial value. Here’s a snippet from Coop’s domain.yml file: ...slots: enddate: type: unfeaturized location: type: unfeaturized num_people: type: unfeaturized startdate: type: unfeaturized... Note that we set the type as “unfeaturized” for each slot as we don’t want the slot values to influence our conversation flow. In order to perform actions on behalf of the user, like we’re trying to do with Coop, we need to fill multiple consecutive slots or key pieces of information. We can do with using FormAction. A FormAction is essentially a python class. It takes a list of slots that need to be filled or questions that need to answered, and asks the user for said information in order to fill each slot. Note that the FormAction only asks the user for information to fill slots that are not already set. Let’s take a look at a happy path. A happy path is where the contextual assistant is able to gather the information it needs from the user without interruption. In other words, the user answers the questions without deviating from their path as shown below. In order to enable the FormAction mechanism, you want to add the “FormPolicy” to your config file typically named “config.yml”: ...policies: - name: FormPolicy... Next, let’s define our custom form class: class BookingForm(FormAction): def name(self): # type: () -> Text """Unique identifier of the form""" return "booking_form" @staticmethod def required_slots(tracker: Tracker) -> List[Text]: """A list of required slots that the form has to fill""" return ["num_people", "location", "startdate", "enddate"] def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: """Define what the form has to do after all required slots are filled""" dispatcher.utter_template('utter_send_email', tracker) return [] As can be seen from the snippet above, our custom form class should define three methods — name, required_slots and submit. The methods are self explanatory. Now let’s tell our model to invoke the booking form action. Open your stories.md file and add one or more happy path stories: ...* request_vacation - booking_form - form{"name": "booking_form"} - form{"name": null}... We’ve defined several interesting slots in Coop. The “location” slot is used to hold information about the user’s vacation destination. We’ve also defined an entity with the same name. Rasa NLU will fill the “location” slot when it identifies the “location” entity in the user’s message. In order for it to be able to do so, we need to train the NLU to extract the location entity. While this is pretty exciting, training the NLU model to identity generic entities like location is a time consuming process that requires a lot of data. This is where the out-of-the-box “SpacyEntityExtractor” component of the Rasa NLU pipeline comes to our rescue. This pretrained component is a named-entity recognizer that identifies various common entities (called dimensions) like person, organization, cities and states. Let’s take a look at how we can hook into this component to fill our location slot. We begin by adding “SpacyEntityExtractor” component to our NLU pipeline. Edit the “config.yml” file. language: enpipeline:...- name: "SpacyEntityExtractor" dimensions: ["GPE", "LOC"] Rasa offers a method called “slot_mappings” in the FormAction class that can be used to further configure the way slots are filled. In our case, we can use this method to ensure that the “location” slot gets filled in the following order: Use the “location” entity identified by our NLU modelIf step 1 fails, use the “GPE” dimension identified by “SpacyEntityExtractor”If step 2 fails, use the “LOC” dimension identified by “SpacyEntityExtractor” Use the “location” entity identified by our NLU model If step 1 fails, use the “GPE” dimension identified by “SpacyEntityExtractor” If step 2 fails, use the “LOC” dimension identified by “SpacyEntityExtractor” def slot_mappings(self): # type: () -> Dict[Text: Union[Dict, List[Dict]]] """A dictionary to map required slots to - an extracted entity - intent: value pairs - a whole message or a list of them, where a first match will be picked""" return {"location": [self.from_entity(entity="location"), self.from_entity(entity="GPE"), self.from_entity(entity="LOC")]} You can read more about the predefined functions here. The other interesting slots in Coop’s domain are “startdate” and “enddate”. As the names suggest, these slots represent the user’s choice for their vacation start and end dates. Instead of training our NLU model to identify and extract this data and potentially solve for entity disambiguation along the way, we can use the “DucklingHTTPExtractor” component. This pretrained component is a named-entity recognizer that identifies various common entities like time, distance, and numbers. Similar to how we configured the “SpacyEntityExtractor”, the “DucklingHTTPExtractor” component should be added to our NLU pipeline. Edit the “config.yml” file. language: enpipeline:...- name: "DucklingHTTPExtractor" url: http://localhost:8000 dimensions: ["time", "number", "amount-of-money", "distance"] As seen from the config above, the “DucklingHTTPExtractor” is expected to be running at the specified host and port. You can use docker to run the duckling service. Note that the FormAction class allows us to define custom validations that can be used to validate user-provided information. For example, we want to ensure that the start date is earlier than the end date. These validation methods should be named based on a convention. If you have a slot named “enddate”, you want to define a method named “validate_enddate” for it to be called by Rasa. def validate_enddate(self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> Optional[Text]: """Ensure that the start date is before the end date.""" try: startdate = tracker.get_slot("startdate") startdate_obj = dateutil.parser.parse(startdate) enddate_obj = dateutil.parser.parse(value) if startdate_obj < enddate_obj: return value else: dispatcher.utter_template('utter_invalid_date', tracker) # validation failed, set slot to None return None except: print("log error") return None FormActions are really useful to gather information from a user and perform actions on behalf of a user. But, as you know, user behavior can be unpredictable, and conversation is messy. There are 30,000 different ways you can ask about the weather; one of my favorite ways is when people say “is it going to be raining cats and dogs today?” Users rarely provide the information required without digressing, engaging in chitchat, changing their minds, correcting their answers, asking follow up questions and so forth — all of which are valid, expected, and need to be handled if you’re building powerful conversational AI. These deviations are known as unhappy paths. I highly recommend using interactive learning through the CLI to train your model to handle unhappy paths. Here’s the command to run Rasa in interactive mode: rasa interactive --endpoints endpoints.yml Once you’re done, you can save the training data and retrain your models. Here’s an example of an unhappy path story. * request_vacation - booking_form - form{"name": "booking_form"} - slot{"requested_slot": "num_people"}...* form: inform{"location": "paris", "GPE": "Paris"} - slot{"location": "paris"} - form: booking_form - slot{"location": "paris"} - slot{"requested_slot": "startdate"}* correct{"num_people": "2"} - slot{"num_people": "2"} - action_correct - booking_form - slot{"requested_slot": "startdate"}* form: inform{"time": "2019-07-04T00:00:00.000-07:00"}... Rasa provides multiple policies that can be used to configure and train its Core dialogue management system. The “Embedding” policy, also known as Recurrent Embedding Dialogue Policy (REDP), can be used to efficiently handle unhappy paths. In addition, it provides hyperparameters that can be used to fine tune the model. You can read more about REDP here. I used the embedding policy for Coop. ...policies: - name: EmbeddingPolicy epochs: 2000 attn_shift_range: 5... Now, let’s take a look at an unhappy path that involves correction and explanation. A correction is when a user issues a revision to their previous answer or statement. For instance, if they got their phone number wrong and wished to correct it. A user issues an explanation when they want to know the reason behind the assistant’s questions. In the example above, notice how Coop guides the conversation back to the topic at hand. The dialogue model learns to handle corrections and provide explanation for why it needs certain information, essentially bringing the user back onto a happy path. There are two significant areas of natural language processing (NLP) that come into play with conversational AI. First, there’s the aspect of trying to understand what the user says; what is the user’s intent? Second, there’s the aspect of generation and responding to the user in a way that’s natural and conversational. The ultimate goal of natural language generation (NLG) is to teach models to turn structured data into natural language, which we can then use to respond to the user in a conversation. Admittedly, you can create personas and write excellent conversation to make your assistant sound naturally conversational. But that may require writing a lot of stories and rules. While rules are great, stable and predictable, they require a lot of engineering and can be hard to scale and maintain. They also lack the spontaneity and creativity that you find in human conversation. By training a large-scale unsupervised language model with data and examples of the language it needs to generate, the model eventually forms its own rules about what it’s supposed to do and has more free rein to be creative. I tweaked an existing transfer learning based language model to generate small talk and chitchat. With more examples and data, this model can generate natural language to summarize text and answer questions without any specific task training. In the example above, notice how Coop continually guides the user back onto a happy path when they engage in chitchat. The dialogue models learns to handle narrow and broad context, and ignore superfluous information. Writing good conversation is critical to conversational AI. Before you launch your contextual assistant to the outside world, you want to invest in writing clear and succinct copy that has the right tone of voice, relevant and contextual vernacular, and persona that resonates with your audience, in addition to having highly performant NLG. Good conversation can delight users, build brand loyalty and ensure high user retention. You also want to think about providing menu buttons and quick replies for the user to tap and trigger certain events in an effort to minimize user input. They’re a great way to suggest options and nudge the user onto a happy path. Writing copy for conversational AI is something that deserves focused attention and is beyond the scope of this article. Read more about writing bot copy here. Coop doesn’t have a lot of conversation or UI options at the moment but as we gather real data, we’ll attempt to understand user behavior, further tweak our custom NLG model as it interacts with real users, focus on writing good copy and make continuous improvements over the next several iterations. In the final part of this series, we’ll talk about various testing strategies that can be used to test and evaluate our models. We’ll also talk about deploying Coop to production, after which we’ll monitor and make continuous improvements.
[ { "code": null, "e": 570, "s": 172, "text": "In the first part of this series, we introduced the different maturity levels of conversational AI and started building a travel assistant using Rasa. In this post, we’ll look at structuring happy and unhappy conversation paths, various machine learning policies and configurations to improve your dialogue model, and use a transfer learning based language model to generate natural conversations." }, { "code": null, "e": 705, "s": 570, "text": "Rasa recently released version 1.0 in which they combined Core and NLU into a single package. We’ll be using Rasa 1.0 in this article." }, { "code": null, "e": 1402, "s": 705, "text": "Since the primary purpose of the assistant, let’s name it Coop, is to book awesome vacations, Coop requires key pieces of information from the user in order to do so. For the purpose of this article, let’s assume Coop only needs the number of people, the holiday destination, and the start and end dates of said vacation. In the next iteration, we want to extract more information from the user with regards to their interests, budget, age, itinerary restrictions, and anything else we need to create curated travel experiences for them. Armed with this initial set of knowledge, let’s take a look at how we can enable Coop to gather this information through a natural conversation with the user." }, { "code": null, "e": 1854, "s": 1402, "text": "Rasa uses slots to hold user provided information, among other things. Slots, which are essentially key-value pairs, can be used to influence conversations with a user. The value of a slot can be set in several ways — through NLU, interactive cards, and actions. Rasa defines this as slot filling. Slots are defined in the “domain.yml” file. Each slot is given a name, type, and an optional initial value. Here’s a snippet from Coop’s domain.yml file:" }, { "code": null, "e": 2001, "s": 1854, "text": "...slots: enddate: type: unfeaturized location: type: unfeaturized num_people: type: unfeaturized startdate: type: unfeaturized..." }, { "code": null, "e": 2128, "s": 2001, "text": "Note that we set the type as “unfeaturized” for each slot as we don’t want the slot values to influence our conversation flow." }, { "code": null, "e": 2615, "s": 2128, "text": "In order to perform actions on behalf of the user, like we’re trying to do with Coop, we need to fill multiple consecutive slots or key pieces of information. We can do with using FormAction. A FormAction is essentially a python class. It takes a list of slots that need to be filled or questions that need to answered, and asks the user for said information in order to fill each slot. Note that the FormAction only asks the user for information to fill slots that are not already set." }, { "code": null, "e": 2873, "s": 2615, "text": "Let’s take a look at a happy path. A happy path is where the contextual assistant is able to gather the information it needs from the user without interruption. In other words, the user answers the questions without deviating from their path as shown below." }, { "code": null, "e": 3001, "s": 2873, "text": "In order to enable the FormAction mechanism, you want to add the “FormPolicy” to your config file typically named “config.yml”:" }, { "code": null, "e": 3037, "s": 3001, "text": "...policies: - name: FormPolicy..." }, { "code": null, "e": 3079, "s": 3037, "text": "Next, let’s define our custom form class:" }, { "code": null, "e": 3752, "s": 3079, "text": "class BookingForm(FormAction): def name(self): # type: () -> Text \"\"\"Unique identifier of the form\"\"\" return \"booking_form\" @staticmethod def required_slots(tracker: Tracker) -> List[Text]: \"\"\"A list of required slots that the form has to fill\"\"\" return [\"num_people\", \"location\", \"startdate\", \"enddate\"] def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: \"\"\"Define what the form has to do after all required slots are filled\"\"\" dispatcher.utter_template('utter_send_email', tracker) return []" }, { "code": null, "e": 3910, "s": 3752, "text": "As can be seen from the snippet above, our custom form class should define three methods — name, required_slots and submit. The methods are self explanatory." }, { "code": null, "e": 4036, "s": 3910, "text": "Now let’s tell our model to invoke the booking form action. Open your stories.md file and add one or more happy path stories:" }, { "code": null, "e": 4137, "s": 4036, "text": "...* request_vacation - booking_form - form{\"name\": \"booking_form\"} - form{\"name\": null}..." }, { "code": null, "e": 4946, "s": 4137, "text": "We’ve defined several interesting slots in Coop. The “location” slot is used to hold information about the user’s vacation destination. We’ve also defined an entity with the same name. Rasa NLU will fill the “location” slot when it identifies the “location” entity in the user’s message. In order for it to be able to do so, we need to train the NLU to extract the location entity. While this is pretty exciting, training the NLU model to identity generic entities like location is a time consuming process that requires a lot of data. This is where the out-of-the-box “SpacyEntityExtractor” component of the Rasa NLU pipeline comes to our rescue. This pretrained component is a named-entity recognizer that identifies various common entities (called dimensions) like person, organization, cities and states." }, { "code": null, "e": 5131, "s": 4946, "text": "Let’s take a look at how we can hook into this component to fill our location slot. We begin by adding “SpacyEntityExtractor” component to our NLU pipeline. Edit the “config.yml” file." }, { "code": null, "e": 5214, "s": 5131, "text": "language: enpipeline:...- name: \"SpacyEntityExtractor\" dimensions: [\"GPE\", \"LOC\"]" }, { "code": null, "e": 5453, "s": 5214, "text": "Rasa offers a method called “slot_mappings” in the FormAction class that can be used to further configure the way slots are filled. In our case, we can use this method to ensure that the “location” slot gets filled in the following order:" }, { "code": null, "e": 5661, "s": 5453, "text": "Use the “location” entity identified by our NLU modelIf step 1 fails, use the “GPE” dimension identified by “SpacyEntityExtractor”If step 2 fails, use the “LOC” dimension identified by “SpacyEntityExtractor”" }, { "code": null, "e": 5715, "s": 5661, "text": "Use the “location” entity identified by our NLU model" }, { "code": null, "e": 5793, "s": 5715, "text": "If step 1 fails, use the “GPE” dimension identified by “SpacyEntityExtractor”" }, { "code": null, "e": 5871, "s": 5793, "text": "If step 2 fails, use the “LOC” dimension identified by “SpacyEntityExtractor”" }, { "code": null, "e": 6338, "s": 5871, "text": "def slot_mappings(self): # type: () -> Dict[Text: Union[Dict, List[Dict]]] \"\"\"A dictionary to map required slots to - an extracted entity - intent: value pairs - a whole message or a list of them, where a first match will be picked\"\"\" return {\"location\": [self.from_entity(entity=\"location\"), self.from_entity(entity=\"GPE\"), self.from_entity(entity=\"LOC\")]}" }, { "code": null, "e": 6393, "s": 6338, "text": "You can read more about the predefined functions here." }, { "code": null, "e": 7041, "s": 6393, "text": "The other interesting slots in Coop’s domain are “startdate” and “enddate”. As the names suggest, these slots represent the user’s choice for their vacation start and end dates. Instead of training our NLU model to identify and extract this data and potentially solve for entity disambiguation along the way, we can use the “DucklingHTTPExtractor” component. This pretrained component is a named-entity recognizer that identifies various common entities like time, distance, and numbers. Similar to how we configured the “SpacyEntityExtractor”, the “DucklingHTTPExtractor” component should be added to our NLU pipeline. Edit the “config.yml” file." }, { "code": null, "e": 7188, "s": 7041, "text": "language: enpipeline:...- name: \"DucklingHTTPExtractor\" url: http://localhost:8000 dimensions: [\"time\", \"number\", \"amount-of-money\", \"distance\"]" }, { "code": null, "e": 7353, "s": 7188, "text": "As seen from the config above, the “DucklingHTTPExtractor” is expected to be running at the specified host and port. You can use docker to run the duckling service." }, { "code": null, "e": 7742, "s": 7353, "text": "Note that the FormAction class allows us to define custom validations that can be used to validate user-provided information. For example, we want to ensure that the start date is earlier than the end date. These validation methods should be named based on a convention. If you have a slot named “enddate”, you want to define a method named “validate_enddate” for it to be called by Rasa." }, { "code": null, "e": 8453, "s": 7742, "text": "def validate_enddate(self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> Optional[Text]: \"\"\"Ensure that the start date is before the end date.\"\"\" try: startdate = tracker.get_slot(\"startdate\") startdate_obj = dateutil.parser.parse(startdate) enddate_obj = dateutil.parser.parse(value) if startdate_obj < enddate_obj: return value else: dispatcher.utter_template('utter_invalid_date', tracker) # validation failed, set slot to None return None except: print(\"log error\") return None" }, { "code": null, "e": 9228, "s": 8453, "text": "FormActions are really useful to gather information from a user and perform actions on behalf of a user. But, as you know, user behavior can be unpredictable, and conversation is messy. There are 30,000 different ways you can ask about the weather; one of my favorite ways is when people say “is it going to be raining cats and dogs today?” Users rarely provide the information required without digressing, engaging in chitchat, changing their minds, correcting their answers, asking follow up questions and so forth — all of which are valid, expected, and need to be handled if you’re building powerful conversational AI. These deviations are known as unhappy paths. I highly recommend using interactive learning through the CLI to train your model to handle unhappy paths." }, { "code": null, "e": 9280, "s": 9228, "text": "Here’s the command to run Rasa in interactive mode:" }, { "code": null, "e": 9323, "s": 9280, "text": "rasa interactive --endpoints endpoints.yml" }, { "code": null, "e": 9441, "s": 9323, "text": "Once you’re done, you can save the training data and retrain your models. Here’s an example of an unhappy path story." }, { "code": null, "e": 9929, "s": 9441, "text": "* request_vacation - booking_form - form{\"name\": \"booking_form\"} - slot{\"requested_slot\": \"num_people\"}...* form: inform{\"location\": \"paris\", \"GPE\": \"Paris\"} - slot{\"location\": \"paris\"} - form: booking_form - slot{\"location\": \"paris\"} - slot{\"requested_slot\": \"startdate\"}* correct{\"num_people\": \"2\"} - slot{\"num_people\": \"2\"} - action_correct - booking_form - slot{\"requested_slot\": \"startdate\"}* form: inform{\"time\": \"2019-07-04T00:00:00.000-07:00\"}..." }, { "code": null, "e": 10286, "s": 9929, "text": "Rasa provides multiple policies that can be used to configure and train its Core dialogue management system. The “Embedding” policy, also known as Recurrent Embedding Dialogue Policy (REDP), can be used to efficiently handle unhappy paths. In addition, it provides hyperparameters that can be used to fine tune the model. You can read more about REDP here." }, { "code": null, "e": 10324, "s": 10286, "text": "I used the embedding policy for Coop." }, { "code": null, "e": 10404, "s": 10324, "text": "...policies: - name: EmbeddingPolicy epochs: 2000 attn_shift_range: 5..." }, { "code": null, "e": 10747, "s": 10404, "text": "Now, let’s take a look at an unhappy path that involves correction and explanation. A correction is when a user issues a revision to their previous answer or statement. For instance, if they got their phone number wrong and wished to correct it. A user issues an explanation when they want to know the reason behind the assistant’s questions." }, { "code": null, "e": 11000, "s": 10747, "text": "In the example above, notice how Coop guides the conversation back to the topic at hand. The dialogue model learns to handle corrections and provide explanation for why it needs certain information, essentially bringing the user back onto a happy path." }, { "code": null, "e": 11507, "s": 11000, "text": "There are two significant areas of natural language processing (NLP) that come into play with conversational AI. First, there’s the aspect of trying to understand what the user says; what is the user’s intent? Second, there’s the aspect of generation and responding to the user in a way that’s natural and conversational. The ultimate goal of natural language generation (NLG) is to teach models to turn structured data into natural language, which we can then use to respond to the user in a conversation." }, { "code": null, "e": 11891, "s": 11507, "text": "Admittedly, you can create personas and write excellent conversation to make your assistant sound naturally conversational. But that may require writing a lot of stories and rules. While rules are great, stable and predictable, they require a lot of engineering and can be hard to scale and maintain. They also lack the spontaneity and creativity that you find in human conversation." }, { "code": null, "e": 12360, "s": 11891, "text": "By training a large-scale unsupervised language model with data and examples of the language it needs to generate, the model eventually forms its own rules about what it’s supposed to do and has more free rein to be creative. I tweaked an existing transfer learning based language model to generate small talk and chitchat. With more examples and data, this model can generate natural language to summarize text and answer questions without any specific task training." }, { "code": null, "e": 12578, "s": 12360, "text": "In the example above, notice how Coop continually guides the user back onto a happy path when they engage in chitchat. The dialogue models learns to handle narrow and broad context, and ignore superfluous information." }, { "code": null, "e": 13240, "s": 12578, "text": "Writing good conversation is critical to conversational AI. Before you launch your contextual assistant to the outside world, you want to invest in writing clear and succinct copy that has the right tone of voice, relevant and contextual vernacular, and persona that resonates with your audience, in addition to having highly performant NLG. Good conversation can delight users, build brand loyalty and ensure high user retention. You also want to think about providing menu buttons and quick replies for the user to tap and trigger certain events in an effort to minimize user input. They’re a great way to suggest options and nudge the user onto a happy path." }, { "code": null, "e": 13701, "s": 13240, "text": "Writing copy for conversational AI is something that deserves focused attention and is beyond the scope of this article. Read more about writing bot copy here. Coop doesn’t have a lot of conversation or UI options at the moment but as we gather real data, we’ll attempt to understand user behavior, further tweak our custom NLG model as it interacts with real users, focus on writing good copy and make continuous improvements over the next several iterations." } ]
How to use replaceAll () in Android textview?
This example demonstrate about How to use replaceAll () in Android textview. 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"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter name" android:layout_height="wrap_content" /> <Button android:id="@+id/click" android:text="Click" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:textSize="25sp" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken name as Edit text, when user click on button it will take data and replace space with emptystring. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText name; Button button; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.name); button = findViewById(R.id.click); text = findViewById(R.id.textview); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { if (name.getText().toString().length() >= 0) { String replace = name.getText().toString().replaceAll("\\s",""); text.setText(String.valueOf(replace)); } } else { name.setError("Plz enter name"); } } }); } } 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 − In the above result, enter the string as “Krishna sai sai” . It replaced all space with empty string value. Click here to download the project code
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrate about How to use replaceAll () in Android textview." }, { "code": null, "e": 1268, "s": 1139, "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": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2223, "s": 1333, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2355, "s": 2223, "text": "In the above code, we have taken name as Edit text, when user click on button it will take data and replace space with emptystring." }, { "code": null, "e": 2412, "s": 2355, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3536, "s": 2412, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n String replace = name.getText().toString().replaceAll(\"\\\\s\",\"\");\n text.setText(String.valueOf(replace));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 3883, "s": 3536, "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 −" }, { "code": null, "e": 3991, "s": 3883, "text": "In the above result, enter the string as “Krishna sai sai” . It replaced all space with empty string value." }, { "code": null, "e": 4031, "s": 3991, "text": "Click here to download the project code" } ]
Program to find minimum absolute sum difference in Python
Suppose we have two positive valued arrays nums1 and nums2, of same size. The absolute sum difference of these two arrays is the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). Now, we can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. We have to find the minimum absolute sum difference after replacing at most one element in the array nums1. The answer may be very large so return it modulo 10^9 + 7. So, if the input is like nums1 = [2,8,6], nums2 = [3,4,6], then the output will be 3 because, we can find two possible optimal solutions Replace the element at index 1 with the element at index 0: [2,8,6] => [2,2,6], or Replace the element at index 1 with the element at index 0: [2,8,6] => [2,2,6], or Replace the element at index 1 with the element at index 2: [2,8,6] => [2,6,6]. Replace the element at index 1 with the element at index 2: [2,8,6] => [2,6,6]. Both of them get a sum difference of |2-3| + (|2-4| or |6-4|) + |6-6| = 3. To solve this, we will follow these steps − if nums1 is same as nums2, thenreturn(0) if nums1 is same as nums2, then return(0) return(0) minn_diff := -infinity minn_diff := -infinity ind := -1 ind := -1 for i in range 0 to size of nums1 - 1, doif |nums1[i]-nums2[i]| > minn_diff, thenind := iminn_diff := |nums1[i] - nums2[i]| for i in range 0 to size of nums1 - 1, do if |nums1[i]-nums2[i]| > minn_diff, thenind := iminn_diff := |nums1[i] - nums2[i]| if |nums1[i]-nums2[i]| > minn_diff, then ind := i ind := i minn_diff := |nums1[i] - nums2[i]| minn_diff := |nums1[i] - nums2[i]| diff := |nums1[ind] - nums2[ind]| diff := |nums1[ind] - nums2[ind]| index := ind index := ind for i in range 0 to size of nums1 - 1, doif i is not same as ind, thenif |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]| for i in range 0 to size of nums1 - 1, do if i is not same as ind, thenif |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]| if i is not same as ind, then if |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]| if |nums1[i] - nums2[ind]| < diff, then index := i index := i diff := |nums1[i]-nums2[ind]| diff := |nums1[i]-nums2[ind]| summ := 0 summ := 0 for i in range 0 to size of nums1 - 1, doif i is same as ind, thensumm := summ + |nums1[index] - nums2[i]|otherwise,summ := summ + |nums1[i] - nums2[i]| for i in range 0 to size of nums1 - 1, do if i is same as ind, thensumm := summ + |nums1[index] - nums2[i]| if i is same as ind, then summ := summ + |nums1[index] - nums2[i]| summ := summ + |nums1[index] - nums2[i]| otherwise,summ := summ + |nums1[i] - nums2[i]| otherwise, summ := summ + |nums1[i] - nums2[i]| summ := summ + |nums1[i] - nums2[i]| return summ mod (10^9 + 7) return summ mod (10^9 + 7) Let us see the following implementation to get better understanding − def solve(nums1, nums2): if(nums1==nums2): return(0) minn_diff = float('-inf') ind = -1 for i in range(len(nums1)): if(abs(nums1[i]-nums2[i]) > minn_diff): ind = i minn_diff = abs(nums1[i]-nums2[i]) diff = abs(nums1[ind]-nums2[ind]) index = ind for i in range(len(nums1)): if(i!=ind): if(abs(nums1[i]-nums2[ind])<diff): index = i diff = abs(nums1[i]-nums2[ind]) summ = 0 for i in range(len(nums1)): if(i==ind): summ += abs(nums1[index]-nums2[i]) else: summ += abs(nums1[i]-nums2[i]) return(summ%(10**9 + 7)) nums1 = [2,8,6] nums2 = [3,4,6] print(solve(nums1, nums2)) [2,8,6], [3,4,6] 3
[ { "code": null, "e": 1542, "s": 1062, "text": "Suppose we have two positive valued arrays nums1 and nums2, of same size. The absolute sum\ndifference of these two arrays is the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). Now, we can replace at most one element of nums1 with any other element in nums1\nto minimize the absolute sum difference. We have to find the minimum absolute sum\ndifference after replacing at most one element in the array nums1. The answer may be very\nlarge so return it modulo 10^9 + 7." }, { "code": null, "e": 1679, "s": 1542, "text": "So, if the input is like nums1 = [2,8,6], nums2 = [3,4,6], then the output will be 3 because, we can find two possible optimal solutions" }, { "code": null, "e": 1762, "s": 1679, "text": "Replace the element at index 1 with the element at index 0: [2,8,6] => [2,2,6], or" }, { "code": null, "e": 1845, "s": 1762, "text": "Replace the element at index 1 with the element at index 0: [2,8,6] => [2,2,6], or" }, { "code": null, "e": 1925, "s": 1845, "text": "Replace the element at index 1 with the element at index 2: [2,8,6] => [2,6,6]." }, { "code": null, "e": 2005, "s": 1925, "text": "Replace the element at index 1 with the element at index 2: [2,8,6] => [2,6,6]." }, { "code": null, "e": 2080, "s": 2005, "text": "Both of them get a sum difference of |2-3| + (|2-4| or |6-4|) + |6-6| = 3." }, { "code": null, "e": 2124, "s": 2080, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2165, "s": 2124, "text": "if nums1 is same as nums2, thenreturn(0)" }, { "code": null, "e": 2197, "s": 2165, "text": "if nums1 is same as nums2, then" }, { "code": null, "e": 2207, "s": 2197, "text": "return(0)" }, { "code": null, "e": 2217, "s": 2207, "text": "return(0)" }, { "code": null, "e": 2240, "s": 2217, "text": "minn_diff := -infinity" }, { "code": null, "e": 2263, "s": 2240, "text": "minn_diff := -infinity" }, { "code": null, "e": 2273, "s": 2263, "text": "ind := -1" }, { "code": null, "e": 2283, "s": 2273, "text": "ind := -1" }, { "code": null, "e": 2407, "s": 2283, "text": "for i in range 0 to size of nums1 - 1, doif |nums1[i]-nums2[i]| > minn_diff, thenind := iminn_diff := |nums1[i] - nums2[i]|" }, { "code": null, "e": 2449, "s": 2407, "text": "for i in range 0 to size of nums1 - 1, do" }, { "code": null, "e": 2532, "s": 2449, "text": "if |nums1[i]-nums2[i]| > minn_diff, thenind := iminn_diff := |nums1[i] - nums2[i]|" }, { "code": null, "e": 2573, "s": 2532, "text": "if |nums1[i]-nums2[i]| > minn_diff, then" }, { "code": null, "e": 2582, "s": 2573, "text": "ind := i" }, { "code": null, "e": 2591, "s": 2582, "text": "ind := i" }, { "code": null, "e": 2626, "s": 2591, "text": "minn_diff := |nums1[i] - nums2[i]|" }, { "code": null, "e": 2661, "s": 2626, "text": "minn_diff := |nums1[i] - nums2[i]|" }, { "code": null, "e": 2695, "s": 2661, "text": "diff := |nums1[ind] - nums2[ind]|" }, { "code": null, "e": 2729, "s": 2695, "text": "diff := |nums1[ind] - nums2[ind]|" }, { "code": null, "e": 2742, "s": 2729, "text": "index := ind" }, { "code": null, "e": 2755, "s": 2742, "text": "index := ind" }, { "code": null, "e": 2904, "s": 2755, "text": "for i in range 0 to size of nums1 - 1, doif i is not same as ind, thenif |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]|" }, { "code": null, "e": 2946, "s": 2904, "text": "for i in range 0 to size of nums1 - 1, do" }, { "code": null, "e": 3054, "s": 2946, "text": "if i is not same as ind, thenif |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]|" }, { "code": null, "e": 3084, "s": 3054, "text": "if i is not same as ind, then" }, { "code": null, "e": 3163, "s": 3084, "text": "if |nums1[i] - nums2[ind]| < diff, thenindex := idiff := |nums1[i]-nums2[ind]|" }, { "code": null, "e": 3203, "s": 3163, "text": "if |nums1[i] - nums2[ind]| < diff, then" }, { "code": null, "e": 3214, "s": 3203, "text": "index := i" }, { "code": null, "e": 3225, "s": 3214, "text": "index := i" }, { "code": null, "e": 3255, "s": 3225, "text": "diff := |nums1[i]-nums2[ind]|" }, { "code": null, "e": 3285, "s": 3255, "text": "diff := |nums1[i]-nums2[ind]|" }, { "code": null, "e": 3295, "s": 3285, "text": "summ := 0" }, { "code": null, "e": 3305, "s": 3295, "text": "summ := 0" }, { "code": null, "e": 3458, "s": 3305, "text": "for i in range 0 to size of nums1 - 1, doif i is same as ind, thensumm := summ + |nums1[index] - nums2[i]|otherwise,summ := summ + |nums1[i] - nums2[i]|" }, { "code": null, "e": 3500, "s": 3458, "text": "for i in range 0 to size of nums1 - 1, do" }, { "code": null, "e": 3566, "s": 3500, "text": "if i is same as ind, thensumm := summ + |nums1[index] - nums2[i]|" }, { "code": null, "e": 3592, "s": 3566, "text": "if i is same as ind, then" }, { "code": null, "e": 3633, "s": 3592, "text": "summ := summ + |nums1[index] - nums2[i]|" }, { "code": null, "e": 3674, "s": 3633, "text": "summ := summ + |nums1[index] - nums2[i]|" }, { "code": null, "e": 3721, "s": 3674, "text": "otherwise,summ := summ + |nums1[i] - nums2[i]|" }, { "code": null, "e": 3732, "s": 3721, "text": "otherwise," }, { "code": null, "e": 3769, "s": 3732, "text": "summ := summ + |nums1[i] - nums2[i]|" }, { "code": null, "e": 3806, "s": 3769, "text": "summ := summ + |nums1[i] - nums2[i]|" }, { "code": null, "e": 3833, "s": 3806, "text": "return summ mod (10^9 + 7)" }, { "code": null, "e": 3860, "s": 3833, "text": "return summ mod (10^9 + 7)" }, { "code": null, "e": 3930, "s": 3860, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 4635, "s": 3930, "text": "def solve(nums1, nums2):\n if(nums1==nums2):\n return(0)\n\n minn_diff = float('-inf')\n ind = -1\n for i in range(len(nums1)):\n if(abs(nums1[i]-nums2[i]) > minn_diff):\n ind = i\n minn_diff = abs(nums1[i]-nums2[i])\n \n diff = abs(nums1[ind]-nums2[ind])\n index = ind\n for i in range(len(nums1)):\n if(i!=ind):\n if(abs(nums1[i]-nums2[ind])<diff):\n index = i\n diff = abs(nums1[i]-nums2[ind])\n\n summ = 0\n for i in range(len(nums1)):\n if(i==ind):\n summ += abs(nums1[index]-nums2[i])\n else:\n summ += abs(nums1[i]-nums2[i])\n return(summ%(10**9 + 7))\n\nnums1 = [2,8,6]\nnums2 = [3,4,6]\nprint(solve(nums1, nums2))\n\n" }, { "code": null, "e": 4652, "s": 4635, "text": "[2,8,6], [3,4,6]" }, { "code": null, "e": 4655, "s": 4652, "text": "3\n" } ]
SAP Webi - Quick Guide
Web Intelligence is part of SAP BusinessObjects product suite and is used for analytical and ad hoc reporting to meet an organization’s business requirements. Web Intelligence is a Business Intelligence reporting tool for business users to analyze data in Data Warehouse. It assists business managers in the decision-making process for building future strategies. Using Web Intelligence, business users can create basic, medium, and complex reports from transactional data in database and by creating Universes using Information Design Tool/UDT. Various SAP and non-SAP data sources can be used to create reports in Web Intelligence. SAP Business Warehouse (BW) system doesn’t require a Universe to connect to Web Intelligence tool. Web Intelligence tool can work as a client tool of BusinessObjects platform and also as a standalone tool for reporting. BusinessObjects was first started in 1990 with the tool name Skipper SQL 2.x, and in the year 1994 Business Objects v3.0 was launched. In 2005, BO XI was released and later on various other versions introduced. Some of the versions are − BO XI R1 BO XI R2 BO XI R3 BO XI R3.1 BO XI R3.2 In 2007, SAP acquired this company for $6.8 billion and the product has been renamed as SAP BusinessObjects. Later in the year 2011, BO XI 4.0 was introduced. The latest version of the tool is SAP BO 4.2. SAP Webi has a three-layered architecture − Database Layer − This layer defines multiple SAP and non-SAP data sources. Database Layer − This layer defines multiple SAP and non-SAP data sources. Semantic Layer − This layer defines multidimensional data model. Semantic Layer − This layer defines multidimensional data model. Presentation Layer − This layer defines where data is presented to end-users. Presentation Layer − This layer defines where data is presented to end-users. Various data sources can be used to create analytical and ad hoc reports. You can pull data from SAP systems, like SAP ECC, SAP ERP, SAP SRM, and other SAP modules. Non-SAP data sources include Oracle Database, Microsoft SQL Server, IBM DB2, and Sybase. BI Launchpad is a Java or HTML based interface of BusinessObjects tool to perform analytical reporting and data analysis. You can set the preference for your BI Launchpad that determines which tool interface is launched via Launchpad. Using Web or Internet Application to access Webi interface via BI Launchpad, you can perform the following tasks − Create, edit and refresh all the reports in Web Intelligence. Create, edit and refresh all the reports in Web Intelligence. Create and edit all the queries in no data source (Universes) but not BEx queries in Web application. Create and edit all the queries in no data source (Universes) but not BEx queries in Web application. Note − If you are using Webi 4.0 SP2, it is not possible to create queries and you can only work on documents and reports. BI Launchpad has the following important tabs − Home − Displays recent messages, alerts, documents, and applications that can be run. Home − Displays recent messages, alerts, documents, and applications that can be run. Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents. Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents. Any open Document − Displays each open document. Any open Document − Displays each open document. You can use the Application tab to start an application including Web Intelligence. You can use the Preference tab to define BI Launchpad preferences. As mentioned, BI Launchpad is HTML5 or Java-based web interface to launch an application via BI Launchpad. To access BI Launchpad, you should have a web URL, user name and password. Access profile to be set for the resources. To get the BI Launchpad details and user credentials you can reach the BO Administrator using the link, http://BOSERVER:8080/BOE/BI To login to BI Launchpad, open the web browser and enter the Launchpad URL provided by your administrator. The following screen pops up. Select the system name you want to login. Enter the user name and password. In the Authentication dropdown, select the Authentication type - Enterprise, Windows AD, etc. (In the above snapshot, this server has a single login). Click ‘Log On’ and it will open the home page for BI Launchpad. You can use Applications tab of Launchpad to run any of the application. Let us now discuss how to set BI preferences. You can set BI Launchpad preferences for the following tasks. General Preferences − These are defined by the administrator. You can reset your password. You can also set time zone, locales preferences, and Web Intelligence preferences. General Tab − Using this tab you can set user default settings. Change Password − As per your user access. Locales and Time Zone − To set product locale, preferred viewing locale, current time zone. Analysis Edition for OLAP − To define accessibility mode. Web Intelligence − You can select the interfaces to use for view and modify modes. You can also select a Default Universe. You can set the drill options. You can also select saving priorities when saving a report in .xls format. BI Workspaces − Used to select a default stylesheet to use when creating a new workspace. Crystal Reports − Used to set crystal reports options like printing options, default measuring unit, etc. There are three different application modes that can be used to build the queries, create documents and to analyze the reports. When you open an existing report, the following modes are available − Data Reading Design In this mode, you can create new data provider, change an existing data source or rename a data provider. You can also create, edit, and manage queries, which is used to pass data to reports. In Data mode, it shows the list of all the available data providers. All the options in tool mode are disabled in this mode. This mode allows you to display existing reports, search text, monitor changes in the reports, and drill down on the data in the report. You can also use the left panel and tool bar in the Reading mode. Design mode allows you to add, delete objects in a report, applying conditional formatting, applying formulas in report, creating variables, etc. Design mode with Structure only allows you to view the structure of the report. All the changes that you make in this mode, they are not applied to the server till you populate it with data. In Design mode with data, all the modifications applied in a report are on the server. In case you have to make a lot of changes in an existing report, it is recommended to make changes in structure mode and then populate the report with data. In this chapter, we will learn how to create Webi documents. When you open Web interface via BI Launchpad or open Webi rich client, you have an option to create a new document or edit an existing one. You can create a new document as blank document or use an interface to create a document based on the following data sources − Universe Flat files in .csv or .xls format BEx queries Analysis view Rich Internet application interface and Webi rich client allows you to use from list of available data sources; however, Web Interface supports only no data source or Universe from IDT/UDT. To create a blank document to use later − Launch Webi Rich Client → Click ‘New document’ option at the top → No Data Source → Ok. Or you can select a blank document by clicking the icon below the list of available data sources. You can also use other data sources like Universe, BW BEx query, and text sources like CSV and XLS files, Analysis view or a web service as data source to create a new document. You can create a Webi document based on Universe using Information Design Tool/Universe Design Tool. .unx − File created with Information Design Tool .unx − File created with Information Design Tool .unv − File created in Universe Design Tool .unv − File created in Universe Design Tool To use a Universe as data source, go to New → Select a Universe as data source and click Ok. It will open a list of all Universes published to BI repository to use in a document. You can select any available universe and click ‘Select’. It will show you all .unx and .unv files available to use in a document. Query Panel will be open. You can select from list of available objects as per your access permissions. You may not be able to use a few of the objects because of permission issues. In query panel, you have Universe outline in the left pane, and result objects, query filters, data preview panels in the main pane. To use BEx as data source, go to New → Select BW BEx query as data source and click ‘Ok’. It will show you a list of all available BEx queries. You can select only those which you have permission to access. On the left side of the screen, it shows you the name of Info provider for BEx query. It will open the Query panel, you can select the list of available objects from Universe Outline and name of BEx query below that. Click New icon → Select Universe → Ok. Select the Analysis view you want to use and click Ok. It will open the Query panel with a list of available objects. You can edit an existing document via BI Launchpad → Web Interface or by opening a document in Webi Rich Client. You can also open recent documents using Webi Rich client directly. Launch Webi rich client and you will get a list of recent open documents on the left side of the screen. You can also select an existing report to edit in Webi. Extension of a Webi File is “.wid.”. To open an existing document, select a blank document. Go to File → Open. Select the path of an existing ‘wid’ file and click ‘Open’. By default, it will open the report in Design mode. To open a document, go to Webi rich client → Click ‘Open’ tab. Navigate through the folder you want to open, select the file and click ‘Open’. This will open the file in Design mode. You can select design and read mode as per your access rights. In this chapter, we will get acquainted with the various ways of sending a document. Open the document in Webi Rich client → Click ‘Send by e-mail attachment’ You have an option to select the different attachment formats like PDF, XLS, CSV, Text, and/or unsecured wid. To send a document to other users/groups, open the document via BI Launchpad. Click ‘Send’ on toolbar → Send to User. Select the users/groups to which you want to send the document to from the list of users and groups. You can select ‘automatically generated’ to send the document with an auto generated name. Select the specific name and enter the name you want to send the document. You can also select “shortcut” to send a shortcut or “Copy” option to send a copy of the document. To send a document via ftp, login to BI Launchpad. You have to save the document first. Click ‘Save’ icon at the top of the screen to save the document. Click ‘Mail’ icon in the tool bar → Select ‘Send to Ftp’. You have to enter the host name, port number, user name and password. Select the naming method for document to send. Click ‘Send’. Webi documents contain at least one or more reports. You can manage multiple reports in a single Webi document. You can also add, delete, rename, and move existing reports in one Webi document. To add, delete, or move a report in a Webi document, right-click on the Report tab. To add a report, right-click on the existing report tab and click ‘Add Report’. To delete a report, right-click on the report tab and click ‘Delete’. Each Webi document should have at least one report. You can use “Rename Report” option to rename an existing report. To save a document in Webi, you have options to save a report locally, save in BI repository, or export as CSV format. To do this, go to File tab and choose from the options Save/Save As/Save as Enterprise. If you open a Webi document, you can click ‘Save’ to keep the changes. ‘Save as’ option is used to save a document in different formats such as − WID PDF Excel Excel 2007 CSV Achieve TXT File When you use the ‘Save as’ option, on the right side of the screen you get many options – Refresh on open, Permanent Regional formatting, Save for all users, Remove document Security. You can enter the report name, change an existing report name and also add a description. Queries in Webi are managed in the Query panel. When you create a Webi report, you use queries in the query panel to get data from the data source. Queries can be created from different interfaces like you can create queries based on Universe, represent data in OLAP database as objects, flat files like Excel and CSV files, data in SAP InfoCubes using BEx queries, Analysis view or Query as a web service. Each query has dimensions and measures. Measures always return numeric data based on the calculation and other objects in the data source. Queries can be hierarchical or non-hierarchical in nature. Non-hierarchical queries have no relationship between the objects. Hierarchies define relationship between the objects. For example: In a Geographical hierarchy, you have measures based on geographical hierarchies like counties, states and cities. Using hierarchies, you can drill up and down to see data at the next level. Query panel is not available, if you use Web Interface of Webi tool. In a Webi document, you retrieve data in report from the data source using the query panel. All the queries are built in the query panel and interface of query panel depends on the data source you are using to get data. Queries can be created on Universe, which contains Relational and OLAP data models, data from flat files like CVS, XLS files, SAP BW BEx query, and Analysis view. Query is run to get data from the data source. You can apply filters and also preview data in the query panel. To open a Query Panel − Go to Web Intelligence → New → Select Data Source → Ok. When you click ‘Ok’, you have to select data source from the list of selected data source type. New window will open known as Query Panel. Select the objects from Universe outline, which you want to add to the report in result objects. To add a filter, select the object in Query filters by dragging an object and select a value. For data preview, click ‘Refresh’ tab. To add this query to the report, click ‘Run Query’ option at the top of the screen to add to Webi document. You can view multiple objects in the Query panel and create, edit, and delete objects in queries as per login user access rights. Users are normally created by BusinessObjects Administrator. CMC is used to create user profiles to login to BO tools. If you don’t have enough access rights, you will not be able to access few objects of a report. Access rights are defined by the BO administrator. Classes are used to group similar objects in a report. A class can contain one or more subclasses. Subclasses contains further subcategory of objects in the upper level of a class. Classes are used to organize objects in a logical manner. While creating queries on Universe, you can find the information on objects that you have to use in query. Dimension lists all the objects using which we want to analyze the data. Dimension provides the basis for analysis in a report. Dimension normally contains non-hierarchical character type data like customer name, product name, customer address, sales office address, etc. Common examples of Dimensions are - Product, Customer, Time, etc. Analysis Dimension − An analysis dimension contains group of hierarchies related to each other. When you add an analysis dimension in a report, its default hierarchy appears in query. − Analysis Dimension appears as this symbol in the query panel Attribute provides data about dimensions or hierarchy. For example − Home address of a customer dimension. Attribute has one-to-one relationship with corresponding dimension. Each customer has only one address object. − Attribute appears as this symbol in the query panel If your Universe is not designed correctly, an object returns the multiple values for a dimension and the corresponding cell in the report shows MULTIVALUE error. Measures are defined as numerical values in the report on which analysis is performed. They are integer values, which are used to compare the performance of an organization with defined KPI’s. For example − Sales in each region, total Revenue per year, profit per product, etc. − Measure appears as this symbol in the query panel A hierarchy represents parent-child relationship in Universe. It allows you to drill up or down in the report to the next level. For example − Geography hierarchy contains Country, State and City. Time hierarchy contains Year, Quarter, Month and Week. Using the member selector in defining hierarchy, you can define which member appears in the result set. In hierarchical data sources, hierarchies are associated with a dimension. Members are defined at different level of hierarchies in a data source. For example − Consider a Geography hierarchy containing members – “India” at the country level and “Haryana” at the State level. You can also include individual members in query from hierarchy, if you don’t want to add all the members. Named set can be used to define a set of members. A named set is defined as named expression and results a set of members. You can define named set at Universe level or a relational or OLAP database level. You can build queries in the Query panel using various data sources like Universe, BEx from SAP BW or an Analysis view. Universe contains data from OLAP and Relational data sources. Data in Universe can be a relational data or hierarchical data. Open Web Intelligence via BI Launchpad → New (Create a new Webi document). You will be prompted to select a Data Source. Select a Universe as data source and click ‘Ok’. You will get a list of all available Universe. Select a Universe, which you want to use to create a Webi document. A new window will open with the name Query Panel. In the query panel, on the left side of the screen, you have a list of available objects. You have Result Objects where you drag objects from the left panel, which you want to add in a Webi document. You have Query Filter using which you can add different filters. Data Preview can be used to view data before it is added to Webi document. Run query tab at the top of the screen is used to run the query. In the Query panel, you have an option using which you can add data from multiple sources in a single Webi document by creating multiple queries. To add a Query, go to Add query option at the top of the screen. You can select different data sources to add a second query. You can also edit the properties of Query, like the name of the query, number of records, etc. ‘View Script’ option allows you to check the script of the query. Following functions can be set using Query Properties − Retrieving duplicate rows Relational .unx, OLAP, but not available in BEx queries. Returning sample result sets Available in relational .unx, but not available in OLAP .unx or BEx queries. Retrieving/excluding empty rows Available in OLAP .unx only. Not available in BEx queries. In this case, you have an option to run multiple queries separately. You can go to Run queries and select the query you want to run. You can also combine queries using the Query Panel. You can create Webi documents based on BEx (Business Exchange Queries) created by BEx Query Designer, which is based on InfoCube in SAP BW system. You can connect to a BEx query in Webi with the use of BI Consumer Service (BICS) connection. You need not create Universe for BEx queries, and all attributes, hierarchies, dimensions and measures are automatically mapped in Webi document. You can edit, create, and refresh documents based on BEx using Web Intelligence Rich Internet Application Interface (Applet based) or Webi Rich Client. If you are using Webi DHTML web interface, you can only view or refresh a Webi document based on BEx but you cannot edit them. Following important points about BEx should be considered − You can only use BEx queries, which are flagged with “Allow External Access to the Query”. You can only use BEx queries, which are flagged with “Allow External Access to the Query”. To manage object mapping, refer to restriction and equivalent pages to ensure correct use of queries. To manage object mapping, refer to restriction and equivalent pages to ensure correct use of queries. Following metadata objects are supported from BEx in Webi − Hierarchies Characteristics Navigation Attributes Display Attributes Basic Key Figures Calculation figures and formulas Restricted Key figures Variables Customized Structure Open BEx Query Designer and select the query you want to use in BO tool. Go to Properties → Advanced tab and select Allow External access to Query. Save the query. You can create a BICS connection in CMC or also in Information Design Tool. A connection can be created to a single BEx query or to an Info Provider. Login to CMC console → Select OLAP connection from the dropdown list. Click on a New Connection → In Provider list, select SAP NetWeaver Business Warehouse. Similarly, you can define a BICS connection in IDT. Select an OLAP connection and choose SAP NetWeaver Business Warehouse → SAP BICS Client Middleware driver. Open Webi Rich Client → New Document. Click on select a BEx query as data source. In the new window, select BICS connection in the right pane and corresponding BEx query → Ok. All the objects from BEx will be added to Query Panel on the left side. You can drag the objects to Result Objects. Once you click on Run query, all the result objects will be added to a new Webi document as shown in the following snapshot. Analysis view is created in BI workspace. Analysis views with custom objects are not supported and it only supports Analysis view coming from SAP NetWeaver BW. Open Webi Rich Client → New Document → Select Analysis view as Data source. Select an Analysis View, and click ‘Ok’. To manage multiple queries, you have an option of Data at the top right corner. This option is not available in Webi DHTML interface. All the data providers appear in the list to the right side of the data pane. It also tells you the Data Source, Refresh date, Duration, status, etc. To see the details of data, double-click on the Query. It will open the details of data added in Query. To edit a query, right-click on query in Data mode. Select edit or you can also select an option of Edit in the tool menu. You can also Rename, Delete, Copy or Purge a query using this Data Manager option. Query filters are used to limit the rows returned in a Webi document. Query filters allow you to hide the data that you don’t want to show to specific people and also limit the size of .wid document. When you run a query, it only returns the rows that meet the query filter definition. Following are the key features used in Query filter − You can retrieve data as per specific business requirement. You can retrieve data as per specific business requirement. You can hide the data that you don’t want specific users to see in a Webi document. You can hide the data that you don’t want specific users to see in a Webi document. Limit the size of Webi document of the network and hence provides performance optimization. Limit the size of Webi document of the network and hence provides performance optimization. Example − Being an Area Sales Manager for NY, you want to see the margin values for your region. Sales universe contains data from all the regions in United States. Also you only want to see data from the stores in NY where the sales margin is greater than 100K USD in the second Quarter (Q2) 2015. Now to create a Webi document with this information, you have to apply filters on these dimensions - State, Year, and Quarter and Filter on sales margin. Filter Operator AND Query filters are applied in Query Panel and they are used to limit the number of rows from data sources and to return the same in the document. Report filters are applied at the report level on reports, tables, charts, etc. These filters are not used to limit the data retrieval from the data source and only hide certain values at the report level. Query filter is applied in this format − Object (On which filter is applied), Operator (You can use various comparison operators), and Operand. Operand − You can select from the following list of Operands − Constant List of Values (LOVs) Prompt Universe Object Result from Other Query Operators − You can select from the following operators − Equal to (=) Not Equal to Greater than Less than Greater than Equal to Less than Equal to Between Following types of query filters are normally used − Predefined Filters Custom Filters Quick Filters Prompts You can add multiple filter types on a single query. These filters are normally Administrators and saved at the Universe level. They are used to populate data that is permanently available. These filters require some good knowledge of database design and complex expressions. Using predefined filters on Universe means you don’t need to create custom filter every time when a new Webi document is created. Also note that you can’t access the components of Predefined filters and it is also not possible to edit them. To add a Predefined filter, you can drag or double-click this filter to Query Panel → Filters Pane. When you run the query, corresponding data w.r.t filters will be added to the report. You can use a Predefined filter by a double-click or just by dragging the filter to Query Filter. Quick filters are used to quickly retrieve the values you want without the use of filter editor. Quick filters use equal to operator while using a single value or list in operator when you use multiple values. Quick filters can’t be used with BEx queries. Quick filters are used in Query panel. To apply a Quick Filter, select the object you want to filter. Select ‘Add Quick Filter’ at the top right corner of Result Object Pane. New dialog box will open. You have to select the value you want to use in the Quick filter from LOVs. That filter will be added Query Filters pane. To delete this filter, select the filter in Query filter pane and press ‘Delete’ button. You can also create custom query filters to meet the business requirement or to hide the data from specific users. To create custom query filter, add the object you want to use in the filter. Drag it to Query filter pane. Click the arrow next to default operator and select the operator. Click on the arrow to select the filter type. You can select the following filter type − Constant Value from list Prompt Object from this query Result from another query Select the value from this that you want to include in the filter. To remove a filter, select the filter and press ‘Delete’ button. To remove all the filters, use ‘Remove All’ option at the top right corner of the screen. Prompt is defined as a special filter for users, which allows them to enter a value every time data is refreshed in the document. Using prompts, you have multiple users viewing one document to display different sub set of data in database. Prompts allow you to retrieve the data from database and reduce the time. Following are the elements of a Prompt − An Object An Operator Message Example − Current Year Equal to (“Enter the Year”). In this Prompt, Current Year is the object, “Equal to” is the Operator and prompt message is “Enter the Year”. A Prompt can be applied to Dimension, Measures, attributes, hierarchies, etc. You can use AND, OR operators to create multiple prompts in the same query. While using BEx and .unx Universe, you can only use AND operator with prompts. When you use multiple data providers in a single document, you can merge multiple prompts with same data type, same operator types and same prompt text are merged. While refreshing all the data providers, one prompt appears for all multiple prompts. LOVs displayed by merged prompt is the list associated with the object in prompt with the most displayed property constraints. You can also create hierarchical prompts where the following objects display their LOVs hierarchically in a Prompt − Hierarchies Levels Dimensions associated with hierarchical LOVs Hierarchical prompts are displayed in a tree form and you can navigate up and down the tree. As per the filters in Prompt, you can select items from different levels of LOVs. To build a prompt, add the object you want to filter with a prompt to Query Filter pane. Select the filter operator from the list and click on the last arrow mark to select a prompt. You can add the text message for Prompt value and run the query. When you run the query, Prompt dialog box will allow you to enter the values as per the selected operator. When the values are selected and you click ‘Ok’, and the data for selected values in the document will be reflected. When you refresh the document in Webi, prompt will appear every time to select the values. You can also select from existing prompts to add to the query in query panel. To use an existing prompt, drag the object on which prompt has to be applied to query filter pane. Select from Universe, select an existing Prompt → Ok. It will display the list of all prompts that are compatible with the object in Query filter. To delete a prompt, select the prompt in Query filter pane and press the ‘Delete’ button. You can also select Remove or Remove all option. You can also combine prompts with query filters to limit the data in the document and to select a specific record from the filtered data. Example − You can apply Query filters for Department and Year and Prompt for a specific Employee name input. State Not Equal to Florida Year 2005 Which Category When you run the query, it will ask you to enter the value for Category. In Webi document, it will filter the data as per filters in the query panel and display the result according to Prompt value. You can also use multiple prompts in a single query. To add multiple prompts, drag all the objects on which you want to apply prompts. Select prompt by clicking on Arrow mark in the end of query. To define the order of Prompts, you have to go to Query properties at the top. From there, you can select the order of prompts as per requirement. You can move up/down a prompt from the list. Subqueries provides a more flexible option to filter the data as compared to an ordinary query filter. Using subqueries, you can limit the values returned with a WHERE clause. You can also compare the values of objects in a subquery with the other objects. Using subqueries, you can implement complex logic to limit the size of data, which is not possible to apply with simple query filters. Subqueries work on SQL which is used to retrieve the query data. SQL is supported by most of RDBMS and each database uses its own syntax. If any database doesn’t support SQL, an option to create a subquery will not highlight in the query panel. Subqueries can be built on dimensions, measures and attributes and not on the hierarchical objects. Select the object in the result pane on which you want to build a subquery. It will add a subquery outline in the Query filter pane. Now if you want to add a WHERE condition, drag an object to the area of subquery. Select the Operator and Value used to filter object in WHERE condition. You can add multiple subqueries to query panel. You can use “AND” or “OR” relationship between subqueries. To change the relationship, you can click on AND to change it to OR. By default, two subqueries are linked with an AND relationship. You can also nest a subquery. Drag a subquery to the area and drop an object. Parameters − You can use the following parameters while passing a subquery to Query filter pane. Filter Objects − These are the objects whose values are used to filter result objects. Filter By Objects − The object that determines which filter value subquery returns. Operator − This operator defines the relationship between the filter object and the filter by object. WHERE Condition − This is used to constraint the list of values of the filter by object. Relationship Operator − AND, OR You can rank the unranked data from the database in your report. Database ranking allows you to rank the data at database level so when you run a query, data returned by query is already ranked. Database ranking is done by editing the script generated by query. If your database doesn’t support ranking, then the option to create ranking will not highlight in query panel. Also note that Ranking can’t be created on hierarchical data. First add the objects to Result Objects in Query panel. Select Add Ranking at the top of Query filter pane. Select the ranking dimension and type - top, bottom, top %, and bottom %. You can select the number of records or % of records you want the rank to return in the next box. Drag the ranking dimensions, measures, to based-on box. You can also drag dimensions to provide a calculation context to Ranked by box. You can also add WHERE condition by dragging a dimension to the bottom of ranking. Click Run Query. Webi Report can contain hierarchical and non-hierarchical data according to data source used to create the report. Hierarchical and non-hierarchical data works in different way in the report. A non-hierarchical data contains no parent-child relationship. Hierarchical data contains parent-child relationship between objects and you can use them to analyze and navigate data in a report. Non-hierarchical data is defined as data with no parent-child relationship. A simple example of non-hierarchical data is Dimension. A non-hierarchical data can be analyzed using various parameters like sorts, filters, etc. Example − Customer, Product Hierarchical data is defined as data with Parent-child relationship and you can analyze the data at different levels of hierarchy. All the measures that are associated with hierarchical data are aggregated as per object level in hierarchy. Example − Consider a Geography hierarchy; you have Country India and State defined as Delhi. Now if you use this geographical hierarchy in report and want to analyze Number of Units sold at each level for different categories, then hierarchies allow you to use Aggregation at country level and if you drill down to state level, for each state too. Hierarchical data is presented in columns in hierarchical tables. Below table shows the hierarchal data in parent-child relation and aggregated on Quantity sold as measure. If you see the above table, the number of units sold for corresponding country India is 1200 and corresponding value at each hierarchy level is also shown. You can use sections to divide the information into smaller part for better analysis. Section allows business managers to analyze the data in a more effective manner. Example − You are an area manager in a multinational company and you have received Sales report showing total revenue for each city and quarter as shown in the following table for the year 2015 − Now if you want to apply Section on Quarter column, you can compare the Total Revenue in each city compared on the basis of Quarter. Q1 Q2 To create a section on a column, Select the data and column, right-click on the column and select set as Section. To create a section from a Dimension, Go to Report Elements → Section → Insert Section. Click on the report area where you want to insert a Section. Choose the Dimension on which Section has to be created. You can also create Section on Hierarchies in the report. When a section is created on a hierarchy, each member of hierarchy becomes a section header. Let us understand this with the help of an Example − If you create a section on Customer Geography, you will get the following report. By expanding the Section header, you will get the following report. To delete a Section, right-click on the section Select → Delete. If you select ‘Cell Only’, it will delete ‘Section Cell’ only and if you select ‘Cell and Section’, it will remove ‘Section and Cell’ both. To Hide Sections − Select Section. Go to Report Elements → Behaviors → Hide to hide the section. ‘Hide When Empty’ is used to hide the section when empty. ‘Hide When-Enter the formula’ is used to hide the Section. If formula is true, it will hide the section. Breaks are used to define all data for every unique value of an object in separate parts. Using Breaks you can apply − Subtotals and Sub aggregations Display data in more effective manner Section breaks up the data into multiple cells that are called section headers and each section header contains a value for dimension and data corresponding to dimension value. Break is used to divide the data into one block and each column carries dimension, attributes and measures. These values are repeated for each row value in the block. Select the column in which you want to insert a Break. Go to Analysis → Display → Break → Add Break. This will divide the table into many mini tables as there are unique values in the column. To manage a break, you should use Design mode. Go to Analysis → Display → Break → Manage Break. It will open a new window and show all the breaks in the table. You can define the following properties about Break in this dialog box. You can prioritize Break using up-down arrows. Display Properties Page Layout Duplicate Values You can also Add or Remove a Break using Break Properties. Sorting can be applied in table on sections, charts to organize the data in a specific order in a Webi report. Default sorting that is applied in a report is from left to right order of objects in Result object of Query Panel. You have the following Sorting Orders − Default − This is default order where data is sorted as − Ascending numeric order for numeric data Ascending numeric order for numeric data Ascending chronological order on date Ascending chronological order on date Chronological order for months Chronological order for months Alphabetical order for alphanumeric data Alphabetical order for alphanumeric data Ascending − In this, smallest value at the top to highest value at the bottom. Example − 1000, 2000, 3000, or Delhi, Kolkata, Mumbai Ascending − In this, smallest value at the top to highest value at the bottom. Example − 1000, 2000, 3000, or Delhi, Kolkata, Mumbai Descending − In this, highest value at the top to smallest value at the bottom Descending − In this, highest value at the top to smallest value at the bottom Custom − Using this, you can define your own sort order. Custom orders are available on dimensions and attributes and not on hierarchies, measures and level. To insert a sort, open report in Design mode. Select the Column you want to sort. Go to Analysis → Display → Sort → Ascending/Descending You can apply multiple sorts in a single table on different columns. You can use ‘Remove All Sorts’ option to delete all the sorts. To manage the Order of Sorts, go to Advance tab. You can define order for all sorts using up and down arrows. You can define Custom Sorts here if no other sort is applied. This can also be used to Add/Remove Sorts. In a Webi document, you can include one or more charts. You can insert charts in an existing document or in a new document. When a Webi document containing chart is exported into an Excel or PDF format, the chart is converted into an image. You can convert the tables in a Webi report into different chart types. There are different Chart types available in Webi. Bar charts are used to compare similar groups of data and they display data in rectangular form horizontally. Following are the different types of Bar Chart − Bar Chart Stacked Bar Chart 100% Stacked Bar Chart As mentioned in description of box charts, it is a graphical display of a five number summary based on distribution of a dataset: the maximum, the minimum, the first quartile, the third quartile, and the median. It can also show abnormal values called outliers. Column charts are constructed of vertically-oriented rectangular bars. The height of the rectangles are proportional to the values associated with different category items. Following are the different types of Column charts − Column Chart Column Chart with 2 Y-axes Combined column Line Chart Stacked Column Chart 100% Stacked Column Chart 3D Column Chart An XY chart that displays lines connecting plots. Value axis plot positions are expressed by analysis category items. The second value axis plot positions represent the associated values. Following are the different types of Line Chart − Line Chart Line Chart with 2 Y Axes Area Chart This chart displays values within nested rectangles that can be colored. The levels of nesting correspond to the levels of hierarchy breakdown. The size of rectangles and their color both express a set of values. Following are the different types of Map Charts − Tree Map Heat Map A circular chart made up of sectors. The area of circle represents a whole, and the sectors of circle represent the parts of a whole. Different types of Pie Charts − Pie Chart Pie Chart with Variable Slice Depth Donut Chart Point chart is an XY chart displaying plots. Plots are positioned with coordinates represented by a pair of values. Following are the different type of Point Charts − Scatter Plot Bubble Chart Polar Scatter Chart Polar Bubble Chart It is also known as Spider chart and displays several axes starting from unique origin with a common scale. A mono dimensional visualization representing data as words where the word font size represents its relative weight in dataset. It is used to show the cumulative effect of values of a measure and each bar starts with the level of previous one. You should be in Design mode to add a chart. There are different ways to add a chart to a Webi Report. Go to Report Element → Chart → Select a Chart and click on the report area where you want to insert a chart. Chart is greyed when there is no data assigned to it. To assign data, you can drag the object from the list of available objects to chart axes. Right-click → Insert → Select the Chart type as shown in the following screenshot. Click the report to add a blank chart and then assign data by dragging objects from the list of available objects. Another method is by converting a table into chart. You can do this by selecting a table in a Webi report. Right-click on a column → Turn Into → Select a Chart. The table will be converted into a column chart. You can also copy a chart from a Webi report to the same report or to an application. To copy a chart, you have to first select the chart. To copy a Chart, right-click on the chart and select copy. Now to paste this chart in the same report, select an area in the report. Right-click and Paste. To copy this chart to an application, you can drag the chart directly to an open application or this can be done by copying the chart to the clipboard and pasting it in the application. To delete a chart, you can select a chart. Right-click → press Delete or select delete option. Select the table or Chart → Right-click → Turn into → More Transformations. Once you click on More Transformation, it will open a window with different Chart options. You can select any chart type and the chart will be changed in the report. You can also resize the chart by using the mouse option. Right-click the chart and select format chart option. It will open a new window. Go to General tab → Width and Height option → Select the chart parameters. Click ‘Apply’ and then ‘Ok’. To format a chart → Select the chart → Right-click → Format Chart. Following are the various chart properties you can choose from − Area Display Data Value Background Border Layout, etc. Once you make Title label visible, it will be displayed at the top of Chart. Conditional Formatting is used to highlight some specific values in the report. If you want you can show specific low or high values with some specific colors. Conditional formatting can be applied to the following elements − Rows in horizon tables Columns in vertical tables Cells in forms and cross-tables Sections Free holding cells Condition formatting can be used to make the following formatting changes − Text color, size and style, cell border, color, size and style, and cell backgrounds. You can add up to 30 conditional formatting formulas in a Webi document. To create a conditional formula, open the report in Design mode. You must be using Rich client or App Interface and shouldn’t work in Web mode. Go to Analysis → Conditional → New Rule. It will open formatting rule editor. Enter the rule name and description. Select the cell contents in filtered object or cell box. You can select Operator and Operands value. You have to define text formatting in Format tab. Click on Format to set the formatting of the tab. You can select the font, font style, size, effects (underline, etc.) and alignment. Once formatting is defined for condition, you have to click Ok. Now to apply conditional formatting to the object, select the column in the report. Go to formatting rules dropdown → Select the conditional formatting rules checkbox you have created. Conditional formatting will be applied to the desired cells. You can add multiple conditions in a single formatting rule on multiple objects. Go to Analysis tab → Conditional → Manage Rules. Once you click ‘Manage Rules’, it will open window for Conditional Formats. To edit a rule, select the rule and click on Edit. You can also change the order of Conditional Formatting rules. You can also duplicate/remove conditional formatting rules using Manage option. You can filter the data in a report to limit the data displayed in a Webi document. You can select filter condition to present the data that is of your interest. Data filtered using Report filters remain in the document and any time you can remove the filters to check hidden data. You have to mention the following elements to create report filters − Filtered object Operator Filter value Report element where filter has to be applied Example − You can apply a filter to see data related to a specific customer or sales region. Query filters are defined at query level in query panel and they are used to limit the data retrieved from the data source and return to a Webi document. Report filters are used to hide the data in a table, report, chart, section in a Webi document. Report filters don’t edit the data that is retrieved from the data source. You can use various operators to filter the data at the report level. Following are some of the common report filter operators − Equal To Not Equal To Different From Operator Greater Than Greater Than or Equal To Less Than Less Than or Equal To Between Not Between In List Not In List Is Null Is Not Null You can create the following types of report filters − Standard Report Filters − These filters are used to filter on a single value or lists of values. These are most flexible type of report filters. Standard Report Filters − These filters are used to filter on a single value or lists of values. These are most flexible type of report filters. Simple Report Filters− They provide an easy way to create filters using Equal to operator. These filters apply on single value. Simple Report Filters− They provide an easy way to create filters using Equal to operator. These filters apply on single value. Select the Report Element you want to apply a filter. Go to Filter → Add Filter. It will open the Report Filter dialog box. You can add objects, operand and value to apply filter at the report level. Using the functions − Add Filter, Remove or Remove All − you can add or delete filters accordingly. To Edit a Filter → Go to Analysis Tab → Filter → Edit Filter. You can make changes to filters in Report Filter Dialog box. Click Ok to apply. To Delete a Filter, Go to Analysis → Filter → Remove Filter. Click “Yes” to remove the filter. Input controls are used to filter and analyze the report data. You define input controls using text boxes and radio buttons. Input controls are associated with report elements, like tables and section headers, and use control to apply filter on report elements. When you select a value for input control, it filters the values in the report element that is associated with input control by selected value. Input controls can also be used on hierarchical data. You should be in Design mode to use input controls. Go to Analysis → Filters → Input Controls → Define Control. It will open Define Input Control dialog. Select the report object used to filter data and click ‘Next’. Note that if you select a Report element and then you select Define Control, you will get an option to include objects from selected block only. If you select this checkbox, it will show you objects only from the selected report element. You will get an option to choose and define control. Choose control allows you to select different control types like single value or multiple values. Define control allows you to select the name of control, description, values in control to select, operator and number of lines displayed in input control, etc. In the next window, you have to assign Report Elements. It will allow you to choose from report elements. You can assign report elements to input controls. (Example − I have selected as input control from both the blocks as shown below). Click ‘Finish’ and input controls will be added to the left pane under Input Control tab. Now as per your selection of input control and type of input control, data will be reflected in the report. To edit an input control → Select Input control from the left pane → Click Edit icon. It will open Edit Input Control dialog box. Make changes to Input Control and click Ok. To organize input controls, go to Input control tab on the left pane. Drag and drop input controls to move them up/down on input controls pane. Just hold the input control dialog box and move it up and down. Use the “x” mark to remove the input control. To view map of input control, select the input control → Click ‘Map’ at the top. You can also use a table or chart to define input control. Select the table → Right-click and select linking → Add Element Linking. You can select a single object or all objects to define as filtering objects. Click ‘Next’. You can enter the name and description of input control. Click ‘Next’. Once you click Next, you can select any other block to use this object as input control. Click ‘Finish’. Similarly, you can use charts as input control for other Report elements. You can also insert formulas and variables in a Webi report. To enter a formula in Webi report, the report should be opened in Design mode. Click the formula editor to enter a formula. Once the formula editor is open, build the formula. If the formula editor is not visible, go to Properties tab → View → Formula Bar. The report should be in Design mode to create a Variable in formula. To create a variable, click on Create Variable icon in formula bar to display variable editor. Enter the name of Variable, Qualification - Dimension, Measure, and Detail. If you select Detail, it opens a new field - Associate dimension. Enter the formula for variable, you can select from the list of available objects, functions and operators to create a formula. You can click on the tick mark to validate the formula. Once the formula is defined, click Ok. On the left side, you can see this new variable in the list of available objects. To use this variable, you can drag this to Webi report. You can also edit or delete the variable. To edit/delete a variable, select the variable from the list of available objects → right-click → Edit/Remove. The drill option is used to analyze data at different levels. With drilling you can go to the next levels to analyze data in tables, charts, and sections. You can also specify how drill options will make changes to reports when you perform drilling in Webi. Setting drill options depends on the Web Intelligence interface used. BI Launchpad Webi Rich Client Note that to use drill option, you should have hierarchy defined at Universe level. Once you have hierarchy at Universe, you can add that object to Result objects in Query panel. Once you run the query, the object will be added to the list of available objects in a Webi document. Drill allows you to move to level up or level down as per the hierarchy in Universe. To set drill option in a Webi report, go to Analysis tab → Interact → Drill → Start Drill. Once you start drill, you can move to the next levels or end drill using the option in the same tab. Example − Drill on 2015 - the results displayed on the drilled table are Q1, Q2, Q3, and Q4 for the year 2015. This means that the quarterly values you drilled are filtered by 2015. You can also take a snapshot of Drill result in a separate report. Use the snapshot option to add a new report with drilled data. You can publish a Webi content outside Webi documents by publishing report elements like charts and tables as web services. This is called BI services. To publish a Webi document as web services, open the report in Design mode. You can use Publish Content Wizard to publish Webi document. The report should be saved in BI repository to publish as web services. Select the Report Element you want to publish, right-click and click ‘Publish as Web Service’. This will open the Publish Content Wizard → Click ‘Next’. For web services, you should reproduce prompts multiple times to produce different responses. Select the prompts you want to Publish and click ‘Next’. If you don’t select any prompts for publishing, web services uses prompt value that was supplied when the document was last refreshed. Before publishing a block as a web service, you use the ‘Define Published Content’ screen in the publish content wizard to name the table, make filters available on the block data, and select the server where the block will be published. You use the ‘Publish new content’ or ‘Re-publish Existing Content as Web Service’ screen in the Publish Content wizard to save and publish the web service to a host server. To re-publish an existing web service, select the web service, click ‘Publish’. To publish a new web service, select the folder where you want to publish the content and click ‘Create to display the Publish Web Service’ dialog box. Enter the name of the web service in the web service box and add the description → Select Authentication method for the web service from the Authentication list. Click Ok and it will save and publish the web service. Choose the web service where you want to publish → Click Finish. This option allows you to merge the data from different data sources. Assume that you have created Query 1 and Query 2 in Query Panel. When you combine both the queries in a single Webi report, objects from both the queries are shown in the list of available objects. Select the unique object from both the queries and click Ok as shown in the following screenshot. It will create a Merge Dimension under the list of available objects. It allows you to synch both the queries and you can add the objects from both the queries in a single report. Sometimes it doesn’t allow you to add objects in the report from either of the queries because of sync issues. In such a case, you can create a new variable for that object. Enter the variable name, qualification as “Detail” and it will add a new field ‘Associate Dimension’. In Associate dimension, select the unique object from the same query. In the Formula tab, select the object from the list of available objects for which you want to create a new variable and click ‘Validate’. Once the variable is created for that object, you can drag that object to the report. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2697, "s": 2333, "text": "Web Intelligence is part of SAP BusinessObjects product suite and is used for analytical and ad hoc reporting to meet an organization’s business requirements. Web Intelligence is a Business Intelligence reporting tool for business users to analyze data in Data Warehouse. It assists business managers in the decision-making process for building future strategies." }, { "code": null, "e": 3066, "s": 2697, "text": "Using Web Intelligence, business users can create basic, medium, and complex reports from transactional data in database and by creating Universes using Information Design Tool/UDT. Various SAP and non-SAP data sources can be used to create reports in Web Intelligence. SAP Business Warehouse (BW) system doesn’t require a Universe to connect to Web Intelligence tool." }, { "code": null, "e": 3187, "s": 3066, "text": "Web Intelligence tool can work as a client tool of BusinessObjects platform and also as a standalone tool for reporting." }, { "code": null, "e": 3322, "s": 3187, "text": "BusinessObjects was first started in 1990 with the tool name Skipper SQL 2.x, and in the year 1994 Business Objects v3.0 was launched." }, { "code": null, "e": 3425, "s": 3322, "text": "In 2005, BO XI was released and later on various other versions introduced. Some of the versions are −" }, { "code": null, "e": 3434, "s": 3425, "text": "BO XI R1" }, { "code": null, "e": 3443, "s": 3434, "text": "BO XI R2" }, { "code": null, "e": 3452, "s": 3443, "text": "BO XI R3" }, { "code": null, "e": 3463, "s": 3452, "text": "BO XI R3.1" }, { "code": null, "e": 3474, "s": 3463, "text": "BO XI R3.2" }, { "code": null, "e": 3583, "s": 3474, "text": "In 2007, SAP acquired this company for $6.8 billion and the product has been renamed as SAP BusinessObjects." }, { "code": null, "e": 3679, "s": 3583, "text": "Later in the year 2011, BO XI 4.0 was introduced. The latest version of the tool is SAP BO 4.2." }, { "code": null, "e": 3723, "s": 3679, "text": "SAP Webi has a three-layered architecture −" }, { "code": null, "e": 3798, "s": 3723, "text": "Database Layer − This layer defines multiple SAP and non-SAP data sources." }, { "code": null, "e": 3873, "s": 3798, "text": "Database Layer − This layer defines multiple SAP and non-SAP data sources." }, { "code": null, "e": 3938, "s": 3873, "text": "Semantic Layer − This layer defines multidimensional data model." }, { "code": null, "e": 4003, "s": 3938, "text": "Semantic Layer − This layer defines multidimensional data model." }, { "code": null, "e": 4081, "s": 4003, "text": "Presentation Layer − This layer defines where data is presented to end-users." }, { "code": null, "e": 4159, "s": 4081, "text": "Presentation Layer − This layer defines where data is presented to end-users." }, { "code": null, "e": 4324, "s": 4159, "text": "Various data sources can be used to create analytical and ad hoc reports. You can pull data from SAP systems, like SAP ECC, SAP ERP, SAP SRM, and other SAP modules." }, { "code": null, "e": 4413, "s": 4324, "text": "Non-SAP data sources include Oracle Database, Microsoft SQL Server, IBM DB2, and Sybase." }, { "code": null, "e": 4648, "s": 4413, "text": "BI Launchpad is a Java or HTML based interface of BusinessObjects tool to perform analytical reporting and data analysis. You can set the preference for your BI Launchpad that determines which tool interface is launched via Launchpad." }, { "code": null, "e": 4763, "s": 4648, "text": "Using Web or Internet Application to access Webi interface via BI Launchpad, you can perform the following tasks −" }, { "code": null, "e": 4825, "s": 4763, "text": "Create, edit and refresh all the reports in Web Intelligence." }, { "code": null, "e": 4887, "s": 4825, "text": "Create, edit and refresh all the reports in Web Intelligence." }, { "code": null, "e": 4989, "s": 4887, "text": "Create and edit all the queries in no data source (Universes) but not BEx queries in Web application." }, { "code": null, "e": 5091, "s": 4989, "text": "Create and edit all the queries in no data source (Universes) but not BEx queries in Web application." }, { "code": null, "e": 5214, "s": 5091, "text": "Note − If you are using Webi 4.0 SP2, it is not possible to create queries and you can only work on documents and reports." }, { "code": null, "e": 5262, "s": 5214, "text": "BI Launchpad has the following important tabs −" }, { "code": null, "e": 5348, "s": 5262, "text": "Home − Displays recent messages, alerts, documents, and applications that can be run." }, { "code": null, "e": 5434, "s": 5348, "text": "Home − Displays recent messages, alerts, documents, and applications that can be run." }, { "code": null, "e": 5554, "s": 5434, "text": "Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents." }, { "code": null, "e": 5674, "s": 5554, "text": "Documents − Displays the available documents and folders, making it easier to view, organize, and manage the documents." }, { "code": null, "e": 5723, "s": 5674, "text": "Any open Document − Displays each open document." }, { "code": null, "e": 5772, "s": 5723, "text": "Any open Document − Displays each open document." }, { "code": null, "e": 5923, "s": 5772, "text": "You can use the Application tab to start an application including Web Intelligence. You can use the Preference tab to define BI Launchpad preferences." }, { "code": null, "e": 6030, "s": 5923, "text": "As mentioned, BI Launchpad is HTML5 or Java-based web interface to launch an application via BI Launchpad." }, { "code": null, "e": 6149, "s": 6030, "text": "To access BI Launchpad, you should have a web URL, user name and password. Access profile to be set for the resources." }, { "code": null, "e": 6281, "s": 6149, "text": "To get the BI Launchpad details and user credentials you can reach the BO Administrator using the link, http://BOSERVER:8080/BOE/BI" }, { "code": null, "e": 6418, "s": 6281, "text": "To login to BI Launchpad, open the web browser and enter the Launchpad URL provided by your administrator. The following screen pops up." }, { "code": null, "e": 6494, "s": 6418, "text": "Select the system name you want to login. Enter the user name and password." }, { "code": null, "e": 6645, "s": 6494, "text": "In the Authentication dropdown, select the Authentication type - Enterprise, Windows AD, etc. (In the above snapshot, this server has a single login)." }, { "code": null, "e": 6709, "s": 6645, "text": "Click ‘Log On’ and it will open the home page for BI Launchpad." }, { "code": null, "e": 6782, "s": 6709, "text": "You can use Applications tab of Launchpad to run any of the application." }, { "code": null, "e": 6828, "s": 6782, "text": "Let us now discuss how to set BI preferences." }, { "code": null, "e": 6890, "s": 6828, "text": "You can set BI Launchpad preferences for the following tasks." }, { "code": null, "e": 7064, "s": 6890, "text": "General Preferences − These are defined by the administrator. You can reset your password. You can also set time zone, locales preferences, and Web Intelligence preferences." }, { "code": null, "e": 7128, "s": 7064, "text": "General Tab − Using this tab you can set user default settings." }, { "code": null, "e": 7171, "s": 7128, "text": "Change Password − As per your user access." }, { "code": null, "e": 7263, "s": 7171, "text": "Locales and Time Zone − To set product locale, preferred viewing locale, current time zone." }, { "code": null, "e": 7321, "s": 7263, "text": "Analysis Edition for OLAP − To define accessibility mode." }, { "code": null, "e": 7550, "s": 7321, "text": "Web Intelligence − You can select the interfaces to use for view and modify modes. You can also select a Default Universe. You can set the drill options. You can also select saving priorities when saving a report in .xls format." }, { "code": null, "e": 7640, "s": 7550, "text": "BI Workspaces − Used to select a default stylesheet to use when creating a new workspace." }, { "code": null, "e": 7746, "s": 7640, "text": "Crystal Reports − Used to set crystal reports options like printing options, default measuring unit, etc." }, { "code": null, "e": 7944, "s": 7746, "text": "There are three different application modes that can be used to build the queries, create documents and to analyze the reports. When you open an existing report, the following modes are available −" }, { "code": null, "e": 7949, "s": 7944, "text": "Data" }, { "code": null, "e": 7957, "s": 7949, "text": "Reading" }, { "code": null, "e": 7964, "s": 7957, "text": "Design" }, { "code": null, "e": 8156, "s": 7964, "text": "In this mode, you can create new data provider, change an existing data source or rename a data provider. You can also create, edit, and manage queries, which is used to pass data to reports." }, { "code": null, "e": 8281, "s": 8156, "text": "In Data mode, it shows the list of all the available data providers. All the options in tool mode are disabled in this mode." }, { "code": null, "e": 8418, "s": 8281, "text": "This mode allows you to display existing reports, search text, monitor changes in the reports, and drill down on the data in the report." }, { "code": null, "e": 8484, "s": 8418, "text": "You can also use the left panel and tool bar in the Reading mode." }, { "code": null, "e": 8630, "s": 8484, "text": "Design mode allows you to add, delete objects in a report, applying conditional formatting, applying formulas in report, creating variables, etc." }, { "code": null, "e": 8821, "s": 8630, "text": "Design mode with Structure only allows you to view the structure of the report. All the changes that you make in this mode, they are not applied to the server till you populate it with data." }, { "code": null, "e": 9065, "s": 8821, "text": "In Design mode with data, all the modifications applied in a report are on the server. In case you have to make a lot of changes in an existing report, it is recommended to make changes in structure mode and then populate the report with data." }, { "code": null, "e": 9126, "s": 9065, "text": "In this chapter, we will learn how to create Webi documents." }, { "code": null, "e": 9393, "s": 9126, "text": "When you open Web interface via BI Launchpad or open Webi rich client, you have an option to create a new document or edit an existing one. You can create a new document as blank document or use an interface to create a document based on the following data sources −" }, { "code": null, "e": 9402, "s": 9393, "text": "Universe" }, { "code": null, "e": 9436, "s": 9402, "text": "Flat files in .csv or .xls format" }, { "code": null, "e": 9448, "s": 9436, "text": "BEx queries" }, { "code": null, "e": 9462, "s": 9448, "text": "Analysis view" }, { "code": null, "e": 9652, "s": 9462, "text": "Rich Internet application interface and Webi rich client allows you to use from list of available data sources; however, Web Interface supports only no data source or Universe from IDT/UDT." }, { "code": null, "e": 9782, "s": 9652, "text": "To create a blank document to use later − Launch Webi Rich Client → Click ‘New document’ option at the top → No Data Source → Ok." }, { "code": null, "e": 9880, "s": 9782, "text": "Or you can select a blank document by clicking the icon below the list of available data sources." }, { "code": null, "e": 10058, "s": 9880, "text": "You can also use other data sources like Universe, BW BEx query, and text sources like CSV and XLS files, Analysis view or a web service as data source to create a new document." }, { "code": null, "e": 10159, "s": 10058, "text": "You can create a Webi document based on Universe using Information Design Tool/Universe Design Tool." }, { "code": null, "e": 10208, "s": 10159, "text": ".unx − File created with Information Design Tool" }, { "code": null, "e": 10257, "s": 10208, "text": ".unx − File created with Information Design Tool" }, { "code": null, "e": 10301, "s": 10257, "text": ".unv − File created in Universe Design Tool" }, { "code": null, "e": 10345, "s": 10301, "text": ".unv − File created in Universe Design Tool" }, { "code": null, "e": 10438, "s": 10345, "text": "To use a Universe as data source, go to New → Select a Universe as data source and click Ok." }, { "code": null, "e": 10582, "s": 10438, "text": "It will open a list of all Universes published to BI repository to use in a document. You can select any available universe and click ‘Select’." }, { "code": null, "e": 10655, "s": 10582, "text": "It will show you all .unx and .unv files available to use in a document." }, { "code": null, "e": 10837, "s": 10655, "text": "Query Panel will be open. You can select from list of available objects as per your access permissions. You may not be able to use a few of the objects because of permission issues." }, { "code": null, "e": 10970, "s": 10837, "text": "In query panel, you have Universe outline in the left pane, and result objects, query filters, data preview panels in the main pane." }, { "code": null, "e": 11060, "s": 10970, "text": "To use BEx as data source, go to New → Select BW BEx query as data source and click ‘Ok’." }, { "code": null, "e": 11263, "s": 11060, "text": "It will show you a list of all available BEx queries. You can select only those which you have permission to access. On the left side of the screen, it shows you the name of Info provider for BEx query." }, { "code": null, "e": 11394, "s": 11263, "text": "It will open the Query panel, you can select the list of available objects from Universe Outline and name of BEx query below that." }, { "code": null, "e": 11433, "s": 11394, "text": "Click New icon → Select Universe → Ok." }, { "code": null, "e": 11488, "s": 11433, "text": "Select the Analysis view you want to use and click Ok." }, { "code": null, "e": 11551, "s": 11488, "text": "It will open the Query panel with a list of available objects." }, { "code": null, "e": 11664, "s": 11551, "text": "You can edit an existing document via BI Launchpad → Web Interface or by opening a document in Webi Rich Client." }, { "code": null, "e": 11837, "s": 11664, "text": "You can also open recent documents using Webi Rich client directly. Launch Webi rich client and you will get a list of recent open documents on the left side of the screen." }, { "code": null, "e": 12004, "s": 11837, "text": "You can also select an existing report to edit in Webi. Extension of a Webi File is “.wid.”. To open an existing document, select a blank document. Go to File → Open." }, { "code": null, "e": 12064, "s": 12004, "text": "Select the path of an existing ‘wid’ file and click ‘Open’." }, { "code": null, "e": 12116, "s": 12064, "text": "By default, it will open the report in Design mode." }, { "code": null, "e": 12179, "s": 12116, "text": "To open a document, go to Webi rich client → Click ‘Open’ tab." }, { "code": null, "e": 12299, "s": 12179, "text": "Navigate through the folder you want to open, select the file and click ‘Open’. This will open the file in Design mode." }, { "code": null, "e": 12362, "s": 12299, "text": "You can select design and read mode as per your access rights." }, { "code": null, "e": 12447, "s": 12362, "text": "In this chapter, we will get acquainted with the various ways of sending a document." }, { "code": null, "e": 12521, "s": 12447, "text": "Open the document in Webi Rich client → Click ‘Send by e-mail attachment’" }, { "code": null, "e": 12631, "s": 12521, "text": "You have an option to select the different attachment formats like PDF, XLS, CSV, Text, and/or unsecured wid." }, { "code": null, "e": 12749, "s": 12631, "text": "To send a document to other users/groups, open the document via BI Launchpad. Click ‘Send’ on toolbar → Send to User." }, { "code": null, "e": 13016, "s": 12749, "text": "Select the users/groups to which you want to send the document to from the list of users and groups. You can select ‘automatically generated’ to send the document with an auto generated name. Select the specific name and enter the name you want to send the document." }, { "code": null, "e": 13115, "s": 13016, "text": "You can also select “shortcut” to send a shortcut or “Copy” option to send a copy of the document." }, { "code": null, "e": 13268, "s": 13115, "text": "To send a document via ftp, login to BI Launchpad. You have to save the document first. Click ‘Save’ icon at the top of the screen to save the document." }, { "code": null, "e": 13326, "s": 13268, "text": "Click ‘Mail’ icon in the tool bar → Select ‘Send to Ftp’." }, { "code": null, "e": 13457, "s": 13326, "text": "You have to enter the host name, port number, user name and password. Select the naming method for document to send. Click ‘Send’." }, { "code": null, "e": 13651, "s": 13457, "text": "Webi documents contain at least one or more reports. You can manage multiple reports in a single Webi document. You can also add, delete, rename, and move existing reports in one Webi document." }, { "code": null, "e": 13735, "s": 13651, "text": "To add, delete, or move a report in a Webi document, right-click on the Report tab." }, { "code": null, "e": 13815, "s": 13735, "text": "To add a report, right-click on the existing report tab and click ‘Add Report’." }, { "code": null, "e": 13937, "s": 13815, "text": "To delete a report, right-click on the report tab and click ‘Delete’. Each Webi document should have at least one report." }, { "code": null, "e": 14002, "s": 13937, "text": "You can use “Rename Report” option to rename an existing report." }, { "code": null, "e": 14209, "s": 14002, "text": "To save a document in Webi, you have options to save a report locally, save in BI repository, or export as CSV format. To do this, go to File tab and choose from the options Save/Save As/Save as Enterprise." }, { "code": null, "e": 14355, "s": 14209, "text": "If you open a Webi document, you can click ‘Save’ to keep the changes. ‘Save as’ option is used to save a document in different formats such as −" }, { "code": null, "e": 14359, "s": 14355, "text": "WID" }, { "code": null, "e": 14363, "s": 14359, "text": "PDF" }, { "code": null, "e": 14369, "s": 14363, "text": "Excel" }, { "code": null, "e": 14380, "s": 14369, "text": "Excel 2007" }, { "code": null, "e": 14392, "s": 14380, "text": "CSV Achieve" }, { "code": null, "e": 14401, "s": 14392, "text": "TXT File" }, { "code": null, "e": 14585, "s": 14401, "text": "When you use the ‘Save as’ option, on the right side of the screen you get many options – Refresh on open, Permanent Regional formatting, Save for all users, Remove document Security." }, { "code": null, "e": 14675, "s": 14585, "text": "You can enter the report name, change an existing report name and also add a description." }, { "code": null, "e": 14823, "s": 14675, "text": "Queries in Webi are managed in the Query panel. When you create a Webi report, you use queries in the query panel to get data from the data source." }, { "code": null, "e": 15082, "s": 14823, "text": "Queries can be created from different interfaces like you can create queries based on Universe, represent data in OLAP database as objects, flat files like Excel and CSV files, data in SAP InfoCubes using BEx queries, Analysis view or Query as a web service." }, { "code": null, "e": 15347, "s": 15082, "text": "Each query has dimensions and measures. Measures always return numeric data based on the calculation and other objects in the data source. Queries can be hierarchical or non-hierarchical in nature. Non-hierarchical queries have no relationship between the objects." }, { "code": null, "e": 15604, "s": 15347, "text": "Hierarchies define relationship between the objects. For example: In a Geographical hierarchy, you have measures based on geographical hierarchies like counties, states and cities. Using hierarchies, you can drill up and down to see data at the next level." }, { "code": null, "e": 15673, "s": 15604, "text": "Query panel is not available, if you use Web Interface of Webi tool." }, { "code": null, "e": 15893, "s": 15673, "text": "In a Webi document, you retrieve data in report from the data source using the query panel. All the queries are built in the query panel and interface of query panel depends on the data source you are using to get data." }, { "code": null, "e": 16167, "s": 15893, "text": "Queries can be created on Universe, which contains Relational and OLAP data models, data from flat files like CVS, XLS files, SAP BW BEx query, and Analysis view. Query is run to get data from the data source. You can apply filters and also preview data in the query panel." }, { "code": null, "e": 16247, "s": 16167, "text": "To open a Query Panel − Go to Web Intelligence → New → Select Data Source → Ok." }, { "code": null, "e": 16343, "s": 16247, "text": "When you click ‘Ok’, you have to select data source from the list of selected data source type." }, { "code": null, "e": 16483, "s": 16343, "text": "New window will open known as Query Panel. Select the objects from Universe outline, which you want to add to the report in result objects." }, { "code": null, "e": 16724, "s": 16483, "text": "To add a filter, select the object in Query filters by dragging an object and select a value. For data preview, click ‘Refresh’ tab. To add this query to the report, click ‘Run Query’ option at the top of the screen to add to Webi document." }, { "code": null, "e": 16973, "s": 16724, "text": "You can view multiple objects in the Query panel and create, edit, and delete objects in queries as per login user access rights. Users are normally created by BusinessObjects Administrator. CMC is used to create user profiles to login to BO tools." }, { "code": null, "e": 17120, "s": 16973, "text": "If you don’t have enough access rights, you will not be able to access few objects of a report. Access rights are defined by the BO administrator." }, { "code": null, "e": 17301, "s": 17120, "text": "Classes are used to group similar objects in a report. A class can contain one or more subclasses. Subclasses contains further subcategory of objects in the upper level of a class." }, { "code": null, "e": 17466, "s": 17301, "text": "Classes are used to organize objects in a logical manner. While creating queries on Universe, you can find the information on objects that you have to use in query." }, { "code": null, "e": 17738, "s": 17466, "text": "Dimension lists all the objects using which we want to analyze the data. Dimension provides the basis for analysis in a report. Dimension normally contains non-hierarchical character type data like customer name, product name, customer address, sales office address, etc." }, { "code": null, "e": 17804, "s": 17738, "text": "Common examples of Dimensions are - Product, Customer, Time, etc." }, { "code": null, "e": 17988, "s": 17804, "text": "Analysis Dimension − An analysis dimension contains group of hierarchies related to each other. When you add an analysis dimension in a report, its default hierarchy appears in query." }, { "code": null, "e": 18052, "s": 17988, "text": " − Analysis Dimension appears as this symbol in the query panel" }, { "code": null, "e": 18270, "s": 18052, "text": "Attribute provides data about dimensions or hierarchy. For example − Home address of a customer dimension. Attribute has one-to-one relationship with corresponding dimension. Each customer has only one address object." }, { "code": null, "e": 18325, "s": 18270, "text": " − Attribute appears as this symbol in the query panel" }, { "code": null, "e": 18488, "s": 18325, "text": "If your Universe is not designed correctly, an object returns the multiple values for a dimension and the corresponding cell in the report shows MULTIVALUE error." }, { "code": null, "e": 18681, "s": 18488, "text": "Measures are defined as numerical values in the report on which analysis is performed. They are integer values, which are used to compare the performance of an organization with defined KPI’s." }, { "code": null, "e": 18766, "s": 18681, "text": "For example − Sales in each region, total Revenue per year, profit per product, etc." }, { "code": null, "e": 18819, "s": 18766, "text": " − Measure appears as this symbol in the query panel" }, { "code": null, "e": 19071, "s": 18819, "text": "A hierarchy represents parent-child relationship in Universe. It allows you to drill up or down in the report to the next level. For example − Geography hierarchy contains Country, State and City. Time hierarchy contains Year, Quarter, Month and Week." }, { "code": null, "e": 19250, "s": 19071, "text": "Using the member selector in defining hierarchy, you can define which member appears in the result set. In hierarchical data sources, hierarchies are associated with a dimension." }, { "code": null, "e": 19451, "s": 19250, "text": "Members are defined at different level of hierarchies in a data source. For example − Consider a Geography hierarchy containing members – “India” at the country level and “Haryana” at the State level." }, { "code": null, "e": 19608, "s": 19451, "text": "You can also include individual members in query from hierarchy, if you don’t want to add all the members. Named set can be used to define a set of members." }, { "code": null, "e": 19764, "s": 19608, "text": "A named set is defined as named expression and results a set of members. You can define named set at Universe level or a relational or OLAP database level." }, { "code": null, "e": 19884, "s": 19764, "text": "You can build queries in the Query panel using various data sources like Universe, BEx from SAP BW or an Analysis view." }, { "code": null, "e": 20010, "s": 19884, "text": "Universe contains data from OLAP and Relational data sources. Data in Universe can be a relational data or hierarchical data." }, { "code": null, "e": 20131, "s": 20010, "text": "Open Web Intelligence via BI Launchpad → New (Create a new Webi document). You will be prompted to select a Data Source." }, { "code": null, "e": 20295, "s": 20131, "text": "Select a Universe as data source and click ‘Ok’. You will get a list of all available Universe. Select a Universe, which you want to use to create a Webi document." }, { "code": null, "e": 20545, "s": 20295, "text": "A new window will open with the name Query Panel. In the query panel, on the left side of the screen, you have a list of available objects. You have Result Objects where you drag objects from the left panel, which you want to add in a Webi document." }, { "code": null, "e": 20750, "s": 20545, "text": "You have Query Filter using which you can add different filters. Data Preview can be used to view data before it is added to Webi document. Run query tab at the top of the screen is used to run the query." }, { "code": null, "e": 20896, "s": 20750, "text": "In the Query panel, you have an option using which you can add data from multiple sources in a single Webi document by creating multiple queries." }, { "code": null, "e": 21022, "s": 20896, "text": "To add a Query, go to Add query option at the top of the screen. You can select different data sources to add a second query." }, { "code": null, "e": 21183, "s": 21022, "text": "You can also edit the properties of Query, like the name of the query, number of records, etc. ‘View Script’ option allows you to check the script of the query." }, { "code": null, "e": 21239, "s": 21183, "text": "Following functions can be set using Query Properties −" }, { "code": null, "e": 21265, "s": 21239, "text": "Retrieving duplicate rows" }, { "code": null, "e": 21322, "s": 21265, "text": "Relational .unx, OLAP, but not available in BEx queries." }, { "code": null, "e": 21351, "s": 21322, "text": "Returning sample result sets" }, { "code": null, "e": 21428, "s": 21351, "text": "Available in relational .unx, but not available in OLAP .unx or BEx queries." }, { "code": null, "e": 21460, "s": 21428, "text": "Retrieving/excluding empty rows" }, { "code": null, "e": 21519, "s": 21460, "text": "Available in OLAP .unx only. Not available in BEx queries." }, { "code": null, "e": 21704, "s": 21519, "text": "In this case, you have an option to run multiple queries separately. You can go to Run queries and select the query you want to run. You can also combine queries using the Query Panel." }, { "code": null, "e": 22091, "s": 21704, "text": "You can create Webi documents based on BEx (Business Exchange Queries) created by BEx Query Designer, which is based on InfoCube in SAP BW system. You can connect to a BEx query in Webi with the use of BI Consumer Service (BICS) connection. You need not create Universe for BEx queries, and all attributes, hierarchies, dimensions and measures are automatically mapped in Webi document." }, { "code": null, "e": 22370, "s": 22091, "text": "You can edit, create, and refresh documents based on BEx using Web Intelligence Rich Internet Application Interface (Applet based) or Webi Rich Client. If you are using Webi DHTML web interface, you can only view or refresh a Webi document based on BEx but you cannot edit them." }, { "code": null, "e": 22430, "s": 22370, "text": "Following important points about BEx should be considered −" }, { "code": null, "e": 22521, "s": 22430, "text": "You can only use BEx queries, which are flagged with “Allow External Access to the Query”." }, { "code": null, "e": 22612, "s": 22521, "text": "You can only use BEx queries, which are flagged with “Allow External Access to the Query”." }, { "code": null, "e": 22714, "s": 22612, "text": "To manage object mapping, refer to restriction and equivalent pages to ensure correct use of queries." }, { "code": null, "e": 22816, "s": 22714, "text": "To manage object mapping, refer to restriction and equivalent pages to ensure correct use of queries." }, { "code": null, "e": 22876, "s": 22816, "text": "Following metadata objects are supported from BEx in Webi −" }, { "code": null, "e": 22888, "s": 22876, "text": "Hierarchies" }, { "code": null, "e": 22904, "s": 22888, "text": "Characteristics" }, { "code": null, "e": 22926, "s": 22904, "text": "Navigation Attributes" }, { "code": null, "e": 22945, "s": 22926, "text": "Display Attributes" }, { "code": null, "e": 22963, "s": 22945, "text": "Basic Key Figures" }, { "code": null, "e": 22996, "s": 22963, "text": "Calculation figures and formulas" }, { "code": null, "e": 23019, "s": 22996, "text": "Restricted Key figures" }, { "code": null, "e": 23029, "s": 23019, "text": "Variables" }, { "code": null, "e": 23050, "s": 23029, "text": "Customized Structure" }, { "code": null, "e": 23214, "s": 23050, "text": "Open BEx Query Designer and select the query you want to use in BO tool. Go to Properties → Advanced tab and select Allow External access to Query. Save the query." }, { "code": null, "e": 23364, "s": 23214, "text": "You can create a BICS connection in CMC or also in Information Design Tool. A connection can be created to a single BEx query or to an Info Provider." }, { "code": null, "e": 23434, "s": 23364, "text": "Login to CMC console → Select OLAP connection from the dropdown list." }, { "code": null, "e": 23521, "s": 23434, "text": "Click on a New Connection → In Provider list, select SAP NetWeaver Business Warehouse." }, { "code": null, "e": 23680, "s": 23521, "text": "Similarly, you can define a BICS connection in IDT. Select an OLAP connection and choose SAP NetWeaver Business Warehouse → SAP BICS Client Middleware driver." }, { "code": null, "e": 23718, "s": 23680, "text": "Open Webi Rich Client → New Document." }, { "code": null, "e": 23856, "s": 23718, "text": "Click on select a BEx query as data source. In the new window, select BICS connection in the right pane and corresponding BEx query → Ok." }, { "code": null, "e": 23972, "s": 23856, "text": "All the objects from BEx will be added to Query Panel on the left side. You can drag the objects to Result Objects." }, { "code": null, "e": 24097, "s": 23972, "text": "Once you click on Run query, all the result objects will be added to a new Webi document as shown in the following snapshot." }, { "code": null, "e": 24257, "s": 24097, "text": "Analysis view is created in BI workspace. Analysis views with custom objects are not supported and it only supports Analysis view coming from SAP NetWeaver BW." }, { "code": null, "e": 24333, "s": 24257, "text": "Open Webi Rich Client → New Document → Select Analysis view as Data source." }, { "code": null, "e": 24374, "s": 24333, "text": "Select an Analysis View, and click ‘Ok’." }, { "code": null, "e": 24508, "s": 24374, "text": "To manage multiple queries, you have an option of Data at the top right corner. This option is not available in Webi DHTML interface." }, { "code": null, "e": 24658, "s": 24508, "text": "All the data providers appear in the list to the right side of the data pane. It also tells you the Data Source, Refresh date, Duration, status, etc." }, { "code": null, "e": 24762, "s": 24658, "text": "To see the details of data, double-click on the Query. It will open the details of data added in Query." }, { "code": null, "e": 24885, "s": 24762, "text": "To edit a query, right-click on query in Data mode. Select edit or you can also select an option of Edit in the tool menu." }, { "code": null, "e": 24968, "s": 24885, "text": "You can also Rename, Delete, Copy or Purge a query using this Data Manager option." }, { "code": null, "e": 25254, "s": 24968, "text": "Query filters are used to limit the rows returned in a Webi document. Query filters allow you to hide the data that you don’t want to show to specific people and also limit the size of .wid document. When you run a query, it only returns the rows that meet the query filter definition." }, { "code": null, "e": 25308, "s": 25254, "text": "Following are the key features used in Query filter −" }, { "code": null, "e": 25368, "s": 25308, "text": "You can retrieve data as per specific business requirement." }, { "code": null, "e": 25428, "s": 25368, "text": "You can retrieve data as per specific business requirement." }, { "code": null, "e": 25512, "s": 25428, "text": "You can hide the data that you don’t want specific users to see in a Webi document." }, { "code": null, "e": 25596, "s": 25512, "text": "You can hide the data that you don’t want specific users to see in a Webi document." }, { "code": null, "e": 25688, "s": 25596, "text": "Limit the size of Webi document of the network and hence provides performance optimization." }, { "code": null, "e": 25780, "s": 25688, "text": "Limit the size of Webi document of the network and hence provides performance optimization." }, { "code": null, "e": 26079, "s": 25780, "text": "Example − Being an Area Sales Manager for NY, you want to see the margin values for your region. Sales universe contains data from all the regions in United States. Also you only want to see data from the stores in NY where the sales margin is greater than 100K USD in the second Quarter (Q2) 2015." }, { "code": null, "e": 26233, "s": 26079, "text": "Now to create a Webi document with this information, you have to apply filters on these dimensions - State, Year, and Quarter and Filter on sales margin." }, { "code": null, "e": 26249, "s": 26233, "text": "Filter Operator" }, { "code": null, "e": 26253, "s": 26249, "text": "AND" }, { "code": null, "e": 26398, "s": 26253, "text": "Query filters are applied in Query Panel and they are used to limit the number of rows from data sources and to return the same in the document." }, { "code": null, "e": 26604, "s": 26398, "text": "Report filters are applied at the report level on reports, tables, charts, etc. These filters are not used to limit the data retrieval from the data source and only hide certain values at the report level." }, { "code": null, "e": 26645, "s": 26604, "text": "Query filter is applied in this format −" }, { "code": null, "e": 26748, "s": 26645, "text": "Object (On which filter is applied), Operator (You can use various comparison operators), and Operand." }, { "code": null, "e": 26811, "s": 26748, "text": "Operand − You can select from the following list of Operands −" }, { "code": null, "e": 26820, "s": 26811, "text": "Constant" }, { "code": null, "e": 26842, "s": 26820, "text": "List of Values (LOVs)" }, { "code": null, "e": 26849, "s": 26842, "text": "Prompt" }, { "code": null, "e": 26865, "s": 26849, "text": "Universe Object" }, { "code": null, "e": 26889, "s": 26865, "text": "Result from Other Query" }, { "code": null, "e": 26947, "s": 26889, "text": "Operators − You can select from the following operators −" }, { "code": null, "e": 26960, "s": 26947, "text": "Equal to (=)" }, { "code": null, "e": 26973, "s": 26960, "text": "Not Equal to" }, { "code": null, "e": 26986, "s": 26973, "text": "Greater than" }, { "code": null, "e": 26996, "s": 26986, "text": "Less than" }, { "code": null, "e": 27018, "s": 26996, "text": "Greater than Equal to" }, { "code": null, "e": 27037, "s": 27018, "text": "Less than Equal to" }, { "code": null, "e": 27045, "s": 27037, "text": "Between" }, { "code": null, "e": 27098, "s": 27045, "text": "Following types of query filters are normally used −" }, { "code": null, "e": 27117, "s": 27098, "text": "Predefined Filters" }, { "code": null, "e": 27132, "s": 27117, "text": "Custom Filters" }, { "code": null, "e": 27146, "s": 27132, "text": "Quick Filters" }, { "code": null, "e": 27154, "s": 27146, "text": "Prompts" }, { "code": null, "e": 27207, "s": 27154, "text": "You can add multiple filter types on a single query." }, { "code": null, "e": 27344, "s": 27207, "text": "These filters are normally Administrators and saved at the Universe level. They are used to populate data that is permanently available." }, { "code": null, "e": 27560, "s": 27344, "text": "These filters require some good knowledge of database design and complex expressions. Using predefined filters on Universe means you don’t need to create custom filter every time when a new Webi document is created." }, { "code": null, "e": 27671, "s": 27560, "text": "Also note that you can’t access the components of Predefined filters and it is also not possible to edit them." }, { "code": null, "e": 27771, "s": 27671, "text": "To add a Predefined filter, you can drag or double-click this filter to Query Panel → Filters Pane." }, { "code": null, "e": 27857, "s": 27771, "text": "When you run the query, corresponding data w.r.t filters will be added to the report." }, { "code": null, "e": 27955, "s": 27857, "text": "You can use a Predefined filter by a double-click or just by dragging the filter to Query Filter." }, { "code": null, "e": 28165, "s": 27955, "text": "Quick filters are used to quickly retrieve the values you want without the use of filter editor. Quick filters use equal to operator while using a single value or list in operator when you use multiple values." }, { "code": null, "e": 28211, "s": 28165, "text": "Quick filters can’t be used with BEx queries." }, { "code": null, "e": 28313, "s": 28211, "text": "Quick filters are used in Query panel. To apply a Quick Filter, select the object you want to filter." }, { "code": null, "e": 28386, "s": 28313, "text": "Select ‘Add Quick Filter’ at the top right corner of Result Object Pane." }, { "code": null, "e": 28488, "s": 28386, "text": "New dialog box will open. You have to select the value you want to use in the Quick filter from LOVs." }, { "code": null, "e": 28623, "s": 28488, "text": "That filter will be added Query Filters pane. To delete this filter, select the filter in Query filter pane and press ‘Delete’ button." }, { "code": null, "e": 28738, "s": 28623, "text": "You can also create custom query filters to meet the business requirement or to hide the data from specific users." }, { "code": null, "e": 28911, "s": 28738, "text": "To create custom query filter, add the object you want to use in the filter. Drag it to Query filter pane. Click the arrow next to default operator and select the operator." }, { "code": null, "e": 28957, "s": 28911, "text": "Click on the arrow to select the filter type." }, { "code": null, "e": 29000, "s": 28957, "text": "You can select the following filter type −" }, { "code": null, "e": 29009, "s": 29000, "text": "Constant" }, { "code": null, "e": 29025, "s": 29009, "text": "Value from list" }, { "code": null, "e": 29032, "s": 29025, "text": "Prompt" }, { "code": null, "e": 29055, "s": 29032, "text": "Object from this query" }, { "code": null, "e": 29081, "s": 29055, "text": "Result from another query" }, { "code": null, "e": 29303, "s": 29081, "text": "Select the value from this that you want to include in the filter. To remove a filter, select the filter and press ‘Delete’ button. To remove all the filters, use ‘Remove All’ option at the top right corner of the screen." }, { "code": null, "e": 29433, "s": 29303, "text": "Prompt is defined as a special filter for users, which allows them to enter a value every time data is refreshed in the document." }, { "code": null, "e": 29617, "s": 29433, "text": "Using prompts, you have multiple users viewing one document to display different sub set of data in database. Prompts allow you to retrieve the data from database and reduce the time." }, { "code": null, "e": 29658, "s": 29617, "text": "Following are the elements of a Prompt −" }, { "code": null, "e": 29668, "s": 29658, "text": "An Object" }, { "code": null, "e": 29680, "s": 29668, "text": "An Operator" }, { "code": null, "e": 29688, "s": 29680, "text": "Message" }, { "code": null, "e": 29851, "s": 29688, "text": "Example − Current Year Equal to (“Enter the Year”). In this Prompt, Current Year is the object, “Equal to” is the Operator and prompt message is “Enter the Year”." }, { "code": null, "e": 29929, "s": 29851, "text": "A Prompt can be applied to Dimension, Measures, attributes, hierarchies, etc." }, { "code": null, "e": 30084, "s": 29929, "text": "You can use AND, OR operators to create multiple prompts in the same query. While using BEx and .unx Universe, you can only use AND operator with prompts." }, { "code": null, "e": 30334, "s": 30084, "text": "When you use multiple data providers in a single document, you can merge multiple prompts with same data type, same operator types and same prompt text are merged. While refreshing all the data providers, one prompt appears for all multiple prompts." }, { "code": null, "e": 30461, "s": 30334, "text": "LOVs displayed by merged prompt is the list associated with the object in prompt with the most displayed property constraints." }, { "code": null, "e": 30578, "s": 30461, "text": "You can also create hierarchical prompts where the following objects display their LOVs hierarchically in a Prompt −" }, { "code": null, "e": 30590, "s": 30578, "text": "Hierarchies" }, { "code": null, "e": 30597, "s": 30590, "text": "Levels" }, { "code": null, "e": 30642, "s": 30597, "text": "Dimensions associated with hierarchical LOVs" }, { "code": null, "e": 30817, "s": 30642, "text": "Hierarchical prompts are displayed in a tree form and you can navigate up and down the tree. As per the filters in Prompt, you can select items from different levels of LOVs." }, { "code": null, "e": 30906, "s": 30817, "text": "To build a prompt, add the object you want to filter with a prompt to Query Filter pane." }, { "code": null, "e": 31000, "s": 30906, "text": "Select the filter operator from the list and click on the last arrow mark to select a prompt." }, { "code": null, "e": 31065, "s": 31000, "text": "You can add the text message for Prompt value and run the query." }, { "code": null, "e": 31172, "s": 31065, "text": "When you run the query, Prompt dialog box will allow you to enter the values as per the selected operator." }, { "code": null, "e": 31289, "s": 31172, "text": "When the values are selected and you click ‘Ok’, and the data for selected values in the document will be reflected." }, { "code": null, "e": 31380, "s": 31289, "text": "When you refresh the document in Webi, prompt will appear every time to select the values." }, { "code": null, "e": 31458, "s": 31380, "text": "You can also select from existing prompts to add to the query in query panel." }, { "code": null, "e": 31557, "s": 31458, "text": "To use an existing prompt, drag the object on which prompt has to be applied to query filter pane." }, { "code": null, "e": 31704, "s": 31557, "text": "Select from Universe, select an existing Prompt → Ok. It will display the list of all prompts that are compatible with the object in Query filter." }, { "code": null, "e": 31843, "s": 31704, "text": "To delete a prompt, select the prompt in Query filter pane and press the ‘Delete’ button. You can also select Remove or Remove all option." }, { "code": null, "e": 31981, "s": 31843, "text": "You can also combine prompts with query filters to limit the data in the document and to select a specific record from the filtered data." }, { "code": null, "e": 32090, "s": 31981, "text": "Example − You can apply Query filters for Department and Year and Prompt for a specific Employee name input." }, { "code": null, "e": 32143, "s": 32090, "text": "State Not Equal to Florida\nYear 2005\nWhich Category\n" }, { "code": null, "e": 32216, "s": 32143, "text": "When you run the query, it will ask you to enter the value for Category." }, { "code": null, "e": 32342, "s": 32216, "text": "In Webi document, it will filter the data as per filters in the query panel and display the result according to Prompt value." }, { "code": null, "e": 32538, "s": 32342, "text": "You can also use multiple prompts in a single query. To add multiple prompts, drag all the objects on which you want to apply prompts. Select prompt by clicking on Arrow mark in the end of query." }, { "code": null, "e": 32730, "s": 32538, "text": "To define the order of Prompts, you have to go to Query properties at the top. From there, you can select the order of prompts as per requirement. You can move up/down a prompt from the list." }, { "code": null, "e": 32987, "s": 32730, "text": "Subqueries provides a more flexible option to filter the data as compared to an ordinary query filter. Using subqueries, you can limit the values returned with a WHERE clause. You can also compare the values of objects in a subquery with the other objects." }, { "code": null, "e": 33122, "s": 32987, "text": "Using subqueries, you can implement complex logic to limit the size of data, which is not possible to apply with simple query filters." }, { "code": null, "e": 33367, "s": 33122, "text": "Subqueries work on SQL which is used to retrieve the query data. SQL is supported by most of RDBMS and each database uses its own syntax. If any database doesn’t support SQL, an option to create a subquery will not highlight in the query panel." }, { "code": null, "e": 33467, "s": 33367, "text": "Subqueries can be built on dimensions, measures and attributes and not on the hierarchical objects." }, { "code": null, "e": 33543, "s": 33467, "text": "Select the object in the result pane on which you want to build a subquery." }, { "code": null, "e": 33682, "s": 33543, "text": "It will add a subquery outline in the Query filter pane. Now if you want to add a WHERE condition, drag an object to the area of subquery." }, { "code": null, "e": 33930, "s": 33682, "text": "Select the Operator and Value used to filter object in WHERE condition. You can add multiple subqueries to query panel. You can use “AND” or “OR” relationship between subqueries. To change the relationship, you can click on AND to change it to OR." }, { "code": null, "e": 34072, "s": 33930, "text": "By default, two subqueries are linked with an AND relationship. You can also nest a subquery. Drag a subquery to the area and drop an object." }, { "code": null, "e": 34169, "s": 34072, "text": "Parameters − You can use the following parameters while passing a subquery to Query filter pane." }, { "code": null, "e": 34256, "s": 34169, "text": "Filter Objects − These are the objects whose values are used to filter result objects." }, { "code": null, "e": 34340, "s": 34256, "text": "Filter By Objects − The object that determines which filter value subquery returns." }, { "code": null, "e": 34442, "s": 34340, "text": "Operator − This operator defines the relationship between the filter object and the filter by object." }, { "code": null, "e": 34531, "s": 34442, "text": "WHERE Condition − This is used to constraint the list of values of the filter by object." }, { "code": null, "e": 34563, "s": 34531, "text": "Relationship Operator − AND, OR" }, { "code": null, "e": 34758, "s": 34563, "text": "You can rank the unranked data from the database in your report. Database ranking allows you to rank the data at database level so when you run a query, data returned by query is already ranked." }, { "code": null, "e": 34936, "s": 34758, "text": "Database ranking is done by editing the script generated by query. If your database doesn’t support ranking, then the option to create ranking will not highlight in query panel." }, { "code": null, "e": 34998, "s": 34936, "text": "Also note that Ranking can’t be created on hierarchical data." }, { "code": null, "e": 35106, "s": 34998, "text": "First add the objects to Result Objects in Query panel. Select Add Ranking at the top of Query filter pane." }, { "code": null, "e": 35180, "s": 35106, "text": "Select the ranking dimension and type - top, bottom, top %, and bottom %." }, { "code": null, "e": 35497, "s": 35180, "text": "You can select the number of records or % of records you want the rank to return in the next box. Drag the ranking dimensions, measures, to based-on box. You can also drag dimensions to provide a calculation context to Ranked by box. You can also add WHERE condition by dragging a dimension to the bottom of ranking." }, { "code": null, "e": 35514, "s": 35497, "text": "Click Run Query." }, { "code": null, "e": 35901, "s": 35514, "text": "Webi Report can contain hierarchical and non-hierarchical data according to data source used to create the report. Hierarchical and non-hierarchical data works in different way in the report. A non-hierarchical data contains no parent-child relationship. Hierarchical data contains parent-child relationship between objects and you can use them to analyze and navigate data in a report." }, { "code": null, "e": 36033, "s": 35901, "text": "Non-hierarchical data is defined as data with no parent-child relationship. A simple example of non-hierarchical data is Dimension." }, { "code": null, "e": 36124, "s": 36033, "text": "A non-hierarchical data can be analyzed using various parameters like sorts, filters, etc." }, { "code": null, "e": 36152, "s": 36124, "text": "Example − Customer, Product" }, { "code": null, "e": 36283, "s": 36152, "text": "Hierarchical data is defined as data with Parent-child relationship and you can analyze the data at different levels of hierarchy." }, { "code": null, "e": 36392, "s": 36283, "text": "All the measures that are associated with hierarchical data are aggregated as per object level in hierarchy." }, { "code": null, "e": 36740, "s": 36392, "text": "Example − Consider a Geography hierarchy; you have Country India and State defined as Delhi. Now if you use this geographical hierarchy in report and want to analyze Number of Units sold at each level for different categories, then hierarchies allow you to use Aggregation at country level and if you drill down to state level, for each state too." }, { "code": null, "e": 36913, "s": 36740, "text": "Hierarchical data is presented in columns in hierarchical tables. Below table shows the hierarchal data in parent-child relation and aggregated on Quantity sold as measure." }, { "code": null, "e": 37069, "s": 36913, "text": "If you see the above table, the number of units sold for corresponding country India is 1200 and corresponding value at each hierarchy level is also shown." }, { "code": null, "e": 37236, "s": 37069, "text": "You can use sections to divide the information into smaller part for better analysis. Section allows business managers to analyze the data in a more effective manner." }, { "code": null, "e": 37432, "s": 37236, "text": "Example − You are an area manager in a multinational company and you have received Sales report showing total revenue for each city and quarter as shown in the following table for the year 2015 −" }, { "code": null, "e": 37565, "s": 37432, "text": "Now if you want to apply Section on Quarter column, you can compare the Total Revenue in each city compared on the basis of Quarter." }, { "code": null, "e": 37568, "s": 37565, "text": "Q1" }, { "code": null, "e": 37571, "s": 37568, "text": "Q2" }, { "code": null, "e": 37685, "s": 37571, "text": "To create a section on a column, Select the data and column, right-click on the column and select set as Section." }, { "code": null, "e": 37773, "s": 37685, "text": "To create a section from a Dimension, Go to Report Elements → Section → Insert Section." }, { "code": null, "e": 37891, "s": 37773, "text": "Click on the report area where you want to insert a Section. Choose the Dimension on which Section has to be created." }, { "code": null, "e": 38042, "s": 37891, "text": "You can also create Section on Hierarchies in the report. When a section is created on a hierarchy, each member of hierarchy becomes a section header." }, { "code": null, "e": 38095, "s": 38042, "text": "Let us understand this with the help of an Example −" }, { "code": null, "e": 38177, "s": 38095, "text": "If you create a section on Customer Geography, you will get the following report." }, { "code": null, "e": 38245, "s": 38177, "text": "By expanding the Section header, you will get the following report." }, { "code": null, "e": 38310, "s": 38245, "text": "To delete a Section, right-click on the section Select → Delete." }, { "code": null, "e": 38450, "s": 38310, "text": "If you select ‘Cell Only’, it will delete ‘Section Cell’ only and if you select ‘Cell and Section’, it will remove ‘Section and Cell’ both." }, { "code": null, "e": 38547, "s": 38450, "text": "To Hide Sections − Select Section. Go to Report Elements → Behaviors → Hide to hide the section." }, { "code": null, "e": 38605, "s": 38547, "text": "‘Hide When Empty’ is used to hide the section when empty." }, { "code": null, "e": 38710, "s": 38605, "text": "‘Hide When-Enter the formula’ is used to hide the Section. If formula is true, it will hide the section." }, { "code": null, "e": 38829, "s": 38710, "text": "Breaks are used to define all data for every unique value of an object in separate parts. Using Breaks you can apply −" }, { "code": null, "e": 38860, "s": 38829, "text": "Subtotals and Sub aggregations" }, { "code": null, "e": 38898, "s": 38860, "text": "Display data in more effective manner" }, { "code": null, "e": 39075, "s": 38898, "text": "Section breaks up the data into multiple cells that are called section headers and each section header contains a value for dimension and data corresponding to dimension value." }, { "code": null, "e": 39242, "s": 39075, "text": "Break is used to divide the data into one block and each column carries dimension, attributes and measures. These values are repeated for each row value in the block." }, { "code": null, "e": 39343, "s": 39242, "text": "Select the column in which you want to insert a Break. Go to Analysis → Display → Break → Add Break." }, { "code": null, "e": 39434, "s": 39343, "text": "This will divide the table into many mini tables as there are unique values in the column." }, { "code": null, "e": 39481, "s": 39434, "text": "To manage a break, you should use Design mode." }, { "code": null, "e": 39594, "s": 39481, "text": "Go to Analysis → Display → Break → Manage Break. It will open a new window and show all the breaks in the table." }, { "code": null, "e": 39713, "s": 39594, "text": "You can define the following properties about Break in this dialog box. You can prioritize Break using up-down arrows." }, { "code": null, "e": 39732, "s": 39713, "text": "Display Properties" }, { "code": null, "e": 39744, "s": 39732, "text": "Page Layout" }, { "code": null, "e": 39761, "s": 39744, "text": "Duplicate Values" }, { "code": null, "e": 39820, "s": 39761, "text": "You can also Add or Remove a Break using Break Properties." }, { "code": null, "e": 40047, "s": 39820, "text": "Sorting can be applied in table on sections, charts to organize the data in a specific order in a Webi report. Default sorting that is applied in a report is from left to right order of objects in Result object of Query Panel." }, { "code": null, "e": 40087, "s": 40047, "text": "You have the following Sorting Orders −" }, { "code": null, "e": 40145, "s": 40087, "text": "Default − This is default order where data is sorted as −" }, { "code": null, "e": 40186, "s": 40145, "text": "Ascending numeric order for numeric data" }, { "code": null, "e": 40227, "s": 40186, "text": "Ascending numeric order for numeric data" }, { "code": null, "e": 40265, "s": 40227, "text": "Ascending chronological order on date" }, { "code": null, "e": 40303, "s": 40265, "text": "Ascending chronological order on date" }, { "code": null, "e": 40334, "s": 40303, "text": "Chronological order for months" }, { "code": null, "e": 40365, "s": 40334, "text": "Chronological order for months" }, { "code": null, "e": 40406, "s": 40365, "text": "Alphabetical order for alphanumeric data" }, { "code": null, "e": 40447, "s": 40406, "text": "Alphabetical order for alphanumeric data" }, { "code": null, "e": 40580, "s": 40447, "text": "Ascending − In this, smallest value at the top to highest value at the bottom. Example − 1000, 2000, 3000, or Delhi, Kolkata, Mumbai" }, { "code": null, "e": 40713, "s": 40580, "text": "Ascending − In this, smallest value at the top to highest value at the bottom. Example − 1000, 2000, 3000, or Delhi, Kolkata, Mumbai" }, { "code": null, "e": 40792, "s": 40713, "text": "Descending − In this, highest value at the top to smallest value at the bottom" }, { "code": null, "e": 40871, "s": 40792, "text": "Descending − In this, highest value at the top to smallest value at the bottom" }, { "code": null, "e": 41029, "s": 40871, "text": "Custom − Using this, you can define your own sort order. Custom orders are available on dimensions and attributes and not on hierarchies, measures and level." }, { "code": null, "e": 41111, "s": 41029, "text": "To insert a sort, open report in Design mode. Select the Column you want to sort." }, { "code": null, "e": 41166, "s": 41111, "text": "Go to Analysis → Display → Sort → Ascending/Descending" }, { "code": null, "e": 41298, "s": 41166, "text": "You can apply multiple sorts in a single table on different columns. You can use ‘Remove All Sorts’ option to delete all the sorts." }, { "code": null, "e": 41470, "s": 41298, "text": "To manage the Order of Sorts, go to Advance tab. You can define order for all sorts using up and down arrows. You can define Custom Sorts here if no other sort is applied." }, { "code": null, "e": 41513, "s": 41470, "text": "This can also be used to Add/Remove Sorts." }, { "code": null, "e": 41637, "s": 41513, "text": "In a Webi document, you can include one or more charts. You can insert charts in an existing document or in a new document." }, { "code": null, "e": 41754, "s": 41637, "text": "When a Webi document containing chart is exported into an Excel or PDF format, the chart is converted into an image." }, { "code": null, "e": 41877, "s": 41754, "text": "You can convert the tables in a Webi report into different chart types. There are different Chart types available in Webi." }, { "code": null, "e": 42036, "s": 41877, "text": "Bar charts are used to compare similar groups of data and they display data in rectangular form horizontally. Following are the different types of Bar Chart −" }, { "code": null, "e": 42046, "s": 42036, "text": "Bar Chart" }, { "code": null, "e": 42064, "s": 42046, "text": "Stacked Bar Chart" }, { "code": null, "e": 42087, "s": 42064, "text": "100% Stacked Bar Chart" }, { "code": null, "e": 42349, "s": 42087, "text": "As mentioned in description of box charts, it is a graphical display of a five number summary based on distribution of a dataset: the maximum, the minimum, the first quartile, the third quartile, and the median. It can also show abnormal values called outliers." }, { "code": null, "e": 42522, "s": 42349, "text": "Column charts are constructed of vertically-oriented rectangular bars. The height of the rectangles are proportional to the values associated with different category items." }, { "code": null, "e": 42575, "s": 42522, "text": "Following are the different types of Column charts −" }, { "code": null, "e": 42588, "s": 42575, "text": "Column Chart" }, { "code": null, "e": 42615, "s": 42588, "text": "Column Chart with 2 Y-axes" }, { "code": null, "e": 42642, "s": 42615, "text": "Combined column Line Chart" }, { "code": null, "e": 42663, "s": 42642, "text": "Stacked Column Chart" }, { "code": null, "e": 42689, "s": 42663, "text": "100% Stacked Column Chart" }, { "code": null, "e": 42705, "s": 42689, "text": "3D Column Chart" }, { "code": null, "e": 42893, "s": 42705, "text": "An XY chart that displays lines connecting plots. Value axis plot positions are expressed by analysis category items. The second value axis plot positions represent the associated values." }, { "code": null, "e": 42943, "s": 42893, "text": "Following are the different types of Line Chart −" }, { "code": null, "e": 42954, "s": 42943, "text": "Line Chart" }, { "code": null, "e": 42979, "s": 42954, "text": "Line Chart with 2 Y Axes" }, { "code": null, "e": 42990, "s": 42979, "text": "Area Chart" }, { "code": null, "e": 43203, "s": 42990, "text": "This chart displays values within nested rectangles that can be colored. The levels of nesting correspond to the levels of hierarchy breakdown. The size of rectangles and their color both express a set of values." }, { "code": null, "e": 43253, "s": 43203, "text": "Following are the different types of Map Charts −" }, { "code": null, "e": 43262, "s": 43253, "text": "Tree Map" }, { "code": null, "e": 43271, "s": 43262, "text": "Heat Map" }, { "code": null, "e": 43405, "s": 43271, "text": "A circular chart made up of sectors. The area of circle represents a whole, and the sectors of circle represent the parts of a whole." }, { "code": null, "e": 43437, "s": 43405, "text": "Different types of Pie Charts −" }, { "code": null, "e": 43447, "s": 43437, "text": "Pie Chart" }, { "code": null, "e": 43483, "s": 43447, "text": "Pie Chart with Variable Slice Depth" }, { "code": null, "e": 43495, "s": 43483, "text": "Donut Chart" }, { "code": null, "e": 43611, "s": 43495, "text": "Point chart is an XY chart displaying plots. Plots are positioned with coordinates represented by a pair of values." }, { "code": null, "e": 43662, "s": 43611, "text": "Following are the different type of Point Charts −" }, { "code": null, "e": 43675, "s": 43662, "text": "Scatter Plot" }, { "code": null, "e": 43688, "s": 43675, "text": "Bubble Chart" }, { "code": null, "e": 43708, "s": 43688, "text": "Polar Scatter Chart" }, { "code": null, "e": 43727, "s": 43708, "text": "Polar Bubble Chart" }, { "code": null, "e": 43835, "s": 43727, "text": "It is also known as Spider chart and displays several axes starting from unique origin with a common scale." }, { "code": null, "e": 43963, "s": 43835, "text": "A mono dimensional visualization representing data as words where the word font size represents its relative weight in dataset." }, { "code": null, "e": 44079, "s": 43963, "text": "It is used to show the cumulative effect of values of a measure and each bar starts with the level of previous one." }, { "code": null, "e": 44182, "s": 44079, "text": "You should be in Design mode to add a chart. There are different ways to add a chart to a Webi Report." }, { "code": null, "e": 44291, "s": 44182, "text": "Go to Report Element → Chart → Select a Chart and click on the report area where you want to insert a chart." }, { "code": null, "e": 44435, "s": 44291, "text": "Chart is greyed when there is no data assigned to it. To assign data, you can drag the object from the list of available objects to chart axes." }, { "code": null, "e": 44633, "s": 44435, "text": "Right-click → Insert → Select the Chart type as shown in the following screenshot. Click the report to add a blank chart and then assign data by dragging objects from the list of available objects." }, { "code": null, "e": 44794, "s": 44633, "text": "Another method is by converting a table into chart. You can do this by selecting a table in a Webi report. Right-click on a column → Turn Into → Select a Chart." }, { "code": null, "e": 44843, "s": 44794, "text": "The table will be converted into a column chart." }, { "code": null, "e": 44982, "s": 44843, "text": "You can also copy a chart from a Webi report to the same report or to an application. To copy a chart, you have to first select the chart." }, { "code": null, "e": 45041, "s": 44982, "text": "To copy a Chart, right-click on the chart and select copy." }, { "code": null, "e": 45138, "s": 45041, "text": "Now to paste this chart in the same report, select an area in the report. Right-click and Paste." }, { "code": null, "e": 45324, "s": 45138, "text": "To copy this chart to an application, you can drag the chart directly to an open application or this can be done by copying the chart to the clipboard and pasting it in the application." }, { "code": null, "e": 45419, "s": 45324, "text": "To delete a chart, you can select a chart. Right-click → press Delete or select delete option." }, { "code": null, "e": 45495, "s": 45419, "text": "Select the table or Chart → Right-click → Turn into → More Transformations." }, { "code": null, "e": 45661, "s": 45495, "text": "Once you click on More Transformation, it will open a window with different Chart options. You can select any chart type and the chart will be changed in the report." }, { "code": null, "e": 45903, "s": 45661, "text": "You can also resize the chart by using the mouse option. Right-click the chart and select format chart option. It will open a new window. Go to General tab → Width and Height option → Select the chart parameters. Click ‘Apply’ and then ‘Ok’." }, { "code": null, "e": 45970, "s": 45903, "text": "To format a chart → Select the chart → Right-click → Format Chart." }, { "code": null, "e": 46035, "s": 45970, "text": "Following are the various chart properties you can choose from −" }, { "code": null, "e": 46048, "s": 46035, "text": "Area Display" }, { "code": null, "e": 46059, "s": 46048, "text": "Data Value" }, { "code": null, "e": 46070, "s": 46059, "text": "Background" }, { "code": null, "e": 46077, "s": 46070, "text": "Border" }, { "code": null, "e": 46090, "s": 46077, "text": "Layout, etc." }, { "code": null, "e": 46167, "s": 46090, "text": "Once you make Title label visible, it will be displayed at the top of Chart." }, { "code": null, "e": 46393, "s": 46167, "text": "Conditional Formatting is used to highlight some specific values in the report. If you want you can show specific low or high values with some specific colors. Conditional formatting can be applied to the following elements −" }, { "code": null, "e": 46416, "s": 46393, "text": "Rows in horizon tables" }, { "code": null, "e": 46443, "s": 46416, "text": "Columns in vertical tables" }, { "code": null, "e": 46475, "s": 46443, "text": "Cells in forms and cross-tables" }, { "code": null, "e": 46484, "s": 46475, "text": "Sections" }, { "code": null, "e": 46503, "s": 46484, "text": "Free holding cells" }, { "code": null, "e": 46665, "s": 46503, "text": "Condition formatting can be used to make the following formatting changes − Text color, size and style, cell border, color, size and style, and cell backgrounds." }, { "code": null, "e": 46738, "s": 46665, "text": "You can add up to 30 conditional formatting formulas in a Webi document." }, { "code": null, "e": 46882, "s": 46738, "text": "To create a conditional formula, open the report in Design mode. You must be using Rich client or App Interface and shouldn’t work in Web mode." }, { "code": null, "e": 46960, "s": 46882, "text": "Go to Analysis → Conditional → New Rule. It will open formatting rule editor." }, { "code": null, "e": 47054, "s": 46960, "text": "Enter the rule name and description. Select the cell contents in filtered object or cell box." }, { "code": null, "e": 47198, "s": 47054, "text": "You can select Operator and Operands value. You have to define text formatting in Format tab. Click on Format to set the formatting of the tab." }, { "code": null, "e": 47346, "s": 47198, "text": "You can select the font, font style, size, effects (underline, etc.) and alignment. Once formatting is defined for condition, you have to click Ok." }, { "code": null, "e": 47531, "s": 47346, "text": "Now to apply conditional formatting to the object, select the column in the report. Go to formatting rules dropdown → Select the conditional formatting rules checkbox you have created." }, { "code": null, "e": 47673, "s": 47531, "text": "Conditional formatting will be applied to the desired cells. You can add multiple conditions in a single formatting rule on multiple objects." }, { "code": null, "e": 47722, "s": 47673, "text": "Go to Analysis tab → Conditional → Manage Rules." }, { "code": null, "e": 47912, "s": 47722, "text": "Once you click ‘Manage Rules’, it will open window for Conditional Formats. To edit a rule, select the rule and click on Edit. You can also change the order of Conditional Formatting rules." }, { "code": null, "e": 47992, "s": 47912, "text": "You can also duplicate/remove conditional formatting rules using Manage option." }, { "code": null, "e": 48154, "s": 47992, "text": "You can filter the data in a report to limit the data displayed in a Webi document. You can select filter condition to present the data that is of your interest." }, { "code": null, "e": 48274, "s": 48154, "text": "Data filtered using Report filters remain in the document and any time you can remove the filters to check hidden data." }, { "code": null, "e": 48344, "s": 48274, "text": "You have to mention the following elements to create report filters −" }, { "code": null, "e": 48360, "s": 48344, "text": "Filtered object" }, { "code": null, "e": 48369, "s": 48360, "text": "Operator" }, { "code": null, "e": 48382, "s": 48369, "text": "Filter value" }, { "code": null, "e": 48428, "s": 48382, "text": "Report element where filter has to be applied" }, { "code": null, "e": 48521, "s": 48428, "text": "Example − You can apply a filter to see data related to a specific customer or sales region." }, { "code": null, "e": 48675, "s": 48521, "text": "Query filters are defined at query level in query panel and they are used to limit the data retrieved from the data source and return to a Webi document." }, { "code": null, "e": 48846, "s": 48675, "text": "Report filters are used to hide the data in a table, report, chart, section in a Webi document. Report filters don’t edit the data that is retrieved from the data source." }, { "code": null, "e": 48975, "s": 48846, "text": "You can use various operators to filter the data at the report level. Following are some of the common report filter operators −" }, { "code": null, "e": 48984, "s": 48975, "text": "Equal To" }, { "code": null, "e": 48997, "s": 48984, "text": "Not Equal To" }, { "code": null, "e": 49021, "s": 48997, "text": "Different From Operator" }, { "code": null, "e": 49034, "s": 49021, "text": "Greater Than" }, { "code": null, "e": 49059, "s": 49034, "text": "Greater Than or Equal To" }, { "code": null, "e": 49069, "s": 49059, "text": "Less Than" }, { "code": null, "e": 49091, "s": 49069, "text": "Less Than or Equal To" }, { "code": null, "e": 49099, "s": 49091, "text": "Between" }, { "code": null, "e": 49111, "s": 49099, "text": "Not Between" }, { "code": null, "e": 49119, "s": 49111, "text": "In List" }, { "code": null, "e": 49131, "s": 49119, "text": "Not In List" }, { "code": null, "e": 49139, "s": 49131, "text": "Is Null" }, { "code": null, "e": 49151, "s": 49139, "text": "Is Not Null" }, { "code": null, "e": 49206, "s": 49151, "text": "You can create the following types of report filters −" }, { "code": null, "e": 49351, "s": 49206, "text": "Standard Report Filters − These filters are used to filter on a single value or lists of values. These are most flexible type of report filters." }, { "code": null, "e": 49496, "s": 49351, "text": "Standard Report Filters − These filters are used to filter on a single value or lists of values. These are most flexible type of report filters." }, { "code": null, "e": 49624, "s": 49496, "text": "Simple Report Filters− They provide an easy way to create filters using Equal to operator. These filters apply on single value." }, { "code": null, "e": 49752, "s": 49624, "text": "Simple Report Filters− They provide an easy way to create filters using Equal to operator. These filters apply on single value." }, { "code": null, "e": 49833, "s": 49752, "text": "Select the Report Element you want to apply a filter. Go to Filter → Add Filter." }, { "code": null, "e": 49952, "s": 49833, "text": "It will open the Report Filter dialog box. You can add objects, operand and value to apply filter at the report level." }, { "code": null, "e": 50052, "s": 49952, "text": "Using the functions − Add Filter, Remove or Remove All − you can add or delete filters accordingly." }, { "code": null, "e": 50114, "s": 50052, "text": "To Edit a Filter → Go to Analysis Tab → Filter → Edit Filter." }, { "code": null, "e": 50194, "s": 50114, "text": "You can make changes to filters in Report Filter Dialog box. Click Ok to apply." }, { "code": null, "e": 50289, "s": 50194, "text": "To Delete a Filter, Go to Analysis → Filter → Remove Filter. Click “Yes” to remove the filter." }, { "code": null, "e": 50551, "s": 50289, "text": "Input controls are used to filter and analyze the report data. You define input controls using text boxes and radio buttons. Input controls are associated with report elements, like tables and section headers, and use control to apply filter on report elements." }, { "code": null, "e": 50695, "s": 50551, "text": "When you select a value for input control, it filters the values in the report element that is associated with input control by selected value." }, { "code": null, "e": 50749, "s": 50695, "text": "Input controls can also be used on hierarchical data." }, { "code": null, "e": 50861, "s": 50749, "text": "You should be in Design mode to use input controls. Go to Analysis → Filters → Input Controls → Define Control." }, { "code": null, "e": 50966, "s": 50861, "text": "It will open Define Input Control dialog. Select the report object used to filter data and click ‘Next’." }, { "code": null, "e": 51204, "s": 50966, "text": "Note that if you select a Report element and then you select Define Control, you will get an option to include objects from selected block only. If you select this checkbox, it will show you objects only from the selected report element." }, { "code": null, "e": 51516, "s": 51204, "text": "You will get an option to choose and define control. Choose control allows you to select different control types like single value or multiple values. Define control allows you to select the name of control, description, values in control to select, operator and number of lines displayed in input control, etc." }, { "code": null, "e": 51754, "s": 51516, "text": "In the next window, you have to assign Report Elements. It will allow you to choose from report elements. You can assign report elements to input controls. (Example − I have selected as input control from both the blocks as shown below)." }, { "code": null, "e": 51844, "s": 51754, "text": "Click ‘Finish’ and input controls will be added to the left pane under Input Control tab." }, { "code": null, "e": 51952, "s": 51844, "text": "Now as per your selection of input control and type of input control, data will be reflected in the report." }, { "code": null, "e": 52038, "s": 51952, "text": "To edit an input control → Select Input control from the left pane → Click Edit icon." }, { "code": null, "e": 52126, "s": 52038, "text": "It will open Edit Input Control dialog box. Make changes to Input Control and click Ok." }, { "code": null, "e": 52196, "s": 52126, "text": "To organize input controls, go to Input control tab on the left pane." }, { "code": null, "e": 52334, "s": 52196, "text": "Drag and drop input controls to move them up/down on input controls pane. Just hold the input control dialog box and move it up and down." }, { "code": null, "e": 52380, "s": 52334, "text": "Use the “x” mark to remove the input control." }, { "code": null, "e": 52461, "s": 52380, "text": "To view map of input control, select the input control → Click ‘Map’ at the top." }, { "code": null, "e": 52593, "s": 52461, "text": "You can also use a table or chart to define input control. Select the table → Right-click and select linking → Add Element Linking." }, { "code": null, "e": 52685, "s": 52593, "text": "You can select a single object or all objects to define as filtering objects. Click ‘Next’." }, { "code": null, "e": 52861, "s": 52685, "text": "You can enter the name and description of input control. Click ‘Next’. Once you click Next, you can select any other block to use this object as input control. Click ‘Finish’." }, { "code": null, "e": 52935, "s": 52861, "text": "Similarly, you can use charts as input control for other Report elements." }, { "code": null, "e": 52996, "s": 52935, "text": "You can also insert formulas and variables in a Webi report." }, { "code": null, "e": 53120, "s": 52996, "text": "To enter a formula in Webi report, the report should be opened in Design mode. Click the formula editor to enter a formula." }, { "code": null, "e": 53253, "s": 53120, "text": "Once the formula editor is open, build the formula. If the formula editor is not visible, go to Properties tab → View → Formula Bar." }, { "code": null, "e": 53322, "s": 53253, "text": "The report should be in Design mode to create a Variable in formula." }, { "code": null, "e": 53417, "s": 53322, "text": "To create a variable, click on Create Variable icon in formula bar to display variable editor." }, { "code": null, "e": 53559, "s": 53417, "text": "Enter the name of Variable, Qualification - Dimension, Measure, and Detail. If you select Detail, it opens a new field - Associate dimension." }, { "code": null, "e": 53782, "s": 53559, "text": "Enter the formula for variable, you can select from the list of available objects, functions and operators to create a formula. You can click on the tick mark to validate the formula. Once the formula is defined, click Ok." }, { "code": null, "e": 53920, "s": 53782, "text": "On the left side, you can see this new variable in the list of available objects. To use this variable, you can drag this to Webi report." }, { "code": null, "e": 54073, "s": 53920, "text": "You can also edit or delete the variable. To edit/delete a variable, select the variable from the list of available objects → right-click → Edit/Remove." }, { "code": null, "e": 54228, "s": 54073, "text": "The drill option is used to analyze data at different levels. With drilling you can go to the next levels to analyze data in tables, charts, and sections." }, { "code": null, "e": 54401, "s": 54228, "text": "You can also specify how drill options will make changes to reports when you perform drilling in Webi. Setting drill options depends on the Web Intelligence interface used." }, { "code": null, "e": 54414, "s": 54401, "text": "BI Launchpad" }, { "code": null, "e": 54431, "s": 54414, "text": "Webi Rich Client" }, { "code": null, "e": 54712, "s": 54431, "text": "Note that to use drill option, you should have hierarchy defined at Universe level. Once you have hierarchy at Universe, you can add that object to Result objects in Query panel. Once you run the query, the object will be added to the list of available objects in a Webi document." }, { "code": null, "e": 54797, "s": 54712, "text": "Drill allows you to move to level up or level down as per the hierarchy in Universe." }, { "code": null, "e": 54888, "s": 54797, "text": "To set drill option in a Webi report, go to Analysis tab → Interact → Drill → Start Drill." }, { "code": null, "e": 54989, "s": 54888, "text": "Once you start drill, you can move to the next levels or end drill using the option in the same tab." }, { "code": null, "e": 55171, "s": 54989, "text": "Example − Drill on 2015 - the results displayed on the drilled table are Q1, Q2, Q3, and Q4 for the year 2015. This means that the quarterly values you drilled are filtered by 2015." }, { "code": null, "e": 55301, "s": 55171, "text": "You can also take a snapshot of Drill result in a separate report. Use the snapshot option to add a new report with drilled data." }, { "code": null, "e": 55453, "s": 55301, "text": "You can publish a Webi content outside Webi documents by publishing report elements like charts and tables as web services. This is called BI services." }, { "code": null, "e": 55662, "s": 55453, "text": "To publish a Webi document as web services, open the report in Design mode. You can use Publish Content Wizard to publish Webi document. The report should be saved in BI repository to publish as web services." }, { "code": null, "e": 55757, "s": 55662, "text": "Select the Report Element you want to publish, right-click and click ‘Publish as Web Service’." }, { "code": null, "e": 55815, "s": 55757, "text": "This will open the Publish Content Wizard → Click ‘Next’." }, { "code": null, "e": 55966, "s": 55815, "text": "For web services, you should reproduce prompts multiple times to produce different responses. Select the prompts you want to Publish and click ‘Next’." }, { "code": null, "e": 56101, "s": 55966, "text": "If you don’t select any prompts for publishing, web services uses prompt value that was supplied when the document was last refreshed." }, { "code": null, "e": 56339, "s": 56101, "text": "Before publishing a block as a web service, you use the ‘Define Published Content’ screen in the publish content wizard to name the table, make filters available on the block data, and select the server where the block will be published." }, { "code": null, "e": 56512, "s": 56339, "text": "You use the ‘Publish new content’ or ‘Re-publish Existing Content as Web Service’ screen in the Publish Content wizard to save and publish the web service to a host server." }, { "code": null, "e": 56592, "s": 56512, "text": "To re-publish an existing web service, select the web service, click ‘Publish’." }, { "code": null, "e": 56744, "s": 56592, "text": "To publish a new web service, select the folder where you want to publish the content and click ‘Create to display the Publish Web Service’ dialog box." }, { "code": null, "e": 56906, "s": 56744, "text": "Enter the name of the web service in the web service box and add the description → Select Authentication method for the web service from the Authentication list." }, { "code": null, "e": 56961, "s": 56906, "text": "Click Ok and it will save and publish the web service." }, { "code": null, "e": 57026, "s": 56961, "text": "Choose the web service where you want to publish → Click Finish." }, { "code": null, "e": 57294, "s": 57026, "text": "This option allows you to merge the data from different data sources. Assume that you have created Query 1 and Query 2 in Query Panel. When you combine both the queries in a single Webi report, objects from both the queries are shown in the list of available objects." }, { "code": null, "e": 57392, "s": 57294, "text": "Select the unique object from both the queries and click Ok as shown in the following screenshot." }, { "code": null, "e": 57462, "s": 57392, "text": "It will create a Merge Dimension under the list of available objects." }, { "code": null, "e": 57746, "s": 57462, "text": "It allows you to synch both the queries and you can add the objects from both the queries in a single report. Sometimes it doesn’t allow you to add objects in the report from either of the queries because of sync issues. In such a case, you can create a new variable for that object." }, { "code": null, "e": 57918, "s": 57746, "text": "Enter the variable name, qualification as “Detail” and it will add a new field ‘Associate Dimension’. In Associate dimension, select the unique object from the same query." }, { "code": null, "e": 58057, "s": 57918, "text": "In the Formula tab, select the object from the list of available objects for which you want to create a new variable and click ‘Validate’." }, { "code": null, "e": 58143, "s": 58057, "text": "Once the variable is created for that object, you can drag that object to the report." }, { "code": null, "e": 58176, "s": 58143, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 58190, "s": 58176, "text": " Sanjo Thomas" }, { "code": null, "e": 58223, "s": 58190, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 58235, "s": 58223, "text": " Neha Gupta" }, { "code": null, "e": 58270, "s": 58235, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 58285, "s": 58270, "text": " Sumit Agarwal" }, { "code": null, "e": 58318, "s": 58285, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 58333, "s": 58318, "text": " Sumit Agarwal" }, { "code": null, "e": 58368, "s": 58333, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58380, "s": 58368, "text": " Neha Malik" }, { "code": null, "e": 58415, "s": 58380, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 58427, "s": 58415, "text": " Neha Malik" }, { "code": null, "e": 58434, "s": 58427, "text": " Print" }, { "code": null, "e": 58445, "s": 58434, "text": " Add Notes" } ]
Java String equalsIgnoreCase() Method with Examples - GeeksforGeeks
10 Nov, 2021 The equalsIgnoreCase() method of the String class compares two strings irrespective of the case (lower or upper) of the string. This method returns a boolean value, true if the argument is not null and represents an equivalent String ignoring case, else false. Syntax: str2.equalsIgnoreCase(str1); Note: Here str1 and str2 both are the strings that we need to compare. Parameters: A string that is supposed to be compared. Return Type: A boolean value, true if the argument is not null and it represents an equivalent String ignoring case, else false. Illustrations: Input : str1 = "pAwAn"; str2 = "PAWan" str2.equalsIgnoreCase(str1); Output :true Input : str1 = "powAn"; str2 = "PAWan" str2.equalsIgnoreCase(str1); Output :false Explanation: powan and pawan are different strings. Note: str1 is a string that needs to be compared with str2. Example: Java // Java Program to Illustrate equalsIgnoreCase() method // Importing required classesimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing strings to compare String str1 = "GeeKS FOr gEEks"; String str2 = "geeKs foR gEEKs"; String str3 = "ksgee orF geeks"; // Comparing strings // If we ignore the cases boolean result1 = str2.equalsIgnoreCase(str1); // Both the strings are equal so display true System.out.println("str2 is equal to str1 = " + result1); // Even if we ignore the cases boolean result2 = str2.equalsIgnoreCase(str3); // Both the strings are not equal so display false System.out.println("str2 is equal to str3 = " + result2); }} str2 is equal to str1 = true str2 is equal to str3 = false nishkarshgandhi sweetyty solankimayank Java-Functions Java-lang package Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples StringBuilder Class in Java with Examples HashMap get() Method in Java Functional Interfaces in Java Strings in Java
[ { "code": null, "e": 23893, "s": 23865, "text": "\n10 Nov, 2021" }, { "code": null, "e": 24154, "s": 23893, "text": "The equalsIgnoreCase() method of the String class compares two strings irrespective of the case (lower or upper) of the string. This method returns a boolean value, true if the argument is not null and represents an equivalent String ignoring case, else false." }, { "code": null, "e": 24163, "s": 24154, "text": "Syntax: " }, { "code": null, "e": 24192, "s": 24163, "text": "str2.equalsIgnoreCase(str1);" }, { "code": null, "e": 24263, "s": 24192, "text": "Note: Here str1 and str2 both are the strings that we need to compare." }, { "code": null, "e": 24317, "s": 24263, "text": "Parameters: A string that is supposed to be compared." }, { "code": null, "e": 24446, "s": 24317, "text": "Return Type: A boolean value, true if the argument is not null and it represents an equivalent String ignoring case, else false." }, { "code": null, "e": 24462, "s": 24446, "text": "Illustrations: " }, { "code": null, "e": 24559, "s": 24462, "text": "Input : str1 = \"pAwAn\";\n str2 = \"PAWan\"\n str2.equalsIgnoreCase(str1);\nOutput :true" }, { "code": null, "e": 24710, "s": 24559, "text": "Input : str1 = \"powAn\";\n str2 = \"PAWan\"\n str2.equalsIgnoreCase(str1);\nOutput :false\nExplanation: powan and pawan are different strings. " }, { "code": null, "e": 24770, "s": 24710, "text": "Note: str1 is a string that needs to be compared with str2." }, { "code": null, "e": 24779, "s": 24770, "text": "Example:" }, { "code": null, "e": 24784, "s": 24779, "text": "Java" }, { "code": "// Java Program to Illustrate equalsIgnoreCase() method // Importing required classesimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing strings to compare String str1 = \"GeeKS FOr gEEks\"; String str2 = \"geeKs foR gEEKs\"; String str3 = \"ksgee orF geeks\"; // Comparing strings // If we ignore the cases boolean result1 = str2.equalsIgnoreCase(str1); // Both the strings are equal so display true System.out.println(\"str2 is equal to str1 = \" + result1); // Even if we ignore the cases boolean result2 = str2.equalsIgnoreCase(str3); // Both the strings are not equal so display false System.out.println(\"str2 is equal to str3 = \" + result2); }}", "e": 25681, "s": 24784, "text": null }, { "code": null, "e": 25740, "s": 25681, "text": "str2 is equal to str1 = true\nstr2 is equal to str3 = false" }, { "code": null, "e": 25756, "s": 25740, "text": "nishkarshgandhi" }, { "code": null, "e": 25765, "s": 25756, "text": "sweetyty" }, { "code": null, "e": 25779, "s": 25765, "text": "solankimayank" }, { "code": null, "e": 25794, "s": 25779, "text": "Java-Functions" }, { "code": null, "e": 25812, "s": 25794, "text": "Java-lang package" }, { "code": null, "e": 25825, "s": 25812, "text": "Java-Strings" }, { "code": null, "e": 25830, "s": 25825, "text": "Java" }, { "code": null, "e": 25843, "s": 25830, "text": "Java-Strings" }, { "code": null, "e": 25848, "s": 25843, "text": "Java" }, { "code": null, "e": 25946, "s": 25848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25955, "s": 25946, "text": "Comments" }, { "code": null, "e": 25968, "s": 25955, "text": "Old Comments" }, { "code": null, "e": 26014, "s": 25968, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26035, "s": 26014, "text": "Constructors in Java" }, { "code": null, "e": 26050, "s": 26035, "text": "Stream In Java" }, { "code": null, "e": 26069, "s": 26050, "text": "Exceptions in Java" }, { "code": null, "e": 26086, "s": 26069, "text": "Generics in Java" }, { "code": null, "e": 26129, "s": 26086, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26171, "s": 26129, "text": "StringBuilder Class in Java with Examples" }, { "code": null, "e": 26200, "s": 26171, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26230, "s": 26200, "text": "Functional Interfaces in Java" } ]
C Program to display hostname and IP address - GeeksforGeeks
24 Nov, 2017 There are many ways to find Hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using C program. We will be using the following functions :- gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database. inet_ntoa() : The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format. C/C++ // C program to display hostname// and IP address#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <netdb.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> // Returns hostname for the local computervoid checkHostName(int hostname){ if (hostname == -1) { perror("gethostname"); exit(1); }} // Returns host information corresponding to host namevoid checkHostEntry(struct hostent * hostentry){ if (hostentry == NULL) { perror("gethostbyname"); exit(1); }} // Converts space-delimited IPv4 addresses// to dotted-decimal formatvoid checkIPbuffer(char *IPbuffer){ if (NULL == IPbuffer) { perror("inet_ntoa"); exit(1); }} // Driver codeint main(){ char hostbuffer[256]; char *IPbuffer; struct hostent *host_entry; int hostname; // To retrieve hostname hostname = gethostname(hostbuffer, sizeof(hostbuffer)); checkHostName(hostname); // To retrieve host information host_entry = gethostbyname(hostbuffer); checkHostEntry(host_entry); // To convert an Internet network // address into ASCII string IPbuffer = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); printf("Hostname: %s\n", hostbuffer); printf("Host IP: %s", IPbuffer); return 0;} Hostname: cContainer Host IP: 10.98.162.101 Output varies machine to machine C Language C++ Computer Networks Computer Networks CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Command line arguments in C/C++ Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Multidimensional Arrays in C / C++
[ { "code": null, "e": 24528, "s": 24500, "text": "\n24 Nov, 2017" }, { "code": null, "e": 24673, "s": 24528, "text": "There are many ways to find Hostname and IP address of a local machine. Here is a simple method to find hostname and IP address using C program." }, { "code": null, "e": 24717, "s": 24673, "text": "We will be using the following functions :-" }, { "code": null, "e": 24815, "s": 24717, "text": "gethostname() : The gethostname function retrieves the standard host name for the local computer." }, { "code": null, "e": 24938, "s": 24815, "text": "gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database." }, { "code": null, "e": 25084, "s": 24938, "text": "inet_ntoa() : The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format." }, { "code": null, "e": 25090, "s": 25084, "text": "C/C++" }, { "code": "// C program to display hostname// and IP address#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <netdb.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h> // Returns hostname for the local computervoid checkHostName(int hostname){ if (hostname == -1) { perror(\"gethostname\"); exit(1); }} // Returns host information corresponding to host namevoid checkHostEntry(struct hostent * hostentry){ if (hostentry == NULL) { perror(\"gethostbyname\"); exit(1); }} // Converts space-delimited IPv4 addresses// to dotted-decimal formatvoid checkIPbuffer(char *IPbuffer){ if (NULL == IPbuffer) { perror(\"inet_ntoa\"); exit(1); }} // Driver codeint main(){ char hostbuffer[256]; char *IPbuffer; struct hostent *host_entry; int hostname; // To retrieve hostname hostname = gethostname(hostbuffer, sizeof(hostbuffer)); checkHostName(hostname); // To retrieve host information host_entry = gethostbyname(hostbuffer); checkHostEntry(host_entry); // To convert an Internet network // address into ASCII string IPbuffer = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); printf(\"Hostname: %s\\n\", hostbuffer); printf(\"Host IP: %s\", IPbuffer); return 0;}", "e": 26466, "s": 25090, "text": null }, { "code": null, "e": 26511, "s": 26466, "text": "Hostname: cContainer\nHost IP: 10.98.162.101\n" }, { "code": null, "e": 26544, "s": 26511, "text": "Output varies machine to machine" }, { "code": null, "e": 26555, "s": 26544, "text": "C Language" }, { "code": null, "e": 26559, "s": 26555, "text": "C++" }, { "code": null, "e": 26577, "s": 26559, "text": "Computer Networks" }, { "code": null, "e": 26595, "s": 26577, "text": "Computer Networks" }, { "code": null, "e": 26599, "s": 26595, "text": "CPP" }, { "code": null, "e": 26697, "s": 26599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26706, "s": 26697, "text": "Comments" }, { "code": null, "e": 26719, "s": 26706, "text": "Old Comments" }, { "code": null, "e": 26754, "s": 26719, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26782, "s": 26754, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26814, "s": 26782, "text": "Command line arguments in C/C++" }, { "code": null, "e": 26854, "s": 26814, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 26900, "s": 26854, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 26918, "s": 26900, "text": "Vector in C++ STL" }, { "code": null, "e": 26937, "s": 26918, "text": "Inheritance in C++" }, { "code": null, "e": 26983, "s": 26937, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27026, "s": 26983, "text": "Map in C++ Standard Template Library (STL)" } ]
Python | Pandas dataframe.between_time() - GeeksforGeeks
16 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.between_time() is used to select values between particular times of the day (e.g. 9:00-9:30 AM). Unlike dataframe.at_time() function, this function extracts values in a range of time. This function is only used with time-series data. The index of the Dataframe must be DatetimeIndex in order to be able to use this function. Syntax: DataFrame.between_time(start_time, end_time, include_start=True, include_end=True) Parameters:start_time : datetime.time or stringend_time : datetime.time or stringinclude_start : boolean, default Trueinclude_end : boolean, default True Returns: values_between_time : type of caller Note: between_time() function raises exception when the index of the dataframe is not a DatetimeIndex Example #1: Use between_time() function to find the values between a given time interval. # importing pandas as pdimport pandas as pd # Creating row index values for dataframe# Taken time frequency to be of 30 minutes interval# Generating eight index value using "period = 8" parameterind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using "ind" as the index for dataframe df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8], "B":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # Printing the dataframedf Now let’s query for time between “02:00” to “03:30” # Find the row values between time "02:00" to "03:30"df.between_time('02:00', '03:30') Output : Example #2: Use between_time() function to find the values between a given time interval while excluding the start and end times. # importing pandas as pdimport pandas as pd # Creating row index values for our data frame# Taken time frequency to be of 30 minutes interval# Generating eight index value using "period = 8" parameterind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using "ind" as the index for our dataframe df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8], "B":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # query for time between "02:00" to "03:30" with# both the start and end time values being excludeddf.between_time('02:00', '03:30', include_start = False, include_end = False) Output : Notice the values corresponding to start time and end time is not included in the dataframe returned by the between_time() function. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24390, "s": 24362, "text": "\n16 Nov, 2018" }, { "code": null, "e": 24604, "s": 24390, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 24946, "s": 24604, "text": "Pandas dataframe.between_time() is used to select values between particular times of the day (e.g. 9:00-9:30 AM). Unlike dataframe.at_time() function, this function extracts values in a range of time. This function is only used with time-series data. The index of the Dataframe must be DatetimeIndex in order to be able to use this function." }, { "code": null, "e": 25037, "s": 24946, "text": "Syntax: DataFrame.between_time(start_time, end_time, include_start=True, include_end=True)" }, { "code": null, "e": 25191, "s": 25037, "text": "Parameters:start_time : datetime.time or stringend_time : datetime.time or stringinclude_start : boolean, default Trueinclude_end : boolean, default True" }, { "code": null, "e": 25237, "s": 25191, "text": "Returns: values_between_time : type of caller" }, { "code": null, "e": 25339, "s": 25237, "text": "Note: between_time() function raises exception when the index of the dataframe is not a DatetimeIndex" }, { "code": null, "e": 25429, "s": 25339, "text": "Example #1: Use between_time() function to find the values between a given time interval." }, { "code": "# importing pandas as pdimport pandas as pd # Creating row index values for dataframe# Taken time frequency to be of 30 minutes interval# Generating eight index value using \"period = 8\" parameterind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using \"ind\" as the index for dataframe df = pd.DataFrame({\"A\":[1, 2, 3, 4, 5, 6, 7, 8], \"B\":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # Printing the dataframedf", "e": 25956, "s": 25429, "text": null }, { "code": null, "e": 26008, "s": 25956, "text": "Now let’s query for time between “02:00” to “03:30”" }, { "code": "# Find the row values between time \"02:00\" to \"03:30\"df.between_time('02:00', '03:30')", "e": 26095, "s": 26008, "text": null }, { "code": null, "e": 26234, "s": 26095, "text": "Output : Example #2: Use between_time() function to find the values between a given time interval while excluding the start and end times." }, { "code": "# importing pandas as pdimport pandas as pd # Creating row index values for our data frame# Taken time frequency to be of 30 minutes interval# Generating eight index value using \"period = 8\" parameterind = pd.date_range('01/01/2000', periods = 8, freq ='30T') # Creating a dataframe with 2 columns# using \"ind\" as the index for our dataframe df = pd.DataFrame({\"A\":[1, 2, 3, 4, 5, 6, 7, 8], \"B\":[10, 20, 30, 40, 50, 60, 70, 80]}, index = ind) # query for time between \"02:00\" to \"03:30\" with# both the start and end time values being excludeddf.between_time('02:00', '03:30', include_start = False, include_end = False)", "e": 26955, "s": 26234, "text": null }, { "code": null, "e": 26964, "s": 26955, "text": "Output :" }, { "code": null, "e": 27097, "s": 26964, "text": "Notice the values corresponding to start time and end time is not included in the dataframe returned by the between_time() function." }, { "code": null, "e": 27121, "s": 27097, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27153, "s": 27121, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27167, "s": 27153, "text": "Python-pandas" }, { "code": null, "e": 27174, "s": 27167, "text": "Python" }, { "code": null, "e": 27272, "s": 27174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27304, "s": 27272, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27346, "s": 27304, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27388, "s": 27346, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27444, "s": 27388, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27471, "s": 27444, "text": "Python Classes and Objects" }, { "code": null, "e": 27493, "s": 27471, "text": "Defaultdict in Python" }, { "code": null, "e": 27522, "s": 27493, "text": "Create a directory in Python" }, { "code": null, "e": 27553, "s": 27522, "text": "Python | os.path.join() method" }, { "code": null, "e": 27589, "s": 27553, "text": "Python | Pandas dataframe.groupby()" } ]
Sankey Charts with Multiple levels
Following is an example of a SanKey Chart with multiple levels. We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a SanKey Chart with multiple levels. We've used Sankey class to show a Sankey chart with multiple levels. type = 'Sankey'; app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = ''; type = 'Sankey'; data = [ ["Brazil","Portugal",5], ["Brazil","France",1], ["Brazil","Spain",1], ["Brazil","England",1], ["Canada","Portugal",1], ["Canada","France",5], ["Canada","England",1], ["Mexico","Portugal",1], ["Mexico","France",1], ["Mexico","Spain",5], ["Mexico","England",1], ["USA","Portugal",1], ["USA","France",1], ["USA","Spain",1], ["USA","England",5], ["Portugal","Angola",2], ["Portugal","Senagal",1], ["Portugal","Morocco",1], ["Portugal","South Africa",3] ]; columnNames = ['From', 'To','Weight']; options = { }; width = 550; height = 400; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 1860, "s": 1796, "text": "Following is an example of a SanKey Chart with multiple levels." }, { "code": null, "e": 2035, "s": 1860, "text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a SanKey Chart with multiple levels." }, { "code": null, "e": 2104, "s": 2035, "text": "We've used Sankey class to show a Sankey chart with multiple levels." }, { "code": null, "e": 2122, "s": 2104, "text": "type = 'Sankey';\n" }, { "code": null, "e": 2139, "s": 2122, "text": "app.component.ts" }, { "code": null, "e": 3054, "s": 2139, "text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = '';\n type = 'Sankey';\n data = [\n [\"Brazil\",\"Portugal\",5],\n [\"Brazil\",\"France\",1],\n [\"Brazil\",\"Spain\",1],\n [\"Brazil\",\"England\",1],\n [\"Canada\",\"Portugal\",1],\n [\"Canada\",\"France\",5],\n [\"Canada\",\"England\",1],\n [\"Mexico\",\"Portugal\",1], \n [\"Mexico\",\"France\",1],\n [\"Mexico\",\"Spain\",5],\n [\"Mexico\",\"England\",1], \n [\"USA\",\"Portugal\",1], \n [\"USA\",\"France\",1],\n [\"USA\",\"Spain\",1],\n [\"USA\",\"England\",5],\n [\"Portugal\",\"Angola\",2], \n [\"Portugal\",\"Senagal\",1],\n [\"Portugal\",\"Morocco\",1],\n [\"Portugal\",\"South Africa\",3]\n ];\n columnNames = ['From', 'To','Weight'];\n options = { \n };\n width = 550;\n height = 400;\n}" }, { "code": null, "e": 3073, "s": 3054, "text": "Verify the result." }, { "code": null, "e": 3108, "s": 3073, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3122, "s": 3108, "text": " Anadi Sharma" }, { "code": null, "e": 3157, "s": 3122, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3171, "s": 3157, "text": " Anadi Sharma" }, { "code": null, "e": 3206, "s": 3171, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3226, "s": 3206, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3261, "s": 3226, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3278, "s": 3261, "text": " Frahaan Hussain" }, { "code": null, "e": 3311, "s": 3278, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3323, "s": 3311, "text": " Senol Atac" }, { "code": null, "e": 3358, "s": 3323, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3370, "s": 3358, "text": " Senol Atac" }, { "code": null, "e": 3377, "s": 3370, "text": " Print" }, { "code": null, "e": 3388, "s": 3377, "text": " Add Notes" } ]
What is useState() & how it has been used to validate input values? - GeeksforGeeks
13 Oct, 2021 The useState() is a hook in ReactJs which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state. We have to import the useState() hook from the react package.import { useState } from 'react'; We have to import the useState() hook from the react package. import { useState } from 'react'; Syntax to create state using useState() hook:const [ state, updateState] = useState("Initial Value") Syntax to create state using useState() hook: const [ state, updateState] = useState("Initial Value") The useState() returns a list with two-element. first is the state itself, and the second is the function to update this state. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder, i.e., foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Example 1:Filename App.js: Javascript import React, { Component, useState } from "react";const App = () => { const [name, updateName] = useState("kapil")const handleUpdate = () => { updateName("Nikhil")} return( <div > <button style = { {margin: 100 }} onClick = { () => { handleUpdate()} } > change Name </button> { name } </div> ); }export default App; Output: Example 2: Validation of Input value in React allows an error message to be displayed if the user has not filled out the form with the expected value. There are many ways to validate input value with React. Filename App.js: Javascript import React from 'react'; export default class App extends React.Component { state = { fields: {}, errors: {} } //method to validate values handleValidation = ()=>{ let fields = this.state.fields; let errors = {}; let formIsValid = true; //Name check if name is empty or not if(!fields["name"]){ formIsValid = false; errors["name"] = "Cannot be empty"; } //name should not contain special char if(typeof fields["name"] !== "undefined"){ if(!fields["name"].match(/^[a-zA-Z]+$/)){ formIsValid = false; errors["name"] = "Only letters"; } } //Email should not be empty if(!fields["email"]){ formIsValid = false; errors["email"] = "Cannot be empty"; } //validating email if(typeof fields["email"] !== "undefined"){ let lastAtPos = fields["email"].lastIndexOf('@'); let lastDotPos = fields["email"].lastIndexOf('.'); if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) { formIsValid = false; errors["email"] = "Email is not valid"; } } this.setState({errors: errors}); return formIsValid; } //after submit form it will be called handleSubmit = (e) =>{ e.preventDefault(); if(this.handleValidation()) alert("form submitted successfully") } //updating the field value handleUpdate(field, e){ let fields = this.state.fields; fields[field] = e.target.value; this.setState({fields});} render(){ return ( <div style = {{margin:200}}> <form onSubmit= {this.handleSubmit.bind(this)}> <input type="text" placeholder="Name" onChange={this.handleUpdate.bind(this, "name")} value={this.state.fields["name"]}/> <span style={{color: "red"}}> {this.state.errors["name"]}</span> <br/> <input type="text" placeholder="Email" onChange={this.handleUpdate.bind(this, "email")} value={this.state.fields["email"]}/> <span style={{color: "red"}}> {this.state.errors["email"]}</span> <br/> <button type = "submit">click</button> </form> </div> ) }} Output: kashishsoda Picked JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26667, "s": 26639, "text": "\n13 Oct, 2021" }, { "code": null, "e": 26866, "s": 26667, "text": "The useState() is a hook in ReactJs which allows a functional component to have a state. We pass the initial state in this function, and it returns us a variable and a function to update that state." }, { "code": null, "e": 26962, "s": 26866, "text": "We have to import the useState() hook from the react package.import { useState } from 'react';" }, { "code": null, "e": 27024, "s": 26962, "text": "We have to import the useState() hook from the react package." }, { "code": null, "e": 27059, "s": 27024, "text": "import { useState } from 'react';" }, { "code": null, "e": 27160, "s": 27059, "text": "Syntax to create state using useState() hook:const [ state, updateState] = useState(\"Initial Value\")" }, { "code": null, "e": 27206, "s": 27160, "text": "Syntax to create state using useState() hook:" }, { "code": null, "e": 27262, "s": 27206, "text": "const [ state, updateState] = useState(\"Initial Value\")" }, { "code": null, "e": 27390, "s": 27262, "text": "The useState() returns a list with two-element. first is the state itself, and the second is the function to update this state." }, { "code": null, "e": 27418, "s": 27390, "text": "Creating React Application:" }, { "code": null, "e": 27482, "s": 27418, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 27514, "s": 27482, "text": "npx create-react-app foldername" }, { "code": null, "e": 27616, "s": 27514, "text": "Step 2: After creating your project folder, i.e., foldername, move to it using the following command:" }, { "code": null, "e": 27630, "s": 27616, "text": "cd foldername" }, { "code": null, "e": 27682, "s": 27630, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27709, "s": 27682, "text": "Example 1:Filename App.js:" }, { "code": null, "e": 27720, "s": 27709, "text": "Javascript" }, { "code": "import React, { Component, useState } from \"react\";const App = () => { const [name, updateName] = useState(\"kapil\")const handleUpdate = () => { updateName(\"Nikhil\")} return( <div > <button style = { {margin: 100 }} onClick = { () => { handleUpdate()} } > change Name </button> { name } </div> ); }export default App;", "e": 28110, "s": 27720, "text": null }, { "code": null, "e": 28118, "s": 28110, "text": "Output:" }, { "code": null, "e": 28326, "s": 28118, "text": "Example 2: Validation of Input value in React allows an error message to be displayed if the user has not filled out the form with the expected value. There are many ways to validate input value with React. " }, { "code": null, "e": 28343, "s": 28326, "text": "Filename App.js:" }, { "code": null, "e": 28354, "s": 28343, "text": "Javascript" }, { "code": "import React from 'react'; export default class App extends React.Component { state = { fields: {}, errors: {} } //method to validate values handleValidation = ()=>{ let fields = this.state.fields; let errors = {}; let formIsValid = true; //Name check if name is empty or not if(!fields[\"name\"]){ formIsValid = false; errors[\"name\"] = \"Cannot be empty\"; } //name should not contain special char if(typeof fields[\"name\"] !== \"undefined\"){ if(!fields[\"name\"].match(/^[a-zA-Z]+$/)){ formIsValid = false; errors[\"name\"] = \"Only letters\"; } } //Email should not be empty if(!fields[\"email\"]){ formIsValid = false; errors[\"email\"] = \"Cannot be empty\"; } //validating email if(typeof fields[\"email\"] !== \"undefined\"){ let lastAtPos = fields[\"email\"].lastIndexOf('@'); let lastDotPos = fields[\"email\"].lastIndexOf('.'); if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields[\"email\"].indexOf('@@') == -1 && lastDotPos > 2 && (fields[\"email\"].length - lastDotPos) > 2)) { formIsValid = false; errors[\"email\"] = \"Email is not valid\"; } } this.setState({errors: errors}); return formIsValid; } //after submit form it will be called handleSubmit = (e) =>{ e.preventDefault(); if(this.handleValidation()) alert(\"form submitted successfully\") } //updating the field value handleUpdate(field, e){ let fields = this.state.fields; fields[field] = e.target.value; this.setState({fields});} render(){ return ( <div style = {{margin:200}}> <form onSubmit= {this.handleSubmit.bind(this)}> <input type=\"text\" placeholder=\"Name\" onChange={this.handleUpdate.bind(this, \"name\")} value={this.state.fields[\"name\"]}/> <span style={{color: \"red\"}}> {this.state.errors[\"name\"]}</span> <br/> <input type=\"text\" placeholder=\"Email\" onChange={this.handleUpdate.bind(this, \"email\")} value={this.state.fields[\"email\"]}/> <span style={{color: \"red\"}}> {this.state.errors[\"email\"]}</span> <br/> <button type = \"submit\">click</button> </form> </div> ) }}", "e": 30913, "s": 28354, "text": null }, { "code": null, "e": 30921, "s": 30913, "text": "Output:" }, { "code": null, "e": 30933, "s": 30921, "text": "kashishsoda" }, { "code": null, "e": 30940, "s": 30933, "text": "Picked" }, { "code": null, "e": 30951, "s": 30940, "text": "JavaScript" }, { "code": null, "e": 30959, "s": 30951, "text": "ReactJS" }, { "code": null, "e": 30976, "s": 30959, "text": "Web Technologies" }, { "code": null, "e": 31074, "s": 30976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31114, "s": 31074, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31175, "s": 31114, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31216, "s": 31175, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31238, "s": 31216, "text": "JavaScript | Promises" }, { "code": null, "e": 31292, "s": 31238, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31335, "s": 31292, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31380, "s": 31335, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 31445, "s": 31380, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 31513, "s": 31445, "text": "How to pass data from one component to other component in ReactJS ?" } ]
All possible binary numbers of length n with equal sum in both halves - GeeksforGeeks
07 Jul, 2021 Given a number n, we need to print all n-digit binary numbers with equal sum in left and right halves. If n is odd, then mid element can be either 0 or 1.Examples: Input : n = 4 Output : 0000 0101 0110 1001 1010 1111 Input : n = 5 Output : 00000 00100 01001 01101 01010 01110 10001 10101 10010 10110 11011 11111 The idea is to recursively build left and right halves and keep track of difference between counts of 1s in them. We print a string when difference becomes 0 and there are no more characters to add. C++ Java Python3 C# Javascript // C++ program to generate all binary strings with// equal sums in left and right halves.#include <bits/stdc++.h>using namespace std; /* Default values are used only in initial call. n is number of bits remaining to be filled di is current difference between sums of left and right halves. left and right are current half substrings. */void equal(int n, string left="", string right="", int di=0){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) cout << left + right << " "; return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put remaining // bit in middle. if (di == 0) { cout << left + "0" + right << " "; cout << left + "1" + right << " "; } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * abs(di) <= n)) { /* add 0 to end in both left and right half. Sum in both half will not change*/ equal(n-2, left+"0", right+"0", di); /* add 0 to end in both left and right half* subtract 1 from di as right sum is increased by 1*/ equal(n-2, left+"0", right+"1", di-1); /* add 1 in end in left half and 0 to the right half. Add 1 to di as left sum is increased by 1*/ equal(n-2, left+"1", right+"0", di+1); /* add 1 in end to both left and right half the sum will not change*/ equal(n-2, left+"1", right+"1", di); }} /* driver function */int main(){ int n = 5; // n-bits equal(n); return 0;} // Java program to generate all binary strings// with equal sums in left and right halves.import java.util.*; class GFG{ // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.static void equal(int n, String left, String right, int di){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) System.out.print(left + right + " "); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { System.out.print(left + "0" + right + " "); System.out.print(left + "1" + right + " "); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + "0", right + "0", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + "0", right + "1", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + "1", right + "0", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + "1", right + "1", di); }} // Driver Codepublic static void main(String args[]){ int n = 5; // n-bits equal(n, "", "", 0);}} // This code is contributed// by SURENDRA_GANGWAR # Python program to generate all binary strings with# equal sums in left and right halves. # Default values are used only in initial call.# n is number of bits remaining to be filled# di is current difference between sums of# left and right halves.# left and right are current half substrings.def equal(n: int, left = "", right = "", di = 0): # TWO BASE CASES # If there are no more characters to add (n is 0) if n == 0: # If difference between counts of 1s and # 0s is 0 (di is 0) if di == 0: print(left + right, end = " ") return # If 1 remains than string length was odd if n == 1: # If difference is 0, we can put remaining # bit in middle. if di == 0: print(left + "0" + right, end = " ") print(left + "1" + right, end = " ") return # If difference is more than what can be # be covered with remaining n digits # (Note that lengths of left and right # must be same) if 2 * abs(di) <= n: # add 0 to end in both left and right # half. Sum in both half will not # change equal(n - 2, left + "0", right + "0", di) # add 0 to end in both left and right # half* subtract 1 from di as right # sum is increased by 1 equal(n - 2, left + "0", right + "1", di - 1) # add 1 in end in left half and 0 to the # right half. Add 1 to di as left sum is # increased by 1 equal(n - 2, left + "1", right + "0", di + 1) # add 1 in end to both left and right # half the sum will not change equal(n - 2, left + "1", right + "1", di) # Driver Codeif __name__ == "__main__": n = 5 # n-bits equal(5) # This code is contributed by# sanjeev2552 // C# program to generate all binary strings// with equal sums in left and right halves.using System; class GFG{ // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.static void equal(int n, String left, String right, int di){ // TWO BASE CASES // If there are no more characters // to add (n is 0) if (n == 0) { // If difference between counts of 1s // and 0s is 0 (di is 0) if (di == 0) Console.Write(left + right + " "); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { Console.Write(left + "0" + right + " "); Console.Write(left + "1" + right + " "); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.Abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + "0", right + "0", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + "0", right + "1", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + "1", right + "0", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + "1", right + "1", di); }} // Driver Codepublic static void Main(String []args){ int n = 5; // n-bits equal(n, "", "", 0);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to generate all binary strings// with equal sums in left and right halves. // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.function equal(n,left,right,di){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) document.write(left + right + " "); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { document.write(left + "0" + right + " "); document.write(left + "1" + right + " "); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + "0", right + "0", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + "0", right + "1", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + "1", right + "0", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + "1", right + "1", di); }} // Driver Codelet n = 5; // n-bitsequal(n, "", "", 0); // This code is contributed by rag2127 </script> Output: 10001 10101 10010 10110 11011 11111 This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. SURENDRA_GANGWAR 29AjayKumar sanjeev2552 shivanik6z rag2127 binary-string Recursion Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Recursive Practice Problems with Solutions Write a program to reverse digits of a number Recursive Functions Check if a number is Palindrome Print all subsequences of a string Count all possible paths from top left to bottom right of a mXn matrix Recursive Bubble Sort Reverse a stack using recursion
[ { "code": null, "e": 26527, "s": 26499, "text": "\n07 Jul, 2021" }, { "code": null, "e": 26693, "s": 26527, "text": "Given a number n, we need to print all n-digit binary numbers with equal sum in left and right halves. If n is odd, then mid element can be either 0 or 1.Examples: " }, { "code": null, "e": 26844, "s": 26693, "text": "Input : n = 4\nOutput : 0000 0101 0110 1001 1010 1111 \nInput : n = 5\nOutput : 00000 00100 01001 01101 01010 01110 10001 10101 10010 10110 11011 11111 " }, { "code": null, "e": 27047, "s": 26846, "text": "The idea is to recursively build left and right halves and keep track of difference between counts of 1s in them. We print a string when difference becomes 0 and there are no more characters to add. " }, { "code": null, "e": 27051, "s": 27047, "text": "C++" }, { "code": null, "e": 27056, "s": 27051, "text": "Java" }, { "code": null, "e": 27064, "s": 27056, "text": "Python3" }, { "code": null, "e": 27067, "s": 27064, "text": "C#" }, { "code": null, "e": 27078, "s": 27067, "text": "Javascript" }, { "code": "// C++ program to generate all binary strings with// equal sums in left and right halves.#include <bits/stdc++.h>using namespace std; /* Default values are used only in initial call. n is number of bits remaining to be filled di is current difference between sums of left and right halves. left and right are current half substrings. */void equal(int n, string left=\"\", string right=\"\", int di=0){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) cout << left + right << \" \"; return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put remaining // bit in middle. if (di == 0) { cout << left + \"0\" + right << \" \"; cout << left + \"1\" + right << \" \"; } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * abs(di) <= n)) { /* add 0 to end in both left and right half. Sum in both half will not change*/ equal(n-2, left+\"0\", right+\"0\", di); /* add 0 to end in both left and right half* subtract 1 from di as right sum is increased by 1*/ equal(n-2, left+\"0\", right+\"1\", di-1); /* add 1 in end in left half and 0 to the right half. Add 1 to di as left sum is increased by 1*/ equal(n-2, left+\"1\", right+\"0\", di+1); /* add 1 in end to both left and right half the sum will not change*/ equal(n-2, left+\"1\", right+\"1\", di); }} /* driver function */int main(){ int n = 5; // n-bits equal(n); return 0;}", "e": 28982, "s": 27078, "text": null }, { "code": "// Java program to generate all binary strings// with equal sums in left and right halves.import java.util.*; class GFG{ // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.static void equal(int n, String left, String right, int di){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) System.out.print(left + right + \" \"); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { System.out.print(left + \"0\" + right + \" \"); System.out.print(left + \"1\" + right + \" \"); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + \"0\", right + \"0\", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + \"0\", right + \"1\", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + \"1\", right + \"0\", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + \"1\", right + \"1\", di); }} // Driver Codepublic static void main(String args[]){ int n = 5; // n-bits equal(n, \"\", \"\", 0);}} // This code is contributed// by SURENDRA_GANGWAR", "e": 31017, "s": 28982, "text": null }, { "code": "# Python program to generate all binary strings with# equal sums in left and right halves. # Default values are used only in initial call.# n is number of bits remaining to be filled# di is current difference between sums of# left and right halves.# left and right are current half substrings.def equal(n: int, left = \"\", right = \"\", di = 0): # TWO BASE CASES # If there are no more characters to add (n is 0) if n == 0: # If difference between counts of 1s and # 0s is 0 (di is 0) if di == 0: print(left + right, end = \" \") return # If 1 remains than string length was odd if n == 1: # If difference is 0, we can put remaining # bit in middle. if di == 0: print(left + \"0\" + right, end = \" \") print(left + \"1\" + right, end = \" \") return # If difference is more than what can be # be covered with remaining n digits # (Note that lengths of left and right # must be same) if 2 * abs(di) <= n: # add 0 to end in both left and right # half. Sum in both half will not # change equal(n - 2, left + \"0\", right + \"0\", di) # add 0 to end in both left and right # half* subtract 1 from di as right # sum is increased by 1 equal(n - 2, left + \"0\", right + \"1\", di - 1) # add 1 in end in left half and 0 to the # right half. Add 1 to di as left sum is # increased by 1 equal(n - 2, left + \"1\", right + \"0\", di + 1) # add 1 in end to both left and right # half the sum will not change equal(n - 2, left + \"1\", right + \"1\", di) # Driver Codeif __name__ == \"__main__\": n = 5 # n-bits equal(5) # This code is contributed by# sanjeev2552", "e": 32783, "s": 31017, "text": null }, { "code": "// C# program to generate all binary strings// with equal sums in left and right halves.using System; class GFG{ // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.static void equal(int n, String left, String right, int di){ // TWO BASE CASES // If there are no more characters // to add (n is 0) if (n == 0) { // If difference between counts of 1s // and 0s is 0 (di is 0) if (di == 0) Console.Write(left + right + \" \"); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { Console.Write(left + \"0\" + right + \" \"); Console.Write(left + \"1\" + right + \" \"); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.Abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + \"0\", right + \"0\", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + \"0\", right + \"1\", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + \"1\", right + \"0\", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + \"1\", right + \"1\", di); }} // Driver Codepublic static void Main(String []args){ int n = 5; // n-bits equal(n, \"\", \"\", 0);}} // This code is contributed by 29AjayKumar", "e": 34880, "s": 32783, "text": null }, { "code": "<script> // JavaScript program to generate all binary strings// with equal sums in left and right halves. // Default values are used only in initial call.// n is number of bits remaining to be filled// di is current difference between sums of// left and right halves.// left and right are current half substrings.function equal(n,left,right,di){ // TWO BASE CASES // If there are no more characters to add (n is 0) if (n == 0) { // If difference between counts of 1s and // 0s is 0 (di is 0) if (di == 0) document.write(left + right + \" \"); return; } /* If 1 remains than string length was odd */ if (n == 1) { // If difference is 0, we can put // remaining bit in middle. if (di == 0) { document.write(left + \"0\" + right + \" \"); document.write(left + \"1\" + right + \" \"); } return; } /* If difference is more than what can be be covered with remaining n digits (Note that lengths of left and right must be same) */ if ((2 * Math.abs(di) <= n)) { // add 0 to end in both left and right // half. Sum in both half will not // change equal(n - 2, left + \"0\", right + \"0\", di); // add 0 to end in both left and right // half* subtract 1 from di as right // sum is increased by 1 equal(n - 2, left + \"0\", right + \"1\", di - 1); // add 1 in end in left half and 0 to the // right half. Add 1 to di as left sum is // increased by 1* equal(n - 2, left + \"1\", right + \"0\", di + 1); // add 1 in end to both left and right // half the sum will not change equal(n - 2, left + \"1\", right + \"1\", di); }} // Driver Codelet n = 5; // n-bitsequal(n, \"\", \"\", 0); // This code is contributed by rag2127 </script>", "e": 36799, "s": 34880, "text": null }, { "code": null, "e": 36809, "s": 36799, "text": "Output: " }, { "code": null, "e": 36846, "s": 36809, "text": "10001 10101 10010 10110 11011 11111 " }, { "code": null, "e": 37261, "s": 36846, "text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. " }, { "code": null, "e": 37278, "s": 37261, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 37290, "s": 37278, "text": "29AjayKumar" }, { "code": null, "e": 37302, "s": 37290, "text": "sanjeev2552" }, { "code": null, "e": 37313, "s": 37302, "text": "shivanik6z" }, { "code": null, "e": 37321, "s": 37313, "text": "rag2127" }, { "code": null, "e": 37335, "s": 37321, "text": "binary-string" }, { "code": null, "e": 37345, "s": 37335, "text": "Recursion" }, { "code": null, "e": 37355, "s": 37345, "text": "Recursion" }, { "code": null, "e": 37453, "s": 37355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37481, "s": 37453, "text": "Backtracking | Introduction" }, { "code": null, "e": 37524, "s": 37481, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 37570, "s": 37524, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 37590, "s": 37570, "text": "Recursive Functions" }, { "code": null, "e": 37622, "s": 37590, "text": "Check if a number is Palindrome" }, { "code": null, "e": 37657, "s": 37622, "text": "Print all subsequences of a string" }, { "code": null, "e": 37728, "s": 37657, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 37750, "s": 37728, "text": "Recursive Bubble Sort" } ]
Change Gregorian Calendar to SimpleDateFormat in Java - GeeksforGeeks
24 Jan, 2022 Given a date in GregorianCalendar format change it into SimpleDateFormat.Examples: Input: Sat Apr 28 13:36:37 UTC 2018 Output: 28-Apr-2018 Input: Wed Apr 03 20:49:45 IST 2019 Output: 03-Apr-2019 Approach: Get the Gregorian Date to be converted.Create an object of SimpleDateFormat that will store the converted dateNow change the Gregorian Date into SimpleDateFormat using the format() method.This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method. Get the Gregorian Date to be converted. Create an object of SimpleDateFormat that will store the converted date Now change the Gregorian Date into SimpleDateFormat using the format() method. This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method. Below is the implementation of the above approach:Example: Java // Java program to convert// GregorianCalendar to SimpleDateFormat import java.text.SimpleDateFormat;import java.util.GregorianCalendar; public class GregorianCalendarToCalendar { public static void convert( GregorianCalendar gregorianCalendarDate) { // Creating an object of SimpleDateFormat SimpleDateFormat formattedDate = new SimpleDateFormat("dd-MMM-yyyy"); // Use format() method to change the format // Using getTime() method, // this required date is passed // to format() method String dateFormatted = formattedDate.format( gregorianCalendarDate.getTime()); // Displaying gregorian date ia SimpleDateFormat System.out.print("SimpleDateFormat: " + dateFormatted); } // Driver code public static void main(String[] args) { // Get the Gregorian Date to be converted. GregorianCalendar gcal = new GregorianCalendar(); gcal.set(GregorianCalendar.YEAR, 2019); // In gregorian calendar month is started from 0 // so for april month will be 03 not 04 gcal.set(GregorianCalendar.MONTH, 03); gcal.set(GregorianCalendar.DATE, 03); // Displaying Current Date // using GregorianCalendar Class System.out.println("Gregorian date: " + gcal.getTime()); // Function to convert this to SimpleDateFormat convert(gcal); }} Gregorian date: Wed Apr 03 05:21:17 UTC 2019 SimpleDateFormat: 03-Apr-2019 clintra sweetyty Java - util package Java-SimpleDateFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Overriding in Java
[ { "code": null, "e": 24460, "s": 24432, "text": "\n24 Jan, 2022" }, { "code": null, "e": 24544, "s": 24460, "text": "Given a date in GregorianCalendar format change it into SimpleDateFormat.Examples: " }, { "code": null, "e": 24657, "s": 24544, "text": "Input: Sat Apr 28 13:36:37 UTC 2018\nOutput: 28-Apr-2018\n\nInput: Wed Apr 03 20:49:45 IST 2019\nOutput: 03-Apr-2019" }, { "code": null, "e": 24668, "s": 24657, "text": "Approach: " }, { "code": null, "e": 25023, "s": 24668, "text": "Get the Gregorian Date to be converted.Create an object of SimpleDateFormat that will store the converted dateNow change the Gregorian Date into SimpleDateFormat using the format() method.This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method." }, { "code": null, "e": 25063, "s": 25023, "text": "Get the Gregorian Date to be converted." }, { "code": null, "e": 25135, "s": 25063, "text": "Create an object of SimpleDateFormat that will store the converted date" }, { "code": null, "e": 25214, "s": 25135, "text": "Now change the Gregorian Date into SimpleDateFormat using the format() method." }, { "code": null, "e": 25381, "s": 25214, "text": "This format method will take the only the date part of Gregorian date as the parameter. Hence using getTime() method, this required date is passed to format() method." }, { "code": null, "e": 25442, "s": 25381, "text": "Below is the implementation of the above approach:Example: " }, { "code": null, "e": 25447, "s": 25442, "text": "Java" }, { "code": "// Java program to convert// GregorianCalendar to SimpleDateFormat import java.text.SimpleDateFormat;import java.util.GregorianCalendar; public class GregorianCalendarToCalendar { public static void convert( GregorianCalendar gregorianCalendarDate) { // Creating an object of SimpleDateFormat SimpleDateFormat formattedDate = new SimpleDateFormat(\"dd-MMM-yyyy\"); // Use format() method to change the format // Using getTime() method, // this required date is passed // to format() method String dateFormatted = formattedDate.format( gregorianCalendarDate.getTime()); // Displaying gregorian date ia SimpleDateFormat System.out.print(\"SimpleDateFormat: \" + dateFormatted); } // Driver code public static void main(String[] args) { // Get the Gregorian Date to be converted. GregorianCalendar gcal = new GregorianCalendar(); gcal.set(GregorianCalendar.YEAR, 2019); // In gregorian calendar month is started from 0 // so for april month will be 03 not 04 gcal.set(GregorianCalendar.MONTH, 03); gcal.set(GregorianCalendar.DATE, 03); // Displaying Current Date // using GregorianCalendar Class System.out.println(\"Gregorian date: \" + gcal.getTime()); // Function to convert this to SimpleDateFormat convert(gcal); }}", "e": 26930, "s": 25447, "text": null }, { "code": null, "e": 27005, "s": 26930, "text": "Gregorian date: Wed Apr 03 05:21:17 UTC 2019\nSimpleDateFormat: 03-Apr-2019" }, { "code": null, "e": 27015, "s": 27007, "text": "clintra" }, { "code": null, "e": 27024, "s": 27015, "text": "sweetyty" }, { "code": null, "e": 27044, "s": 27024, "text": "Java - util package" }, { "code": null, "e": 27066, "s": 27044, "text": "Java-SimpleDateFormat" }, { "code": null, "e": 27084, "s": 27066, "text": "Java-text package" }, { "code": null, "e": 27089, "s": 27084, "text": "Java" }, { "code": null, "e": 27094, "s": 27089, "text": "Java" }, { "code": null, "e": 27192, "s": 27094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27201, "s": 27192, "text": "Comments" }, { "code": null, "e": 27214, "s": 27201, "text": "Old Comments" }, { "code": null, "e": 27246, "s": 27214, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27276, "s": 27246, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27295, "s": 27276, "text": "Interfaces in Java" }, { "code": null, "e": 27326, "s": 27295, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27344, "s": 27326, "text": "ArrayList in Java" }, { "code": null, "e": 27395, "s": 27344, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27427, "s": 27395, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27447, "s": 27427, "text": "Stack Class in Java" }, { "code": null, "e": 27466, "s": 27447, "text": "LinkedList in Java" } ]
Where Machine Learning meets Cryptography | by Dr. Robert Kübler | Towards Data Science
When reading this, chances are that you know one or another thing about machine learning already. You know that machine learning algorithms typically take in a bunch of samples, each containing a fixed amount of features, and output a prediction in the end. What you maybe have heard about (but did not dig deeper into) is the field of cryptography. It is this mysterious subject where it’s all security, passwords, hiding things. Maybe you have even heard about AES or RSA, which are algorithms to encrypt data. But don’t worry, even if you have never dealt with cryptography before, you will be able to follow along since I will explain everything on an introductory level . In this article, I want to bring both fields together. I will present to you an easy to understand, yet hard to solve problem used to build cryptographic algorithms — the so-called Learning Parity with Noise problem, LPN for short. The “L” in LPN should ring your machine learning alarm bells already because this problem can be seen as a routine machine learning problem! But first, let us see where the LPN problem naturally arises in a cryptographic setting and how to define it. We will solve the LPN problem by using machine learning afterward. Imagine that you own a hotel and you want to manage access to the guests’ rooms, i.e. each guest should only be able to enter their own room. Makes sense, right? Now, traditionally you could use normal, physical keys. The disadvantage is that people sometimes lose their keys, which means a lot of costs for your business since you have to replace the lock from the affected doors. So you decide on deploying smart cards, in particular cards with RFID (radio-frequency identification) chips, and also the corresponding locks. Since you have to provide for a lot of doors and you want to save money, you choose very weak RFID chips, i.e. chips with diminishing computational power, maybe even without its own source of electricity. The way your system should work is the following: Every lock and every card has a secret key stored, a binary vector such as s=(1,0,1,0), just much longer in practice. If you hold your card next to a lock, the lock works as a reader, scanning the card’s secret key. The chip is called a tag in this context. The clue: If the secret keys of the card and the door match, the door opens. Perfect! But how to do it? Well, an easy way is to hold your card next to the lock and the lock tells the chip on the card to send its secret key to the lock. Then the lock checks if both secret keys are equal and open the door, if yes. This makes sense, because if you do not have the correct card, i.e. the secret key on your chip is different from the secret key in the door lock, the door will not open. The trouble with this solution begins when a guest wants to enter their room: A bad guy, usually called an attacker in cryptography, could sit in the hallway, apparently just typing innocently on their notebook. What the attacker actually does is sniffing the RFID traffic, i.e. reading the communication between the lock and the guest’s chip. If the chip sends the secret key directly, the attacker will see it, store it, forge a card containing this key and then will be able to enter the room. So, this is a bad idea. It only works if there are no bad people in the world (highly unlikely). Instead, we have to arm ourselves and improve security for our guests. The idea is the following: The chip somehow has to prove to the lock that it possesses the correct secret key without revealing it. I hear you scream: That’s what encryption is for! And you are right. The attacker would only see garbage in the sniffing tool and wouldn’t be able to reconstruct the key. But sadly, the RFID chip is much too weak for encrypting anything because you wanted to save money, remember? Sadly, this is also true for bigger companies in the real world. The chip has nearly no computational power and also only barely enough storage for its secret key. So we need another, more light-weight solution. One way to do that is to use a cryptographic protocol like the HB Protocol by Hopper and Blum [1]. This protocol makes it difficult for this attacker to extract the key. The vanilla HB Protocol that I am going to introduce has other vulnerabilities and should not be used in practice. I just use because it is easy to explain. For real-world security, more secure extensions of this protocol or other secure protocols should be used. So, you have a reader R (the lock) and a tag T (your chip). T now wants to prove to R that it possesses the same secret key without revealing it. This is done by R repeatedly challenging T with questions only a tag with the correct secret key can answer. So far, we have seen that the single question “What is your secret key?” is insecure since this reveals too much information already. Instead, in the HB Protocol T is asked to only reveal small portions of the secret one tiny bit at a time, until R can be sure that T has the correct secret key. Imagine that the secret keys of R and T are in fact both the same s=(1,0,1,0). Now R sends a random binary vector a (e.g. a=(1,0,1,1)) to T and expects T to respond back to it the scalar product b=<a, s>, which is in this example. We call this a a challenge. Remember, we deal with bit arithmetic here, so the “+” is, in fact, an XOR. The multiplication is the same as in the real numbers. Or for mathematicians: we calculate in the field GF(2) or F2, the field with 2 elements. R can compute the scalar product itself (it knows a and s) and checks T’s answer. If T’s answer is the same, R can be a bit more confident that T indeed has the same secret key. To increase confidence, this game is repeated several times. For example, if T does not have the correct key, it would be very unlikely to succeed after a sufficient number of rounds, since a single response would be only correct with probability 0.5. Hence, after 10 rounds, for example, the chance of successful authentication is just 1/1024, less than 0,1%. This sounds much better, right? T is not revealing its secret in one go now, instead, it gives some information to R by answering the challenges. But sadly, this is also completely insecure. An attacker could still write down the complete communication between R and T and then easily solve a system of linear equations to recover s. This is done in the following way: Imagine the attacker has written down the following for challenge/response pairs: The attacker also knows that where A is the matrix containing the ai’s as rows and b the bi’s. In our case: So solving this system for s yields the secret. This can also easily be done via Gaussian Elimination if s is much larger, i.e. 1024 bits long. The solution is s=(1,0,1,0) by the way. :) There is one very small but extremely important tweak to make this secure against our attacker: T just adds some random Bernoulli noise to its responses. Instead of sending <a,s> back to R, it flips a coin e which is 1 with probability p and 0 otherwise and sends back <a,s>+e to the reader. In other words, with probability 1-p the tag sends <a,s> back to R and with probability p it flips the response bit from 0 to 1 or from 1 to 0. We assume that p<0.5. This does not prevent the attacker from sniffing the communication between R and T and taking notes, of course, but they have to solve the following problem now: This notation indicates that each equation of the equation system is only correct with probability 1-p. More formally, you can write it as As+e=b, where e is the noise vector with each component (independently) being 1 with probability p and 0 with probability 1-p. Thus, the attacker has to solve a noisy system of equations over GF(2). For a constant error rate p, this problem — the Learning Parity with Noise (LPN) Problem — is conjectured to be infeasible to solve for large enough length of the secret key. This is also true, if the attacker can get arbitrarily many equations. Even with these errors added, R can do its job of determining whether T knows s or not. If T has the correct s, a fraction of about 1-p responses will be correct. That means if p=0.25 the HB Protocol runs for 1000 iterations, T should give around 750 correct responses. If T does not have the correct s, it will give a fraction of around 0.5 correct answers, i.e. 500 out of 1000 rounds protocol run. This allows R to decide whether T has the correct secret or not and this protocol still makes sense for our use case. Let’s get to the fun part now. We have established that solving the LPN problem means, given a random binary matrix A and a binary vector b=As+e, recovering s. The important observation: We can treat each row ai of matrix A now as a sample and the corresponding value bi=<ai, s>+ei in the vector b as the label. As found in normal datasets used in machine learning, a label bi actually resembles the scalar product of the feature vector ai and a fixed secret vector s (some ground truth), but with an error term added. But how can we get the secret s when we throw a machine learning algorithm for predicting the labels on it? Well, if we could learn the problem reasonably well, we could generate good predictions for the labels (the scalar products; the ground truth) for each feature vector ai we like. If we throw in the vector a=(1,0,0,0), we would then receive a good guess for the first bit of s! Do the same with the vectors (0, 1, 0, 0), (0, 0, 1, 0) and (0, 0, 0, 1) and we have all the bits of the secret key. Thus, we can solve the LPN problem using machine learning. The LPN Problem is a very versatile problem that you can also use to build encryption, identity-based encryption, user authentication, oblivious transfer, message authentication codes, and probably more constructions. Also, unlike the factorization problem, the LPN problem cannot easily be solved using quantum computers. Paired together with its light-weightiness it is a good candidate for building post-quantum secure algorithms. So, no worries, if RSA, which is kind of based on factoring large numbers, dies in the presence of quantum computers. ;) For more information and a better, mathematical definition of the LPN problem, please refer to my dissertation [2]. Let us first define an LPN oracle, i.e. a class that we can feed with a secret key and an error level p upon instantiation, which gives us as many samples as we want. This can easily be done using the following code: import numpy as npclass LPNOracle: def __init__(self, secret, error_rate): self.secret = secret self.dimension = len(secret) self.error_rate = error_rate def sample(self, n_amount): # Create random matrix. A = np.random.randint(0, 2, size=(n_amount, self.dimension)) # Add Bernoulli errors. e = np.random.binomial(1, self.error_rate, n_amount) # Compute the labels. b = np.mod(A @ self.secret + e, 2) return A, b We can now instantiate this an oracle with a random secret of length 16 and p=0.125. p = 0.125dim = 16s = np.random.randint(0, 2, dim)lpn = LPNOracle(s, p) We can now sample from the lpn : lpn.sample(3)my output: (array([[1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0]]), array([1, 1, 1], dtype=int32)) Here we have sampled 3 data points. Now, let us try to find s using a Decision Tree. Why? Just because it’s fast and Logistic Regression and Bernoulli Naive Bayes did not work for me. from sklearn.tree import DecisionTreeClassifierdt = DecisionTreeClassifier()# Get 100000 samples.A, b = lpn.sample(100000)# Fit the tree.dt.fit(A, b)# Predict all canonical unit vectors (1, 0, 0, ..., 0), (0, 1, 0 ,0, ..., 0), ..., (0, 0, ..., 0, 1).s_candidate = dt.predict(np.eye(dim))# Check if the candidate solution is correct.if np.mod(A @ s_candidate + b, 2).sum() < 14000: print(s_candidate, s)else: print('Wrong candidate. Try again!') The learning algorithm might fail to capture the ground truth and learn another function. In this case, the so-called Hamming weight of the vector is quite high (around 50000 for our vector of length 100000). This corresponds to the case where the tag T has the wrong key and can answer about half of the challenges correctly. If s_candidate = s, the Hamming weight will be around 0.125 * 100000 = 12500. Having a threshold of 14000 in this example is a good tradeoff between recognizing the correct secret and not outputting a wrong candidate as the solution. You can find how to get this bound in [2, page 23]. We have defined the LPN problem and seen how it arises when trying to break the cryptographic HB Protocol. Then we have solved a small instance using a simple Decision Tree. But the journey just starts here: We can use other/better algorithms (deep learning, anyone?) or clever tricks to get higher success rates, using fewer samples and being able to solve problems with higher dimensions. For a list and explanations of non-machine learning algorithms to solve LPN, check out my dissertation [2]. Also, if you want fame, try to solve an instance with a secret length of 512 and p=0.125, for example. This LPN instance is currently unbroken and used for some real-world cryptosystems. Good luck! ;) [1] N. Hopper and M. Blum, Secure human identification protocols (2001), International conference on the theory and application of cryptology and information security, Springer [2] R. Kübler, Time-Memory Trade-Offs for the Learning Parity with Noise Problem (2018), Dissertation (Ruhr University Bochum) I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 429, "s": 171, "text": "When reading this, chances are that you know one or another thing about machine learning already. You know that machine learning algorithms typically take in a bunch of samples, each containing a fixed amount of features, and output a prediction in the end." }, { "code": null, "e": 684, "s": 429, "text": "What you maybe have heard about (but did not dig deeper into) is the field of cryptography. It is this mysterious subject where it’s all security, passwords, hiding things. Maybe you have even heard about AES or RSA, which are algorithms to encrypt data." }, { "code": null, "e": 848, "s": 684, "text": "But don’t worry, even if you have never dealt with cryptography before, you will be able to follow along since I will explain everything on an introductory level ." }, { "code": null, "e": 1221, "s": 848, "text": "In this article, I want to bring both fields together. I will present to you an easy to understand, yet hard to solve problem used to build cryptographic algorithms — the so-called Learning Parity with Noise problem, LPN for short. The “L” in LPN should ring your machine learning alarm bells already because this problem can be seen as a routine machine learning problem!" }, { "code": null, "e": 1398, "s": 1221, "text": "But first, let us see where the LPN problem naturally arises in a cryptographic setting and how to define it. We will solve the LPN problem by using machine learning afterward." }, { "code": null, "e": 1560, "s": 1398, "text": "Imagine that you own a hotel and you want to manage access to the guests’ rooms, i.e. each guest should only be able to enter their own room. Makes sense, right?" }, { "code": null, "e": 1780, "s": 1560, "text": "Now, traditionally you could use normal, physical keys. The disadvantage is that people sometimes lose their keys, which means a lot of costs for your business since you have to replace the lock from the affected doors." }, { "code": null, "e": 2129, "s": 1780, "text": "So you decide on deploying smart cards, in particular cards with RFID (radio-frequency identification) chips, and also the corresponding locks. Since you have to provide for a lot of doors and you want to save money, you choose very weak RFID chips, i.e. chips with diminishing computational power, maybe even without its own source of electricity." }, { "code": null, "e": 2437, "s": 2129, "text": "The way your system should work is the following: Every lock and every card has a secret key stored, a binary vector such as s=(1,0,1,0), just much longer in practice. If you hold your card next to a lock, the lock works as a reader, scanning the card’s secret key. The chip is called a tag in this context." }, { "code": null, "e": 2514, "s": 2437, "text": "The clue: If the secret keys of the card and the door match, the door opens." }, { "code": null, "e": 2751, "s": 2514, "text": "Perfect! But how to do it? Well, an easy way is to hold your card next to the lock and the lock tells the chip on the card to send its secret key to the lock. Then the lock checks if both secret keys are equal and open the door, if yes." }, { "code": null, "e": 2922, "s": 2751, "text": "This makes sense, because if you do not have the correct card, i.e. the secret key on your chip is different from the secret key in the door lock, the door will not open." }, { "code": null, "e": 3419, "s": 2922, "text": "The trouble with this solution begins when a guest wants to enter their room: A bad guy, usually called an attacker in cryptography, could sit in the hallway, apparently just typing innocently on their notebook. What the attacker actually does is sniffing the RFID traffic, i.e. reading the communication between the lock and the guest’s chip. If the chip sends the secret key directly, the attacker will see it, store it, forge a card containing this key and then will be able to enter the room." }, { "code": null, "e": 3614, "s": 3419, "text": "So, this is a bad idea. It only works if there are no bad people in the world (highly unlikely). Instead, we have to arm ourselves and improve security for our guests. The idea is the following:" }, { "code": null, "e": 3719, "s": 3614, "text": "The chip somehow has to prove to the lock that it possesses the correct secret key without revealing it." }, { "code": null, "e": 4212, "s": 3719, "text": "I hear you scream: That’s what encryption is for! And you are right. The attacker would only see garbage in the sniffing tool and wouldn’t be able to reconstruct the key. But sadly, the RFID chip is much too weak for encrypting anything because you wanted to save money, remember? Sadly, this is also true for bigger companies in the real world. The chip has nearly no computational power and also only barely enough storage for its secret key. So we need another, more light-weight solution." }, { "code": null, "e": 4382, "s": 4212, "text": "One way to do that is to use a cryptographic protocol like the HB Protocol by Hopper and Blum [1]. This protocol makes it difficult for this attacker to extract the key." }, { "code": null, "e": 4646, "s": 4382, "text": "The vanilla HB Protocol that I am going to introduce has other vulnerabilities and should not be used in practice. I just use because it is easy to explain. For real-world security, more secure extensions of this protocol or other secure protocols should be used." }, { "code": null, "e": 5197, "s": 4646, "text": "So, you have a reader R (the lock) and a tag T (your chip). T now wants to prove to R that it possesses the same secret key without revealing it. This is done by R repeatedly challenging T with questions only a tag with the correct secret key can answer. So far, we have seen that the single question “What is your secret key?” is insecure since this reveals too much information already. Instead, in the HB Protocol T is asked to only reveal small portions of the secret one tiny bit at a time, until R can be sure that T has the correct secret key." }, { "code": null, "e": 5411, "s": 5197, "text": "Imagine that the secret keys of R and T are in fact both the same s=(1,0,1,0). Now R sends a random binary vector a (e.g. a=(1,0,1,1)) to T and expects T to respond back to it the scalar product b=<a, s>, which is" }, { "code": null, "e": 5676, "s": 5411, "text": "in this example. We call this a a challenge. Remember, we deal with bit arithmetic here, so the “+” is, in fact, an XOR. The multiplication is the same as in the real numbers. Or for mathematicians: we calculate in the field GF(2) or F2, the field with 2 elements." }, { "code": null, "e": 5915, "s": 5676, "text": "R can compute the scalar product itself (it knows a and s) and checks T’s answer. If T’s answer is the same, R can be a bit more confident that T indeed has the same secret key. To increase confidence, this game is repeated several times." }, { "code": null, "e": 6215, "s": 5915, "text": "For example, if T does not have the correct key, it would be very unlikely to succeed after a sufficient number of rounds, since a single response would be only correct with probability 0.5. Hence, after 10 rounds, for example, the chance of successful authentication is just 1/1024, less than 0,1%." }, { "code": null, "e": 6666, "s": 6215, "text": "This sounds much better, right? T is not revealing its secret in one go now, instead, it gives some information to R by answering the challenges. But sadly, this is also completely insecure. An attacker could still write down the complete communication between R and T and then easily solve a system of linear equations to recover s. This is done in the following way: Imagine the attacker has written down the following for challenge/response pairs:" }, { "code": null, "e": 6695, "s": 6666, "text": "The attacker also knows that" }, { "code": null, "e": 6774, "s": 6695, "text": "where A is the matrix containing the ai’s as rows and b the bi’s. In our case:" }, { "code": null, "e": 6961, "s": 6774, "text": "So solving this system for s yields the secret. This can also easily be done via Gaussian Elimination if s is much larger, i.e. 1024 bits long. The solution is s=(1,0,1,0) by the way. :)" }, { "code": null, "e": 7419, "s": 6961, "text": "There is one very small but extremely important tweak to make this secure against our attacker: T just adds some random Bernoulli noise to its responses. Instead of sending <a,s> back to R, it flips a coin e which is 1 with probability p and 0 otherwise and sends back <a,s>+e to the reader. In other words, with probability 1-p the tag sends <a,s> back to R and with probability p it flips the response bit from 0 to 1 or from 1 to 0. We assume that p<0.5." }, { "code": null, "e": 7581, "s": 7419, "text": "This does not prevent the attacker from sniffing the communication between R and T and taking notes, of course, but they have to solve the following problem now:" }, { "code": null, "e": 7847, "s": 7581, "text": "This notation indicates that each equation of the equation system is only correct with probability 1-p. More formally, you can write it as As+e=b, where e is the noise vector with each component (independently) being 1 with probability p and 0 with probability 1-p." }, { "code": null, "e": 8165, "s": 7847, "text": "Thus, the attacker has to solve a noisy system of equations over GF(2). For a constant error rate p, this problem — the Learning Parity with Noise (LPN) Problem — is conjectured to be infeasible to solve for large enough length of the secret key. This is also true, if the attacker can get arbitrarily many equations." }, { "code": null, "e": 8435, "s": 8165, "text": "Even with these errors added, R can do its job of determining whether T knows s or not. If T has the correct s, a fraction of about 1-p responses will be correct. That means if p=0.25 the HB Protocol runs for 1000 iterations, T should give around 750 correct responses." }, { "code": null, "e": 8684, "s": 8435, "text": "If T does not have the correct s, it will give a fraction of around 0.5 correct answers, i.e. 500 out of 1000 rounds protocol run. This allows R to decide whether T has the correct secret or not and this protocol still makes sense for our use case." }, { "code": null, "e": 8844, "s": 8684, "text": "Let’s get to the fun part now. We have established that solving the LPN problem means, given a random binary matrix A and a binary vector b=As+e, recovering s." }, { "code": null, "e": 8996, "s": 8844, "text": "The important observation: We can treat each row ai of matrix A now as a sample and the corresponding value bi=<ai, s>+ei in the vector b as the label." }, { "code": null, "e": 9311, "s": 8996, "text": "As found in normal datasets used in machine learning, a label bi actually resembles the scalar product of the feature vector ai and a fixed secret vector s (some ground truth), but with an error term added. But how can we get the secret s when we throw a machine learning algorithm for predicting the labels on it?" }, { "code": null, "e": 9568, "s": 9311, "text": "Well, if we could learn the problem reasonably well, we could generate good predictions for the labels (the scalar products; the ground truth) for each feature vector ai we like. If we throw in the vector a=(1,0,0,0), we would then receive a good guess for" }, { "code": null, "e": 9705, "s": 9568, "text": "the first bit of s! Do the same with the vectors (0, 1, 0, 0), (0, 0, 1, 0) and (0, 0, 0, 1) and we have all the bits of the secret key." }, { "code": null, "e": 9764, "s": 9705, "text": "Thus, we can solve the LPN problem using machine learning." }, { "code": null, "e": 10319, "s": 9764, "text": "The LPN Problem is a very versatile problem that you can also use to build encryption, identity-based encryption, user authentication, oblivious transfer, message authentication codes, and probably more constructions. Also, unlike the factorization problem, the LPN problem cannot easily be solved using quantum computers. Paired together with its light-weightiness it is a good candidate for building post-quantum secure algorithms. So, no worries, if RSA, which is kind of based on factoring large numbers, dies in the presence of quantum computers. ;)" }, { "code": null, "e": 10435, "s": 10319, "text": "For more information and a better, mathematical definition of the LPN problem, please refer to my dissertation [2]." }, { "code": null, "e": 10602, "s": 10435, "text": "Let us first define an LPN oracle, i.e. a class that we can feed with a secret key and an error level p upon instantiation, which gives us as many samples as we want." }, { "code": null, "e": 10652, "s": 10602, "text": "This can easily be done using the following code:" }, { "code": null, "e": 11141, "s": 10652, "text": "import numpy as npclass LPNOracle: def __init__(self, secret, error_rate): self.secret = secret self.dimension = len(secret) self.error_rate = error_rate def sample(self, n_amount): # Create random matrix. A = np.random.randint(0, 2, size=(n_amount, self.dimension)) # Add Bernoulli errors. e = np.random.binomial(1, self.error_rate, n_amount) # Compute the labels. b = np.mod(A @ self.secret + e, 2) return A, b" }, { "code": null, "e": 11226, "s": 11141, "text": "We can now instantiate this an oracle with a random secret of length 16 and p=0.125." }, { "code": null, "e": 11297, "s": 11226, "text": "p = 0.125dim = 16s = np.random.randint(0, 2, dim)lpn = LPNOracle(s, p)" }, { "code": null, "e": 11330, "s": 11297, "text": "We can now sample from the lpn :" }, { "code": null, "e": 11559, "s": 11330, "text": "lpn.sample(3)my output: (array([[1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0], [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0]]), array([1, 1, 1], dtype=int32))" }, { "code": null, "e": 11743, "s": 11559, "text": "Here we have sampled 3 data points. Now, let us try to find s using a Decision Tree. Why? Just because it’s fast and Logistic Regression and Bernoulli Naive Bayes did not work for me." }, { "code": null, "e": 12194, "s": 11743, "text": "from sklearn.tree import DecisionTreeClassifierdt = DecisionTreeClassifier()# Get 100000 samples.A, b = lpn.sample(100000)# Fit the tree.dt.fit(A, b)# Predict all canonical unit vectors (1, 0, 0, ..., 0), (0, 1, 0 ,0, ..., 0), ..., (0, 0, ..., 0, 1).s_candidate = dt.predict(np.eye(dim))# Check if the candidate solution is correct.if np.mod(A @ s_candidate + b, 2).sum() < 14000: print(s_candidate, s)else: print('Wrong candidate. Try again!')" }, { "code": null, "e": 12599, "s": 12194, "text": "The learning algorithm might fail to capture the ground truth and learn another function. In this case, the so-called Hamming weight of the vector is quite high (around 50000 for our vector of length 100000). This corresponds to the case where the tag T has the wrong key and can answer about half of the challenges correctly. If s_candidate = s, the Hamming weight will be around 0.125 * 100000 = 12500." }, { "code": null, "e": 12807, "s": 12599, "text": "Having a threshold of 14000 in this example is a good tradeoff between recognizing the correct secret and not outputting a wrong candidate as the solution. You can find how to get this bound in [2, page 23]." }, { "code": null, "e": 12981, "s": 12807, "text": "We have defined the LPN problem and seen how it arises when trying to break the cryptographic HB Protocol. Then we have solved a small instance using a simple Decision Tree." }, { "code": null, "e": 13095, "s": 12981, "text": "But the journey just starts here: We can use other/better algorithms (deep learning, anyone?) or clever tricks to" }, { "code": null, "e": 13121, "s": 13095, "text": "get higher success rates," }, { "code": null, "e": 13145, "s": 13121, "text": "using fewer samples and" }, { "code": null, "e": 13198, "s": 13145, "text": "being able to solve problems with higher dimensions." }, { "code": null, "e": 13507, "s": 13198, "text": "For a list and explanations of non-machine learning algorithms to solve LPN, check out my dissertation [2]. Also, if you want fame, try to solve an instance with a secret length of 512 and p=0.125, for example. This LPN instance is currently unbroken and used for some real-world cryptosystems. Good luck! ;)" }, { "code": null, "e": 13684, "s": 13507, "text": "[1] N. Hopper and M. Blum, Secure human identification protocols (2001), International conference on the theory and application of cryptology and information security, Springer" }, { "code": null, "e": 13812, "s": 13684, "text": "[2] R. Kübler, Time-Memory Trade-Offs for the Learning Parity with Noise Problem (2018), Dissertation (Ruhr University Bochum)" }, { "code": null, "e": 13902, "s": 13812, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 13928, "s": 13902, "text": "As the last point, if you" }, { "code": null, "e": 14031, "s": 13928, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 14093, "s": 14031, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 14135, "s": 14093, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 14192, "s": 14135, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 14305, "s": 14192, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 14350, "s": 14305, "text": "Thanks a lot, if you consider supporting me!" } ]
Check whether the bit at given position is set or unset in Python
Suppose we have a number n and another value k. We have to check whether the kth bit in n is set (1) or unset (0). The value of k is considered from right hand side. So, if the input is like n = 18 k = 2, then the output will be Set as binary form of 18 is 10010 so the second last bit is 1 (set). To solve this, we will follow these steps − temp := n after shifting bits (k - 1) times to the right if temp AND 1 is 1, thenreturn "Set" return "Set" return "Unset" Let us see the following implementation to get better understanding − Live Demo def solve(n,k): temp = n >> (k - 1) if temp & 1: return "Set" return "Unset" n = 18 k = 2 print(solve(n, k)) 18 Set
[ { "code": null, "e": 1228, "s": 1062, "text": "Suppose we have a number n and another value k. We have to check whether the kth bit in n is set (1) or unset (0). The value of k is considered from right hand side." }, { "code": null, "e": 1360, "s": 1228, "text": "So, if the input is like n = 18 k = 2, then the output will be Set as binary form of 18 is 10010 so the second last bit is 1 (set)." }, { "code": null, "e": 1404, "s": 1360, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1461, "s": 1404, "text": "temp := n after shifting bits (k - 1) times to the right" }, { "code": null, "e": 1498, "s": 1461, "text": "if temp AND 1 is 1, thenreturn \"Set\"" }, { "code": null, "e": 1511, "s": 1498, "text": "return \"Set\"" }, { "code": null, "e": 1526, "s": 1511, "text": "return \"Unset\"" }, { "code": null, "e": 1596, "s": 1526, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1606, "s": 1596, "text": "Live Demo" }, { "code": null, "e": 1731, "s": 1606, "text": "def solve(n,k):\n temp = n >> (k - 1)\n if temp & 1:\n return \"Set\"\n return \"Unset\"\n\nn = 18\nk = 2\nprint(solve(n, k))" }, { "code": null, "e": 1735, "s": 1731, "text": "18\n" }, { "code": null, "e": 1739, "s": 1735, "text": "Set" } ]
GWT - HTML Widget
The HTML widget can cantain arbitrary HTML it can be interpreted as HTML. This widget uses a <div> element, causing it to be displayed with block layout. Following is the declaration for com.google.gwt.user.client.ui.Label class − public class HTML extends Label implements HasHTML Following default CSS Style rule will be applied to all the HTML widget. You can override it as per your requirements. .gwt-HTML { } HTML() Creates an empty HTML. protected HTML(Element element) This constructor may be used by subclasses to explicitly use an existing element. HTML(java.lang.String html) Creates a HTML with the specified html contents. HTML(java.lang.String html, boolean wordWrap) Creates an HTML widget with the specified contents, optionally treating it as HTML, and optionally disabling word wrapping. java.lang.String getHTML() Gets this object's contents as HTML. void setHTML(java.lang.String html) Sets this object's contents via HTML. static HTML wrap(Element element) Creates an HTML widget that wraps an existing <div> or <span> element. This class inherits methods from the following classes − com.google.gwt.user.client.ui.Label com.google.gwt.user.client.ui.Label com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.HasText com.google.gwt.user.client.ui.HasText java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a HTML Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-Green-Border{ border:1px solid green; } .gwt-Blue-Border{ border:1px solid blue; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>HTML Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of HTML widget. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { // create two HTML widgets HTML html1 = new HTML("This is first GWT HTML widget using <b> tag of html."); HTML html2 = new HTML("This is second GWT HTML widget using <i> tag of html."); // use UIObject methods to set HTML widget properties. html1.addStyleName("gwt-Green-Border"); html2.addStyleName("gwt-Blue-Border"); // add widgets to the root panel. VerticalPanel panel = new VerticalPanel(); panel.setSpacing(10); panel.add(html1); panel.add(html2); RootPanel.get("gwtContainer").add(panel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − Print Add Notes Bookmark this page
[ { "code": null, "e": 2177, "s": 2023, "text": "The HTML widget can cantain arbitrary HTML it can be interpreted as HTML. This widget uses a <div> element, causing it to be displayed with block layout." }, { "code": null, "e": 2254, "s": 2177, "text": "Following is the declaration for com.google.gwt.user.client.ui.Label class −" }, { "code": null, "e": 2314, "s": 2254, "text": "public class HTML\n extends Label\n implements HasHTML" }, { "code": null, "e": 2433, "s": 2314, "text": "Following default CSS Style rule will be applied to all the HTML widget. You can override it as per your requirements." }, { "code": null, "e": 2447, "s": 2433, "text": ".gwt-HTML { }" }, { "code": null, "e": 2454, "s": 2447, "text": "HTML()" }, { "code": null, "e": 2477, "s": 2454, "text": "Creates an empty HTML." }, { "code": null, "e": 2509, "s": 2477, "text": "protected HTML(Element element)" }, { "code": null, "e": 2591, "s": 2509, "text": "This constructor may be used by subclasses to explicitly use an existing element." }, { "code": null, "e": 2619, "s": 2591, "text": "HTML(java.lang.String html)" }, { "code": null, "e": 2668, "s": 2619, "text": "Creates a HTML with the specified html contents." }, { "code": null, "e": 2714, "s": 2668, "text": "HTML(java.lang.String html, boolean wordWrap)" }, { "code": null, "e": 2838, "s": 2714, "text": "Creates an HTML widget with the specified contents, optionally treating it as HTML, and optionally disabling word wrapping." }, { "code": null, "e": 2865, "s": 2838, "text": "java.lang.String getHTML()" }, { "code": null, "e": 2902, "s": 2865, "text": "Gets this object's contents as HTML." }, { "code": null, "e": 2938, "s": 2902, "text": "void setHTML(java.lang.String html)" }, { "code": null, "e": 2976, "s": 2938, "text": "Sets this object's contents via HTML." }, { "code": null, "e": 3010, "s": 2976, "text": "static HTML wrap(Element element)" }, { "code": null, "e": 3081, "s": 3010, "text": "Creates an HTML widget that wraps an existing <div> or <span> element." }, { "code": null, "e": 3138, "s": 3081, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 3174, "s": 3138, "text": "com.google.gwt.user.client.ui.Label" }, { "code": null, "e": 3210, "s": 3174, "text": "com.google.gwt.user.client.ui.Label" }, { "code": null, "e": 3249, "s": 3210, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 3288, "s": 3249, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 3325, "s": 3288, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3362, "s": 3325, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3400, "s": 3362, "text": "com.google.gwt.user.client.ui.HasText" }, { "code": null, "e": 3438, "s": 3400, "text": "com.google.gwt.user.client.ui.HasText" }, { "code": null, "e": 3455, "s": 3438, "text": "java.lang.Object" }, { "code": null, "e": 3472, "s": 3455, "text": "java.lang.Object" }, { "code": null, "e": 3666, "s": 3472, "text": "This example will take you through simple steps to show usage of a HTML Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 3768, "s": 3666, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 4377, "s": 3768, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 4455, "s": 4377, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 4739, "s": 4455, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-Green-Border{ \n border:1px solid green;\n}\n\n.gwt-Blue-Border{ \n border:1px solid blue;\n}" }, { "code": null, "e": 4816, "s": 4739, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 5139, "s": 4816, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>HTML Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 5264, "s": 5139, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of HTML widget." }, { "code": null, "e": 6169, "s": 5264, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.client.ui.HTML;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n // create two HTML widgets\n HTML html1 = \n new HTML(\"This is first GWT HTML widget using <b> tag of html.\");\n HTML html2 = \n new HTML(\"This is second GWT HTML widget using <i> tag of html.\");\n\n // use UIObject methods to set HTML widget properties.\n html1.addStyleName(\"gwt-Green-Border\");\n html2.addStyleName(\"gwt-Blue-Border\");\n\n // add widgets to the root panel.\n VerticalPanel panel = new VerticalPanel();\n panel.setSpacing(10);\n panel.add(html1);\n panel.add(html2);\n \n RootPanel.get(\"gwtContainer\").add(panel);\n }\n}" }, { "code": null, "e": 6403, "s": 6169, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 6410, "s": 6403, "text": " Print" }, { "code": null, "e": 6421, "s": 6410, "text": " Add Notes" } ]
How to calculate row means by excluding NA values in an R data frame?
To find the row means we can use rowMeans function but if we have some missing values in the data frame then na.rm=TRUE argument can be used in the same way as it is used while calculating the means for columns. For example, if we have a data frame df that contains two columns x and y each having some missing values then the row means can be calculated as rowMeans(df,na.rm=TRUE). Consider the below data frame − Live Demo set.seed(1515) x1<-sample(c(NA,1,25,31),20,replace=TRUE) x2<-sample(c(NA,5,12,27),20,replace=TRUE) x3<-sample(c(NA,15),20,replace=TRUE) x4<-sample(c(NA,15,9),20,replace=TRUE) df1<-data.frame(x1,x2,x3,x4) df1 x1 x2 x3 x4 1 25 NA NA NA 2 25 12 15 NA 3 25 NA 15 NA 4 31 5 NA NA 5 31 27 15 15 6 NA 5 NA 9 7 25 12 15 NA 8 31 5 15 NA 9 1 5 15 15 10 1 27 NA NA 11 25 NA 15 NA 12 25 12 15 15 13 25 NA 15 9 14 31 NA 15 15 15 31 27 15 9 16 1 12 NA 15 17 1 NA NA 9 18 25 27 15 NA 19 31 5 15 9 20 NA 5 15 NA Finding the row means of df1 − rowMeans(df1,na.rm=TRUE) [1] 25.000000 17.333333 20.000000 18.000000 22.000000 7.000000 17.333333 [8] 17.000000 9.000000 14.000000 20.000000 16.750000 16.333333 20.333333 [15] 20.500000 9.333333 5.000000 22.333333 15.000000 10.000000 Let’s have a look at another example − Live Demo y1<-sample(c(NA,rnorm(5,1,0.003)),20,replace=TRUE) y2<-sample(c(NA,rnorm(10,50,2.47)),20,replace=TRUE) y3<-sample(c(NA,runif(5,1,4)),20,replace=TRUE) y4<-sample(c(NA,runif(5,2,10)),20,replace=TRUE) y5<-sample(c(NA,rexp(5,3.5)),20,replace=TRUE) df2<-data.frame(y1,y2,y3,y4,y5) df2 y1 y2 y3 y4 y5 1 0.9965744 48.73434 2.097240 9.657755 0.32815971 2 1.0003618 44.83392 2.877004 9.735341 0.27053003 3 0.9974534 NA 2.097240 9.657755 0.64288668 4 0.9999057 54.12249 2.097240 NA 0.06486254 5 1.0003618 54.12249 2.877004 5.945301 NA 6 0.9965744 NA NA NA 0.27053003 7 1.0003618 54.12249 NA 5.945301 0.06486254 8 1.0022832 44.83392 1.065712 5.945301 0.64288668 9 1.0003618 54.34290 NA 9.735341 0.64288668 10 1.0003618 NA 2.323069 3.774950 NA 11 0.9999057 54.12249 1.834897 3.774950 0.64288668 12 0.9999057 53.84937 1.834897 NA 0.44797666 13 0.9974534 47.75855 1.065712 9.735341 0.44797666 14 1.0022832 NA 1.065712 3.774950 0.32815971 15 1.0003618 54.12249 2.877004 5.945301 0.27053003 16 0.9974534 54.34290 2.323069 9.657755 0.64288668 17 NA 44.83392 1.065712 3.774950 0.32815971 18 0.9965744 54.34290 NA NA 0.06486254 19 1.0022832 49.89409 2.323069 3.774950 0.06486254 20 1.0003618 49.89409 1.065712 4.078849 0.32815971 Finding the row means of df2 − rowMeans(df2,na.rm=TRUE) [1] 12.3628143 11.7434319 3.3488338 14.3211253 15.9862898 0.6335522 [7] 15.2832544 10.6980210 16.4303723 2.3661269 12.2750266 14.2830369 [13] 12.0010071 1.5427764 12.8431379 13.5928126 12.5006862 18.4681122 [19] 11.4118515 11.2734351
[ { "code": null, "e": 1445, "s": 1062, "text": "To find the row means we can use rowMeans function but if we have some missing values in the data frame then na.rm=TRUE argument can be used in the same way as it is used while calculating the means for columns. For example, if we have a data frame df that contains two columns x and y each having some missing values then the row means can be calculated as rowMeans(df,na.rm=TRUE)." }, { "code": null, "e": 1477, "s": 1445, "text": "Consider the below data frame −" }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 1696, "s": 1488, "text": "set.seed(1515)\nx1<-sample(c(NA,1,25,31),20,replace=TRUE)\nx2<-sample(c(NA,5,12,27),20,replace=TRUE)\nx3<-sample(c(NA,15),20,replace=TRUE)\nx4<-sample(c(NA,15,9),20,replace=TRUE)\ndf1<-data.frame(x1,x2,x3,x4)\ndf1" }, { "code": null, "e": 1986, "s": 1696, "text": " x1 x2 x3 x4\n1 25 NA NA NA\n2 25 12 15 NA\n3 25 NA 15 NA\n4 31 5 NA NA\n5 31 27 15 15\n6 NA 5 NA 9\n7 25 12 15 NA\n8 31 5 15 NA\n9 1 5 15 15\n10 1 27 NA NA\n11 25 NA 15 NA\n12 25 12 15 15\n13 25 NA 15 9\n14 31 NA 15 15\n15 31 27 15 9\n16 1 12 NA 15\n17 1 NA NA 9\n18 25 27 15 NA\n19 31 5 15 9\n20 NA 5 15 NA" }, { "code": null, "e": 2017, "s": 1986, "text": "Finding the row means of df1 −" }, { "code": null, "e": 2042, "s": 2017, "text": "rowMeans(df1,na.rm=TRUE)" }, { "code": null, "e": 2253, "s": 2042, "text": "[1] 25.000000 17.333333 20.000000 18.000000 22.000000 7.000000 17.333333\n[8] 17.000000 9.000000 14.000000 20.000000 16.750000 16.333333 20.333333\n[15] 20.500000 9.333333 5.000000 22.333333 15.000000 10.000000" }, { "code": null, "e": 2292, "s": 2253, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2303, "s": 2292, "text": " Live Demo" }, { "code": null, "e": 2583, "s": 2303, "text": "y1<-sample(c(NA,rnorm(5,1,0.003)),20,replace=TRUE)\ny2<-sample(c(NA,rnorm(10,50,2.47)),20,replace=TRUE)\ny3<-sample(c(NA,runif(5,1,4)),20,replace=TRUE)\ny4<-sample(c(NA,runif(5,2,10)),20,replace=TRUE)\ny5<-sample(c(NA,rexp(5,3.5)),20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3,y4,y5)\ndf2" }, { "code": null, "e": 3514, "s": 2583, "text": "y1 y2 y3 y4 y5\n1 0.9965744 48.73434 2.097240 9.657755 0.32815971\n2 1.0003618 44.83392 2.877004 9.735341 0.27053003\n3 0.9974534 NA 2.097240 9.657755 0.64288668\n4 0.9999057 54.12249 2.097240 NA 0.06486254\n5 1.0003618 54.12249 2.877004 5.945301 NA\n6 0.9965744 NA NA NA 0.27053003\n7 1.0003618 54.12249 NA 5.945301 0.06486254\n8 1.0022832 44.83392 1.065712 5.945301 0.64288668\n9 1.0003618 54.34290 NA 9.735341 0.64288668\n10 1.0003618 NA 2.323069 3.774950 NA\n11 0.9999057 54.12249 1.834897 3.774950 0.64288668\n12 0.9999057 53.84937 1.834897 NA 0.44797666\n13 0.9974534 47.75855 1.065712 9.735341 0.44797666\n14 1.0022832 NA 1.065712 3.774950 0.32815971\n15 1.0003618 54.12249 2.877004 5.945301 0.27053003\n16 0.9974534 54.34290 2.323069 9.657755 0.64288668\n17 NA 44.83392 1.065712 3.774950 0.32815971\n18 0.9965744 54.34290 NA NA 0.06486254\n19 1.0022832 49.89409 2.323069 3.774950 0.06486254\n20 1.0003618 49.89409 1.065712 4.078849 0.32815971" }, { "code": null, "e": 3545, "s": 3514, "text": "Finding the row means of df2 −" }, { "code": null, "e": 3570, "s": 3545, "text": "rowMeans(df2,na.rm=TRUE)" }, { "code": null, "e": 3806, "s": 3570, "text": "[1] 12.3628143 11.7434319 3.3488338 14.3211253 15.9862898 0.6335522\n[7] 15.2832544 10.6980210 16.4303723 2.3661269 12.2750266 14.2830369\n[13] 12.0010071 1.5427764 12.8431379 13.5928126 12.5006862 18.4681122\n[19] 11.4118515 11.2734351" } ]
Rat and Poisoned bottle Problem - GeeksforGeeks
06 Jun, 2021 Given N number of bottles in which one bottle is poisoned. So the task is to find out minimum number of rats required to identify the poisoned bottle. A rat can drink any number of bottles at a time. Examples: Input: N = 4 Output: 2 Input: N = 100 Output: 7 Approach: Let’s start from the base case. For 2 bottles: Taking one rat (R1). If the rat R1 drinks the bottle 1 and dies, then bottle 1 is poisonous. Else the bottle 2 is poisonous. Hence 1 rat is enough to identify For 3 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous. So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous. Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 is poisonous. Hence 2 rats are enough to identify. For 4 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous. So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous. Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 or bottle 4 is poisonous. So the rat R1 drinks the bottle 2 then. If it dies, then the bottle 2 is poisonous, Else the bottle 4 is poisonous. Hence 2 rats are enough to identify. For N bottles: Minimum number of rats required are = ceil(log2 N)) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number of ratsint minRats(int n){ return ceil(log2(n));} // Driver Codeint main(){ // Number of bottles int n = 1025; cout << "Minimum " << minRats(n) << " rat(s) are required" << endl; return 0;} // Java program to implement// the above approachclass GFG{ public static double log2(int x) { return (Math.log(x) / Math.log(2)); } // Function to find the minimum number of rats static int minRats(int n) { return (int)(Math.floor(log2(n)) + 1); } // Driver Code public static void main (String[] args) { // Number of bottles int n = 1025; System.out.println("Minimum " + minRats(n) + " rat(s) are required"); } } // This code is contributed by AnkitRai01 # Python3 program to implement# the above approachimport math # Function to find the# minimum number of ratsdef minRats(n): return math.ceil(math.log2(n)); # Driver Code # Number of bottlesn = 1025;print("Minimum ", end = "")print(minRats(n), end = " ")print("rat(s) are required") # This code is contributed# by divyamohan123 // C# program to implement// the above approachusing System; class GFG{ public static double log2(int x) { return (Math.Log(x) / Math.Log(2)); } // Function to find the minimum number of rats static int minRats(int n) { return (int)(Math.Floor(log2(n)) + 1); } // Driver Code public static void Main (String[] args) { // Number of bottles int n = 1025; Console.WriteLine("Minimum " + minRats(n) + " rat(s) are required"); }} // This code is contributed by 29AjayKumar <script> // Javascript program to implement// the above approach // Function to find the minimum number of ratsfunction minRats(n){ return Math.ceil(Math.log2(n));} // Driver Code // Number of bottlesvar n = 1025;document.write("Minimum " + minRats(n) + " rat(s) are required"); // This code is contributed by importantly </script> Minimum 11 rat(s) are required divyamohan123 ankthon 29AjayKumar ManasChhabra2 sohamkhunte123 importantly Puzzles Puzzles Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation Algorithm to solve Rubik's Cube Top 20 Puzzles Commonly Asked During SDE Interviews Container with Most Water Puzzle 21 | (3 Ants and Triangle) Puzzle 24 | (10 Coins Puzzle) Puzzle | Set 35 (2 Eggs and 100 Floors) Puzzle | 3 cuts to cut round cake into 8 equal pieces Puzzle 31 | (Minimum cut Puzzle) Puzzle 27 | (Hourglasses Puzzle)
[ { "code": null, "e": 24142, "s": 24114, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24343, "s": 24142, "text": "Given N number of bottles in which one bottle is poisoned. So the task is to find out minimum number of rats required to identify the poisoned bottle. A rat can drink any number of bottles at a time. " }, { "code": null, "e": 24354, "s": 24343, "text": "Examples: " }, { "code": null, "e": 24404, "s": 24354, "text": "Input: N = 4 \nOutput: 2\n\nInput: N = 100\nOutput: 7" }, { "code": null, "e": 24447, "s": 24404, "text": "Approach: Let’s start from the base case. " }, { "code": null, "e": 24621, "s": 24447, "text": "For 2 bottles: Taking one rat (R1). If the rat R1 drinks the bottle 1 and dies, then bottle 1 is poisonous. Else the bottle 2 is poisonous. Hence 1 rat is enough to identify" }, { "code": null, "e": 25021, "s": 24621, "text": "For 3 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous. So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous. Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 is poisonous. Hence 2 rats are enough to identify. " }, { "code": null, "e": 25549, "s": 25021, "text": "For 4 bottles: Taking two rats (R1) and (R2). If the rat R1 drinks the bottle 1 and bottle 3 and dies, then bottle 1 or bottle 3 is poisonous. So the rat R2 drinks the bottle 1 then. If it dies, then the bottle 1 is poisonous, Else the bottle 3 is poisonous. Now if the rat R1 does not die after drinking from bottle 1 and bottle 3, then bottle 2 or bottle 4 is poisonous. So the rat R1 drinks the bottle 2 then. If it dies, then the bottle 2 is poisonous, Else the bottle 4 is poisonous. Hence 2 rats are enough to identify. " }, { "code": null, "e": 25565, "s": 25549, "text": "For N bottles: " }, { "code": null, "e": 25618, "s": 25565, "text": "Minimum number of rats required are = ceil(log2 N)) " }, { "code": null, "e": 25671, "s": 25618, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25675, "s": 25671, "text": "C++" }, { "code": null, "e": 25680, "s": 25675, "text": "Java" }, { "code": null, "e": 25688, "s": 25680, "text": "Python3" }, { "code": null, "e": 25691, "s": 25688, "text": "C#" }, { "code": null, "e": 25702, "s": 25691, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number of ratsint minRats(int n){ return ceil(log2(n));} // Driver Codeint main(){ // Number of bottles int n = 1025; cout << \"Minimum \" << minRats(n) << \" rat(s) are required\" << endl; return 0;}", "e": 26058, "s": 25702, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ public static double log2(int x) { return (Math.log(x) / Math.log(2)); } // Function to find the minimum number of rats static int minRats(int n) { return (int)(Math.floor(log2(n)) + 1); } // Driver Code public static void main (String[] args) { // Number of bottles int n = 1025; System.out.println(\"Minimum \" + minRats(n) + \" rat(s) are required\"); } } // This code is contributed by AnkitRai01", "e": 26622, "s": 26058, "text": null }, { "code": "# Python3 program to implement# the above approachimport math # Function to find the# minimum number of ratsdef minRats(n): return math.ceil(math.log2(n)); # Driver Code # Number of bottlesn = 1025;print(\"Minimum \", end = \"\")print(minRats(n), end = \" \")print(\"rat(s) are required\") # This code is contributed# by divyamohan123", "e": 26957, "s": 26622, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ public static double log2(int x) { return (Math.Log(x) / Math.Log(2)); } // Function to find the minimum number of rats static int minRats(int n) { return (int)(Math.Floor(log2(n)) + 1); } // Driver Code public static void Main (String[] args) { // Number of bottles int n = 1025; Console.WriteLine(\"Minimum \" + minRats(n) + \" rat(s) are required\"); }} // This code is contributed by 29AjayKumar", "e": 27529, "s": 26957, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to find the minimum number of ratsfunction minRats(n){ return Math.ceil(Math.log2(n));} // Driver Code // Number of bottlesvar n = 1025;document.write(\"Minimum \" + minRats(n) + \" rat(s) are required\"); // This code is contributed by importantly </script>", "e": 27893, "s": 27529, "text": null }, { "code": null, "e": 27924, "s": 27893, "text": "Minimum 11 rat(s) are required" }, { "code": null, "e": 27940, "s": 27926, "text": "divyamohan123" }, { "code": null, "e": 27948, "s": 27940, "text": "ankthon" }, { "code": null, "e": 27960, "s": 27948, "text": "29AjayKumar" }, { "code": null, "e": 27974, "s": 27960, "text": "ManasChhabra2" }, { "code": null, "e": 27989, "s": 27974, "text": "sohamkhunte123" }, { "code": null, "e": 28001, "s": 27989, "text": "importantly" }, { "code": null, "e": 28009, "s": 28001, "text": "Puzzles" }, { "code": null, "e": 28017, "s": 28009, "text": "Puzzles" }, { "code": null, "e": 28025, "s": 28017, "text": "Puzzles" }, { "code": null, "e": 28123, "s": 28025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28132, "s": 28123, "text": "Comments" }, { "code": null, "e": 28145, "s": 28132, "text": "Old Comments" }, { "code": null, "e": 28194, "s": 28145, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 28226, "s": 28194, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28278, "s": 28226, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 28304, "s": 28278, "text": "Container with Most Water" }, { "code": null, "e": 28338, "s": 28304, "text": "Puzzle 21 | (3 Ants and Triangle)" }, { "code": null, "e": 28368, "s": 28338, "text": "Puzzle 24 | (10 Coins Puzzle)" }, { "code": null, "e": 28408, "s": 28368, "text": "Puzzle | Set 35 (2 Eggs and 100 Floors)" }, { "code": null, "e": 28462, "s": 28408, "text": "Puzzle | 3 cuts to cut round cake into 8 equal pieces" }, { "code": null, "e": 28495, "s": 28462, "text": "Puzzle 31 | (Minimum cut Puzzle)" } ]
How to extract img src and alt from html using PHP? - GeeksforGeeks
15 May, 2019 Extraction of image attributes like ‘src’, ‘alt’, ‘height’, ‘width’ etc from a HTML page using PHP. This task can be done using the following steps. Loading HTML content in a variable(DOM variable). Selecting each image in that document. Selecting attribute and save it’s content to a variable. Output as HTML img object or as plain values as required. Example 1: This example displays the image object as output. <?php// error_reporting(0); function crawl_page($url) { $dom = new DOMDocument('1.0'); // Loading HTML content in $dom @$dom->loadHTMLFile($url); // Selecting all image i.e. img tag object $anchors = $dom -> getElementsByTagName('img'); // Extracting attribute from each object foreach ($anchors as $element) { // Extracting value of src attribute of // the current image object $src = $element -> getAttribute('src'); // Extracting value of alt attribute of // the current image object $alt = $element -> getAttribute('alt'); // Extracting value of height attribute // of the current image object $height = $element -> getAttribute('height'); // Extracting value of width attribute of // the current image object $width = $element -> getAttribute('width'); // Given Output as image with extracted attribute, // you can print value of those attributes also echo '<img src="'.$src.'" alt="'.$alt.'" height="' . $height.'" width="'.$width.'"/>'; }} crawl_page("https://www.google.com/search?q=geeksforgeeks&tbm=isch"); ?> Output: Example 2: This example displays the attribute of an image object. <?php// error_reporting(0); function crawl_page($url) { $dom = new DOMDocument('1.0'); // Loading HTML content in $dom @$dom->loadHTMLFile($url); // Selecting all image i.e. img tag object $anchors = $dom -> getElementsByTagName('img'); // Extracting attribute from each object foreach ($anchors as $element) { // Extracting value of src attribute of // the current image object $src = $element -> getAttribute('src'); // Extracting value of alt attribute of // the current image object $alt = $element -> getAttribute('alt'); // Extracting value of height attribute // of the current image object $height = $element -> getAttribute('height'); // Extracting value of width attribute of // the current image object $width = $element -> getAttribute('width'); // Display Output as value of those attributes echo 'src='.$src.'<br> alt='.$alt.'<br> height=' . $height.'<br> width='.$width.'<hr>'; }} crawl_page("https://www.google.com/search?q=flowers&tbm=isch"); ?> Output: Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP Database connection How to pass a PHP array to a JavaScript function? String comparison using == vs strcmp() in PHP How to fetch data from localserver database and display on HTML table using PHP ? How to call PHP function on the click of a Button ? String comparison using == vs strcmp() in PHP How to pass a PHP array to a JavaScript function? How to encrypt and decrypt passwords using PHP ?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n15 May, 2019" }, { "code": null, "e": 24730, "s": 24581, "text": "Extraction of image attributes like ‘src’, ‘alt’, ‘height’, ‘width’ etc from a HTML page using PHP. This task can be done using the following steps." }, { "code": null, "e": 24780, "s": 24730, "text": "Loading HTML content in a variable(DOM variable)." }, { "code": null, "e": 24819, "s": 24780, "text": "Selecting each image in that document." }, { "code": null, "e": 24876, "s": 24819, "text": "Selecting attribute and save it’s content to a variable." }, { "code": null, "e": 24934, "s": 24876, "text": "Output as HTML img object or as plain values as required." }, { "code": null, "e": 24995, "s": 24934, "text": "Example 1: This example displays the image object as output." }, { "code": "<?php// error_reporting(0); function crawl_page($url) { $dom = new DOMDocument('1.0'); // Loading HTML content in $dom @$dom->loadHTMLFile($url); // Selecting all image i.e. img tag object $anchors = $dom -> getElementsByTagName('img'); // Extracting attribute from each object foreach ($anchors as $element) { // Extracting value of src attribute of // the current image object $src = $element -> getAttribute('src'); // Extracting value of alt attribute of // the current image object $alt = $element -> getAttribute('alt'); // Extracting value of height attribute // of the current image object $height = $element -> getAttribute('height'); // Extracting value of width attribute of // the current image object $width = $element -> getAttribute('width'); // Given Output as image with extracted attribute, // you can print value of those attributes also echo '<img src=\"'.$src.'\" alt=\"'.$alt.'\" height=\"' . $height.'\" width=\"'.$width.'\"/>'; }} crawl_page(\"https://www.google.com/search?q=geeksforgeeks&tbm=isch\"); ?>", "e": 26237, "s": 24995, "text": null }, { "code": null, "e": 26245, "s": 26237, "text": "Output:" }, { "code": null, "e": 26312, "s": 26245, "text": "Example 2: This example displays the attribute of an image object." }, { "code": "<?php// error_reporting(0); function crawl_page($url) { $dom = new DOMDocument('1.0'); // Loading HTML content in $dom @$dom->loadHTMLFile($url); // Selecting all image i.e. img tag object $anchors = $dom -> getElementsByTagName('img'); // Extracting attribute from each object foreach ($anchors as $element) { // Extracting value of src attribute of // the current image object $src = $element -> getAttribute('src'); // Extracting value of alt attribute of // the current image object $alt = $element -> getAttribute('alt'); // Extracting value of height attribute // of the current image object $height = $element -> getAttribute('height'); // Extracting value of width attribute of // the current image object $width = $element -> getAttribute('width'); // Display Output as value of those attributes echo 'src='.$src.'<br> alt='.$alt.'<br> height=' . $height.'<br> width='.$width.'<hr>'; }} crawl_page(\"https://www.google.com/search?q=flowers&tbm=isch\"); ?>", "e": 27490, "s": 26312, "text": null }, { "code": null, "e": 27498, "s": 27490, "text": "Output:" }, { "code": null, "e": 27505, "s": 27498, "text": "Picked" }, { "code": null, "e": 27509, "s": 27505, "text": "PHP" }, { "code": null, "e": 27522, "s": 27509, "text": "PHP Programs" }, { "code": null, "e": 27539, "s": 27522, "text": "Web Technologies" }, { "code": null, "e": 27566, "s": 27539, "text": "Web technologies Questions" }, { "code": null, "e": 27570, "s": 27566, "text": "PHP" }, { "code": null, "e": 27668, "s": 27570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27677, "s": 27668, "text": "Comments" }, { "code": null, "e": 27690, "s": 27677, "text": "Old Comments" }, { "code": null, "e": 27772, "s": 27690, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27814, "s": 27772, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 27838, "s": 27814, "text": "PHP Database connection" }, { "code": null, "e": 27888, "s": 27838, "text": "How to pass a PHP array to a JavaScript function?" }, { "code": null, "e": 27934, "s": 27888, "text": "String comparison using == vs strcmp() in PHP" }, { "code": null, "e": 28016, "s": 27934, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28068, "s": 28016, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28114, "s": 28068, "text": "String comparison using == vs strcmp() in PHP" }, { "code": null, "e": 28164, "s": 28114, "text": "How to pass a PHP array to a JavaScript function?" } ]
Tryit Editor v3.7
CSS Grid Item Tryit: The grid-row property
[ { "code": null, "e": 23, "s": 9, "text": "CSS Grid Item" } ]
Customer Churn Prediction within Music Streaming using PySpark | by Isak Kabir | Towards Data Science
It is key for a music streaming business to identify users that are likely to churn, i.e. users who are at risk of downgrading from premium and free subscription to cancelling the service. If a music streaming business accurately identifies such users in advance, they can offer them discounts or other similar incentives and save millions in revenues. It is a well-known fact that it is more expensive to acquire a new customer than it is to retain an existing one. This is because returning customers will likely spend 67% more on your company’s products and services. We want to identify the users that could potentially cancel their account and leave the service. Our goal in this project was to help a fictional business (similar to Spotify and Pandora) by building and training a binary classifier that is able to accurately identify users who cancelled the music streaming service, based on the patterns obtained from their past activity and interaction with the service. Define churn variable: 1 — users who cancelled their subscription within the observation period, and 0 — users who kept the service throughout Due to the size of the data-set, the project was carried out by leveraging Apache Spark distributed cluster-computing framework capabilities, using Python API for Spark, PySpark. # import librariesfrom pyspark import SparkContext, SparkConffrom pyspark.sql import SparkSessionfrom pyspark.sql import Windowfrom pyspark.sql.functions import udf, col, concat, count, lit, avg, lag, first, last, whenfrom pyspark.sql.functions import min as Fmin, max as Fmax, sum as Fsum, round as Froundfrom pyspark.sql.types import IntegerType, DateType, TimestampTypefrom pyspark.ml import Pipelinefrom pyspark.ml.feature import VectorAssembler, Normalizer, StandardScalerfrom pyspark.ml.regression import LinearRegressionfrom pyspark.ml.classification import LogisticRegression, RandomForestClassifier, GBTClassifierfrom pyspark.ml.clustering import KMeansfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilderfrom pyspark.ml.evaluation import BinaryClassificationEvaluator,# create a Spark sessionspark = SparkSession \.builder \.appName(‘CustomerChurn’) \.getOrCreate()# Check Spark configurationspark.sparkContext.getConf().getAll()path = "mini_sparkify_event_data.json"df = spark.read.json(path) The data-set contains user activity logs recorded between October 1, 2018 and December 01, 2018. The full data-set consists of approximately 26 million rows/logs, whereas the subset contains 286 500 rows. The full data-set collects logs of 22 277 different users, whereas the subset only covers the activities of 225 users. The subset dataset contains 58 300 Free users and 228 000 Paid users. Both data-sets have 18 columns, as listed below. root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true) Every activity log belongs to a specific user. Seven columns in the data-set represent static user-level information (fixed for all logs belonging to a specific user): artist: artist that the user was listening touserId: user identifier;sessionId: a unique ID that identifies a single continuous period of use by a user of the service. Multiple users can have sessions labelled with the same sessionIdfirstName: user’s first namelastName: user’s last namegender: user’s gender; 2 categories (M and F)location: user’s locationuserAgent: agent used by the user to access the streaming service; 57 different categoriesregistration: user’s registration timestamplevel (non-static): subscription level; 2 categories (free and paid)page: what page was the user visiting when this event got generated. The different types of pages are detailed in the section below The page column contains logs for all the page a user has visited in the app. >>> df.select('page').distinct().show(10)+--------------------+| page|+--------------------+| Cancel|| Submit Downgrade|| Thumbs Down|| Home|| Downgrade|| Roll Advert|| Logout|| Save Settings||Cancellation Conf...|| About|+-------------------- Based on the analysis performed it seems that the maximum time between two consecutive logs that still belong to the same session is one hour. # Explore the auth columndf.groupby('auth').count().show()+----------+------+| auth| count|+----------+------+|Logged Out| 8249|| Cancelled| 52|| Guest| 97|| Logged In|278102|+----------+------+ We can also see that users are quite active, one of the top users has listed to about 8000 songs in total. The graphs below indicates that churned users are usually from California and New Jersey, mostly paid subscribers are leaving the Music app and more men than women tend to cancel their subscription. California and New York states tend to be denser in population, and therefore could expect higher numbers of churn and higher in overall engagement. It is easy to see from the plot below that the provided Sparkify data-set is a case of an imbalanced dataset, as the share of churned users is only a bit more than 20% (52) compared to 174. First, we had to transform the original data-set (one row per log) to a data-set with user-level information or statistics (one row per user). We achieved this by performing several mapping (e.g. obtaining user’s gender, length of observation period, etc.) and aggregation steps. For the few users who registered after October 1 the registration times are not consistent with the actual log timestamps and activity types. We thus had to identify late registrations by finding Submit Registration logs in the page column. This step was not trivial as such log events are not mapped to any userId so those had to be extracted from the sessionId information. For the few users who registered late the observation start was then set to the timestamp of their first log, whereas for all other users the default October 1 was used. # Lag the page columnwindowsession = Window.partitionBy('sessionId').orderBy('ts')df = df.withColumn("lagged_page", lag(df.page).over(windowsession))windowuser = Window.partitionBy('userId').orderBy('ts').rangeBetween(Window.unboundedPreceding, Window.unboundedFollowing)# Identify users that registered after the start of observation, and infer the start date accordinglydf = df.withColumn("beforefirstlog", first(col('lagged_page')).over(windowuser))df = df.withColumn("firstlogtime", first(col('ts')).over(windowuser))df = df.withColumn("obsstart", when(df.beforefirstlog == "Submit Registration", df.firstlogtime).otherwise(obs_start_default))# For each log compute the time from the beginning of observation...df = df.withColumn("timefromstart", col('ts')-col("obsstart"))# ...and time before the end of observationdf = df.withColumn("timebeforeend", col('obsend')-col('ts')) Similar to above, there are users who cancelled their service before the end of the default observation period, the so-called churned users. For each such user the end of the respective observation period has been set to the timestamp of his/her last log entry, whereas for all other users the default 1st of December. The newly created user-level data-set includes the following columns: lastlevel: user’s last subscription level, transformed into binary format (1 — paid tier, 0 — free tier)gender: gender, transformed into binary format (1 — female, 0 — male)obsstart, obsend: start and end of user-specific observation period endstate: user’s last interaction in the observation periodnact: user’s total number of interactions in the observation periodnsongs, ntbup, ntbdown, nfriend, nplaylist, ndgrade, nupgrade, nhome, nadvert, nhelp, nsettings, nerror: number of songs played, thumbs up given, thumbs down given, friends added, songs added to playlist, downgrades, upgrades, home page visits, advertisements played, help page visits, settings visits, errors, respectively nact_recent, nact_oldest: user’s activity in the last and first k days of the observation window, respectivelynsongs_recent, nsongs_oldest: songs played in the last and first k days of the observation window, respectively # Aggregation by userIddf_user = df.groupby(‘userId’)\.agg( # User-level features first(when(col(‘lastlevel’) == ‘paid’, 1).otherwise(0)).alias(‘lastlevel’), first(when(col(‘gender’) == “F”, 1).otherwise(0)).alias(‘gender’), first(col(‘obsstart’)).alias(‘obsstart’), first(col(‘obsend’)).alias(‘obsend’), first(col(‘endstate’)).alias(‘endstate’), # Aggregated activity statistics count(col(‘page’)).alias(‘nact’),Fsum(when(col(‘page’) == “NextSong”, 1).otherwise(0)).alias(“nsongs”), Fsum(when(col(‘page’) == “Thumbs Up”, 1).otherwise(0)).alias(“ntbup”), Fsum(when(col(‘page’) == “Thumbs Down”, 1).otherwise(0)).alias(“ntbdown”), Fsum(when(col(‘page’) == “Add Friend”, 1).otherwise(0)).alias(“nfriend”), Fsum(when(col(‘page’) == “Add to Playlist”, 1).otherwise(0)).alias(“nplaylist”), Fsum(when(col(‘page’) == “Submit Downgrade”, 1).otherwise(0)).alias(“ndgrade”), Fsum(when(col(‘page’) == “Submit Upgrade”, 1).otherwise(0)).alias(“nugrade”), Fsum(when(col(‘page’) == “Home”, 1).otherwise(0)).alias(“nhome”), Fsum(when(col(‘page’) == “Roll Advert”, 1).otherwise(0)).alias(“nadvert”), Fsum(when(col(‘page’) == “Help”, 1).otherwise(0)).alias(“nhelp”), Fsum(when(col(‘page’) == “Settings”, 1).otherwise(0)).alias(“nsettings”), Fsum(when(col(‘page’) == “Error”, 1).otherwise(0)).alias(“nerror”), # Aggregated activity statistics in different periods Fsum(when(col(‘timebeforeend’) < trend_est, 1).otherwise(0)).alias(“nact_recent”), Fsum(when(col(‘timefromstart’) < trend_est, 1).otherwise(0)).alias(“nact_oldest”), Fsum(when((col(‘page’) == “NextSong”) & (col(‘timebeforeend’) < trend_est), 1).otherwise(0)).alias(“nsongs_recent”), Fsum(when((col(‘page’) == “NextSong”) & (col(‘timefromstart’) < trend_est), 1).otherwise(0)).alias(“nsongs_oldest”) ) After completing the feature engineering step we have analysed the correlations between the built features. # For visualization purposes we switch to pandas dataframesdf_user_pd = df_user.toPandas()# Calculate correlations between numerical featurescormat = df_user_pd[['nact_perh','nsongs_perh', 'nhome_perh', 'ntbup_perh','ntbdown_perh', 'nfriend_perh','nplaylist_perh', 'nadvert_perh', 'nerror_perh', 'upgradedowngrade', 'songratio', 'positiveratio','negativeratio', 'updownratio', 'trend_act', 'trend_songs', 'avgsessionitems', 'avgsessionlength','avgsongs']].corr()# Plot correlationsplt.rcParams['figure.figsize'] = (10,10)plt.subplots_adjust(left=0.20, right=0.9, top=0.95, bottom=0.15)sns.heatmap(cormat, cmap = "YlGnBu", square = True, vmin = -1, vmax = 1);plt.title('Feature correlations');plt.savefig('correlations.png') The heat-map above describes a high correlation between variables nact_perh and nsongs_perh. This is expected, as listening to songs is obviously by far the most common user activity. For the same reason there is a high correlation between trend_act and trend_songs. In both cases we decided to simply remove from all further analyses and keep only variables that measure the most important interaction — playing songs. In order to further reduce the multi-colinearity in the data, we also decided not to use nhome_perh and nplaylist_perh in the model. Moreover, avgsessionlength is highly correlated with average items in each session, hence it can be ignored too. From the visualisations presented below the following observations have been made: on average churned users played more songs per hour; churned users gave significantly more thumbs down per hour, and had to watch more advertisements on average; the ratio of songs and positive interactions relative to total activity was typically lower for churned users churned users had on average less interactions per session churn rate is higher for users in the free subscription plan churn rate is slightly higher for male users No features have been removed based on this analysis. We first performed grid search with cross validation to test the performance of several parameter combinations, all on the user-level data obtained from the smaller Sparkify user activity data-set. Based on the performance results obtained in cross validation (measured by AUC and F1 score), we identified the best-performing model instances and retrained them on the entire training set. maxIter (maximum number of iterations, default=100) : [10, 30] regParam (regularization parameter, default=0.0) : [0.0, 0.1] elasticNetParam (mixing parameter — 0 for L2 penalty, 1 for L1 penalty, default=0.0) : [0.0, 0.5] maxDepth (maximum tree depth, default=5) : [4, 5, 6, 7] numTrees (number of trees, default=20) : [20, 40] maxDepth (maximum tree depth, default=5) : [4, 5] maxIter (maximum number of iterations, default=20) : [20, 100] In the defined grid search objects the performance of each parameter combination is by default measured by average AUC score (area under the ROC) obtained in 4-fold cross validation. AUC is briefly explained in Section 4.4 below. numeric_columns = [‘nsongs_perh’, ‘ntbup_perh’,’ntbdown_perh’, ‘nfriend_perh’, ‘nadvert_perh’, ‘nerror_perh’, ‘upgradedowngrade’, ‘songratio’, ‘positiveratio’,’negativeratio’, ‘updownratio’, ‘trend_songs’, ‘avgsessionitems’,’avgsongs’]# Combining multiple numerical features using VectorAssemblernumeric_assembler = VectorAssembler(inputCols = numeric_columns, outputCol = “numericvectorized”)# Standardizing numerical featuresscaler = StandardScaler(inputCol = “numericvectorized”, outputCol = “numericscaled”, withStd = True, withMean = True)# Adding the two binary featuresbinary_columns = [‘lastlevel’, ‘gender’]total_assembler = VectorAssembler(inputCols = binary_columns + [“numericscaled”], outputCol = “features”)# Defining three different pipelines with three different classifiers, all with default parameters# Logistic regression lr = LogisticRegression()pipeline_lr = Pipeline(stages = [numeric_assembler, scaler, total_assembler, lr])# Random forest classifierrf = RandomForestClassifier()pipeline_rf = Pipeline(stages = [numeric_assembler, scaler, total_assembler, rf])# Gradient-boosted tree classifiergb = GBTClassifier()pipeline_gb = Pipeline(stages = [numeric_assembler, scaler, total_assembler, gb]) F1 score is preferred performance metrics to this problem. The input user-level data-set is imbalanced. Music streaming service aims to identify most of the users that are likely to churn (aiming for high recall), but at the same time does not want to give too many discounts for no reason (aiming for high precision), i.e. to users who are actually happy with the service (false positives) — this can help music streaming business prevent financial losses. class F1score(Evaluator):def __init__(self, predictionCol = “prediction”, labelCol=”label”): self.predictionCol = predictionCol self.labelCol = labelColdef _evaluate(self, dataset): # Calculate F1 score tp = dataset.where((dataset.label == 1) & (dataset.prediction == 1)).count() fp = dataset.where((dataset.label == 0) & (dataset.prediction == 1)).count() tn = dataset.where((dataset.label == 0) & (dataset.prediction == 0)).count() fn = dataset.where((dataset.label == 1) & (dataset.prediction == 0)).count() # Add epsilon to prevent division by zero precision = tp / (tp + fp + 0.00001) recall = tp / (tp + fn + 0.00001) f1 = 2 * precision * recall / (precision + recall + 0.00001) return f1def isLargerBetter(self): return True The best performing model has AUC score of 0.981 and F1 score of 0.855. As seen in the visualisation above, the most important feature for identifying churned users is the nerror_perh which measures how many error pages have been shown to the user per hour. The more errors a user has to experience the more likely it is that he/she is dissatisfied with the service. Similar holds also for the second and third most important feature, ntbdown_perh and nadvert_perh which measure the number of thumbs down given per hour and number of advertisements seen per hour, respectively. Most interesting feature is the trend_songs variable which measures a user’s song listening activity trend, as the fourth most important. The Gradient-boosted tree classifier has a F1 score (precision and recall) of 0.855 and can identify churned users based on past user activity and interaction with the music streaming service, which can help the business prevent from severe financial losses. Some improvements are to perform comprehensive grid search for the model on the full Sparkify data-set. Utilise song-level features that have been ignored so far, e.g. calculate the user’s listening diversity in terms of different songs/artists listened to in the specified observation period, etc. Build new features such as e.g. average length of song listening sessions, ratios of skipped or partially listened songs, etc. For more details about this project, see the link to my Github available here.
[ { "code": null, "e": 743, "s": 172, "text": "It is key for a music streaming business to identify users that are likely to churn, i.e. users who are at risk of downgrading from premium and free subscription to cancelling the service. If a music streaming business accurately identifies such users in advance, they can offer them discounts or other similar incentives and save millions in revenues. It is a well-known fact that it is more expensive to acquire a new customer than it is to retain an existing one. This is because returning customers will likely spend 67% more on your company’s products and services." }, { "code": null, "e": 1151, "s": 743, "text": "We want to identify the users that could potentially cancel their account and leave the service. Our goal in this project was to help a fictional business (similar to Spotify and Pandora) by building and training a binary classifier that is able to accurately identify users who cancelled the music streaming service, based on the patterns obtained from their past activity and interaction with the service." }, { "code": null, "e": 1294, "s": 1151, "text": "Define churn variable: 1 — users who cancelled their subscription within the observation period, and 0 — users who kept the service throughout" }, { "code": null, "e": 1473, "s": 1294, "text": "Due to the size of the data-set, the project was carried out by leveraging Apache Spark distributed cluster-computing framework capabilities, using Python API for Spark, PySpark." }, { "code": null, "e": 2487, "s": 1473, "text": "# import librariesfrom pyspark import SparkContext, SparkConffrom pyspark.sql import SparkSessionfrom pyspark.sql import Windowfrom pyspark.sql.functions import udf, col, concat, count, lit, avg, lag, first, last, whenfrom pyspark.sql.functions import min as Fmin, max as Fmax, sum as Fsum, round as Froundfrom pyspark.sql.types import IntegerType, DateType, TimestampTypefrom pyspark.ml import Pipelinefrom pyspark.ml.feature import VectorAssembler, Normalizer, StandardScalerfrom pyspark.ml.regression import LinearRegressionfrom pyspark.ml.classification import LogisticRegression, RandomForestClassifier, GBTClassifierfrom pyspark.ml.clustering import KMeansfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilderfrom pyspark.ml.evaluation import BinaryClassificationEvaluator,# create a Spark sessionspark = SparkSession \\.builder \\.appName(‘CustomerChurn’) \\.getOrCreate()# Check Spark configurationspark.sparkContext.getConf().getAll()path = \"mini_sparkify_event_data.json\"df = spark.read.json(path)" }, { "code": null, "e": 2930, "s": 2487, "text": "The data-set contains user activity logs recorded between October 1, 2018 and December 01, 2018. The full data-set consists of approximately 26 million rows/logs, whereas the subset contains 286 500 rows. The full data-set collects logs of 22 277 different users, whereas the subset only covers the activities of 225 users. The subset dataset contains 58 300 Free users and 228 000 Paid users. Both data-sets have 18 columns, as listed below." }, { "code": null, "e": 3606, "s": 2930, "text": "root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true)" }, { "code": null, "e": 3774, "s": 3606, "text": "Every activity log belongs to a specific user. Seven columns in the data-set represent static user-level information (fixed for all logs belonging to a specific user):" }, { "code": null, "e": 4464, "s": 3774, "text": "artist: artist that the user was listening touserId: user identifier;sessionId: a unique ID that identifies a single continuous period of use by a user of the service. Multiple users can have sessions labelled with the same sessionIdfirstName: user’s first namelastName: user’s last namegender: user’s gender; 2 categories (M and F)location: user’s locationuserAgent: agent used by the user to access the streaming service; 57 different categoriesregistration: user’s registration timestamplevel (non-static): subscription level; 2 categories (free and paid)page: what page was the user visiting when this event got generated. The different types of pages are detailed in the section below" }, { "code": null, "e": 4542, "s": 4464, "text": "The page column contains logs for all the page a user has visited in the app." }, { "code": null, "e": 4891, "s": 4542, "text": ">>> df.select('page').distinct().show(10)+--------------------+| page|+--------------------+| Cancel|| Submit Downgrade|| Thumbs Down|| Home|| Downgrade|| Roll Advert|| Logout|| Save Settings||Cancellation Conf...|| About|+--------------------" }, { "code": null, "e": 5034, "s": 4891, "text": "Based on the analysis performed it seems that the maximum time between two consecutive logs that still belong to the same session is one hour." }, { "code": null, "e": 5245, "s": 5034, "text": "# Explore the auth columndf.groupby('auth').count().show()+----------+------+| auth| count|+----------+------+|Logged Out| 8249|| Cancelled| 52|| Guest| 97|| Logged In|278102|+----------+------+" }, { "code": null, "e": 5890, "s": 5245, "text": "We can also see that users are quite active, one of the top users has listed to about 8000 songs in total. The graphs below indicates that churned users are usually from California and New Jersey, mostly paid subscribers are leaving the Music app and more men than women tend to cancel their subscription. California and New York states tend to be denser in population, and therefore could expect higher numbers of churn and higher in overall engagement. It is easy to see from the plot below that the provided Sparkify data-set is a case of an imbalanced dataset, as the share of churned users is only a bit more than 20% (52) compared to 174." }, { "code": null, "e": 6170, "s": 5890, "text": "First, we had to transform the original data-set (one row per log) to a data-set with user-level information or statistics (one row per user). We achieved this by performing several mapping (e.g. obtaining user’s gender, length of observation period, etc.) and aggregation steps." }, { "code": null, "e": 6546, "s": 6170, "text": "For the few users who registered after October 1 the registration times are not consistent with the actual log timestamps and activity types. We thus had to identify late registrations by finding Submit Registration logs in the page column. This step was not trivial as such log events are not mapped to any userId so those had to be extracted from the sessionId information." }, { "code": null, "e": 6716, "s": 6546, "text": "For the few users who registered late the observation start was then set to the timestamp of their first log, whereas for all other users the default October 1 was used." }, { "code": null, "e": 7616, "s": 6716, "text": "# Lag the page columnwindowsession = Window.partitionBy('sessionId').orderBy('ts')df = df.withColumn(\"lagged_page\", lag(df.page).over(windowsession))windowuser = Window.partitionBy('userId').orderBy('ts').rangeBetween(Window.unboundedPreceding, Window.unboundedFollowing)# Identify users that registered after the start of observation, and infer the start date accordinglydf = df.withColumn(\"beforefirstlog\", first(col('lagged_page')).over(windowuser))df = df.withColumn(\"firstlogtime\", first(col('ts')).over(windowuser))df = df.withColumn(\"obsstart\", when(df.beforefirstlog == \"Submit Registration\", df.firstlogtime).otherwise(obs_start_default))# For each log compute the time from the beginning of observation...df = df.withColumn(\"timefromstart\", col('ts')-col(\"obsstart\"))# ...and time before the end of observationdf = df.withColumn(\"timebeforeend\", col('obsend')-col('ts'))" }, { "code": null, "e": 7935, "s": 7616, "text": "Similar to above, there are users who cancelled their service before the end of the default observation period, the so-called churned users. For each such user the end of the respective observation period has been set to the timestamp of his/her last log entry, whereas for all other users the default 1st of December." }, { "code": null, "e": 8005, "s": 7935, "text": "The newly created user-level data-set includes the following columns:" }, { "code": null, "e": 8246, "s": 8005, "text": "lastlevel: user’s last subscription level, transformed into binary format (1 — paid tier, 0 — free tier)gender: gender, transformed into binary format (1 — female, 0 — male)obsstart, obsend: start and end of user-specific observation period" }, { "code": null, "e": 8696, "s": 8246, "text": "endstate: user’s last interaction in the observation periodnact: user’s total number of interactions in the observation periodnsongs, ntbup, ntbdown, nfriend, nplaylist, ndgrade, nupgrade, nhome, nadvert, nhelp, nsettings, nerror: number of songs played, thumbs up given, thumbs down given, friends added, songs added to playlist, downgrades, upgrades, home page visits, advertisements played, help page visits, settings visits, errors, respectively" }, { "code": null, "e": 8918, "s": 8696, "text": "nact_recent, nact_oldest: user’s activity in the last and first k days of the observation window, respectivelynsongs_recent, nsongs_oldest: songs played in the last and first k days of the observation window, respectively" }, { "code": null, "e": 10669, "s": 8918, "text": "# Aggregation by userIddf_user = df.groupby(‘userId’)\\.agg( # User-level features first(when(col(‘lastlevel’) == ‘paid’, 1).otherwise(0)).alias(‘lastlevel’), first(when(col(‘gender’) == “F”, 1).otherwise(0)).alias(‘gender’), first(col(‘obsstart’)).alias(‘obsstart’), first(col(‘obsend’)).alias(‘obsend’), first(col(‘endstate’)).alias(‘endstate’), # Aggregated activity statistics count(col(‘page’)).alias(‘nact’),Fsum(when(col(‘page’) == “NextSong”, 1).otherwise(0)).alias(“nsongs”), Fsum(when(col(‘page’) == “Thumbs Up”, 1).otherwise(0)).alias(“ntbup”), Fsum(when(col(‘page’) == “Thumbs Down”, 1).otherwise(0)).alias(“ntbdown”), Fsum(when(col(‘page’) == “Add Friend”, 1).otherwise(0)).alias(“nfriend”), Fsum(when(col(‘page’) == “Add to Playlist”, 1).otherwise(0)).alias(“nplaylist”), Fsum(when(col(‘page’) == “Submit Downgrade”, 1).otherwise(0)).alias(“ndgrade”), Fsum(when(col(‘page’) == “Submit Upgrade”, 1).otherwise(0)).alias(“nugrade”), Fsum(when(col(‘page’) == “Home”, 1).otherwise(0)).alias(“nhome”), Fsum(when(col(‘page’) == “Roll Advert”, 1).otherwise(0)).alias(“nadvert”), Fsum(when(col(‘page’) == “Help”, 1).otherwise(0)).alias(“nhelp”), Fsum(when(col(‘page’) == “Settings”, 1).otherwise(0)).alias(“nsettings”), Fsum(when(col(‘page’) == “Error”, 1).otherwise(0)).alias(“nerror”), # Aggregated activity statistics in different periods Fsum(when(col(‘timebeforeend’) < trend_est, 1).otherwise(0)).alias(“nact_recent”), Fsum(when(col(‘timefromstart’) < trend_est, 1).otherwise(0)).alias(“nact_oldest”), Fsum(when((col(‘page’) == “NextSong”) & (col(‘timebeforeend’) < trend_est), 1).otherwise(0)).alias(“nsongs_recent”), Fsum(when((col(‘page’) == “NextSong”) & (col(‘timefromstart’) < trend_est), 1).otherwise(0)).alias(“nsongs_oldest”) )" }, { "code": null, "e": 10777, "s": 10669, "text": "After completing the feature engineering step we have analysed the correlations between the built features." }, { "code": null, "e": 11502, "s": 10777, "text": "# For visualization purposes we switch to pandas dataframesdf_user_pd = df_user.toPandas()# Calculate correlations between numerical featurescormat = df_user_pd[['nact_perh','nsongs_perh', 'nhome_perh', 'ntbup_perh','ntbdown_perh', 'nfriend_perh','nplaylist_perh', 'nadvert_perh', 'nerror_perh', 'upgradedowngrade', 'songratio', 'positiveratio','negativeratio', 'updownratio', 'trend_act', 'trend_songs', 'avgsessionitems', 'avgsessionlength','avgsongs']].corr()# Plot correlationsplt.rcParams['figure.figsize'] = (10,10)plt.subplots_adjust(left=0.20, right=0.9, top=0.95, bottom=0.15)sns.heatmap(cormat, cmap = \"YlGnBu\", square = True, vmin = -1, vmax = 1);plt.title('Feature correlations');plt.savefig('correlations.png')" }, { "code": null, "e": 11922, "s": 11502, "text": "The heat-map above describes a high correlation between variables nact_perh and nsongs_perh. This is expected, as listening to songs is obviously by far the most common user activity. For the same reason there is a high correlation between trend_act and trend_songs. In both cases we decided to simply remove from all further analyses and keep only variables that measure the most important interaction — playing songs." }, { "code": null, "e": 12168, "s": 11922, "text": "In order to further reduce the multi-colinearity in the data, we also decided not to use nhome_perh and nplaylist_perh in the model. Moreover, avgsessionlength is highly correlated with average items in each session, hence it can be ignored too." }, { "code": null, "e": 12251, "s": 12168, "text": "From the visualisations presented below the following observations have been made:" }, { "code": null, "e": 12304, "s": 12251, "text": "on average churned users played more songs per hour;" }, { "code": null, "e": 12413, "s": 12304, "text": "churned users gave significantly more thumbs down per hour, and had to watch more advertisements on average;" }, { "code": null, "e": 12523, "s": 12413, "text": "the ratio of songs and positive interactions relative to total activity was typically lower for churned users" }, { "code": null, "e": 12582, "s": 12523, "text": "churned users had on average less interactions per session" }, { "code": null, "e": 12643, "s": 12582, "text": "churn rate is higher for users in the free subscription plan" }, { "code": null, "e": 12688, "s": 12643, "text": "churn rate is slightly higher for male users" }, { "code": null, "e": 12742, "s": 12688, "text": "No features have been removed based on this analysis." }, { "code": null, "e": 13131, "s": 12742, "text": "We first performed grid search with cross validation to test the performance of several parameter combinations, all on the user-level data obtained from the smaller Sparkify user activity data-set. Based on the performance results obtained in cross validation (measured by AUC and F1 score), we identified the best-performing model instances and retrained them on the entire training set." }, { "code": null, "e": 13194, "s": 13131, "text": "maxIter (maximum number of iterations, default=100) : [10, 30]" }, { "code": null, "e": 13256, "s": 13194, "text": "regParam (regularization parameter, default=0.0) : [0.0, 0.1]" }, { "code": null, "e": 13354, "s": 13256, "text": "elasticNetParam (mixing parameter — 0 for L2 penalty, 1 for L1 penalty, default=0.0) : [0.0, 0.5]" }, { "code": null, "e": 13410, "s": 13354, "text": "maxDepth (maximum tree depth, default=5) : [4, 5, 6, 7]" }, { "code": null, "e": 13460, "s": 13410, "text": "numTrees (number of trees, default=20) : [20, 40]" }, { "code": null, "e": 13510, "s": 13460, "text": "maxDepth (maximum tree depth, default=5) : [4, 5]" }, { "code": null, "e": 13573, "s": 13510, "text": "maxIter (maximum number of iterations, default=20) : [20, 100]" }, { "code": null, "e": 13803, "s": 13573, "text": "In the defined grid search objects the performance of each parameter combination is by default measured by average AUC score (area under the ROC) obtained in 4-fold cross validation. AUC is briefly explained in Section 4.4 below." }, { "code": null, "e": 15022, "s": 13803, "text": "numeric_columns = [‘nsongs_perh’, ‘ntbup_perh’,’ntbdown_perh’, ‘nfriend_perh’, ‘nadvert_perh’, ‘nerror_perh’, ‘upgradedowngrade’, ‘songratio’, ‘positiveratio’,’negativeratio’, ‘updownratio’, ‘trend_songs’, ‘avgsessionitems’,’avgsongs’]# Combining multiple numerical features using VectorAssemblernumeric_assembler = VectorAssembler(inputCols = numeric_columns, outputCol = “numericvectorized”)# Standardizing numerical featuresscaler = StandardScaler(inputCol = “numericvectorized”, outputCol = “numericscaled”, withStd = True, withMean = True)# Adding the two binary featuresbinary_columns = [‘lastlevel’, ‘gender’]total_assembler = VectorAssembler(inputCols = binary_columns + [“numericscaled”], outputCol = “features”)# Defining three different pipelines with three different classifiers, all with default parameters# Logistic regression lr = LogisticRegression()pipeline_lr = Pipeline(stages = [numeric_assembler, scaler, total_assembler, lr])# Random forest classifierrf = RandomForestClassifier()pipeline_rf = Pipeline(stages = [numeric_assembler, scaler, total_assembler, rf])# Gradient-boosted tree classifiergb = GBTClassifier()pipeline_gb = Pipeline(stages = [numeric_assembler, scaler, total_assembler, gb])" }, { "code": null, "e": 15480, "s": 15022, "text": "F1 score is preferred performance metrics to this problem. The input user-level data-set is imbalanced. Music streaming service aims to identify most of the users that are likely to churn (aiming for high recall), but at the same time does not want to give too many discounts for no reason (aiming for high precision), i.e. to users who are actually happy with the service (false positives) — this can help music streaming business prevent financial losses." }, { "code": null, "e": 16217, "s": 15480, "text": "class F1score(Evaluator):def __init__(self, predictionCol = “prediction”, labelCol=”label”): self.predictionCol = predictionCol self.labelCol = labelColdef _evaluate(self, dataset): # Calculate F1 score tp = dataset.where((dataset.label == 1) & (dataset.prediction == 1)).count() fp = dataset.where((dataset.label == 0) & (dataset.prediction == 1)).count() tn = dataset.where((dataset.label == 0) & (dataset.prediction == 0)).count() fn = dataset.where((dataset.label == 1) & (dataset.prediction == 0)).count() # Add epsilon to prevent division by zero precision = tp / (tp + fp + 0.00001) recall = tp / (tp + fn + 0.00001) f1 = 2 * precision * recall / (precision + recall + 0.00001) return f1def isLargerBetter(self): return True" }, { "code": null, "e": 16289, "s": 16217, "text": "The best performing model has AUC score of 0.981 and F1 score of 0.855." }, { "code": null, "e": 16584, "s": 16289, "text": "As seen in the visualisation above, the most important feature for identifying churned users is the nerror_perh which measures how many error pages have been shown to the user per hour. The more errors a user has to experience the more likely it is that he/she is dissatisfied with the service." }, { "code": null, "e": 16795, "s": 16584, "text": "Similar holds also for the second and third most important feature, ntbdown_perh and nadvert_perh which measure the number of thumbs down given per hour and number of advertisements seen per hour, respectively." }, { "code": null, "e": 16933, "s": 16795, "text": "Most interesting feature is the trend_songs variable which measures a user’s song listening activity trend, as the fourth most important." }, { "code": null, "e": 17192, "s": 16933, "text": "The Gradient-boosted tree classifier has a F1 score (precision and recall) of 0.855 and can identify churned users based on past user activity and interaction with the music streaming service, which can help the business prevent from severe financial losses." }, { "code": null, "e": 17618, "s": 17192, "text": "Some improvements are to perform comprehensive grid search for the model on the full Sparkify data-set. Utilise song-level features that have been ignored so far, e.g. calculate the user’s listening diversity in terms of different songs/artists listened to in the specified observation period, etc. Build new features such as e.g. average length of song listening sessions, ratios of skipped or partially listened songs, etc." } ]
Assignment Operators in C/C++ - GeeksforGeeks
11 Oct, 2019 Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.Different types of assignment operators are shown below: “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.For example:a = 10; b = 20; ch = 'y'; a = 10; b = 20; ch = 'y'; “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:(a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11. (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11. “-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.Example:(a -= b) can be written as (a = a - b) If initially value stored in a is 8. Then (a -= 6) = 2. (a -= b) can be written as (a = a - b) If initially value stored in a is 8. Then (a -= 6) = 2. “*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:(a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30. (a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30. “/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:(a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3. (a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3. Below example illustrates the various Assignment Operators: C C++ // C program to demonstrate// working of Assignment operators #include <stdio.h> int main(){ // Assigning value 10 to a // using "=" operator int a = 10; printf("Value of a is %d\n", a); // Assigning value by adding 10 to a // using "+=" operator a += 10; printf("Value of a is %d\n", a); // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; printf("Value of a is %d\n", a); // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; printf("Value of a is %d\n", a); // Assigning value by dividing 10 from a // using "/=" operator a /= 10; printf("Value of a is %d\n", a); return 0;} // C++ program to demonstrate // working of Assignment operators #include <iostream>using namespace std; int main() { // Assigning value 10 to a // using "=" operator int a = 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by adding 10 to a // using "+=" operator a += 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by dividing 10 from a // using "/=" operator a /= 10; cout << "Value of a is "<<a<<"\n"; return 0; } Value of a is 10 Value of a is 20 Value of a is 10 Value of a is 100 Value of a is 10 C Basics C-Operators CPP-Basics cpp-operator C Language cpp-operator Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Multiple Inheritance in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C UDP Server-Client implementation in C Ways to copy a vector in C++
[ { "code": null, "e": 25589, "s": 25561, "text": "\n11 Oct, 2019" }, { "code": null, "e": 25969, "s": 25589, "text": "Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.Different types of assignment operators are shown below:" }, { "code": null, "e": 26138, "s": 25969, "text": "“=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.For example:a = 10;\nb = 20;\nch = 'y';\n" }, { "code": null, "e": 26165, "s": 26138, "text": "a = 10;\nb = 20;\nch = 'y';\n" }, { "code": null, "e": 26479, "s": 26165, "text": "“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:(a += b) can be written as (a = a + b)\nIf initially value stored in a is 5. Then (a += 6) = 11." }, { "code": null, "e": 26519, "s": 26479, "text": "(a += b) can be written as (a = a + b)\n" }, { "code": null, "e": 26576, "s": 26519, "text": "If initially value stored in a is 5. Then (a += 6) = 11." }, { "code": null, "e": 26894, "s": 26576, "text": "“-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.Example:(a -= b) can be written as (a = a - b)\nIf initially value stored in a is 8. Then (a -= 6) = 2." }, { "code": null, "e": 26934, "s": 26894, "text": "(a -= b) can be written as (a = a - b)\n" }, { "code": null, "e": 26990, "s": 26934, "text": "If initially value stored in a is 8. Then (a -= 6) = 2." }, { "code": null, "e": 27308, "s": 26990, "text": "“*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.Example:(a *= b) can be written as (a = a * b)\nIf initially value stored in a is 5. Then (a *= 6) = 30." }, { "code": null, "e": 27348, "s": 27308, "text": "(a *= b) can be written as (a = a * b)\n" }, { "code": null, "e": 27405, "s": 27348, "text": "If initially value stored in a is 5. Then (a *= 6) = 30." }, { "code": null, "e": 27719, "s": 27405, "text": "“/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.Example:(a /= b) can be written as (a = a / b)\nIf initially value stored in a is 6. Then (a /= 2) = 3." }, { "code": null, "e": 27759, "s": 27719, "text": "(a /= b) can be written as (a = a / b)\n" }, { "code": null, "e": 27815, "s": 27759, "text": "If initially value stored in a is 6. Then (a /= 2) = 3." }, { "code": null, "e": 27875, "s": 27815, "text": "Below example illustrates the various Assignment Operators:" }, { "code": null, "e": 27877, "s": 27875, "text": "C" }, { "code": null, "e": 27881, "s": 27877, "text": "C++" }, { "code": "// C program to demonstrate// working of Assignment operators #include <stdio.h> int main(){ // Assigning value 10 to a // using \"=\" operator int a = 10; printf(\"Value of a is %d\\n\", a); // Assigning value by adding 10 to a // using \"+=\" operator a += 10; printf(\"Value of a is %d\\n\", a); // Assigning value by subtracting 10 from a // using \"-=\" operator a -= 10; printf(\"Value of a is %d\\n\", a); // Assigning value by multiplying 10 to a // using \"*=\" operator a *= 10; printf(\"Value of a is %d\\n\", a); // Assigning value by dividing 10 from a // using \"/=\" operator a /= 10; printf(\"Value of a is %d\\n\", a); return 0;}", "e": 28580, "s": 27881, "text": null }, { "code": "// C++ program to demonstrate // working of Assignment operators #include <iostream>using namespace std; int main() { // Assigning value 10 to a // using \"=\" operator int a = 10; cout << \"Value of a is \"<<a<<\"\\n\"; // Assigning value by adding 10 to a // using \"+=\" operator a += 10; cout << \"Value of a is \"<<a<<\"\\n\"; // Assigning value by subtracting 10 from a // using \"-=\" operator a -= 10; cout << \"Value of a is \"<<a<<\"\\n\"; // Assigning value by multiplying 10 to a // using \"*=\" operator a *= 10; cout << \"Value of a is \"<<a<<\"\\n\"; // Assigning value by dividing 10 from a // using \"/=\" operator a /= 10; cout << \"Value of a is \"<<a<<\"\\n\"; return 0; }", "e": 29337, "s": 28580, "text": null }, { "code": null, "e": 29424, "s": 29337, "text": "Value of a is 10\nValue of a is 20\nValue of a is 10\nValue of a is 100\nValue of a is 10\n" }, { "code": null, "e": 29433, "s": 29424, "text": "C Basics" }, { "code": null, "e": 29445, "s": 29433, "text": "C-Operators" }, { "code": null, "e": 29456, "s": 29445, "text": "CPP-Basics" }, { "code": null, "e": 29469, "s": 29456, "text": "cpp-operator" }, { "code": null, "e": 29480, "s": 29469, "text": "C Language" }, { "code": null, "e": 29493, "s": 29480, "text": "cpp-operator" }, { "code": null, "e": 29591, "s": 29493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29629, "s": 29591, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29655, "s": 29629, "text": "Exception Handling in C++" }, { "code": null, "e": 29677, "s": 29655, "text": "'this' pointer in C++" }, { "code": null, "e": 29697, "s": 29677, "text": "Multithreading in C" }, { "code": null, "e": 29738, "s": 29697, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29766, "s": 29738, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 29808, "s": 29766, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 29844, "s": 29808, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 29882, "s": 29844, "text": "UDP Server-Client implementation in C" } ]
Count the number of holes in an integer - GeeksforGeeks
29 Apr, 2021 Given an integer num, the task is to count the number of holes in that number. The holes in each digit are given below: Examples: Input: num = 6457819 Output: 5Input: num = 2537312 Output: 0 Approach: Initialize holes = 0 and an array hole[] with the values given where hole[i] stores the number of holes in the digit i. Now, for every digit d in num update holes = holes + hole[d]. Print the holes in the end.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Global array for hole valuesint hole[] = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count// of holes in numint countHoles(int num){ int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes;} // Driver codeint main(){ int num = 6457819; cout << countHoles(num); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ // Global array for hole valuesstatic int hole[] = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count// of holes in numstatic int countHoles(int num){ int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes;} // Driver codepublic static void main (String[] args){ int num = 6457819; System.out.println(countHoles(num));}} // This code is contributed by// shk # Python3 implementation of the approach # Global array for hole valueshole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ] # Function to return the count# of holes in numdef countHoles(num): holes = 0 while (num > 0) : # Last digit in num d = num % 10 # Update holes holes = holes + hole[d] # Remove last digit num = num // 10 # Return the count of holes # in the original num return holes # Driver codenum = 6457819print(countHoles(num)) # This code is contributed by ihritik // C# implementation of the approachusing System; class GFG{ // Global array for hole values static int []hole = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count // of holes in num static int countHoles(int num) { int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes; } // Driver code public static void Main() { int num = 6457819; Console.WriteLine(countHoles(num)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Global array for hole values$hole = array(1, 0, 0, 0, 1, 0, 1, 0, 2, 1); // Function to return the count// of holes in numfunction countHoles($num){ global $hole; $holes = 0; while ($num > 0) { // Last digit in num $d = $num % 10; // Update holes $holes += $hole[$d]; // Remove last digit $num = (int)($num / 10); } // Return the count of holes // in the original num return $holes;} // Driver code$num = 6457819; echo countHoles($num); // This code is contributed// by Akanksha Rai?> <script> // Javascript implementation of the approach // Global array for hole valueslet hole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ]; // Function to return the count// of holes in numfunction countHoles( num){ let holes = 0; while (num > 0) { // Last digit in num let d = num % 10; // Update holes holes += hole[d]; // Remove last digit num = Math.floor(num/10); } // Return the count of holes // in the original num return holes;} // Driver Code let num = 6457819; document.write(countHoles(num)); </script> 5 Shashank12 ankthon ihritik Akanksha_Rai jana_sayantan Infosys number-digits School Programming Infosys Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Operator Overloading in C++ Polymorphism in C++ Copy Constructor in C++ Friend class and function in C++ Types of Operating Systems Introduction To PYTHON Exceptions in Java Overriding in Java Constructors in Java
[ { "code": null, "e": 24617, "s": 24589, "text": "\n29 Apr, 2021" }, { "code": null, "e": 24739, "s": 24617, "text": "Given an integer num, the task is to count the number of holes in that number. The holes in each digit are given below: " }, { "code": null, "e": 24751, "s": 24739, "text": "Examples: " }, { "code": null, "e": 24814, "s": 24751, "text": "Input: num = 6457819 Output: 5Input: num = 2537312 Output: 0 " }, { "code": null, "e": 25087, "s": 24816, "text": "Approach: Initialize holes = 0 and an array hole[] with the values given where hole[i] stores the number of holes in the digit i. Now, for every digit d in num update holes = holes + hole[d]. Print the holes in the end.Below is the implementation of the above approach: " }, { "code": null, "e": 25091, "s": 25087, "text": "C++" }, { "code": null, "e": 25096, "s": 25091, "text": "Java" }, { "code": null, "e": 25104, "s": 25096, "text": "Python3" }, { "code": null, "e": 25107, "s": 25104, "text": "C#" }, { "code": null, "e": 25111, "s": 25107, "text": "PHP" }, { "code": null, "e": 25122, "s": 25111, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Global array for hole valuesint hole[] = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count// of holes in numint countHoles(int num){ int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes;} // Driver codeint main(){ int num = 6457819; cout << countHoles(num); return 0;}", "e": 25720, "s": 25122, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Global array for hole valuesstatic int hole[] = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count// of holes in numstatic int countHoles(int num){ int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes;} // Driver codepublic static void main (String[] args){ int num = 6457819; System.out.println(countHoles(num));}} // This code is contributed by// shk", "e": 26384, "s": 25720, "text": null }, { "code": "# Python3 implementation of the approach # Global array for hole valueshole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ] # Function to return the count# of holes in numdef countHoles(num): holes = 0 while (num > 0) : # Last digit in num d = num % 10 # Update holes holes = holes + hole[d] # Remove last digit num = num // 10 # Return the count of holes # in the original num return holes # Driver codenum = 6457819print(countHoles(num)) # This code is contributed by ihritik", "e": 26924, "s": 26384, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Global array for hole values static int []hole = { 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 }; // Function to return the count // of holes in num static int countHoles(int num) { int holes = 0; while (num > 0) { // Last digit in num int d = num % 10; // Update holes holes += hole[d]; // Remove last digit num /= 10; } // Return the count of holes // in the original num return holes; } // Driver code public static void Main() { int num = 6457819; Console.WriteLine(countHoles(num)); }} // This code is contributed by Ryuga", "e": 27703, "s": 26924, "text": null }, { "code": "<?php// PHP implementation of the approach // Global array for hole values$hole = array(1, 0, 0, 0, 1, 0, 1, 0, 2, 1); // Function to return the count// of holes in numfunction countHoles($num){ global $hole; $holes = 0; while ($num > 0) { // Last digit in num $d = $num % 10; // Update holes $holes += $hole[$d]; // Remove last digit $num = (int)($num / 10); } // Return the count of holes // in the original num return $holes;} // Driver code$num = 6457819; echo countHoles($num); // This code is contributed// by Akanksha Rai?>", "e": 28306, "s": 27703, "text": null }, { "code": "<script> // Javascript implementation of the approach // Global array for hole valueslet hole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ]; // Function to return the count// of holes in numfunction countHoles( num){ let holes = 0; while (num > 0) { // Last digit in num let d = num % 10; // Update holes holes += hole[d]; // Remove last digit num = Math.floor(num/10); } // Return the count of holes // in the original num return holes;} // Driver Code let num = 6457819; document.write(countHoles(num)); </script>", "e": 28898, "s": 28306, "text": null }, { "code": null, "e": 28900, "s": 28898, "text": "5" }, { "code": null, "e": 28913, "s": 28902, "text": "Shashank12" }, { "code": null, "e": 28921, "s": 28913, "text": "ankthon" }, { "code": null, "e": 28929, "s": 28921, "text": "ihritik" }, { "code": null, "e": 28942, "s": 28929, "text": "Akanksha_Rai" }, { "code": null, "e": 28956, "s": 28942, "text": "jana_sayantan" }, { "code": null, "e": 28964, "s": 28956, "text": "Infosys" }, { "code": null, "e": 28978, "s": 28964, "text": "number-digits" }, { "code": null, "e": 28997, "s": 28978, "text": "School Programming" }, { "code": null, "e": 29005, "s": 28997, "text": "Infosys" }, { "code": null, "e": 29103, "s": 29005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29122, "s": 29103, "text": "Interfaces in Java" }, { "code": null, "e": 29150, "s": 29122, "text": "Operator Overloading in C++" }, { "code": null, "e": 29170, "s": 29150, "text": "Polymorphism in C++" }, { "code": null, "e": 29194, "s": 29170, "text": "Copy Constructor in C++" }, { "code": null, "e": 29227, "s": 29194, "text": "Friend class and function in C++" }, { "code": null, "e": 29254, "s": 29227, "text": "Types of Operating Systems" }, { "code": null, "e": 29277, "s": 29254, "text": "Introduction To PYTHON" }, { "code": null, "e": 29296, "s": 29277, "text": "Exceptions in Java" }, { "code": null, "e": 29315, "s": 29296, "text": "Overriding in Java" } ]
How to update an existing document in MongoDB collection using Java?
The update() method updates the values in the existing document. db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA) In Java, you can update a single document using the updateOne()method of the com.mongodb.client.MongoCollection interface. To this method, you need to pass the filter and values for the update. import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; public class UpdatingDocuments { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Connecting to the database MongoDatabase database = mongo.getDatabase("myDatabase"); //Creating a collection object MongoCollection<Document>collection = database.getCollection("myCollection"); //Preparing documents Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad"); Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam"); Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi"); //Inserting the created documents List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); list.add(document3); collection.insertMany(list); //Updating a document collection.updateOne(Filters.eq("name", "Robert"), Updates.set("city", "Delhi")); System.out.println("Document update successfully..."); FindIterable<Document> iterDoc = collection.find(); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } Document update successfully... Document after update: Document{{_id=5e86dd21e9b25f3460b1abe0, name=Ram, age=26, city=Hyderabad}} Document{{_id=5e86dd21e9b25f3460b1abe1, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e86dd21e9b25f3460b1abe2, name=Rhim, age=30, city=Delhi}}
[ { "code": null, "e": 1127, "s": 1062, "text": "The update() method updates the values in the existing document." }, { "code": null, "e": 1188, "s": 1127, "text": "db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)" }, { "code": null, "e": 1382, "s": 1188, "text": "In Java, you can update a single document using the updateOne()method of the com.mongodb.client.MongoCollection interface. To this method, you need to pass the filter and values for the update." }, { "code": null, "e": 3031, "s": 1382, "text": "import com.mongodb.client.FindIterable;\nimport com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\nimport com.mongodb.client.model.Filters;\nimport com.mongodb.client.model.Updates;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\npublic class UpdatingDocuments {\n public static void main( String args[] ) {\n // Creating a Mongo client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Connecting to the database\n MongoDatabase database = mongo.getDatabase(\"myDatabase\");\n //Creating a collection object\n MongoCollection<Document>collection = database.getCollection(\"myCollection\");\n //Preparing documents\n Document document1 = new Document(\"name\", \"Ram\").append(\"age\", 26).append(\"city\", \"Hyderabad\");\n Document document2 = new Document(\"name\", \"Robert\").append(\"age\", 27).append(\"city\", \"Vishakhapatnam\");\n Document document3 = new Document(\"name\", \"Rhim\").append(\"age\", 30).append(\"city\", \"Delhi\");\n //Inserting the created documents\n List<Document> list = new ArrayList<Document>();\n list.add(document1);\n list.add(document2);\n list.add(document3);\n collection.insertMany(list);\n //Updating a document\n collection.updateOne(Filters.eq(\"name\", \"Robert\"), Updates.set(\"city\", \"Delhi\"));\n System.out.println(\"Document update successfully...\");\n FindIterable<Document> iterDoc = collection.find();\n Iterator it = iterDoc.iterator();\n while (it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}" }, { "code": null, "e": 3316, "s": 3031, "text": "Document update successfully...\nDocument after update:\nDocument{{_id=5e86dd21e9b25f3460b1abe0, name=Ram, age=26, city=Hyderabad}}\nDocument{{_id=5e86dd21e9b25f3460b1abe1, name=Robert, age=27, city=Vishakhapatnam}}\nDocument{{_id=5e86dd21e9b25f3460b1abe2, name=Rhim, age=30, city=Delhi}}" } ]
Java Program to Represent Graphs Using Linked List - GeeksforGeeks
26 Jul, 2021 Data structures are divided into two categories Linear data structures and Non-Linear data structures. The major disadvantage of the linear data structure is we cannot arrange the data of linear data structure in hierarchy manner that’s why in the computer field we use Non-Linear data structures. The most commonly used Non-Linear data structure is Graphs and Trees both data structures can be implemented using Linear data structures. In this article, we will discuss how to represent Graphs using Linked List. Graphs consist of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes. Graphs are represented in two different ways. One method is using adjacency List representation and the second is adjacency matrix representation. Adjacency List representation is mostly used because of dynamic memory allocation using list representation. Graphs are of two types: Directed Graphs: In this arrangement of graphs, every node is directed to one vertex is called directed Graphs. Undirected Graphs: In this arrangement of graphs, two nodes are connected using bi-direction vertex is called undirected graphs. Undirected Graphs representation: Maximum number of a vertex in the undirected graphs is n*(n-1) where n is the total number of nodes present in the Undirected Graphs. LinkedList Representation of undirected Graphs is as follows: In undirected graphs, two nodes are connected in bi-direction vertex. We can use both Array List and Linked List collections to represent the undirected graphs. In Linked List the Manipulation of the data is faster than the Array List because Array List internally used the dynamic array to store the data whereas Linked List used Doubly Linked List that is faster in the operation of manipulation but not in accessing the elements. Implementation: Here we will be discussing out both types of graphs in order to implement the same. Example 1 Java // Java Program to Implement the Unidirectional Graph// Using Linked List // Importing required classes from packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To make pair of nodes static void addEdge(LinkedList<LinkedList<Integer> > Adj, int u, int v) { // Creating bi-directional vertex Adj.get(u).add(v); Adj.get(v).add(u); } // Method 2 // To print the adjacency list static void printadjacencylist(LinkedList<LinkedList<Integer> > adj) { for (int i = 0; i < adj.size(); ++i) { // Printing the head System.out.print(i + "->"); for (int v : adj.get(i)) { // Printing the nodes System.out.print(v + " "); } // Now a new lin eis needed System.out.println(); } } // Method 3 // Main driver method public static void main(String[] args) { // Creating vertex int V = 5; LinkedList<LinkedList<Integer> > adj = new LinkedList<LinkedList<Integer> >(); for (int i = 0; i < V; ++i) { adj.add(new LinkedList<Integer>()); } // Inserting nodes // Custom input node elements addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); // Printing adjacency list printadjacencylist(adj); }} 0->1 4 1->0 2 3 4 2->1 3 3->1 2 4 4->0 1 3 Now jumping onto the next type of graphs that is our directed graphs representation using Linked List. In directed graphs, two nodes are connected in uni-direction vertex. Example 2 Java // Java Program to Implement the Directed Graph// Using Linked List // Importing standard classes from respectively packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To make pair of nodes static void addEdge(LinkedList<LinkedList<Integer> > Adj, int u, int v) { // Creating unidirectional vertex Adj.get(u).add(v); } // Method 2 // To print the adjacency List static void printadjacencylist(LinkedList<LinkedList<Integer> > adj) { for (int i = 0; i < adj.size(); ++i) { // Printing the head if (adj.get(i).size() != 0) { System.out.print(i + "->"); for (int v : adj.get(i)) { // Printing the nodes System.out.print(v + " "); } // A new line is needed System.out.println(); } } } // Method 3 // Main driver method public static void main(String[] args) { // Creating vertex int V = 5; LinkedList<LinkedList<Integer> > adj = new LinkedList<LinkedList<Integer> >(); for (int i = 0; i < V; ++i) { adj.add(new LinkedList<Integer>()); } // Inserting nodes // Custom input elements addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); // Printing adjacency List printadjacencylist(adj); }} 0->1 4 1->2 simmytarika5 Picked Graph Java Java Programs Linked List Linked List Java Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Longest Path in a Directed Acyclic Graph Graph Coloring | Set 1 (Introduction and Applications) Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 26335, "s": 26307, "text": "\n26 Jul, 2021" }, { "code": null, "e": 26848, "s": 26335, "text": "Data structures are divided into two categories Linear data structures and Non-Linear data structures. The major disadvantage of the linear data structure is we cannot arrange the data of linear data structure in hierarchy manner that’s why in the computer field we use Non-Linear data structures. The most commonly used Non-Linear data structure is Graphs and Trees both data structures can be implemented using Linear data structures. In this article, we will discuss how to represent Graphs using Linked List." }, { "code": null, "e": 27206, "s": 26848, "text": "Graphs consist of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes. Graphs are represented in two different ways. One method is using adjacency List representation and the second is adjacency matrix representation. Adjacency List representation is mostly used because of dynamic memory allocation using list representation." }, { "code": null, "e": 27231, "s": 27206, "text": "Graphs are of two types:" }, { "code": null, "e": 27343, "s": 27231, "text": "Directed Graphs: In this arrangement of graphs, every node is directed to one vertex is called directed Graphs." }, { "code": null, "e": 27472, "s": 27343, "text": "Undirected Graphs: In this arrangement of graphs, two nodes are connected using bi-direction vertex is called undirected graphs." }, { "code": null, "e": 27640, "s": 27472, "text": "Undirected Graphs representation: Maximum number of a vertex in the undirected graphs is n*(n-1) where n is the total number of nodes present in the Undirected Graphs." }, { "code": null, "e": 27702, "s": 27640, "text": "LinkedList Representation of undirected Graphs is as follows:" }, { "code": null, "e": 28136, "s": 27702, "text": " In undirected graphs, two nodes are connected in bi-direction vertex. We can use both Array List and Linked List collections to represent the undirected graphs. In Linked List the Manipulation of the data is faster than the Array List because Array List internally used the dynamic array to store the data whereas Linked List used Doubly Linked List that is faster in the operation of manipulation but not in accessing the elements." }, { "code": null, "e": 28237, "s": 28136, "text": "Implementation: Here we will be discussing out both types of graphs in order to implement the same. " }, { "code": null, "e": 28247, "s": 28237, "text": "Example 1" }, { "code": null, "e": 28252, "s": 28247, "text": "Java" }, { "code": "// Java Program to Implement the Unidirectional Graph// Using Linked List // Importing required classes from packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To make pair of nodes static void addEdge(LinkedList<LinkedList<Integer> > Adj, int u, int v) { // Creating bi-directional vertex Adj.get(u).add(v); Adj.get(v).add(u); } // Method 2 // To print the adjacency list static void printadjacencylist(LinkedList<LinkedList<Integer> > adj) { for (int i = 0; i < adj.size(); ++i) { // Printing the head System.out.print(i + \"->\"); for (int v : adj.get(i)) { // Printing the nodes System.out.print(v + \" \"); } // Now a new lin eis needed System.out.println(); } } // Method 3 // Main driver method public static void main(String[] args) { // Creating vertex int V = 5; LinkedList<LinkedList<Integer> > adj = new LinkedList<LinkedList<Integer> >(); for (int i = 0; i < V; ++i) { adj.add(new LinkedList<Integer>()); } // Inserting nodes // Custom input node elements addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); // Printing adjacency list printadjacencylist(adj); }}", "e": 29783, "s": 28252, "text": null }, { "code": null, "e": 29834, "s": 29786, "text": "0->1 4 \n1->0 2 3 4 \n2->1 3 \n3->1 2 4 \n4->0 1 3 " }, { "code": null, "e": 30008, "s": 29836, "text": "Now jumping onto the next type of graphs that is our directed graphs representation using Linked List. In directed graphs, two nodes are connected in uni-direction vertex." }, { "code": null, "e": 30022, "s": 30012, "text": "Example 2" }, { "code": null, "e": 30029, "s": 30024, "text": "Java" }, { "code": "// Java Program to Implement the Directed Graph// Using Linked List // Importing standard classes from respectively packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Method 1 // To make pair of nodes static void addEdge(LinkedList<LinkedList<Integer> > Adj, int u, int v) { // Creating unidirectional vertex Adj.get(u).add(v); } // Method 2 // To print the adjacency List static void printadjacencylist(LinkedList<LinkedList<Integer> > adj) { for (int i = 0; i < adj.size(); ++i) { // Printing the head if (adj.get(i).size() != 0) { System.out.print(i + \"->\"); for (int v : adj.get(i)) { // Printing the nodes System.out.print(v + \" \"); } // A new line is needed System.out.println(); } } } // Method 3 // Main driver method public static void main(String[] args) { // Creating vertex int V = 5; LinkedList<LinkedList<Integer> > adj = new LinkedList<LinkedList<Integer> >(); for (int i = 0; i < V; ++i) { adj.add(new LinkedList<Integer>()); } // Inserting nodes // Custom input elements addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); // Printing adjacency List printadjacencylist(adj); }}", "e": 31505, "s": 30029, "text": null }, { "code": null, "e": 31522, "s": 31508, "text": "0->1 4 \n1->2 " }, { "code": null, "e": 31537, "s": 31524, "text": "simmytarika5" }, { "code": null, "e": 31544, "s": 31537, "text": "Picked" }, { "code": null, "e": 31550, "s": 31544, "text": "Graph" }, { "code": null, "e": 31555, "s": 31550, "text": "Java" }, { "code": null, "e": 31569, "s": 31555, "text": "Java Programs" }, { "code": null, "e": 31581, "s": 31569, "text": "Linked List" }, { "code": null, "e": 31593, "s": 31581, "text": "Linked List" }, { "code": null, "e": 31598, "s": 31593, "text": "Java" }, { "code": null, "e": 31604, "s": 31598, "text": "Graph" }, { "code": null, "e": 31702, "s": 31604, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31738, "s": 31702, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 31780, "s": 31738, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 31807, "s": 31780, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 31848, "s": 31807, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 31903, "s": 31848, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 31918, "s": 31903, "text": "Arrays in Java" }, { "code": null, "e": 31962, "s": 31918, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31984, "s": 31962, "text": "For-each loop in Java" }, { "code": null, "e": 32035, "s": 31984, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to add a Money field in Django?
Sometimes, we may have to add money-related data in a website, like salary, fees or income. Django provides an integer field but many a time, it doesn't work like we want. So, for handling money field, we can use a third-package library that will add the money field to our model. Make a project and an app, I named it "MoneyFieldDemo" and "myapp". Set the basic things like urls and INSTALLED_APPS. And yes, install a library − pip install django-money Add the following line in settings.py − INSTALLED_APPS+= ["djmoney"] In app's, urls.py, add the following lines − from django.urls import path from . import views urlpatterns = [ path('', views.home,name="home"), ] Here, we simply define our url endpoint which will render the html. In the templates folder's home.html, add − <!DOCTYPE html> <html> <head> <title> TUT </title> </head> <body> <h2>Hi</h2> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> It is the html file that we are going to render as the frontend. In models.py, add the following − from django.db import models from djmoney.models.fields import MoneyField # Create your models here. class Data(models.Model): Name=models.CharField(max_length=100) salary = MoneyField(max_digits=14, decimal_places=2, defa ult_currency='USD') #This is money field Here, we created a model which has two value employee names and his salary in USD. In view.py, add the following − from django.shortcuts import render from django import forms from .models import Data # Create your views here. class SalaryForm(forms.ModelForm): class Meta: model=Data fields="__all__" def home(request): if request.method=='POST': form=SalaryForm(request.POST) if form.is_valid(): form.save() else: form=SalaryForm() return render(request,'home.html',{'form':form}) There is nothing fancy in views.py. We made a form in it and then just render it and also handle post request.
[ { "code": null, "e": 1343, "s": 1062, "text": "Sometimes, we may have to add money-related data in a website, like salary, fees or income. Django provides an integer field but many a time, it doesn't work like we want. So, for handling money field, we can use a third-package library that will add the money field to our model." }, { "code": null, "e": 1411, "s": 1343, "text": "Make a project and an app, I named it \"MoneyFieldDemo\" and \"myapp\"." }, { "code": null, "e": 1462, "s": 1411, "text": "Set the basic things like urls and INSTALLED_APPS." }, { "code": null, "e": 1491, "s": 1462, "text": "And yes, install a library −" }, { "code": null, "e": 1516, "s": 1491, "text": "pip install django-money" }, { "code": null, "e": 1556, "s": 1516, "text": "Add the following line in settings.py −" }, { "code": null, "e": 1585, "s": 1556, "text": "INSTALLED_APPS+= [\"djmoney\"]" }, { "code": null, "e": 1630, "s": 1585, "text": "In app's, urls.py, add the following lines −" }, { "code": null, "e": 1735, "s": 1630, "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home,name=\"home\"),\n]" }, { "code": null, "e": 1803, "s": 1735, "text": "Here, we simply define our url endpoint which will render the html." }, { "code": null, "e": 1846, "s": 1803, "text": "In the templates folder's home.html, add −" }, { "code": null, "e": 2123, "s": 1846, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>\n TUT\n </title>\n </head>\n <body>\n <h2>Hi</h2>\n <form action=\"/\" method=\"post\">\n {% csrf_token %}\n {{ form }}\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" }, { "code": null, "e": 2188, "s": 2123, "text": "It is the html file that we are going to render as the frontend." }, { "code": null, "e": 2222, "s": 2188, "text": "In models.py, add the following −" }, { "code": null, "e": 2493, "s": 2222, "text": "from django.db import models\nfrom djmoney.models.fields import MoneyField\n\n# Create your models here.\nclass Data(models.Model):\n Name=models.CharField(max_length=100)\n salary = MoneyField(max_digits=14, decimal_places=2, defa\nult_currency='USD') #This is money field" }, { "code": null, "e": 2576, "s": 2493, "text": "Here, we created a model which has two value employee names and his salary in USD." }, { "code": null, "e": 2608, "s": 2576, "text": "In view.py, add the following −" }, { "code": null, "e": 3036, "s": 2608, "text": "from django.shortcuts import render\nfrom django import forms\nfrom .models import Data\n# Create your views here.\n\nclass SalaryForm(forms.ModelForm):\n class Meta:\n model=Data\n fields=\"__all__\"\ndef home(request):\n if request.method=='POST':\n form=SalaryForm(request.POST)\n if form.is_valid():\n form.save()\n\n else:\n form=SalaryForm()\n\n return render(request,'home.html',{'form':form})" }, { "code": null, "e": 3147, "s": 3036, "text": "There is nothing fancy in views.py. We made a form in it and then just render it and also handle post request." } ]
Setup Your Own Deep Learning Sandbox: Quick Guide | by Thomas Morris | Towards Data Science
Like many data science enthusiasts I dove into this field by filling every spare minute learning the DS eco-system –namely Python, Jupyter, NumPy, Pandas, Scikit-learn, Matplotlib, and a dash of Seaborn. Together with the all powerful Unix tools –vi, less, sort, cut, grep, cat, tail, head, etc.– you have an incredibly productive framework to source, clean and analyze datasets, engineer features, run regression models, and build professional visuals. However, once your curiosity (or job) pulls you towards the “deep learning” end of the “machine learning” world, you will quickly discover –as I did– not even a high-end Macbook Pro will have enough muscle to run even the most basic convolutional neural net models (CNN for short). I figured this out quickly working through the fast.ai course by Jeremy Howard and Rachel Thomas. If you are like me and your data science training funding comes from your own pocket then I have an inexpensive, simple, yet powerful solution for you. Firstly, I admit I like running everything I can on my laptop. However, for some things my laptop just doesn’t cut it e.g. for my music composition hobby, I have a beefed up Intel i7 box in my basement that runs a music library server. But for training DL models an i7 and lots of RAM won’t do much for you. You need GPUs. And GPUs are expensive. But they’re not expense to rent. With the buffet table of cloud options now available in the marketplace my new MO has become, don’t buy, rent. Through a bit of Google’ing, and trial-and-error I setup a Jupyter based client-server sandbox using my Macbook Pro and Visual Studio Code as the client, and Jupyter server running on a high-end Linux instance on Google Cloud. The results? My DL model training now happens in seconds. On my Macbook Pro? Well, after 30 minutes running and the fan blazing away I killed the process. You get the picture? Note: This approach uses a full Linux server in the Google cloud. There are other paths that cost less e.g. Google Colab, and Kaggle Kernels. However, with this approach you gain configuration flexibility, a $300 credit (if used sparingly will last a while), and some experience with the Google Cloud Platform and using their command line interface. First step is to create an account on the Google Cloud Platform (GCP). I’m going to assume you’ve figured that out and are logged into to the GCP console. Next, check to ensure you got your $300 credit. In the top left corner click on the menu and select Billing → Overview. In the bottom right corner of the Overview you should see the Promotional credits balance. And it should be $300. GCP now has a service for provisioning a VM server configured specifically for running Jupyter notebooks. Click on the GCP menu (top left corner) and scroll down to the ARTIFICIAL INTELLIGENCE section. Then select AI Platform → Notebooks. From the Notebook Instances screen select NEW INSTANCE at the top. This menu has many options including some beta and experimental choices. I am going with the PyTorch 1.4 option with one NVIDIA Tesla T4 GPU. Next screen presents options. For this exercise I am going with the defaults. The Customize button allows you to add more disk space to your boot drive, add GPUs RAM, etc. The default costs $0.382 per hour. Google E2 instances are billed by the second after the first minute of usage. This default configuration will run 38.2 cents per hour. That’s 785 hours of free usage. Once you click on Create, Google will take a couple minutes to provision your VM instance. When it’s complete you will see a screen like the following. You now have a fully functioning Jupyter Notebook with a powerful GPU to support DL model building. Click on OPEN JUPYTERLAB next to your Instance Name. A new tab will open in your browser and a Jupyter notebook will be opened. The interface is very straight forward. You can browse the file system, create a Git repository, or startup up a terminal session. At this stage you have a fully functioning, powerful DL sandbox. However, this is not a cost effective way to work. Your new VM instance is eating away at that $300 credit every second you have the instance running. I prefer to do all my data gathering, feature engineering, and initial regression work locally on my macbook. Then when I have my dataset cleaned and prepped and I am at the stage to try and fit a DL model I crank up my VM instance, connect, run my model, get my results, then shutdown the instance. To execute this workflow efficiently there’s a few more steps I will now walk through. Go back to the Notebooks console and shutdown your instance. Tip: Go to the Billing section and under Budgets & alerts create a Budget that will email you when you have reached $1 of usage. To open up remote access to your VM instance you need to do two things. Step 1. Open up HTTP access to your VM instance. From the main console menu, under the COMPUTE section, select Compute Engine → VM instances. Then click on your instance from the list. The details of your instance will be displayed. We need to make two changes here. Click on EDIT at the top, scroll down and check the two HTTP boxes in the Firewalls section, then scroll on to the bottom and click Save. Step 2. Follow the menu below and then click CREATE FIREWALL RULE at the top of the Firewall console. Input the noted fields in the following two screens. Your firewall rule should now be active. If it isn’t you will know in the next steps. Step 3. Stop your VM Instance. Go back to the Notebooks console click the check box next to your instance and click on STOP. Step 1. First step is to install the SDK on you local computer. Here’s the Google instructions for downloading and installing their SDK for MacOS, Windows, and Linux. Make sure you follow all steps including putting the SDK in your PATH. Step 2. Initialize the SDK by running the following command from a terminal. > gcloud init...> You must log in to continue. Would you like to log in (Y/n)? You will be prompted to log in. When you press Y and Return you will be redirected to a Google website to log into your account. Once you successfully log in you should be returned to your terminal session where you will be prompted to select a compute region. > Do you want to configure a default Compute Region and Zone? (Y/n)? Select Y. In one of the earlier screen shots I suggested noting your instance name and the region in which it was created. Find that region in the list that is presented and enter its index number. Once that completes run the following command. > gcloud config list You should see something like the following in your terminal window. Step 3. Before we left our VM instance we shut it down. Let’s now start it back up using the SDK. Here’s the command. Replace inst_name with the name of your instance. > gcloud compute instances start inst_name Now let’s practice stopping the instance. Here’s the command. > gcloud compute instances stop inst_name This can take a couple minutes so just let it run. After the little spinner thing completes you should get this as a result. Once you see the ...done then startup your instance again and let’s move on. Step 4. Time to connect to the instance and finish the server side setup. Enter the following command and replace inst_name with your instance. > gcloud compute ssh inst_name You will be prompted for a password. This is the account password you created initially. Next you will see a screen like the following. Okay, we are almost there. Just a few configuration changes to Jupyter and then we will be able to connect with Visual Studio Code and run a model. Yeah! 😎 Step 1. Create a folder for notebooks. This is where Jupyter will store notebook files. I also recommend creating two subfolder whose purpose will become clear when we run the sample model below. > mkdir jnotebooks> mkdir jnotebooks/data> mkdir jnotebooks/pics Step 2. Create Jupyter configuration. This creates a .jupyter folder off your root directory. > jupyter notebook --generate-config Now for a little tricky part. We need to configure a few Jupyter parameters in the file .jupyter/jupyter_notebook_config.py. I recommend using vim. Before editing the file note your root path by executing pwd. Here’s the parameters. All these parameters are already in the file. However, they are commented out. They need to be uncommented and modified. c.NotebookApp.ip = '*'c.NotebookApp.port = 8888c.NotebookApp.notebook_dir = '/home/username/jnotebooks'c.NotebookApp.open_browser = False Remember we created the jnotebooks folder. Enter its full path for the notebook_dir parameter. Here’s a short vim cheatsheet of the commands you will need. Step 3. Set a Jupyter password. This is optional but highly recommended since we just opened HTTP access. From the command line enter the following and then enter your password. You will have to enter this every time you access this server from VSC so I recommend not going overboard here. > jupyter notebook password Step 4. Final step here. Let’s startup the Jupyter Notebook server. Here’s the command. > jupyter-notebook If your screen doesn’t closely resemble this then kill the process by pressing Control-c and go back and check the four parameters in the Jupyter config file. I am a big Visual Studio Code fan. Microsoft open-sourced it some time ago and it has since evolved quickly to become a very user friendly and highly functional editor. And the thing I find really cool is that it now fully supports Jupyter Notebooks. I personally am not in love with running notebooks in a browser when I am in work mode. I prefer a real code editor that I use for Python and Java (and hopefully Swift will be supported soon). In VSC I can build my models in notebooks and then easily export to a Python file and start moving towards production’izing my project, all in the same editor. Enough rambling. Let’s connect to our server and train a model. Step 1. Install and setup Visual Studio Code. If you use an Anaconda distribution then you are all set. Anaconda and VSC work well together. Otherwise click here to get the latest version for your operating system. VSC supports Jupyter natively so there’s nothing extra that needs to be installed. Step 2. Open VSC and create a new Jupyter notebook. The easiest way to do this is by using the command browser. On MacOS the command is shift+command+p. Then type in Python: Create New Blank Jupyter Notebook Step 3. Connect to your server. Did you note your external IP address when you started up your server? You’ll need it here. Once again access the command browser via shift+command+p. Then enter the command Python: Specify local or remote Jupyter server for connections You see this next.Select Existing. Here’s where you need the external IP address of you VM instance. After entering your http address above and pressing return there’s a chance VSC will require a restart. If that does happen then close VSC, start it up again, and then follow this Step 3 back to this point. Type in some test Python code and execute the cell. VSC will send the code to the server and will display the returned result. Then you will see your Jupyter Server address in the top right corner like the highlight below. SUCCESS! Now it’s time for some real fun! I believe every data science hacker, coder, and professional is familiar with the Titanic data set at Kaggle. It’s like the “Hello World” of data science. I’ve toyed around with this data set as well. I’ve applied just basic reasoning like “assume all men die”. That will get you a mediocre score with just a few lines of code. For fun, I’ve done a lot of feature engineering and then applied all the Scikit-learn models and Xgboost. Then for real fun I thought I would apply a DL model. My model is available on Github. I recommend following along to see the workflow. Step 1. Get model from Github here. Step 2. Switch VSC to a local Python instance. shift+command+p followed by Python: Specify local or remote Jupyter server for connections then select Default from the menu. This will force a reload of VSC (hopefully this reloading requirement will go away in the future). Step 3. Open the file titanic_feature_creation.ipynb in VSC and execute each cell. The final cell will write out the files titanic_train_wrangled.csv, and titanic_test_wrangled.csv into a subfolder called data. Those two files have to be copied to your VM instance. Step 4. Copy data files to VM instance. From the titanic folder you retrieved from Github execute the following command. Substitute your instance name for inst_name. > gcloud compute scp ./data/*.csv inst_name:~/jnotebooks/data/ Step 5. Connect VSC to your Server. Shift+command+p followed by Python: Specify local or remote Jupyter server for connections then select your server from the menu. This will force a reload of VSC. Step 6. Open the file titanic_model_evaluation_cnn.ipynb. Note, in the first cell the data files that are read. You created these locally and then transferred them to your VM instance. Step 7. Execute all the cells to generate a submission.csv file. Disclaimer: The cell titled, Convert features to square PNG, is just a simple way to translate each row (or record) of both data files into an image for this exercise. There are many better ways to translate data for DL models. I wanted to keep it bare-bones simple for this demonstration. All created images are stored in a sub folder on the server called images_titanic. Step1. Now let’s retrieve the file submissions.csv that was created in the last cell shown below. Here’s the command. Once again, substitute your instance name for inst_name. > gcloud compute scp inst_name:~/jnotebooks/data/submission.csv . Step 2. Visit Kaggle’s Titanic site here and submit your work. 78% percentile is okay. Not bad. However, if you’re a real DS practitioner you would laugh at this. It’s an extreme case of over engineering. But this was not an exercise in optimal deep-learning-model engineering. This was all about how to set up a sandbox so you then go focus on building optimal models. One last thing.
[ { "code": null, "e": 1158, "s": 172, "text": "Like many data science enthusiasts I dove into this field by filling every spare minute learning the DS eco-system –namely Python, Jupyter, NumPy, Pandas, Scikit-learn, Matplotlib, and a dash of Seaborn. Together with the all powerful Unix tools –vi, less, sort, cut, grep, cat, tail, head, etc.– you have an incredibly productive framework to source, clean and analyze datasets, engineer features, run regression models, and build professional visuals. However, once your curiosity (or job) pulls you towards the “deep learning” end of the “machine learning” world, you will quickly discover –as I did– not even a high-end Macbook Pro will have enough muscle to run even the most basic convolutional neural net models (CNN for short). I figured this out quickly working through the fast.ai course by Jeremy Howard and Rachel Thomas. If you are like me and your data science training funding comes from your own pocket then I have an inexpensive, simple, yet powerful solution for you." }, { "code": null, "e": 1649, "s": 1158, "text": "Firstly, I admit I like running everything I can on my laptop. However, for some things my laptop just doesn’t cut it e.g. for my music composition hobby, I have a beefed up Intel i7 box in my basement that runs a music library server. But for training DL models an i7 and lots of RAM won’t do much for you. You need GPUs. And GPUs are expensive. But they’re not expense to rent. With the buffet table of cloud options now available in the marketplace my new MO has become, don’t buy, rent." }, { "code": null, "e": 2052, "s": 1649, "text": "Through a bit of Google’ing, and trial-and-error I setup a Jupyter based client-server sandbox using my Macbook Pro and Visual Studio Code as the client, and Jupyter server running on a high-end Linux instance on Google Cloud. The results? My DL model training now happens in seconds. On my Macbook Pro? Well, after 30 minutes running and the fan blazing away I killed the process. You get the picture?" }, { "code": null, "e": 2402, "s": 2052, "text": "Note: This approach uses a full Linux server in the Google cloud. There are other paths that cost less e.g. Google Colab, and Kaggle Kernels. However, with this approach you gain configuration flexibility, a $300 credit (if used sparingly will last a while), and some experience with the Google Cloud Platform and using their command line interface." }, { "code": null, "e": 2791, "s": 2402, "text": "First step is to create an account on the Google Cloud Platform (GCP). I’m going to assume you’ve figured that out and are logged into to the GCP console. Next, check to ensure you got your $300 credit. In the top left corner click on the menu and select Billing → Overview. In the bottom right corner of the Overview you should see the Promotional credits balance. And it should be $300." }, { "code": null, "e": 3030, "s": 2791, "text": "GCP now has a service for provisioning a VM server configured specifically for running Jupyter notebooks. Click on the GCP menu (top left corner) and scroll down to the ARTIFICIAL INTELLIGENCE section. Then select AI Platform → Notebooks." }, { "code": null, "e": 3239, "s": 3030, "text": "From the Notebook Instances screen select NEW INSTANCE at the top. This menu has many options including some beta and experimental choices. I am going with the PyTorch 1.4 option with one NVIDIA Tesla T4 GPU." }, { "code": null, "e": 3613, "s": 3239, "text": "Next screen presents options. For this exercise I am going with the defaults. The Customize button allows you to add more disk space to your boot drive, add GPUs RAM, etc. The default costs $0.382 per hour. Google E2 instances are billed by the second after the first minute of usage. This default configuration will run 38.2 cents per hour. That’s 785 hours of free usage." }, { "code": null, "e": 3765, "s": 3613, "text": "Once you click on Create, Google will take a couple minutes to provision your VM instance. When it’s complete you will see a screen like the following." }, { "code": null, "e": 4124, "s": 3765, "text": "You now have a fully functioning Jupyter Notebook with a powerful GPU to support DL model building. Click on OPEN JUPYTERLAB next to your Instance Name. A new tab will open in your browser and a Jupyter notebook will be opened. The interface is very straight forward. You can browse the file system, create a Git repository, or startup up a terminal session." }, { "code": null, "e": 4727, "s": 4124, "text": "At this stage you have a fully functioning, powerful DL sandbox. However, this is not a cost effective way to work. Your new VM instance is eating away at that $300 credit every second you have the instance running. I prefer to do all my data gathering, feature engineering, and initial regression work locally on my macbook. Then when I have my dataset cleaned and prepped and I am at the stage to try and fit a DL model I crank up my VM instance, connect, run my model, get my results, then shutdown the instance. To execute this workflow efficiently there’s a few more steps I will now walk through." }, { "code": null, "e": 4788, "s": 4727, "text": "Go back to the Notebooks console and shutdown your instance." }, { "code": null, "e": 4917, "s": 4788, "text": "Tip: Go to the Billing section and under Budgets & alerts create a Budget that will email you when you have reached $1 of usage." }, { "code": null, "e": 4989, "s": 4917, "text": "To open up remote access to your VM instance you need to do two things." }, { "code": null, "e": 5131, "s": 4989, "text": "Step 1. Open up HTTP access to your VM instance. From the main console menu, under the COMPUTE section, select Compute Engine → VM instances." }, { "code": null, "e": 5394, "s": 5131, "text": "Then click on your instance from the list. The details of your instance will be displayed. We need to make two changes here. Click on EDIT at the top, scroll down and check the two HTTP boxes in the Firewalls section, then scroll on to the bottom and click Save." }, { "code": null, "e": 5496, "s": 5394, "text": "Step 2. Follow the menu below and then click CREATE FIREWALL RULE at the top of the Firewall console." }, { "code": null, "e": 5549, "s": 5496, "text": "Input the noted fields in the following two screens." }, { "code": null, "e": 5635, "s": 5549, "text": "Your firewall rule should now be active. If it isn’t you will know in the next steps." }, { "code": null, "e": 5760, "s": 5635, "text": "Step 3. Stop your VM Instance. Go back to the Notebooks console click the check box next to your instance and click on STOP." }, { "code": null, "e": 5998, "s": 5760, "text": "Step 1. First step is to install the SDK on you local computer. Here’s the Google instructions for downloading and installing their SDK for MacOS, Windows, and Linux. Make sure you follow all steps including putting the SDK in your PATH." }, { "code": null, "e": 6075, "s": 5998, "text": "Step 2. Initialize the SDK by running the following command from a terminal." }, { "code": null, "e": 6154, "s": 6075, "text": "> gcloud init...> You must log in to continue. Would you like to log in (Y/n)?" }, { "code": null, "e": 6415, "s": 6154, "text": "You will be prompted to log in. When you press Y and Return you will be redirected to a Google website to log into your account. Once you successfully log in you should be returned to your terminal session where you will be prompted to select a compute region." }, { "code": null, "e": 6484, "s": 6415, "text": "> Do you want to configure a default Compute Region and Zone? (Y/n)?" }, { "code": null, "e": 6729, "s": 6484, "text": "Select Y. In one of the earlier screen shots I suggested noting your instance name and the region in which it was created. Find that region in the list that is presented and enter its index number. Once that completes run the following command." }, { "code": null, "e": 6750, "s": 6729, "text": "> gcloud config list" }, { "code": null, "e": 6819, "s": 6750, "text": "You should see something like the following in your terminal window." }, { "code": null, "e": 6987, "s": 6819, "text": "Step 3. Before we left our VM instance we shut it down. Let’s now start it back up using the SDK. Here’s the command. Replace inst_name with the name of your instance." }, { "code": null, "e": 7030, "s": 6987, "text": "> gcloud compute instances start inst_name" }, { "code": null, "e": 7092, "s": 7030, "text": "Now let’s practice stopping the instance. Here’s the command." }, { "code": null, "e": 7134, "s": 7092, "text": "> gcloud compute instances stop inst_name" }, { "code": null, "e": 7259, "s": 7134, "text": "This can take a couple minutes so just let it run. After the little spinner thing completes you should get this as a result." }, { "code": null, "e": 7336, "s": 7259, "text": "Once you see the ...done then startup your instance again and let’s move on." }, { "code": null, "e": 7480, "s": 7336, "text": "Step 4. Time to connect to the instance and finish the server side setup. Enter the following command and replace inst_name with your instance." }, { "code": null, "e": 7511, "s": 7480, "text": "> gcloud compute ssh inst_name" }, { "code": null, "e": 7647, "s": 7511, "text": "You will be prompted for a password. This is the account password you created initially. Next you will see a screen like the following." }, { "code": null, "e": 7803, "s": 7647, "text": "Okay, we are almost there. Just a few configuration changes to Jupyter and then we will be able to connect with Visual Studio Code and run a model. Yeah! 😎" }, { "code": null, "e": 7999, "s": 7803, "text": "Step 1. Create a folder for notebooks. This is where Jupyter will store notebook files. I also recommend creating two subfolder whose purpose will become clear when we run the sample model below." }, { "code": null, "e": 8064, "s": 7999, "text": "> mkdir jnotebooks> mkdir jnotebooks/data> mkdir jnotebooks/pics" }, { "code": null, "e": 8158, "s": 8064, "text": "Step 2. Create Jupyter configuration. This creates a .jupyter folder off your root directory." }, { "code": null, "e": 8195, "s": 8158, "text": "> jupyter notebook --generate-config" }, { "code": null, "e": 8549, "s": 8195, "text": "Now for a little tricky part. We need to configure a few Jupyter parameters in the file .jupyter/jupyter_notebook_config.py. I recommend using vim. Before editing the file note your root path by executing pwd. Here’s the parameters. All these parameters are already in the file. However, they are commented out. They need to be uncommented and modified." }, { "code": null, "e": 8687, "s": 8549, "text": "c.NotebookApp.ip = '*'c.NotebookApp.port = 8888c.NotebookApp.notebook_dir = '/home/username/jnotebooks'c.NotebookApp.open_browser = False" }, { "code": null, "e": 8782, "s": 8687, "text": "Remember we created the jnotebooks folder. Enter its full path for the notebook_dir parameter." }, { "code": null, "e": 8843, "s": 8782, "text": "Here’s a short vim cheatsheet of the commands you will need." }, { "code": null, "e": 9133, "s": 8843, "text": "Step 3. Set a Jupyter password. This is optional but highly recommended since we just opened HTTP access. From the command line enter the following and then enter your password. You will have to enter this every time you access this server from VSC so I recommend not going overboard here." }, { "code": null, "e": 9161, "s": 9133, "text": "> jupyter notebook password" }, { "code": null, "e": 9249, "s": 9161, "text": "Step 4. Final step here. Let’s startup the Jupyter Notebook server. Here’s the command." }, { "code": null, "e": 9268, "s": 9249, "text": "> jupyter-notebook" }, { "code": null, "e": 9427, "s": 9268, "text": "If your screen doesn’t closely resemble this then kill the process by pressing Control-c and go back and check the four parameters in the Jupyter config file." }, { "code": null, "e": 10095, "s": 9427, "text": "I am a big Visual Studio Code fan. Microsoft open-sourced it some time ago and it has since evolved quickly to become a very user friendly and highly functional editor. And the thing I find really cool is that it now fully supports Jupyter Notebooks. I personally am not in love with running notebooks in a browser when I am in work mode. I prefer a real code editor that I use for Python and Java (and hopefully Swift will be supported soon). In VSC I can build my models in notebooks and then easily export to a Python file and start moving towards production’izing my project, all in the same editor. Enough rambling. Let’s connect to our server and train a model." }, { "code": null, "e": 10393, "s": 10095, "text": "Step 1. Install and setup Visual Studio Code. If you use an Anaconda distribution then you are all set. Anaconda and VSC work well together. Otherwise click here to get the latest version for your operating system. VSC supports Jupyter natively so there’s nothing extra that needs to be installed." }, { "code": null, "e": 10601, "s": 10393, "text": "Step 2. Open VSC and create a new Jupyter notebook. The easiest way to do this is by using the command browser. On MacOS the command is shift+command+p. Then type in Python: Create New Blank Jupyter Notebook" }, { "code": null, "e": 10870, "s": 10601, "text": "Step 3. Connect to your server. Did you note your external IP address when you started up your server? You’ll need it here. Once again access the command browser via shift+command+p. Then enter the command Python: Specify local or remote Jupyter server for connections" }, { "code": null, "e": 10905, "s": 10870, "text": "You see this next.Select Existing." }, { "code": null, "e": 10971, "s": 10905, "text": "Here’s where you need the external IP address of you VM instance." }, { "code": null, "e": 11401, "s": 10971, "text": "After entering your http address above and pressing return there’s a chance VSC will require a restart. If that does happen then close VSC, start it up again, and then follow this Step 3 back to this point. Type in some test Python code and execute the cell. VSC will send the code to the server and will display the returned result. Then you will see your Jupyter Server address in the top right corner like the highlight below." }, { "code": null, "e": 11443, "s": 11401, "text": "SUCCESS! Now it’s time for some real fun!" }, { "code": null, "e": 12013, "s": 11443, "text": "I believe every data science hacker, coder, and professional is familiar with the Titanic data set at Kaggle. It’s like the “Hello World” of data science. I’ve toyed around with this data set as well. I’ve applied just basic reasoning like “assume all men die”. That will get you a mediocre score with just a few lines of code. For fun, I’ve done a lot of feature engineering and then applied all the Scikit-learn models and Xgboost. Then for real fun I thought I would apply a DL model. My model is available on Github. I recommend following along to see the workflow." }, { "code": null, "e": 12049, "s": 12013, "text": "Step 1. Get model from Github here." }, { "code": null, "e": 12321, "s": 12049, "text": "Step 2. Switch VSC to a local Python instance. shift+command+p followed by Python: Specify local or remote Jupyter server for connections then select Default from the menu. This will force a reload of VSC (hopefully this reloading requirement will go away in the future)." }, { "code": null, "e": 12587, "s": 12321, "text": "Step 3. Open the file titanic_feature_creation.ipynb in VSC and execute each cell. The final cell will write out the files titanic_train_wrangled.csv, and titanic_test_wrangled.csv into a subfolder called data. Those two files have to be copied to your VM instance." }, { "code": null, "e": 12753, "s": 12587, "text": "Step 4. Copy data files to VM instance. From the titanic folder you retrieved from Github execute the following command. Substitute your instance name for inst_name." }, { "code": null, "e": 12816, "s": 12753, "text": "> gcloud compute scp ./data/*.csv inst_name:~/jnotebooks/data/" }, { "code": null, "e": 13015, "s": 12816, "text": "Step 5. Connect VSC to your Server. Shift+command+p followed by Python: Specify local or remote Jupyter server for connections then select your server from the menu. This will force a reload of VSC." }, { "code": null, "e": 13200, "s": 13015, "text": "Step 6. Open the file titanic_model_evaluation_cnn.ipynb. Note, in the first cell the data files that are read. You created these locally and then transferred them to your VM instance." }, { "code": null, "e": 13265, "s": 13200, "text": "Step 7. Execute all the cells to generate a submission.csv file." }, { "code": null, "e": 13638, "s": 13265, "text": "Disclaimer: The cell titled, Convert features to square PNG, is just a simple way to translate each row (or record) of both data files into an image for this exercise. There are many better ways to translate data for DL models. I wanted to keep it bare-bones simple for this demonstration. All created images are stored in a sub folder on the server called images_titanic." }, { "code": null, "e": 13736, "s": 13638, "text": "Step1. Now let’s retrieve the file submissions.csv that was created in the last cell shown below." }, { "code": null, "e": 13813, "s": 13736, "text": "Here’s the command. Once again, substitute your instance name for inst_name." }, { "code": null, "e": 13879, "s": 13813, "text": "> gcloud compute scp inst_name:~/jnotebooks/data/submission.csv ." }, { "code": null, "e": 13942, "s": 13879, "text": "Step 2. Visit Kaggle’s Titanic site here and submit your work." }, { "code": null, "e": 14249, "s": 13942, "text": "78% percentile is okay. Not bad. However, if you’re a real DS practitioner you would laugh at this. It’s an extreme case of over engineering. But this was not an exercise in optimal deep-learning-model engineering. This was all about how to set up a sandbox so you then go focus on building optimal models." } ]
Laravel - Controllers
In the MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views and Models. In this chapter, you will learn about Controllers in Laravel. Open the command prompt or terminal based on the operating system you are using and type the following command to create controller using the Artisan CLI (Command Line Interface). php artisan make:controller <controller-name> --plain Replace the <controller-name> with the name of your controller. This will create a plain constructor as we are passing the argument — plain. If you don’t want to create a plain constructor, you can simply ignore the argument. The created constructor can be seen at app/Http/Controllers. You will see that some basic coding has already been done for you and you can add your custom coding. The created controller can be called from routes.php by the following syntax. Route::get(‘base URI’,’controller@method’); Step 1 − Execute the following command to create UserController. php artisan make:controller UserController --plain Step 2 − After successful execution, you will receive the following output. Step 3 − You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { // } We have seen middleware before and it can be used with controller also. Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller. Route::get('profile', [ 'middleware' => 'auth', 'uses' => 'UserController@showProfile' ]); Here we are assigning auth middleware to UserController in profile route. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct() { $this->middleware('auth'); } } Here we are assigning auth middleware using the middleware method in the UserController constructor. Step 1 − Add the following lines of code to the app/Http/routes.php file and save it. routes.php <?php Route::get('/usercontroller/path',[ 'middleware' => 'First', 'uses' => 'UserController@showPath' ]); Step 2 − Create a middleware called FirstMiddleware by executing the following line of code. php artisan make:middleware FirstMiddleware Step 3 − Add the following code into the handle method of the newly created FirstMiddleware at app/Http/Middleware. FirstMiddleware.php <?php namespace App\Http\Middleware; use Closure; class FirstMiddleware { public function handle($request, Closure $next) { echo '<br>First Middleware'; return $next($request); } } Step 4 − Create a middleware called SecondMiddleware by executing the following command. php artisan make:middleware SecondMiddleware Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at app/Http/Middleware. SecondMiddleware.php <?php namespace App\Http\Middleware; use Closure; class SecondMiddleware { public function handle($request, Closure $next) { echo '<br>Second Middleware'; return $next($request); } } Step 6 − Create a controller called UserController by executing the following line. php artisan make:controller UserController --plain Step 7 − After successful execution of the URL, you will receive the following output − Step 8 − Copy the following code to app/Http/UserController.php file. app/Http/UserController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class UserController extends Controller { public function __construct() { $this->middleware('Second'); } public function showPath(Request $request) { $uri = $request->path(); echo '<br>URI: '.$uri; $url = $request->url(); echo '<br>'; echo 'URL: '.$url; $method = $request->method(); echo '<br>'; echo 'Method: '.$method; } } Step 9 − Now launch the php’s internal web server by executing the following command, if you haven’t executed it yet. php artisan serve Step 10 − Visit the following URL. http://localhost:8000/usercontroller/path Step 11 − The output will appear as shown in the following image. Often while making an application we need to perform CRUD (Create, Read, Update, Delete) operations. Laravel makes this job easy for us. Just create a controller and Laravel will automatically provide all the methods for the CRUD operations. You can also register a single route for all the methods in routes.php file. Step 1 − Create a controller called MyController by executing the following command. php artisan make:controller MyController Step 2 − Add the following code in app/Http/Controllers/MyController.php file. app/Http/Controllers/MyController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class MyController extends Controller { public function index() { echo 'index'; } public function create() { echo 'create'; } public function store(Request $request) { echo 'store'; } public function show($id) { echo 'show'; } public function edit($id) { echo 'edit'; } public function update(Request $request, $id) { echo 'update'; } public function destroy($id) { echo 'destroy'; } } Step 3 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::resource('my','MyController'); Step 4 − We are now registering all the methods of MyController by registering a controller with resource. Below is the table of actions handled by resource controller. Step 5 − Try executing the URLs shown in the following table. Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route:controller method as shown below. Route::controller(‘base URI’,’<class-name-of-the-controller>’); Replace the <class-name-of-the-controller> with the class name that you have given to your controller. The method name of the controller should start with HTTP verb like get or post. If you start it with get, it will handle only get request and if it starts with post then it will handle the post request. After the HTTP verb you can, you can give any name to the method but it should follow the title case version of the URI. Step 1 − Execute the below command to create a controller. We have kept the class name ImplicitController. You can give any name of your choice to the class. php artisan make:controller ImplicitController --plain Step 2 − After successful execution of step 1, you will receive the following output − Step 3 − Copy the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { /** * Responds to requests to GET /test */ public function getIndex() { echo 'index method'; } /** * Responds to requests to GET /test/show/1 */ public function getShow($id) { echo 'show method'; } /** * Responds to requests to GET /test/admin-profile */ public function getAdminProfile() { echo 'admin profile method'; } /** * Responds to requests to POST /test/profile */ public function postProfile() { echo 'profile method'; } } Step 4 − Add the following line to app/Http/routes.php file to route the requests to specified controller. app/Http/routes.php Route::controller('test','ImplicitController'); The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The dependencies will automatically be resolved and injected into the controller instance. Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php class MyClass{ public $foo = 'bar'; } Route::get('/myclass','ImplicitController@index'); Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { private $myclass; public function __construct(\MyClass $myclass) { $this->myclass = $myclass; } public function index() { dd($this->myclass); } } Step 3 − Visit the following URL to test the constructor injection. http://localhost:8000/myclass Step 4 − The output will appear as shown in the following image. In addition to constructor injection, you may also type — hint dependencies on your controller's action methods. Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php class MyClass{ public $foo = 'bar'; } Route::get('/myclass','ImplicitController@index'); Step 2 − Add the following code to app/Http/Controllers/ImplicitController.php file. app/Http/Controllers/ImplicitController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ImplicitController extends Controller { public function index(\MyClass $myclass) { dd($myclass); } } Step 3 − Visit the following URL to test the constructor injection. http://localhost:8000/myclass It will produce the following output − 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2651, "s": 2472, "text": "In the MVC framework, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views and Models. In this chapter, you will learn about Controllers in Laravel." }, { "code": null, "e": 2831, "s": 2651, "text": "Open the command prompt or terminal based on the operating system you are using and type the following command to create controller using the Artisan CLI (Command Line Interface)." }, { "code": null, "e": 2886, "s": 2831, "text": "php artisan make:controller <controller-name> --plain\n" }, { "code": null, "e": 3173, "s": 2886, "text": "Replace the <controller-name> with the name of your controller. This will create a plain constructor as we are passing the argument — plain. If you don’t want to create a plain constructor, you can simply ignore the argument. The created constructor can be seen at app/Http/Controllers." }, { "code": null, "e": 3353, "s": 3173, "text": "You will see that some basic coding has already been done for you and you can add your custom coding. The created controller can be called from routes.php by the following syntax." }, { "code": null, "e": 3398, "s": 3353, "text": "Route::get(‘base URI’,’controller@method’);\n" }, { "code": null, "e": 3463, "s": 3398, "text": "Step 1 − Execute the following command to create UserController." }, { "code": null, "e": 3515, "s": 3463, "text": "php artisan make:controller UserController --plain\n" }, { "code": null, "e": 3591, "s": 3515, "text": "Step 2 − After successful execution, you will receive the following output." }, { "code": null, "e": 3776, "s": 3591, "text": "Step 3 − You can see the created controller at app/Http/Controller/UserController.php with some basic coding already written for you and you can add your own coding based on your need." }, { "code": null, "e": 3956, "s": 3776, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass UserController extends Controller {\n //\n}" }, { "code": null, "e": 4283, "s": 3956, "text": "We have seen middleware before and it can be used with controller also. Middleware can also be assigned to controller’s route or within your controller’s constructor. You can use the middleware method to assign middleware to the controller. The registered middleware can also be restricted to certain method of the controller." }, { "code": null, "e": 4381, "s": 4283, "text": "Route::get('profile', [\n 'middleware' => 'auth',\n 'uses' => 'UserController@showProfile'\n]);\n" }, { "code": null, "e": 4455, "s": 4381, "text": "Here we are assigning auth middleware to UserController in profile route." }, { "code": null, "e": 4702, "s": 4455, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass UserController extends Controller {\n public function __construct() {\n $this->middleware('auth');\n }\n}" }, { "code": null, "e": 4803, "s": 4702, "text": "Here we are assigning auth middleware using the middleware method in the UserController constructor." }, { "code": null, "e": 4889, "s": 4803, "text": "Step 1 − Add the following lines of code to the app/Http/routes.php file and save it." }, { "code": null, "e": 4900, "s": 4889, "text": "routes.php" }, { "code": null, "e": 5013, "s": 4900, "text": "<?php\nRoute::get('/usercontroller/path',[\n 'middleware' => 'First',\n 'uses' => 'UserController@showPath'\n]);" }, { "code": null, "e": 5106, "s": 5013, "text": "Step 2 − Create a middleware called FirstMiddleware by executing the following line of code." }, { "code": null, "e": 5151, "s": 5106, "text": "php artisan make:middleware FirstMiddleware\n" }, { "code": null, "e": 5267, "s": 5151, "text": "Step 3 − Add the following code into the handle method of the newly created FirstMiddleware at app/Http/Middleware." }, { "code": null, "e": 5287, "s": 5267, "text": "FirstMiddleware.php" }, { "code": null, "e": 5488, "s": 5287, "text": "<?php\n\nnamespace App\\Http\\Middleware;\nuse Closure;\n\nclass FirstMiddleware {\n public function handle($request, Closure $next) {\n echo '<br>First Middleware';\n return $next($request);\n }\n}" }, { "code": null, "e": 5577, "s": 5488, "text": "Step 4 − Create a middleware called SecondMiddleware by executing the following command." }, { "code": null, "e": 5623, "s": 5577, "text": "php artisan make:middleware SecondMiddleware\n" }, { "code": null, "e": 5738, "s": 5623, "text": "Step 5 − Add the following code in the handle method of the newly created SecondMiddleware at app/Http/Middleware." }, { "code": null, "e": 5759, "s": 5738, "text": "SecondMiddleware.php" }, { "code": null, "e": 5962, "s": 5759, "text": "<?php\n\nnamespace App\\Http\\Middleware;\nuse Closure;\n\nclass SecondMiddleware {\n public function handle($request, Closure $next) {\n echo '<br>Second Middleware';\n return $next($request);\n }\n}" }, { "code": null, "e": 6046, "s": 5962, "text": "Step 6 − Create a controller called UserController by executing the following line." }, { "code": null, "e": 6098, "s": 6046, "text": "php artisan make:controller UserController --plain\n" }, { "code": null, "e": 6186, "s": 6098, "text": "Step 7 − After successful execution of the URL, you will receive the following output −" }, { "code": null, "e": 6256, "s": 6186, "text": "Step 8 − Copy the following code to app/Http/UserController.php file." }, { "code": null, "e": 6284, "s": 6256, "text": "app/Http/UserController.php" }, { "code": null, "e": 6827, "s": 6284, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass UserController extends Controller {\n public function __construct() {\n $this->middleware('Second');\n }\n public function showPath(Request $request) {\n $uri = $request->path();\n echo '<br>URI: '.$uri;\n \n $url = $request->url();\n echo '<br>';\n \n echo 'URL: '.$url;\n $method = $request->method();\n echo '<br>';\n \n echo 'Method: '.$method;\n }\n}" }, { "code": null, "e": 6945, "s": 6827, "text": "Step 9 − Now launch the php’s internal web server by executing the following command, if you haven’t executed it yet." }, { "code": null, "e": 6964, "s": 6945, "text": "php artisan serve\n" }, { "code": null, "e": 6999, "s": 6964, "text": "Step 10 − Visit the following URL." }, { "code": null, "e": 7042, "s": 6999, "text": "http://localhost:8000/usercontroller/path\n" }, { "code": null, "e": 7108, "s": 7042, "text": "Step 11 − The output will appear as shown in the following image." }, { "code": null, "e": 7427, "s": 7108, "text": "Often while making an application we need to perform CRUD (Create, Read, Update, Delete) operations. Laravel makes this job easy for us. Just create a controller and Laravel will automatically provide all the methods for the CRUD operations. You can also register a single route for all the methods in routes.php file." }, { "code": null, "e": 7512, "s": 7427, "text": "Step 1 − Create a controller called MyController by executing the following command." }, { "code": null, "e": 7554, "s": 7512, "text": "php artisan make:controller MyController\n" }, { "code": null, "e": 7589, "s": 7554, "text": "Step 2 − Add the following code in" }, { "code": null, "e": 7633, "s": 7589, "text": "app/Http/Controllers/MyController.php file." }, { "code": null, "e": 7671, "s": 7633, "text": "app/Http/Controllers/MyController.php" }, { "code": null, "e": 8271, "s": 7671, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass MyController extends Controller {\n public function index() {\n echo 'index';\n }\n public function create() {\n echo 'create';\n }\n public function store(Request $request) {\n echo 'store';\n }\n public function show($id) {\n echo 'show';\n }\n public function edit($id) {\n echo 'edit';\n }\n public function update(Request $request, $id) {\n echo 'update';\n }\n public function destroy($id) {\n echo 'destroy';\n }\n}" }, { "code": null, "e": 8340, "s": 8271, "text": "Step 3 − Add the following line of code in app/Http/routes.php file." }, { "code": null, "e": 8360, "s": 8340, "text": "app/Http/routes.php" }, { "code": null, "e": 8399, "s": 8360, "text": "Route::resource('my','MyController');\n" }, { "code": null, "e": 8568, "s": 8399, "text": "Step 4 − We are now registering all the methods of MyController by registering a controller with resource. Below is the table of actions handled by resource controller." }, { "code": null, "e": 8630, "s": 8568, "text": "Step 5 − Try executing the URLs shown in the following table." }, { "code": null, "e": 8809, "s": 8630, "text": "Implicit Controllers allow you to define a single route to handle every action in the controller. You can define it in route.php file with Route:controller method as shown below." }, { "code": null, "e": 8874, "s": 8809, "text": "Route::controller(‘base URI’,’<class-name-of-the-controller>’);\n" }, { "code": null, "e": 8977, "s": 8874, "text": "Replace the <class-name-of-the-controller> with the class name that you have given to your controller." }, { "code": null, "e": 9301, "s": 8977, "text": "The method name of the controller should start with HTTP verb like get or post. If you start it with get, it will handle only get request and if it starts with post then it will handle the post request. After the HTTP verb you can, you can give any name to the method but it should follow the title case version of the URI." }, { "code": null, "e": 9459, "s": 9301, "text": "Step 1 − Execute the below command to create a controller. We have kept the class name ImplicitController. You can give any name of your choice to the class." }, { "code": null, "e": 9515, "s": 9459, "text": "php artisan make:controller ImplicitController --plain\n" }, { "code": null, "e": 9602, "s": 9515, "text": "Step 2 − After successful execution of step 1, you will receive the following output −" }, { "code": null, "e": 9638, "s": 9602, "text": "Step 3 − Copy the following code to" }, { "code": null, "e": 9688, "s": 9638, "text": "app/Http/Controllers/ImplicitController.php file." }, { "code": null, "e": 9732, "s": 9688, "text": "app/Http/Controllers/ImplicitController.php" }, { "code": null, "e": 10449, "s": 9732, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass ImplicitController extends Controller {\n /**\n * Responds to requests to GET /test\n */\n public function getIndex() {\n echo 'index method';\n }\n \n /**\n * Responds to requests to GET /test/show/1\n */\n public function getShow($id) {\n echo 'show method';\n }\n \n /**\n * Responds to requests to GET /test/admin-profile\n */\n public function getAdminProfile() {\n echo 'admin profile method';\n }\n \n /**\n * Responds to requests to POST /test/profile\n */\n public function postProfile() {\n echo 'profile method';\n }\n}" }, { "code": null, "e": 10556, "s": 10449, "text": "Step 4 − Add the following line to app/Http/routes.php file to route the requests to specified controller." }, { "code": null, "e": 10576, "s": 10556, "text": "app/Http/routes.php" }, { "code": null, "e": 10625, "s": 10576, "text": "Route::controller('test','ImplicitController');\n" }, { "code": null, "e": 10891, "s": 10625, "text": "The Laravel service container is used to resolve all Laravel controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The dependencies will automatically be resolved and injected into the controller instance." }, { "code": null, "e": 10952, "s": 10891, "text": "Step 1 − Add the following code to app/Http/routes.php file." }, { "code": null, "e": 10972, "s": 10952, "text": "app/Http/routes.php" }, { "code": null, "e": 11064, "s": 10972, "text": "class MyClass{\n public $foo = 'bar';\n}\nRoute::get('/myclass','ImplicitController@index');" }, { "code": null, "e": 11099, "s": 11064, "text": "Step 2 − Add the following code to" }, { "code": null, "e": 11149, "s": 11099, "text": "app/Http/Controllers/ImplicitController.php file." }, { "code": null, "e": 11193, "s": 11149, "text": "app/Http/Controllers/ImplicitController.php" }, { "code": null, "e": 11546, "s": 11193, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass ImplicitController extends Controller {\n private $myclass;\n \n public function __construct(\\MyClass $myclass) {\n $this->myclass = $myclass;\n }\n public function index() {\n dd($this->myclass);\n }\n}" }, { "code": null, "e": 11614, "s": 11546, "text": "Step 3 − Visit the following URL to test the constructor injection." }, { "code": null, "e": 11645, "s": 11614, "text": "http://localhost:8000/myclass\n" }, { "code": null, "e": 11710, "s": 11645, "text": "Step 4 − The output will appear as shown in the following image." }, { "code": null, "e": 11823, "s": 11710, "text": "In addition to constructor injection, you may also type — hint dependencies on your controller's action methods." }, { "code": null, "e": 11884, "s": 11823, "text": "Step 1 − Add the following code to app/Http/routes.php file." }, { "code": null, "e": 11904, "s": 11884, "text": "app/Http/routes.php" }, { "code": null, "e": 11997, "s": 11904, "text": "class MyClass{\n public $foo = 'bar';\n}\nRoute::get('/myclass','ImplicitController@index');\n" }, { "code": null, "e": 12032, "s": 11997, "text": "Step 2 − Add the following code to" }, { "code": null, "e": 12082, "s": 12032, "text": "app/Http/Controllers/ImplicitController.php file." }, { "code": null, "e": 12126, "s": 12082, "text": "app/Http/Controllers/ImplicitController.php" }, { "code": null, "e": 12376, "s": 12126, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass ImplicitController extends Controller {\n public function index(\\MyClass $myclass) {\n dd($myclass);\n }\n} " }, { "code": null, "e": 12444, "s": 12376, "text": "Step 3 − Visit the following URL to test the constructor injection." }, { "code": null, "e": 12475, "s": 12444, "text": "http://localhost:8000/myclass\n" }, { "code": null, "e": 12514, "s": 12475, "text": "It will produce the following output −" }, { "code": null, "e": 12547, "s": 12514, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 12567, "s": 12547, "text": " Sebastian Sulinski" }, { "code": null, "e": 12602, "s": 12567, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12616, "s": 12602, "text": " Antonio Papa" }, { "code": null, "e": 12650, "s": 12616, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12670, "s": 12650, "text": " Sebastian Sulinski" }, { "code": null, "e": 12703, "s": 12670, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 12723, "s": 12703, "text": " Skillbakerystudios" }, { "code": null, "e": 12758, "s": 12723, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 12781, "s": 12758, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 12816, "s": 12781, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 12836, "s": 12816, "text": " Hafizullah Masoudi" }, { "code": null, "e": 12843, "s": 12836, "text": " Print" }, { "code": null, "e": 12854, "s": 12843, "text": " Add Notes" } ]
Classification of Amazon Food Reviews | by Sohail Hosseini | Towards Data Science
The goal here is to classify Food reviews based on customers' text. So the first step would be to download the dataset. It would be fascinating for suppliers to use reviews from their customers to provide better service to them. Reviews include several features like ‘ProductId’, ‘UserId’, ‘Score’, and ‘text’. But how can we analyze these sorts of problems? Let’s look at features included in dataset: print(“There are {} observations and {} features in this dataset. “\ .format(reviews.shape[0],reviews.shape[1]))There are 568454 observations and 10 features in this dataset. As it shows, the dataset consists of 568454 reviews that span a period of more than ten years. They are ten different features available in this dataset, but we only work ‘text’ and ‘Score’ columns as our input/output, respectively. We are going to predict Score based on customers' texts. This is called Sentiment Analysis. Other features do not affect the relation between target and feature. Now, let’s look at features included in dataset: reviews.head() To have a better understanding of target (Score) distribution, we use .countplot from the seaborn library. By applying this imported function, we can see the distribution of scores. import seaborn as sns import matplotlib.pyplot as plt sns.countplot(reviews[‘Score’]) plt.show() It shows that Score five has the maximum number between the rest of them. Based on Score distribution, which in our case, we use it as our target, it shows that the distribution is skewed, and we can also consider applying logarithm to make it more look like Gaussian. Machine learning works better when inputs and outputs have Gaussian distributions. Let’s look at the type of each feature with pandas .info() function, which also can give you a general overview of features. It can be helpful to know if there is any missing value for each column, so you will be able to deal with it in an effective way. reviews.info() Since we are only working with only two columns, and there is no missing value, we do not need to remove any observation or use an imputation transformer for completing missing values. Multinomial Naive Bayes classifier is suitable for text classification. Based on the size of the dataset and creating discrete features, I think it is practical to use a machine learning algorithm that runs fast. Otherwise, it takes a while to get a satisfactory output. Our goal here is to find a relation between input and output. I use the ‘text’ feature as input and ‘score’ as output. So my first step is to convert texts to vectors. We must do that because we are using the Naive Bayes classifier for multinomial models, and this method also accepts numerical inputs. This is the same technique for applying any machine learning algorithm. from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline We need to convert feedback (texts) to a matrix of token counts in order to extract numerical features from text content. By doing it, a sparse representation of the counts is generated. It is very beneficial as you can imagine unique mapping words to vectors create the massive size of a matrix. CountVectorizer is used for this purpose, which can be imported as follows. from sklearn.feature_extraction.text import CountVectorizer There are many words like ‘the,’ ‘them,’ ‘are’ that do not have any effect on the meaning of context, which are called stop words. They are not informative and can be removed by selecting step_words=’english’ as a hyperparameter in CountVectorizer function. The next step is to normalize the count matrix using tf-idf representation. The main reason behind normalizing frequencies instead of using the raw ones is to decrease the effect of tokens that occur several times in the text, and there’s not as informative as those presented a few times. For instance, the word “document” occurs a thousand times in a given corpus, and “awesome” happens two times. tf-idf works in this situation, like preprocessing data to change raw feature vectors into a representation that is more suitable for machine learning algorithms. from sklearn.feature_extraction.text import TfidfTransformer I used the pipeline function to do all steps together. Sequentially apply a list of transforms and a final estimator. Therefore, it starts applying CountVectorizer, Tfidf, and then MultinomialNB. You can have any number of transformers required for your work in Pipeline. twitter_sentiment = Pipeline([('CVec', CountVectorizer(stop_words='english')), ('Tfidf', TfidfTransformer()), ('MNB', MultinomialNB())]) In the end, cross_validate is used with the roc_auc metric. k-fold cross-validation is applied and the performance measure is calculated as the average of the values in the loop. In our case, k is assigned as five. Five and ten are common values selected in k-fold cross-validation. The snippet of code is written below. from sklearn.model_selection import cross_validatecv_pred = cross_validate(twitter_sentiment, reviews['Text'], reviews['Score'], cv=5, scoring=('roc_auc_ovr'), n_jobs=-1, verbose =10) This is a classification problem, so we use Complete Area Under the Receiver Operating Characteristic Curve (ROC-AUC) to measure prediction scores. Since we have a multiclass problem, we are going to ‘roc_auc_ovr’. There are other options available, which could be used for this case. The results we have measured using ROC_AUC are as follows. cv_pred['test_score']array([0.80588185, 0.81448439, 0.8088359 , 0.81728556, 0.81103624]) For each fold, the score is more than 80%. There are algorithms available like Random Forest, Gradient Boosting which also could be used here. But it depends on what you are looking for in solving each case. Are you searching for a fast answer and better accuracy? Ther is always a trade-off between these two options and you would need to select the best option for each dataset. The complete code can be accessed through this link.
[ { "code": null, "e": 483, "s": 172, "text": "The goal here is to classify Food reviews based on customers' text. So the first step would be to download the dataset. It would be fascinating for suppliers to use reviews from their customers to provide better service to them. Reviews include several features like ‘ProductId’, ‘UserId’, ‘Score’, and ‘text’." }, { "code": null, "e": 531, "s": 483, "text": "But how can we analyze these sorts of problems?" }, { "code": null, "e": 575, "s": 531, "text": "Let’s look at features included in dataset:" }, { "code": null, "e": 750, "s": 575, "text": "print(“There are {} observations and {} features in this dataset. “\\ .format(reviews.shape[0],reviews.shape[1]))There are 568454 observations and 10 features in this dataset." }, { "code": null, "e": 983, "s": 750, "text": "As it shows, the dataset consists of 568454 reviews that span a period of more than ten years. They are ten different features available in this dataset, but we only work ‘text’ and ‘Score’ columns as our input/output, respectively." }, { "code": null, "e": 1145, "s": 983, "text": "We are going to predict Score based on customers' texts. This is called Sentiment Analysis. Other features do not affect the relation between target and feature." }, { "code": null, "e": 1194, "s": 1145, "text": "Now, let’s look at features included in dataset:" }, { "code": null, "e": 1209, "s": 1194, "text": "reviews.head()" }, { "code": null, "e": 1391, "s": 1209, "text": "To have a better understanding of target (Score) distribution, we use .countplot from the seaborn library. By applying this imported function, we can see the distribution of scores." }, { "code": null, "e": 1488, "s": 1391, "text": "import seaborn as sns import matplotlib.pyplot as plt sns.countplot(reviews[‘Score’]) plt.show()" }, { "code": null, "e": 1840, "s": 1488, "text": "It shows that Score five has the maximum number between the rest of them. Based on Score distribution, which in our case, we use it as our target, it shows that the distribution is skewed, and we can also consider applying logarithm to make it more look like Gaussian. Machine learning works better when inputs and outputs have Gaussian distributions." }, { "code": null, "e": 2095, "s": 1840, "text": "Let’s look at the type of each feature with pandas .info() function, which also can give you a general overview of features. It can be helpful to know if there is any missing value for each column, so you will be able to deal with it in an effective way." }, { "code": null, "e": 2110, "s": 2095, "text": "reviews.info()" }, { "code": null, "e": 2295, "s": 2110, "text": "Since we are only working with only two columns, and there is no missing value, we do not need to remove any observation or use an imputation transformer for completing missing values." }, { "code": null, "e": 2566, "s": 2295, "text": "Multinomial Naive Bayes classifier is suitable for text classification. Based on the size of the dataset and creating discrete features, I think it is practical to use a machine learning algorithm that runs fast. Otherwise, it takes a while to get a satisfactory output." }, { "code": null, "e": 2941, "s": 2566, "text": "Our goal here is to find a relation between input and output. I use the ‘text’ feature as input and ‘score’ as output. So my first step is to convert texts to vectors. We must do that because we are using the Naive Bayes classifier for multinomial models, and this method also accepts numerical inputs. This is the same technique for applying any machine learning algorithm." }, { "code": null, "e": 3086, "s": 2941, "text": "from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline" }, { "code": null, "e": 3459, "s": 3086, "text": "We need to convert feedback (texts) to a matrix of token counts in order to extract numerical features from text content. By doing it, a sparse representation of the counts is generated. It is very beneficial as you can imagine unique mapping words to vectors create the massive size of a matrix. CountVectorizer is used for this purpose, which can be imported as follows." }, { "code": null, "e": 3519, "s": 3459, "text": "from sklearn.feature_extraction.text import CountVectorizer" }, { "code": null, "e": 3777, "s": 3519, "text": "There are many words like ‘the,’ ‘them,’ ‘are’ that do not have any effect on the meaning of context, which are called stop words. They are not informative and can be removed by selecting step_words=’english’ as a hyperparameter in CountVectorizer function." }, { "code": null, "e": 4340, "s": 3777, "text": "The next step is to normalize the count matrix using tf-idf representation. The main reason behind normalizing frequencies instead of using the raw ones is to decrease the effect of tokens that occur several times in the text, and there’s not as informative as those presented a few times. For instance, the word “document” occurs a thousand times in a given corpus, and “awesome” happens two times. tf-idf works in this situation, like preprocessing data to change raw feature vectors into a representation that is more suitable for machine learning algorithms." }, { "code": null, "e": 4401, "s": 4340, "text": "from sklearn.feature_extraction.text import TfidfTransformer" }, { "code": null, "e": 4673, "s": 4401, "text": "I used the pipeline function to do all steps together. Sequentially apply a list of transforms and a final estimator. Therefore, it starts applying CountVectorizer, Tfidf, and then MultinomialNB. You can have any number of transformers required for your work in Pipeline." }, { "code": null, "e": 4850, "s": 4673, "text": "twitter_sentiment = Pipeline([('CVec', CountVectorizer(stop_words='english')), ('Tfidf', TfidfTransformer()), ('MNB', MultinomialNB())])" }, { "code": null, "e": 5171, "s": 4850, "text": "In the end, cross_validate is used with the roc_auc metric. k-fold cross-validation is applied and the performance measure is calculated as the average of the values in the loop. In our case, k is assigned as five. Five and ten are common values selected in k-fold cross-validation. The snippet of code is written below." }, { "code": null, "e": 5469, "s": 5171, "text": "from sklearn.model_selection import cross_validatecv_pred = cross_validate(twitter_sentiment, reviews['Text'], reviews['Score'], cv=5, scoring=('roc_auc_ovr'), n_jobs=-1, verbose =10)" }, { "code": null, "e": 5813, "s": 5469, "text": "This is a classification problem, so we use Complete Area Under the Receiver Operating Characteristic Curve (ROC-AUC) to measure prediction scores. Since we have a multiclass problem, we are going to ‘roc_auc_ovr’. There are other options available, which could be used for this case. The results we have measured using ROC_AUC are as follows." }, { "code": null, "e": 5902, "s": 5813, "text": "cv_pred['test_score']array([0.80588185, 0.81448439, 0.8088359 , 0.81728556, 0.81103624])" }, { "code": null, "e": 6283, "s": 5902, "text": "For each fold, the score is more than 80%. There are algorithms available like Random Forest, Gradient Boosting which also could be used here. But it depends on what you are looking for in solving each case. Are you searching for a fast answer and better accuracy? Ther is always a trade-off between these two options and you would need to select the best option for each dataset." } ]
SQL AND, OR, NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE. The OR operator displays a record if any of the conditions separated by OR is TRUE. The NOT operator displays a record if the condition(s) is NOT TRUE. The table below shows the complete "Customers" table from the Northwind sample database: The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin": The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München": The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain": The following SQL statement selects all fields from "Customers" where country is NOT "Germany": You can also combine the AND, OR and NOT operators. The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" OR "München" (use parenthesis to form complex expressions): The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and NOT "USA": Select all records where the City column has the value 'Berlin' and the PostalCode column has the value 12209. * FROM Customers City = 'Berlin' = 12209; Start the Exercise 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: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "The WHERE clause can be combined with \nAND, OR, and \nNOT operators." }, { "code": null, "e": 155, "s": 68, "text": "The AND and OR operators are used to filter records based on more than one \ncondition:" }, { "code": null, "e": 245, "s": 155, "text": "The AND operator displays a record if all the conditions separated by \n AND \n are TRUE." }, { "code": null, "e": 332, "s": 245, "text": "The OR operator displays a record if any of the conditions separated by \n OR is TRUE." }, { "code": null, "e": 400, "s": 332, "text": "The NOT operator displays a record if the condition(s) is NOT TRUE." }, { "code": null, "e": 489, "s": 400, "text": "The table below shows the complete \"Customers\" table from the Northwind sample database:" }, { "code": null, "e": 602, "s": 489, "text": "The following SQL statement selects all fields from \"Customers\" where country is \"Germany\" AND city is \"Berlin\":" }, { "code": null, "e": 704, "s": 602, "text": "The following SQL statement selects all fields from \"Customers\" where city is \"Berlin\" OR \"München\":" }, { "code": null, "e": 807, "s": 704, "text": "The following SQL statement selects all fields from \"Customers\" where country is \"Germany\" OR \"Spain\":" }, { "code": null, "e": 903, "s": 807, "text": "The following SQL statement selects all fields from \"Customers\" where country is NOT \"Germany\":" }, { "code": null, "e": 956, "s": 903, "text": "You can also combine the AND, \nOR and NOT operators." }, { "code": null, "e": 1135, "s": 956, "text": "The following SQL statement selects all fields from \"Customers\" where country is \"Germany\" AND city must be \"Berlin\" \nOR \"München\" (use parenthesis to form complex expressions):" }, { "code": null, "e": 1246, "s": 1135, "text": "The following SQL statement selects all fields from \"Customers\" where country is \nNOT \"Germany\" and NOT \"USA\":" }, { "code": null, "e": 1357, "s": 1246, "text": "Select all records where the City column has the value 'Berlin' and the PostalCode column has the value 12209." }, { "code": null, "e": 1404, "s": 1357, "text": " * FROM Customers\n City = 'Berlin'\n = 12209;\n" }, { "code": null, "e": 1423, "s": 1404, "text": "Start the Exercise" }, { "code": null, "e": 1456, "s": 1423, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1498, "s": 1456, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1605, "s": 1498, "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": 1624, "s": 1605, "text": "[email protected]" } ]
MongoDB find() to operate on recursive search?
Use find() with dot notation to perform recursive search. Let us first create a collection with documents − > db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":101,"ClientName":"Chris"},{"ClientId":102,"ClientName":"Robert"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9a118b50a6c6dd317ad99") } > db.findOperationDemo.insertOne({"ClientDetails":[{"ClientId":110,"ClientName":"David"},{"ClientId":112,"ClientName":"Mike"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9a12fb50a6c6dd317ad9a") } Following is the query to display all documents from a collection with the help of find() method − > db.findOperationDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd9a118b50a6c6dd317ad99"), "ClientDetails" : [ { "ClientId" : 101, "ClientName" : "Chris" }, { "ClientId" : 102, "ClientName" : "Robert" } ] } { "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"), "ClientDetails" : [ { "ClientId" : 110, "ClientName" : "David" }, { "ClientId" : 112, "ClientName" : "Mike" } ] } Following is the query to implement find() for recursive search using dot notation − > db.findOperationDemo.find({"ClientDetails.ClientId":110}); This will produce the following output − { "_id" : ObjectId("5cd9a12fb50a6c6dd317ad9a"), "ClientDetails" : [ { "ClientId" : 110, "ClientName" : "David" }, { "ClientId" : 112, "ClientName" : "Mike" } ] }
[ { "code": null, "e": 1170, "s": 1062, "text": "Use find() with dot notation to perform recursive search. Let us first create a collection with documents −" }, { "code": null, "e": 1602, "s": 1170, "text": "> db.findOperationDemo.insertOne({\"ClientDetails\":[{\"ClientId\":101,\"ClientName\":\"Chris\"},{\"ClientId\":102,\"ClientName\":\"Robert\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9a118b50a6c6dd317ad99\")\n}\n> db.findOperationDemo.insertOne({\"ClientDetails\":[{\"ClientId\":110,\"ClientName\":\"David\"},{\"ClientId\":112,\"ClientName\":\"Mike\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd9a12fb50a6c6dd317ad9a\")\n}" }, { "code": null, "e": 1701, "s": 1602, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1741, "s": 1701, "text": "> db.findOperationDemo.find().pretty();" }, { "code": null, "e": 1782, "s": 1741, "text": "This will produce the following output −" }, { "code": null, "e": 2246, "s": 1782, "text": "{\n \"_id\" : ObjectId(\"5cd9a118b50a6c6dd317ad99\"),\n \"ClientDetails\" : [\n {\n \"ClientId\" : 101,\n \"ClientName\" : \"Chris\"\n },\n {\n \"ClientId\" : 102,\n \"ClientName\" : \"Robert\"\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5cd9a12fb50a6c6dd317ad9a\"),\n \"ClientDetails\" : [\n {\n \"ClientId\" : 110,\n \"ClientName\" : \"David\"\n },\n {\n \"ClientId\" : 112,\n \"ClientName\" : \"Mike\"\n }\n ]\n}" }, { "code": null, "e": 2331, "s": 2246, "text": "Following is the query to implement find() for recursive search using dot notation −" }, { "code": null, "e": 2392, "s": 2331, "text": "> db.findOperationDemo.find({\"ClientDetails.ClientId\":110});" }, { "code": null, "e": 2433, "s": 2392, "text": "This will produce the following output −" }, { "code": null, "e": 2595, "s": 2433, "text": "{ \"_id\" : ObjectId(\"5cd9a12fb50a6c6dd317ad9a\"), \"ClientDetails\" : [ { \"ClientId\" : 110, \"ClientName\" : \"David\" }, { \"ClientId\" : 112, \"ClientName\" : \"Mike\" } ] }" } ]
New Features of Java 12 - GeeksforGeeks
24 Jan, 2022 Oracle released Java SE(Standard Edition) 12 on March 19, 2019, after which they plan to have a new release every six months. JDK 12 came with a lot of improvements over JDK 11. This latest version offers a list of new features such as Switch Expressions, Default CDS Archives, Shenandoah, Microbenchmark Suite, among others. These new features are discussed below. 1. Changes in Switch expressions: Switch expressions will now be used as a statement as well as expressions. This makes code simplification and pattern matching possible for the switch. In earlier versions, missing break statements resulted in default fall through which was error-prone. The default case is mandatory in the switch expressions. Now, the new Arrow syntax for switch introduced as case X -> {} Denotes that only if the label matches, statements on the right side of the arrow will be executed. The Switch expressions of Java 11 and Java 12 can be compared as follows: Java 11 Java // Java program to demonstrate the// classic switch statement import java.io.*; class Java11switchStatement { static int getMealNumber(String meal) { // stores mealNumber int mealNumber; // classic switch statement switch (meal) { case "SOUP": mealNumber = 1; break; case "BURGER": case "CHIPS": case "SANDWICH": mealNumber = 2; break; case "SPAGHETTI": case "MACARONI": mealNumber = 3; break; default: throw new IllegalStateException( "Cannot prepare " + meal); } return mealNumber; } public static void main(String[] args) { // define meal String meal = "BURGER"; // print mealNumber System.out.println("The mealNumber is : " + getMealNumber(meal)); }} The mealNumber is : 2 Java 12 Java // Java program to demonstrate the// new switch expression import java.io.*; class Java11switchStatement { // returns mealNumber static int getMealNumber(String meal) { // stores mealNumber using // new switch expression int mealNumber = switch (meal) { case "SOUP" -> 1; case "BURGER", "CHIPS", "SANDWICH" -> 2; case "SPAGHETTI", "MACARONI" -> 3; default -> throw new IllegalException(""); } return mealNumber; } public static void main(String[] args) { // define meal String meal = "BURGER"; // print mealNumber System.out.println("The mealNumber is : " + getMealNumber(meal)); }} Output The mealNumber is : 2 2. Shenandoah (A new and improved Garbage Collector) This is an experimental feature and introduces a new garbage collection (GC) algorithm, Shenandoah. It offers low pause time by concurrent execution of evacuation work with running Java threads. With this, pause times are independent of the heap size. For example, a 5MB heap will have the same pause time as that of a 10GB one. 3. JVM constants API: This API helps those programs that manipulate classes and methods. These programs need to model byte code instructions and handle loadable constants. Constants of the type String or Integer work fine. However, it becomes tricky with Constant type as Class. Loading classes can fail if Class is inaccessible or doesn’t exist. With the new API in place, interfaces such as ClassDesc, MethodTypeDesc, MethodHandleDesc, and DynamicConstantDesc, handle constant values symbolically thereby eliminating complexity. 4. Abortable mixed collections for G1: The default garbage collector, Garbage First (G1), uses an analysis engine to determine the collection set and once the collection starts, all live objects should be collected without stopping. This results in exceeding the target pause time. To address this issue, G1 collection sets are made abortable by breaking the set into optional and mandatory parts. By prioritizing the mandatory set, the pause time target can be achieved often. 5. Default CDS archives: A class data sharing (CDS) archive is created to make the JDK build process more efficient thereby improving the out-of-the-box startup time. 6. Microbenchmark suite: Developers can run existing or new benchmarks easily with the microbenchmark suite added to the JDK source code. 7. Promptly return unused committed memory from G1: With this improved feature, when G1 is idle, the garbage collector automatically returns unused heap memory to the operating system. This is done by concurrent checks of Java heap by G1. 8) Files.mismatch() method: This new method compares two files. Method Signature public static long mismatch(Path path1, Path path2) throws IOException Returns: -1L if no mismatch else Position of the first mismatch. It returns the position of the mismatch in either of the two cases. Case 1: if the size of the files does not match. Here, the size of the smaller file is returned. Case 2: if the bytes does not match. Here, the first mismatching byte is returned. Example: Java import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; public class FilesCompareExample { public static void main(String[] args) throws IOException { Path path1 = Files.createTempFile("file1", ".txt"); Path path2 = Files.createTempFile("file2", ".txt"); Files.writeString(path1, "Geeks for geeks"); Files.writeString(path2, "Geeks for geeks"); long mismatch1 = Files.mismatch(path1, path2); System.out.println( "File Mismatch position or -1 is returned if there is no mismatch"); System.out.println( "Mismatch position in file1 and file2 is : " + mismatch1); path1.toFile().deleteOnExit(); path2.toFile().deleteOnExit(); System.out.println(); Path path3 = Files.createTempFile("file3", ".txt"); Path path4 = Files.createTempFile("file4", ".txt"); Files.writeString(path3, "Geeks for geeks"); Files.writeString(path4, "Geeks for the geeks"); long mismatch2 = Files.mismatch(path3, path4); System.out.println( "Mismatch position in file3 and file4 is : " + mismatch2); path3.toFile().deleteOnExit(); path4.toFile().deleteOnExit(); }} Output Mismatch position in file1 and file2 is : -1 Mismatch position in file3 and file4 is : 10 9) Compact Number Formatting: It is the formatting applied to general-purpose numbers e.g. decimal, currency, percentage to make them compact due to space constraint. In the below example, 1000 will be formatted as ‘1K’ in a short style and ‘1 thousand’ in a long style. Java import java.text.NumberFormat;import java.util.Locale; public class CompactFormatExample { public static void main(String[] args) { NumberFormat fmtLong = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); System.out.println(fmtLong.format(100)); System.out.println(fmtLong.format(1000)); System.out.println(fmtLong.format(10000)); NumberFormat fmtShort = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); System.out.println(fmtShort.format(100)); System.out.println(fmtShort.format(1000)); System.out.println(fmtShort.format(10000)); }} Output 100 1 thousand 10 thousand 100 1K 10K 10) Teeing Collectors in Stream API: Collectors.teeing() is the new helper function that helps in performing two steps function into a single step. This results in less verbose code. Method Signature public static Collector teeing​ (Collector downstream1, Collector downstream2, BiFunction merger); Here, we are performing two different stream operations on two different collectors and the result is merged using the supplied BiFunction. Example: Java import java.io.*;import java.util.*; class TeeingCollectorsExample { public static void main(String[] args) { double mean = Stream.of(2, 3, 4, 5, 6) .collect(Collectors.teeing( summingDouble(i -> i), counting(), (sum, n) -> sum / n)); System.out.println(mean); }} Output 4.0 11) Java String New Methods: Java 12 introduced the following new methods in the String class: i) indent(int n): It adjusts the indentation of each line of the given string based on the argument passed. Based on the value of n passed, we can have the following cases : If n > 0, spaces are inserted at beginning of each line If n < 0, spaces are removed at the beginning of each line If n < 0 and n < available white spaces, all leading spaces are removed If n = 0, line remains unchanged String str = "**********\n Welcome\n Good Morning\n**********"; System.out.println(str.indent(0)); System.out.println(str.indent(3)); Output ********** Welcome Good Morning ********** ********** Welcome Good Morning ********** ********** Welcome Good Morning ********** ii) transform(Function<? super String,​? extends R> f): It is used to call a function expecting a string argument and producing result R. String s = "Java,Python,Angular"; List result = s.transform(s1 -> {return Arrays.asList(s1.split(","));}); System.out.println(result); Output [Java, Python, Angular] iii) Optional<String> describeConstable(): This method will return an Optional object containing a descriptor for the String instance. String message = "Welcome!"; Optional<String> opOfMessage = message.describeConstable(); System.out.println(opOfMessage); Output Optional[Welcome!] iv) String resolveConstantDesc​(MethodHandles.Lookup lookup): This method will return a String object which is the descriptor for the invoking String instance. String message = "Welcome!"; String constantDesc = message.resolveConstantDesc(MethodHandles.lookup()); System.out.println(constantDesc); Output Welcome! Though Java 12 is yet to gain popularity as compared to Java 8, still the addition of new features more frequently is making Java comparable with better features of other languages thus maintaining its popularity in the market. clintra Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n24 Jan, 2022" }, { "code": null, "e": 25713, "s": 25347, "text": "Oracle released Java SE(Standard Edition) 12 on March 19, 2019, after which they plan to have a new release every six months. JDK 12 came with a lot of improvements over JDK 11. This latest version offers a list of new features such as Switch Expressions, Default CDS Archives, Shenandoah, Microbenchmark Suite, among others. These new features are discussed below." }, { "code": null, "e": 25747, "s": 25713, "text": "1. Changes in Switch expressions:" }, { "code": null, "e": 25899, "s": 25747, "text": "Switch expressions will now be used as a statement as well as expressions. This makes code simplification and pattern matching possible for the switch." }, { "code": null, "e": 26001, "s": 25899, "text": "In earlier versions, missing break statements resulted in default fall through which was error-prone." }, { "code": null, "e": 26058, "s": 26001, "text": "The default case is mandatory in the switch expressions." }, { "code": null, "e": 26111, "s": 26058, "text": "Now, the new Arrow syntax for switch introduced as " }, { "code": null, "e": 26125, "s": 26111, "text": "case X -> {} " }, { "code": null, "e": 26225, "s": 26125, "text": "Denotes that only if the label matches, statements on the right side of the arrow will be executed." }, { "code": null, "e": 26299, "s": 26225, "text": "The Switch expressions of Java 11 and Java 12 can be compared as follows:" }, { "code": null, "e": 26307, "s": 26299, "text": "Java 11" }, { "code": null, "e": 26312, "s": 26307, "text": "Java" }, { "code": "// Java program to demonstrate the// classic switch statement import java.io.*; class Java11switchStatement { static int getMealNumber(String meal) { // stores mealNumber int mealNumber; // classic switch statement switch (meal) { case \"SOUP\": mealNumber = 1; break; case \"BURGER\": case \"CHIPS\": case \"SANDWICH\": mealNumber = 2; break; case \"SPAGHETTI\": case \"MACARONI\": mealNumber = 3; break; default: throw new IllegalStateException( \"Cannot prepare \" + meal); } return mealNumber; } public static void main(String[] args) { // define meal String meal = \"BURGER\"; // print mealNumber System.out.println(\"The mealNumber is : \" + getMealNumber(meal)); }}", "e": 27234, "s": 26312, "text": null }, { "code": null, "e": 27256, "s": 27234, "text": "The mealNumber is : 2" }, { "code": null, "e": 27264, "s": 27256, "text": "Java 12" }, { "code": null, "e": 27269, "s": 27264, "text": "Java" }, { "code": "// Java program to demonstrate the// new switch expression import java.io.*; class Java11switchStatement { // returns mealNumber static int getMealNumber(String meal) { // stores mealNumber using // new switch expression int mealNumber = switch (meal) { case \"SOUP\" -> 1; case \"BURGER\", \"CHIPS\", \"SANDWICH\" -> 2; case \"SPAGHETTI\", \"MACARONI\" -> 3; default -> throw new IllegalException(\"\"); } return mealNumber; } public static void main(String[] args) { // define meal String meal = \"BURGER\"; // print mealNumber System.out.println(\"The mealNumber is : \" + getMealNumber(meal)); }}", "e": 28035, "s": 27269, "text": null }, { "code": null, "e": 28042, "s": 28035, "text": "Output" }, { "code": null, "e": 28064, "s": 28042, "text": "The mealNumber is : 2" }, { "code": null, "e": 28117, "s": 28064, "text": "2. Shenandoah (A new and improved Garbage Collector)" }, { "code": null, "e": 28446, "s": 28117, "text": "This is an experimental feature and introduces a new garbage collection (GC) algorithm, Shenandoah. It offers low pause time by concurrent execution of evacuation work with running Java threads. With this, pause times are independent of the heap size. For example, a 5MB heap will have the same pause time as that of a 10GB one." }, { "code": null, "e": 28978, "s": 28446, "text": "3. JVM constants API: This API helps those programs that manipulate classes and methods. These programs need to model byte code instructions and handle loadable constants. Constants of the type String or Integer work fine. However, it becomes tricky with Constant type as Class. Loading classes can fail if Class is inaccessible or doesn’t exist. With the new API in place, interfaces such as ClassDesc, MethodTypeDesc, MethodHandleDesc, and DynamicConstantDesc, handle constant values symbolically thereby eliminating complexity. " }, { "code": null, "e": 29458, "s": 28978, "text": "4. Abortable mixed collections for G1: The default garbage collector, Garbage First (G1), uses an analysis engine to determine the collection set and once the collection starts, all live objects should be collected without stopping. This results in exceeding the target pause time. To address this issue, G1 collection sets are made abortable by breaking the set into optional and mandatory parts. By prioritizing the mandatory set, the pause time target can be achieved often. " }, { "code": null, "e": 29625, "s": 29458, "text": "5. Default CDS archives: A class data sharing (CDS) archive is created to make the JDK build process more efficient thereby improving the out-of-the-box startup time." }, { "code": null, "e": 29763, "s": 29625, "text": "6. Microbenchmark suite: Developers can run existing or new benchmarks easily with the microbenchmark suite added to the JDK source code." }, { "code": null, "e": 30002, "s": 29763, "text": "7. Promptly return unused committed memory from G1: With this improved feature, when G1 is idle, the garbage collector automatically returns unused heap memory to the operating system. This is done by concurrent checks of Java heap by G1." }, { "code": null, "e": 30068, "s": 30002, "text": "8) Files.mismatch() method: This new method compares two files. " }, { "code": null, "e": 30085, "s": 30068, "text": "Method Signature" }, { "code": null, "e": 30156, "s": 30085, "text": "public static long mismatch(Path path1, Path path2) throws IOException" }, { "code": null, "e": 30221, "s": 30156, "text": "Returns: -1L if no mismatch else Position of the first mismatch." }, { "code": null, "e": 30289, "s": 30221, "text": "It returns the position of the mismatch in either of the two cases." }, { "code": null, "e": 30386, "s": 30289, "text": "Case 1: if the size of the files does not match. Here, the size of the smaller file is returned." }, { "code": null, "e": 30469, "s": 30386, "text": "Case 2: if the bytes does not match. Here, the first mismatching byte is returned." }, { "code": null, "e": 30478, "s": 30469, "text": "Example:" }, { "code": null, "e": 30483, "s": 30478, "text": "Java" }, { "code": "import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; public class FilesCompareExample { public static void main(String[] args) throws IOException { Path path1 = Files.createTempFile(\"file1\", \".txt\"); Path path2 = Files.createTempFile(\"file2\", \".txt\"); Files.writeString(path1, \"Geeks for geeks\"); Files.writeString(path2, \"Geeks for geeks\"); long mismatch1 = Files.mismatch(path1, path2); System.out.println( \"File Mismatch position or -1 is returned if there is no mismatch\"); System.out.println( \"Mismatch position in file1 and file2 is : \" + mismatch1); path1.toFile().deleteOnExit(); path2.toFile().deleteOnExit(); System.out.println(); Path path3 = Files.createTempFile(\"file3\", \".txt\"); Path path4 = Files.createTempFile(\"file4\", \".txt\"); Files.writeString(path3, \"Geeks for geeks\"); Files.writeString(path4, \"Geeks for the geeks\"); long mismatch2 = Files.mismatch(path3, path4); System.out.println( \"Mismatch position in file3 and file4 is : \" + mismatch2); path3.toFile().deleteOnExit(); path4.toFile().deleteOnExit(); }}", "e": 31748, "s": 30483, "text": null }, { "code": null, "e": 31756, "s": 31748, "text": " Output" }, { "code": null, "e": 31848, "s": 31756, "text": "Mismatch position in file1 and file2 is : -1 \nMismatch position in file3 and file4 is : 10 " }, { "code": null, "e": 32119, "s": 31848, "text": "9) Compact Number Formatting: It is the formatting applied to general-purpose numbers e.g. decimal, currency, percentage to make them compact due to space constraint. In the below example, 1000 will be formatted as ‘1K’ in a short style and ‘1 thousand’ in a long style." }, { "code": null, "e": 32124, "s": 32119, "text": "Java" }, { "code": "import java.text.NumberFormat;import java.util.Locale; public class CompactFormatExample { public static void main(String[] args) { NumberFormat fmtLong = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); System.out.println(fmtLong.format(100)); System.out.println(fmtLong.format(1000)); System.out.println(fmtLong.format(10000)); NumberFormat fmtShort = NumberFormat.getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); System.out.println(fmtShort.format(100)); System.out.println(fmtShort.format(1000)); System.out.println(fmtShort.format(10000)); }}", "e": 32834, "s": 32124, "text": null }, { "code": null, "e": 32841, "s": 32834, "text": "Output" }, { "code": null, "e": 32879, "s": 32841, "text": "100\n1 thousand\n10 thousand\n100\n1K\n10K" }, { "code": null, "e": 33062, "s": 32879, "text": "10) Teeing Collectors in Stream API: Collectors.teeing() is the new helper function that helps in performing two steps function into a single step. This results in less verbose code." }, { "code": null, "e": 33079, "s": 33062, "text": "Method Signature" }, { "code": null, "e": 33178, "s": 33079, "text": "public static Collector teeing​ (Collector downstream1, Collector downstream2, BiFunction merger);" }, { "code": null, "e": 33318, "s": 33178, "text": "Here, we are performing two different stream operations on two different collectors and the result is merged using the supplied BiFunction." }, { "code": null, "e": 33327, "s": 33318, "text": "Example:" }, { "code": null, "e": 33332, "s": 33327, "text": "Java" }, { "code": "import java.io.*;import java.util.*; class TeeingCollectorsExample { public static void main(String[] args) { double mean = Stream.of(2, 3, 4, 5, 6) .collect(Collectors.teeing( summingDouble(i -> i), counting(), (sum, n) -> sum / n)); System.out.println(mean); }}", "e": 33690, "s": 33332, "text": null }, { "code": null, "e": 33697, "s": 33690, "text": "Output" }, { "code": null, "e": 33701, "s": 33697, "text": "4.0" }, { "code": null, "e": 33796, "s": 33701, "text": "11) Java String New Methods: Java 12 introduced the following new methods in the String class:" }, { "code": null, "e": 33904, "s": 33796, "text": "i) indent(int n): It adjusts the indentation of each line of the given string based on the argument passed." }, { "code": null, "e": 33970, "s": 33904, "text": "Based on the value of n passed, we can have the following cases :" }, { "code": null, "e": 34026, "s": 33970, "text": "If n > 0, spaces are inserted at beginning of each line" }, { "code": null, "e": 34085, "s": 34026, "text": "If n < 0, spaces are removed at the beginning of each line" }, { "code": null, "e": 34157, "s": 34085, "text": "If n < 0 and n < available white spaces, all leading spaces are removed" }, { "code": null, "e": 34190, "s": 34157, "text": "If n = 0, line remains unchanged" }, { "code": null, "e": 34326, "s": 34190, "text": "String str = \"**********\\n Welcome\\n Good Morning\\n**********\";\nSystem.out.println(str.indent(0));\nSystem.out.println(str.indent(3));" }, { "code": null, "e": 34333, "s": 34326, "text": "Output" }, { "code": null, "e": 34483, "s": 34333, "text": "**********\n Welcome\n Good Morning\n**********\n **********\n Welcome\n Good Morning\n **********\n**********\nWelcome\nGood Morning\n********** " }, { "code": null, "e": 34622, "s": 34483, "text": "ii) transform(Function<? super String,​? extends R> f): It is used to call a function expecting a string argument and producing result R. " }, { "code": null, "e": 34757, "s": 34622, "text": "String s = \"Java,Python,Angular\";\nList result = s.transform(s1 -> {return Arrays.asList(s1.split(\",\"));});\nSystem.out.println(result);" }, { "code": null, "e": 34764, "s": 34757, "text": "Output" }, { "code": null, "e": 34788, "s": 34764, "text": "[Java, Python, Angular]" }, { "code": null, "e": 34923, "s": 34788, "text": "iii) Optional<String> describeConstable(): This method will return an Optional object containing a descriptor for the String instance." }, { "code": null, "e": 35045, "s": 34923, "text": "String message = \"Welcome!\";\nOptional<String> opOfMessage = message.describeConstable();\nSystem.out.println(opOfMessage);" }, { "code": null, "e": 35052, "s": 35045, "text": "Output" }, { "code": null, "e": 35071, "s": 35052, "text": "Optional[Welcome!]" }, { "code": null, "e": 35231, "s": 35071, "text": "iv) String resolveConstantDesc​(MethodHandles.Lookup lookup): This method will return a String object which is the descriptor for the invoking String instance." }, { "code": null, "e": 35369, "s": 35231, "text": "String message = \"Welcome!\";\nString constantDesc = message.resolveConstantDesc(MethodHandles.lookup());\nSystem.out.println(constantDesc);" }, { "code": null, "e": 35376, "s": 35369, "text": "Output" }, { "code": null, "e": 35385, "s": 35376, "text": "Welcome!" }, { "code": null, "e": 35614, "s": 35385, "text": "Though Java 12 is yet to gain popularity as compared to Java 8, still the addition of new features more frequently is making Java comparable with better features of other languages thus maintaining its popularity in the market. " }, { "code": null, "e": 35622, "s": 35614, "text": "clintra" }, { "code": null, "e": 35627, "s": 35622, "text": "Java" }, { "code": null, "e": 35632, "s": 35627, "text": "Java" }, { "code": null, "e": 35730, "s": 35632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35745, "s": 35730, "text": "Stream In Java" }, { "code": null, "e": 35766, "s": 35745, "text": "Constructors in Java" }, { "code": null, "e": 35785, "s": 35766, "text": "Exceptions in Java" }, { "code": null, "e": 35815, "s": 35785, "text": "Functional Interfaces in Java" }, { "code": null, "e": 35861, "s": 35815, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 35878, "s": 35861, "text": "Generics in Java" }, { "code": null, "e": 35899, "s": 35878, "text": "Introduction to Java" }, { "code": null, "e": 35942, "s": 35899, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 35964, "s": 35942, "text": "PriorityQueue in Java" } ]
Mood's Median Test - GeeksforGeeks
25 Aug, 2021 Mood’s Median Test: It is a non-parametric alternative to one way ANOVA. It is a special case of Pearson’s Chi-Squared Test. It tests whether the medians of two or more groups differ and also calculates a range of values that is likely to include the difference between population medians. In this test, different data groups have similarly shaped distributions. Data in each of the samples are assigned to two groups- One consisting of data whose values are higher than the combined median of the samples. The other consisting of data whose value are at the median or below. Assumptions of Mood’s Median Test Data should include only one categorical factor. Response variable should be continuous. Sample data need not be normally distributed. Sample sizes can be unequal too. Null and Alternate Hypothesis of Mood’s Median Test Null Hypothesis: The population Medians are all equal. Alternate Hypothesis: The Medians are not all equal OR At least 2 of them differ from each other. H0 : M1 = M2 = M3 = ..... Mk ; M= Median H1 : At least two of them show significant difference. Test Statistic for Mood’s Median Test Test statistic for this type of test is the Chi=Squared statistic where we look for the Observed and Expected frequencies. OiAM = Observed Frequencies of ith sample above Median OiBM = Observed Frequencies of ith sample below Median EiAM = Expected Frequencies of ith sample above Median EiBM = Expected Frequencies of ith sample below Median Rejection Criteria We reject the Null Hypothesis if Test Statistic X02 is greater than the critical value at a given level of significance (alpha) and k-1 degrees of freedom. Steps to Perform Mood’s Median Test Let us take an example to understand how to perform this test. Example: 35 Students from a City in India were asked to provide ratings for a restaurant chain in different areas of the city. There were 11 Students for Area A, 12 Students for Area B and 12 Students for Area C. The ratings are given on the basis of 4 conditions of cleanliness, taste etc. Each condition can get a maximum of 5 points hence a Restaurant can get a Maximum rating of 20 points. Test whether the Medians are the same for the 3 Restaurant chains. ( alpha = 5%) Step 1: Define NULL and Alternate Hypothesis H0 : MA = MB = MC. M= Median. H1 : At least two of them differ from each other. Step 2: State Alpha (Level of Significance) Alpha = 0.05 Step 3: Calculate Degrees of Freedom DF = K-1 ; K = number of sample groups. Here , DF = 3-1 =2. Step 4: Find out the Critical Chi-Square Value. Use this table to find out the critical chi-square value for alpha = 0.05 and DF = 2. X2 = 5.991 Step 5: State Decision Rule If X02 is greater than 5.991 , reject the Null Hypothesis. Step 6: Calculate the Overall Median There are total 35 data entries so the median will be the 18th element after arranging in ascending order. Arranging in ascending order - 10 10 11 12 12 12 13 13 13 13 13 14 14 15 15 15 15 15 16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 20 The overall median is 15 Step 7: Construct a table using the Observed values with two columns – one showing the number of ratings above the overall median for each Area and the other showing the number of ratings below the overall median for each Area. Here 7 ratings in Area A are above the overall Median and 4 are below or equal to the overall Median. Step 8: Construct a similar table of Expected values. The expected values are obtained by – (Column total * Row Total) / N ; N= total number of data entries Here, For Area A the Expected value for > overall median will be (11*17)/35 = 5.34 Step 9: Calculate the Test Statistic X02 = 2.067 Step 10: State Results Since X02 is less than 5.991 , We accept the Null Hypothesis. Step 11: State Conclusion We can conclude that the Medians are the same for the 3 Restaurant Chains. This is all about the Mood’s Median Test. For any queries do leave a comment down below. saurabh1990aror abhishek0719kadiyan Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Intuition of Adam Optimizer Introduction to Recurrent Neural Network Singular Value Decomposition (SVD) CNN | Introduction to Pooling Layer k-nearest neighbor algorithm in Python Python | Decision Tree Regression using sklearn DBSCAN Clustering in ML | Density based clustering Bagging vs Boosting in Machine Learning Python | Stemming words with NLTK
[ { "code": null, "e": 24442, "s": 24414, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24805, "s": 24442, "text": "Mood’s Median Test: It is a non-parametric alternative to one way ANOVA. It is a special case of Pearson’s Chi-Squared Test. It tests whether the medians of two or more groups differ and also calculates a range of values that is likely to include the difference between population medians. In this test, different data groups have similarly shaped distributions." }, { "code": null, "e": 24861, "s": 24805, "text": "Data in each of the samples are assigned to two groups-" }, { "code": null, "e": 24949, "s": 24861, "text": "One consisting of data whose values are higher than the combined median of the samples." }, { "code": null, "e": 25018, "s": 24949, "text": "The other consisting of data whose value are at the median or below." }, { "code": null, "e": 25052, "s": 25018, "text": "Assumptions of Mood’s Median Test" }, { "code": null, "e": 25101, "s": 25052, "text": "Data should include only one categorical factor." }, { "code": null, "e": 25141, "s": 25101, "text": "Response variable should be continuous." }, { "code": null, "e": 25187, "s": 25141, "text": "Sample data need not be normally distributed." }, { "code": null, "e": 25220, "s": 25187, "text": "Sample sizes can be unequal too." }, { "code": null, "e": 25272, "s": 25220, "text": "Null and Alternate Hypothesis of Mood’s Median Test" }, { "code": null, "e": 25327, "s": 25272, "text": "Null Hypothesis: The population Medians are all equal." }, { "code": null, "e": 25426, "s": 25327, "text": "Alternate Hypothesis: The Medians are not all equal OR At least 2 of them differ from each other." }, { "code": null, "e": 25523, "s": 25426, "text": "H0 : M1 = M2 = M3 = ..... Mk ; M= Median\nH1 : At least two of them show significant difference." }, { "code": null, "e": 25561, "s": 25523, "text": "Test Statistic for Mood’s Median Test" }, { "code": null, "e": 25684, "s": 25561, "text": "Test statistic for this type of test is the Chi=Squared statistic where we look for the Observed and Expected frequencies." }, { "code": null, "e": 25904, "s": 25684, "text": "OiAM = Observed Frequencies of ith sample above Median\nOiBM = Observed Frequencies of ith sample below Median\nEiAM = Expected Frequencies of ith sample above Median\nEiBM = Expected Frequencies of ith sample below Median" }, { "code": null, "e": 25923, "s": 25904, "text": "Rejection Criteria" }, { "code": null, "e": 26080, "s": 25923, "text": "We reject the Null Hypothesis if Test Statistic X02 is greater than the critical value at a given level of significance (alpha) and k-1 degrees of freedom." }, { "code": null, "e": 26116, "s": 26080, "text": "Steps to Perform Mood’s Median Test" }, { "code": null, "e": 26179, "s": 26116, "text": "Let us take an example to understand how to perform this test." }, { "code": null, "e": 26654, "s": 26179, "text": "Example: 35 Students from a City in India were asked to provide ratings for a restaurant chain in different areas of the city. There were 11 Students for Area A, 12 Students for Area B and 12 Students for Area C. The ratings are given on the basis of 4 conditions of cleanliness, taste etc. Each condition can get a maximum of 5 points hence a Restaurant can get a Maximum rating of 20 points. Test whether the Medians are the same for the 3 Restaurant chains. ( alpha = 5%)" }, { "code": null, "e": 26699, "s": 26654, "text": "Step 1: Define NULL and Alternate Hypothesis" }, { "code": null, "e": 26779, "s": 26699, "text": "H0 : MA = MB = MC. M= Median.\nH1 : At least two of them differ from each other." }, { "code": null, "e": 26823, "s": 26779, "text": "Step 2: State Alpha (Level of Significance)" }, { "code": null, "e": 26836, "s": 26823, "text": "Alpha = 0.05" }, { "code": null, "e": 26873, "s": 26836, "text": "Step 3: Calculate Degrees of Freedom" }, { "code": null, "e": 26939, "s": 26873, "text": "DF = K-1 ; K = number of sample groups.\nHere , DF = 3-1 =2." }, { "code": null, "e": 26988, "s": 26939, "text": "Step 4: Find out the Critical Chi-Square Value." }, { "code": null, "e": 27074, "s": 26988, "text": "Use this table to find out the critical chi-square value for alpha = 0.05 and DF = 2." }, { "code": null, "e": 27085, "s": 27074, "text": "X2 = 5.991" }, { "code": null, "e": 27113, "s": 27085, "text": "Step 5: State Decision Rule" }, { "code": null, "e": 27172, "s": 27113, "text": "If X02 is greater than 5.991 , reject the Null Hypothesis." }, { "code": null, "e": 27209, "s": 27172, "text": "Step 6: Calculate the Overall Median" }, { "code": null, "e": 27316, "s": 27209, "text": "There are total 35 data entries so the median will be the 18th element after arranging in ascending order." }, { "code": null, "e": 27455, "s": 27316, "text": "Arranging in ascending order - \n10 10 11 12 12 12 13 13 13 13 13 14 14 15 15 15 15 15 \n16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 20 " }, { "code": null, "e": 27480, "s": 27455, "text": "The overall median is 15" }, { "code": null, "e": 27708, "s": 27480, "text": "Step 7: Construct a table using the Observed values with two columns – one showing the number of ratings above the overall median for each Area and the other showing the number of ratings below the overall median for each Area." }, { "code": null, "e": 27810, "s": 27708, "text": "Here 7 ratings in Area A are above the overall Median and 4 are below or equal to the overall Median." }, { "code": null, "e": 27865, "s": 27810, "text": "Step 8: Construct a similar table of Expected values. " }, { "code": null, "e": 27904, "s": 27865, "text": "The expected values are obtained by – " }, { "code": null, "e": 28059, "s": 27904, "text": "(Column total * Row Total) / N ; N= total number of data entries\n\nHere, For Area A the Expected value for > overall median will be (11*17)/35 = 5.34" }, { "code": null, "e": 28096, "s": 28059, "text": "Step 9: Calculate the Test Statistic" }, { "code": null, "e": 28108, "s": 28096, "text": "X02 = 2.067" }, { "code": null, "e": 28131, "s": 28108, "text": "Step 10: State Results" }, { "code": null, "e": 28193, "s": 28131, "text": "Since X02 is less than 5.991 , We accept the Null Hypothesis." }, { "code": null, "e": 28219, "s": 28193, "text": "Step 11: State Conclusion" }, { "code": null, "e": 28294, "s": 28219, "text": "We can conclude that the Medians are the same for the 3 Restaurant Chains." }, { "code": null, "e": 28383, "s": 28294, "text": "This is all about the Mood’s Median Test. For any queries do leave a comment down below." }, { "code": null, "e": 28399, "s": 28383, "text": "saurabh1990aror" }, { "code": null, "e": 28419, "s": 28399, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28436, "s": 28419, "text": "Machine Learning" }, { "code": null, "e": 28453, "s": 28436, "text": "Machine Learning" }, { "code": null, "e": 28551, "s": 28453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28584, "s": 28551, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28612, "s": 28584, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 28653, "s": 28612, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28688, "s": 28653, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 28724, "s": 28688, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 28763, "s": 28724, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 28811, "s": 28763, "text": "Python | Decision Tree Regression using sklearn" }, { "code": null, "e": 28862, "s": 28811, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 28902, "s": 28862, "text": "Bagging vs Boosting in Machine Learning" } ]
Python | Get positive elements from given list of lists - GeeksforGeeks
25 Apr, 2019 Given a list of list, the task is to get only positive element from given list. Below are some ways to solve the above problem. Method #1: Using Iteration # Python code to get positive # element from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]]Output = [] # Using iterationfor elem in Input: temp = [] for x in elem: if x>0: temp.append(x) Output.append(temp) # printing outputprint("Initial List is :", Input)print("Modified list is :", Output) Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]] Modified list is : [[10, 222], [42, 99]] Method #2: Using map and list Comprehension # Python code to get positive element # from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]] # Using list comprehension and maptemp = map(lambda elem: filter(lambda a: a>0, elem), Input)Output = [[a for a in elem if a>0] for elem in temp] # printing outputprint("Initial List is :", Input)print("Modified list is :", Output) Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]] Modified list is : [[10, 222], [42, 99]] Method #3: Using List Comprehension # Python code to get positive element # from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]] # Using list comprehensionOutput = [ [b for b in a if b>0] for a in Input] # printing outputprint("Initial List is :", Input)print("Modified list is :", Output) Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]] Modified list is : [[10, 222], [42, 99]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26411, "s": 26383, "text": "\n25 Apr, 2019" }, { "code": null, "e": 26539, "s": 26411, "text": "Given a list of list, the task is to get only positive element from given list. Below are some ways to solve the above problem." }, { "code": null, "e": 26566, "s": 26539, "text": "Method #1: Using Iteration" }, { "code": "# Python code to get positive # element from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]]Output = [] # Using iterationfor elem in Input: temp = [] for x in elem: if x>0: temp.append(x) Output.append(temp) # printing outputprint(\"Initial List is :\", Input)print(\"Modified list is :\", Output)", "e": 26930, "s": 26566, "text": null }, { "code": null, "e": 27034, "s": 26930, "text": "Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]\nModified list is : [[10, 222], [42, 99]]\n" }, { "code": null, "e": 27079, "s": 27034, "text": " Method #2: Using map and list Comprehension" }, { "code": "# Python code to get positive element # from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]] # Using list comprehension and maptemp = map(lambda elem: filter(lambda a: a>0, elem), Input)Output = [[a for a in elem if a>0] for elem in temp] # printing outputprint(\"Initial List is :\", Input)print(\"Modified list is :\", Output)", "e": 27445, "s": 27079, "text": null }, { "code": null, "e": 27549, "s": 27445, "text": "Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]\nModified list is : [[10, 222], [42, 99]]\n" }, { "code": null, "e": 27586, "s": 27549, "text": " Method #3: Using List Comprehension" }, { "code": "# Python code to get positive element # from list of list # List InitialisationInput = [[10, -11, 222], [42, -222, -412, 99, -87]] # Using list comprehensionOutput = [ [b for b in a if b>0] for a in Input] # printing outputprint(\"Initial List is :\", Input)print(\"Modified list is :\", Output)", "e": 27881, "s": 27586, "text": null }, { "code": null, "e": 27985, "s": 27881, "text": "Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]\nModified list is : [[10, 222], [42, 99]]\n" }, { "code": null, "e": 28006, "s": 27985, "text": "Python list-programs" }, { "code": null, "e": 28013, "s": 28006, "text": "Python" }, { "code": null, "e": 28029, "s": 28013, "text": "Python Programs" }, { "code": null, "e": 28127, "s": 28029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28145, "s": 28127, "text": "Python Dictionary" }, { "code": null, "e": 28177, "s": 28145, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28199, "s": 28177, "text": "Enumerate() in Python" }, { "code": null, "e": 28241, "s": 28199, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28267, "s": 28241, "text": "Python String | replace()" }, { "code": null, "e": 28289, "s": 28267, "text": "Defaultdict in Python" }, { "code": null, "e": 28328, "s": 28289, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28374, "s": 28328, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28412, "s": 28374, "text": "Python | Convert a list to dictionary" } ]
Analysis of test data using K-Means Clustering in Python - GeeksforGeeks
09 Feb, 2018 This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-libLet’s first visualize test data with Multiple Features using matplot-lib tool. # importing required toolsimport numpy as npfrom matplotlib import pyplot as plt # creating two test dataX = np.random.randint(10,35,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y))Z = Z.reshape((50,2)) # convert to np.float32Z = np.float32(Z) plt.xlabel('Test Data')plt.ylabel('Z samples') plt.hist(Z,256,[0,256]) plt.show() Here ‘Z’ is an array of size 100, and values ranging from 0 to 255. Now, reshaped ‘z’ to a column vector. It will be more useful when more than one features are present. Then change the data to np.float32 type. Output: Now, apply the k-Means clustering algorithm to the same example as in the above test data and see its behavior.Steps Involved:1) First we need to set a test data.2) Define criteria and apply kmeans().3) Now separate the data.4) Finally Plot the data. import numpy as npimport cv2from matplotlib import pyplot as plt X = np.random.randint(10,45,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y)) # convert to np.float32Z = np.float32(Z) # define criteria and apply kmeans()criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)ret,label,center = cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS) # Now separate the dataA = Z[label.ravel()==0]B = Z[label.ravel()==1] # Plot the dataplt.scatter(A[:,0],A[:,1])plt.scatter(B[:,0],B[:,1],c = 'r')plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's')plt.xlabel('Test Data'),plt.ylabel('Z samples')plt.show() Output: This example is meant to illustrate where k-means will produce intuitively possible clusters.Applications:1) Identifying Cancerous Data.2) Prediction of Students’ Academic Performance.3) Drug Activity Prediction. Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Decision Tree Introduction with example Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation Decision Tree Agents in Artificial Intelligence Activation functions in Neural Networks Decision Tree Introduction with example Support Vector Machine Algorithm
[ { "code": null, "e": 25629, "s": 25601, "text": "\n09 Feb, 2018" }, { "code": null, "e": 25740, "s": 25629, "text": "This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library." }, { "code": null, "e": 25861, "s": 25740, "text": "Pre-requisites: Numpy, OpenCV, matplot-libLet’s first visualize test data with Multiple Features using matplot-lib tool." }, { "code": "# importing required toolsimport numpy as npfrom matplotlib import pyplot as plt # creating two test dataX = np.random.randint(10,35,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y))Z = Z.reshape((50,2)) # convert to np.float32Z = np.float32(Z) plt.xlabel('Test Data')plt.ylabel('Z samples') plt.hist(Z,256,[0,256]) plt.show()", "e": 26206, "s": 25861, "text": null }, { "code": null, "e": 26417, "s": 26206, "text": "Here ‘Z’ is an array of size 100, and values ranging from 0 to 255. Now, reshaped ‘z’ to a column vector. It will be more useful when more than one features are present. Then change the data to np.float32 type." }, { "code": null, "e": 26425, "s": 26417, "text": "Output:" }, { "code": null, "e": 26676, "s": 26425, "text": "Now, apply the k-Means clustering algorithm to the same example as in the above test data and see its behavior.Steps Involved:1) First we need to set a test data.2) Define criteria and apply kmeans().3) Now separate the data.4) Finally Plot the data." }, { "code": "import numpy as npimport cv2from matplotlib import pyplot as plt X = np.random.randint(10,45,(25,2))Y = np.random.randint(55,70,(25,2))Z = np.vstack((X,Y)) # convert to np.float32Z = np.float32(Z) # define criteria and apply kmeans()criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)ret,label,center = cv2.kmeans(Z,2,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS) # Now separate the dataA = Z[label.ravel()==0]B = Z[label.ravel()==1] # Plot the dataplt.scatter(A[:,0],A[:,1])plt.scatter(B[:,0],B[:,1],c = 'r')plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's')plt.xlabel('Test Data'),plt.ylabel('Z samples')plt.show()", "e": 27332, "s": 26676, "text": null }, { "code": null, "e": 27340, "s": 27332, "text": "Output:" }, { "code": null, "e": 27553, "s": 27340, "text": "This example is meant to illustrate where k-means will produce intuitively possible clusters.Applications:1) Identifying Cancerous Data.2) Prediction of Students’ Academic Performance.3) Drug Activity Prediction." }, { "code": null, "e": 27579, "s": 27553, "text": "Advanced Computer Subject" }, { "code": null, "e": 27596, "s": 27579, "text": "Machine Learning" }, { "code": null, "e": 27603, "s": 27596, "text": "Python" }, { "code": null, "e": 27620, "s": 27603, "text": "Machine Learning" }, { "code": null, "e": 27718, "s": 27620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27732, "s": 27718, "text": "Decision Tree" }, { "code": null, "e": 27772, "s": 27732, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27816, "s": 27772, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27839, "s": 27816, "text": "System Design Tutorial" }, { "code": null, "e": 27877, "s": 27839, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27891, "s": 27877, "text": "Decision Tree" }, { "code": null, "e": 27925, "s": 27891, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 27965, "s": 27925, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 28005, "s": 27965, "text": "Decision Tree Introduction with example" } ]
Sudoku Solver in C++
Suppose we have a Sudoku grid and we have to solve this famous number maze problem, Sudoku. We know that Sudoku is a 9 x 9 number grid, and the whole grid are also divided into 3 x 3 boxes There are some rules to solve the Sudoku. We have to use digits 1 to 9 for solving this problem. We have to use digits 1 to 9 for solving this problem. One digit cannot be repeated in one row, one column or in one 3 x 3 box. One digit cannot be repeated in one row, one column or in one 3 x 3 box. Using backtracking algorithm, we will try to solve Sudoku problem. When some cell is filled with a digit, it checks whether it is valid or not. When it is not valid, it checks for other numbers. If all numbers are checked from 1-9, and no valid digit found to place, it backtracks to previous option. So if the input is like − The output will be − To solve this, we will follow these steps − Define a method called isPresentInCol(), this will take call and num Define a method called isPresentInCol(), this will take call and num for each row r in the grid, doif grid[r, col] = num, then return true for each row r in the grid, do if grid[r, col] = num, then return true if grid[r, col] = num, then return true return false otherwise return false otherwise Define a method called isPresentInRow(), this will take row and num Define a method called isPresentInRow(), this will take row and num for each column c in the grid, doif grid[row, c] = num, then return true for each column c in the grid, do if grid[row, c] = num, then return true if grid[row, c] = num, then return true return false otherwise return false otherwise Define a method called isPresentInBox() this will take boxStartRow, boxStartCol, num Define a method called isPresentInBox() this will take boxStartRow, boxStartCol, num for each row r in boxStartRow to next 3 rows, dofor each col r in boxStartCol to next 3 columns, doif grid[r, c] = num, then return true for each row r in boxStartRow to next 3 rows, do for each col r in boxStartCol to next 3 columns, doif grid[r, c] = num, then return true for each col r in boxStartCol to next 3 columns, do if grid[r, c] = num, then return true if grid[r, c] = num, then return true return false otherwise return false otherwise Define a method called findEmptyPlace(), this will take row and col Define a method called findEmptyPlace(), this will take row and col for each row r in the grid, dofor each column c in the grid, doif grid[r, c] = 0, then return true for each row r in the grid, do for each column c in the grid, doif grid[r, c] = 0, then return true for each column c in the grid, do if grid[r, c] = 0, then return true if grid[r, c] = 0, then return true return false return false Define a method called isValidPlace(), this will take row, col, num Define a method called isValidPlace(), this will take row, col, num if isPresentInRow(row, num) and isPresentInCol(col, num) and isPresntInBox(row – row mod 3, col – col mod 3, num) all are false, then return true if isPresentInRow(row, num) and isPresentInCol(col, num) and isPresntInBox(row – row mod 3, col – col mod 3, num) all are false, then return true Define a method called solveSudoku(), this will take the grid Define a method called solveSudoku(), this will take the grid if no place in the grid is empty, then return true if no place in the grid is empty, then return true for number 1 to 9, doif isValidPlace(row, col, number), thengrid[row, col] := numberif solveSudoku = true, then return truegrid[row, col] := 0 for number 1 to 9, do if isValidPlace(row, col, number), thengrid[row, col] := numberif solveSudoku = true, then return truegrid[row, col] := 0 if isValidPlace(row, col, number), then grid[row, col] := number grid[row, col] := number if solveSudoku = true, then return true if solveSudoku = true, then return true grid[row, col] := 0 grid[row, col] := 0 return false return false Let us see the following implementation to get a better understanding − Live Demo #include <iostream> #define N 9 using namespace std; int grid[N][N] = { {3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, {0, 0, 5, 2, 0, 6, 3, 0, 0} }; bool isPresentInCol(int col, int num){ //check whether num is present in col or not for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false; } bool isPresentInRow(int row, int num){ //check whether num is present in row or not for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false; } bool isPresentInBox(int boxStartRow, int boxStartCol, int num){ //check whether num is present in 3x3 box or not for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if (grid[row+boxStartRow][col+boxStartCol] == num) return true; return false; } void sudokuGrid(){ //print the sudoku grid after solve for (int row = 0; row < N; row++){ for (int col = 0; col < N; col++){ if(col == 3 || col == 6) cout << " | "; cout << grid[row][col] <<" "; } if(row == 2 || row == 5){ cout << endl; for(int i = 0; i<N; i++) cout << "---"; } cout << endl; } } bool findEmptyPlace(int &row, int &col){ //get empty location and update row and column for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == 0) //marked with 0 is empty return true; return false; } bool isValidPlace(int row, int col, int num){ //when item not found in col, row and current 3x3 box return !isPresentInRow(row, num) && !isPresentInCol(col, num) && !isPresentInBox(row - row%3 , col - col%3, num); } bool solveSudoku(){ int row, col; if (!findEmptyPlace(row, col)) return true; //when all places are filled for (int num = 1; num <= 9; num++){ //valid numbers are 1 - 9 if (isValidPlace(row, col, num)){ //check validation, if yes, put the number in the grid grid[row][col] = num; if (solveSudoku()) //recursively go for other rooms in the grid return true; grid[row][col] = 0; //turn to unassigned space when conditions are not satisfied } } return false; } int main(){ if (solveSudoku() == true) sudokuGrid(); else cout << "No solution exists"; } {3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, {0, 0, 5, 2, 0, 6, 3, 0, 0} 3 1 6 | 5 7 8 | 4 9 2 5 2 9 | 1 3 4 | 7 6 8 4 8 7 | 6 2 9 | 5 3 1 --------------------------- 2 6 3 | 4 1 5 | 9 8 7 9 7 4 | 8 6 3 | 1 2 5 8 5 1 | 7 9 2 | 6 4 3 --------------------------- 1 3 8 | 9 4 7 | 2 5 6 6 9 2 | 3 5 1 | 8 7 4 7 4 5 | 2 8 6 | 3 1 9
[ { "code": null, "e": 1293, "s": 1062, "text": "Suppose we have a Sudoku grid and we have to solve this famous number maze problem, Sudoku. We know that Sudoku is a 9 x 9 number grid, and the whole grid are also divided into 3 x 3 boxes There are some rules to solve the Sudoku." }, { "code": null, "e": 1348, "s": 1293, "text": "We have to use digits 1 to 9 for solving this problem." }, { "code": null, "e": 1403, "s": 1348, "text": "We have to use digits 1 to 9 for solving this problem." }, { "code": null, "e": 1476, "s": 1403, "text": "One digit cannot be repeated in one row, one column or in one 3 x 3 box." }, { "code": null, "e": 1549, "s": 1476, "text": "One digit cannot be repeated in one row, one column or in one 3 x 3 box." }, { "code": null, "e": 1850, "s": 1549, "text": "Using backtracking algorithm, we will try to solve Sudoku problem. When some cell is filled with a digit, it checks whether it is valid or not. When it is not valid, it checks for other numbers. If all numbers are checked from 1-9, and no valid digit found to place, it backtracks to previous option." }, { "code": null, "e": 1876, "s": 1850, "text": "So if the input is like −" }, { "code": null, "e": 1897, "s": 1876, "text": "The output will be −" }, { "code": null, "e": 1941, "s": 1897, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2010, "s": 1941, "text": "Define a method called isPresentInCol(), this will take call and num" }, { "code": null, "e": 2079, "s": 2010, "text": "Define a method called isPresentInCol(), this will take call and num" }, { "code": null, "e": 2149, "s": 2079, "text": "for each row r in the grid, doif grid[r, col] = num, then return true" }, { "code": null, "e": 2180, "s": 2149, "text": "for each row r in the grid, do" }, { "code": null, "e": 2220, "s": 2180, "text": "if grid[r, col] = num, then return true" }, { "code": null, "e": 2260, "s": 2220, "text": "if grid[r, col] = num, then return true" }, { "code": null, "e": 2283, "s": 2260, "text": "return false otherwise" }, { "code": null, "e": 2306, "s": 2283, "text": "return false otherwise" }, { "code": null, "e": 2374, "s": 2306, "text": "Define a method called isPresentInRow(), this will take row and num" }, { "code": null, "e": 2442, "s": 2374, "text": "Define a method called isPresentInRow(), this will take row and num" }, { "code": null, "e": 2515, "s": 2442, "text": "for each column c in the grid, doif grid[row, c] = num, then return true" }, { "code": null, "e": 2549, "s": 2515, "text": "for each column c in the grid, do" }, { "code": null, "e": 2589, "s": 2549, "text": "if grid[row, c] = num, then return true" }, { "code": null, "e": 2629, "s": 2589, "text": "if grid[row, c] = num, then return true" }, { "code": null, "e": 2652, "s": 2629, "text": "return false otherwise" }, { "code": null, "e": 2675, "s": 2652, "text": "return false otherwise" }, { "code": null, "e": 2760, "s": 2675, "text": "Define a method called isPresentInBox() this will take boxStartRow, boxStartCol, num" }, { "code": null, "e": 2845, "s": 2760, "text": "Define a method called isPresentInBox() this will take boxStartRow, boxStartCol, num" }, { "code": null, "e": 2982, "s": 2845, "text": "for each row r in boxStartRow to next 3 rows, dofor each col r in boxStartCol to next 3 columns, doif grid[r, c] = num, then return true" }, { "code": null, "e": 3031, "s": 2982, "text": "for each row r in boxStartRow to next 3 rows, do" }, { "code": null, "e": 3120, "s": 3031, "text": "for each col r in boxStartCol to next 3 columns, doif grid[r, c] = num, then return true" }, { "code": null, "e": 3172, "s": 3120, "text": "for each col r in boxStartCol to next 3 columns, do" }, { "code": null, "e": 3210, "s": 3172, "text": "if grid[r, c] = num, then return true" }, { "code": null, "e": 3248, "s": 3210, "text": "if grid[r, c] = num, then return true" }, { "code": null, "e": 3271, "s": 3248, "text": "return false otherwise" }, { "code": null, "e": 3294, "s": 3271, "text": "return false otherwise" }, { "code": null, "e": 3362, "s": 3294, "text": "Define a method called findEmptyPlace(), this will take row and col" }, { "code": null, "e": 3430, "s": 3362, "text": "Define a method called findEmptyPlace(), this will take row and col" }, { "code": null, "e": 3529, "s": 3430, "text": "for each row r in the grid, dofor each column c in the grid, doif grid[r, c] = 0, then return true" }, { "code": null, "e": 3560, "s": 3529, "text": "for each row r in the grid, do" }, { "code": null, "e": 3629, "s": 3560, "text": "for each column c in the grid, doif grid[r, c] = 0, then return true" }, { "code": null, "e": 3663, "s": 3629, "text": "for each column c in the grid, do" }, { "code": null, "e": 3699, "s": 3663, "text": "if grid[r, c] = 0, then return true" }, { "code": null, "e": 3735, "s": 3699, "text": "if grid[r, c] = 0, then return true" }, { "code": null, "e": 3748, "s": 3735, "text": "return false" }, { "code": null, "e": 3761, "s": 3748, "text": "return false" }, { "code": null, "e": 3829, "s": 3761, "text": "Define a method called isValidPlace(), this will take row, col, num" }, { "code": null, "e": 3897, "s": 3829, "text": "Define a method called isValidPlace(), this will take row, col, num" }, { "code": null, "e": 4043, "s": 3897, "text": "if isPresentInRow(row, num) and isPresentInCol(col, num) and isPresntInBox(row – row mod 3, col – col mod 3, num) all are false, then return true" }, { "code": null, "e": 4189, "s": 4043, "text": "if isPresentInRow(row, num) and isPresentInCol(col, num) and isPresntInBox(row – row mod 3, col – col mod 3, num) all are false, then return true" }, { "code": null, "e": 4251, "s": 4189, "text": "Define a method called solveSudoku(), this will take the grid" }, { "code": null, "e": 4313, "s": 4251, "text": "Define a method called solveSudoku(), this will take the grid" }, { "code": null, "e": 4364, "s": 4313, "text": "if no place in the grid is empty, then return true" }, { "code": null, "e": 4415, "s": 4364, "text": "if no place in the grid is empty, then return true" }, { "code": null, "e": 4558, "s": 4415, "text": "for number 1 to 9, doif isValidPlace(row, col, number), thengrid[row, col] := numberif solveSudoku = true, then return truegrid[row, col] := 0" }, { "code": null, "e": 4580, "s": 4558, "text": "for number 1 to 9, do" }, { "code": null, "e": 4702, "s": 4580, "text": "if isValidPlace(row, col, number), thengrid[row, col] := numberif solveSudoku = true, then return truegrid[row, col] := 0" }, { "code": null, "e": 4742, "s": 4702, "text": "if isValidPlace(row, col, number), then" }, { "code": null, "e": 4767, "s": 4742, "text": "grid[row, col] := number" }, { "code": null, "e": 4792, "s": 4767, "text": "grid[row, col] := number" }, { "code": null, "e": 4832, "s": 4792, "text": "if solveSudoku = true, then return true" }, { "code": null, "e": 4872, "s": 4832, "text": "if solveSudoku = true, then return true" }, { "code": null, "e": 4892, "s": 4872, "text": "grid[row, col] := 0" }, { "code": null, "e": 4912, "s": 4892, "text": "grid[row, col] := 0" }, { "code": null, "e": 4925, "s": 4912, "text": "return false" }, { "code": null, "e": 4938, "s": 4925, "text": "return false" }, { "code": null, "e": 5010, "s": 4938, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 5021, "s": 5010, "text": " Live Demo" }, { "code": null, "e": 7580, "s": 5021, "text": "#include <iostream>\n#define N 9\nusing namespace std;\nint grid[N][N] = {\n {3, 0, 6, 5, 0, 8, 4, 0, 0},\n {5, 2, 0, 0, 0, 0, 0, 0, 0},\n {0, 8, 7, 0, 0, 0, 0, 3, 1},\n {0, 0, 3, 0, 1, 0, 0, 8, 0},\n {9, 0, 0, 8, 6, 3, 0, 0, 5},\n {0, 5, 0, 0, 9, 0, 6, 0, 0},\n {1, 3, 0, 0, 0, 0, 2, 5, 0},\n {0, 0, 0, 0, 0, 0, 0, 7, 4},\n {0, 0, 5, 2, 0, 6, 3, 0, 0}\n};\nbool isPresentInCol(int col, int num){ //check whether num is present in col or not\n for (int row = 0; row < N; row++)\n if (grid[row][col] == num)\n return true;\n return false;\n}\nbool isPresentInRow(int row, int num){ //check whether num is present in row or not\n for (int col = 0; col < N; col++)\n if (grid[row][col] == num)\n return true;\n return false;\n}\nbool isPresentInBox(int boxStartRow, int boxStartCol, int num){\n//check whether num is present in 3x3 box or not\n for (int row = 0; row < 3; row++)\n for (int col = 0; col < 3; col++)\n if (grid[row+boxStartRow][col+boxStartCol] == num)\n return true;\n return false;\n}\nvoid sudokuGrid(){ //print the sudoku grid after solve\n for (int row = 0; row < N; row++){\n for (int col = 0; col < N; col++){\n if(col == 3 || col == 6)\n cout << \" | \";\n cout << grid[row][col] <<\" \";\n }\n if(row == 2 || row == 5){\n cout << endl;\n for(int i = 0; i<N; i++)\n cout << \"---\";\n }\n cout << endl;\n }\n}\nbool findEmptyPlace(int &row, int &col){ //get empty location and update row and column\n for (row = 0; row < N; row++)\n for (col = 0; col < N; col++)\n if (grid[row][col] == 0) //marked with 0 is empty\n return true;\n return false;\n}\nbool isValidPlace(int row, int col, int num){\n //when item not found in col, row and current 3x3 box\n return !isPresentInRow(row, num) && !isPresentInCol(col, num) && !isPresentInBox(row - row%3 ,\ncol - col%3, num);\n}\nbool solveSudoku(){\n int row, col;\n if (!findEmptyPlace(row, col))\n return true; //when all places are filled\n for (int num = 1; num <= 9; num++){ //valid numbers are 1 - 9\n if (isValidPlace(row, col, num)){ //check validation, if yes, put the number in the grid\n grid[row][col] = num;\n if (solveSudoku()) //recursively go for other rooms in the grid\n return true;\n grid[row][col] = 0; //turn to unassigned space when conditions are not satisfied\n }\n }\n return false;\n}\nint main(){\n if (solveSudoku() == true)\n sudokuGrid();\n else\n cout << \"No solution exists\";\n}" }, { "code": null, "e": 7840, "s": 7580, "text": "{3, 0, 6, 5, 0, 8, 4, 0, 0},\n{5, 2, 0, 0, 0, 0, 0, 0, 0},\n{0, 8, 7, 0, 0, 0, 0, 3, 1},\n{0, 0, 3, 0, 1, 0, 0, 8, 0},\n{9, 0, 0, 8, 6, 3, 0, 0, 5},\n{0, 5, 0, 0, 9, 0, 6, 0, 0},\n{1, 3, 0, 0, 0, 0, 2, 5, 0},\n{0, 0, 0, 0, 0, 0, 0, 7, 4},\n{0, 0, 5, 2, 0, 6, 3, 0, 0}" }, { "code": null, "e": 8094, "s": 7840, "text": "3 1 6 | 5 7 8 | 4 9 2\n5 2 9 | 1 3 4 | 7 6 8\n4 8 7 | 6 2 9 | 5 3 1\n---------------------------\n2 6 3 | 4 1 5 | 9 8 7\n9 7 4 | 8 6 3 | 1 2 5\n8 5 1 | 7 9 2 | 6 4 3\n---------------------------\n1 3 8 | 9 4 7 | 2 5 6\n6 9 2 | 3 5 1 | 8 7 4\n7 4 5 | 2 8 6 | 3 1 9" } ]
Example of Interfacing Seven Segments LED Display with 8085 - GeeksforGeeks
22 Jan, 2021 Seven segments LED display : A seven-segment LED is a kind of LED(Light Emitting Diode) consisting of 7 small LEDs it usually comes with the microprocessor’s as we commonly need to interface them with microprocessors like 8085. Structure of Seven Segments LED : The LED in Seven Segment display are arranged as below It can be used to represent numbers from 0 to 8 with a decimal point. We have eight segments in a Seven Segment LED display consisting of 7 segments which include ‘.’. The seven segments are denoted as “a, b, c, d, e, f, g, h” respectively, and ‘.’ is represented by “h” Interfacing Seven Segment Display with 8085 : We will see a program to Interfacing Seven Segment Display with 8085 assuming address decoders with an address of AE H. Note logic needed for activation – Common Anode – 0 will make an LED glow. Common Cathode – 1 will make an LED glow. Common Anode Method : Here we are using a common anode display therefore 0 logic is needed to activate the segment. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated. The instructions to execute it is given as, MVI A,99 OUT AE First, we are storing the 99H in the accumulator i.e. 10010000 by using MVI instruction. By OUT instruction we are sending the data stored in the accumulator to the port AFH Common Cathode Method : Here we are using common cathode 1 logic is needed to activate the signal. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated. The instructions to execute it is given as, MVI A,6F OUT AE First, we are storing the 6FH in the accumulator i.e.01101111 by using MVI instruction. By OUT instruction we are sending the data stored in the accumulator to the port AFH microprocessor Computer Organization and Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced RISC Machine (ARM) Processor Difference between Cache Coherence and Memory Consistency Basic Cache Optimization Techniques Difference between Hardware and Peripherals Advantages and disadvantages of Hard Disk Factors affecting Cache Memory Performance Representing Instructions in Computer Simultaneous and Hierarchical Cache Accesses 8085 program to find 2's complement of the contents of Flag Register Computer Organization and Architecture | Computer Organization and Architecture | Question 1
[ { "code": null, "e": 26141, "s": 26113, "text": "\n22 Jan, 2021" }, { "code": null, "e": 26170, "s": 26141, "text": "Seven segments LED display :" }, { "code": null, "e": 26369, "s": 26170, "text": "A seven-segment LED is a kind of LED(Light Emitting Diode) consisting of 7 small LEDs it usually comes with the microprocessor’s as we commonly need to interface them with microprocessors like 8085." }, { "code": null, "e": 26403, "s": 26369, "text": "Structure of Seven Segments LED :" }, { "code": null, "e": 26458, "s": 26403, "text": "The LED in Seven Segment display are arranged as below" }, { "code": null, "e": 26528, "s": 26458, "text": "It can be used to represent numbers from 0 to 8 with a decimal point." }, { "code": null, "e": 26626, "s": 26528, "text": "We have eight segments in a Seven Segment LED display consisting of 7 segments which include ‘.’." }, { "code": null, "e": 26729, "s": 26626, "text": "The seven segments are denoted as “a, b, c, d, e, f, g, h” respectively, and ‘.’ is represented by “h”" }, { "code": null, "e": 26775, "s": 26729, "text": "Interfacing Seven Segment Display with 8085 :" }, { "code": null, "e": 26895, "s": 26775, "text": "We will see a program to Interfacing Seven Segment Display with 8085 assuming address decoders with an address of AE H." }, { "code": null, "e": 26930, "s": 26895, "text": "Note logic needed for activation –" }, { "code": null, "e": 26970, "s": 26930, "text": "Common Anode – 0 will make an LED glow." }, { "code": null, "e": 27012, "s": 26970, "text": "Common Cathode – 1 will make an LED glow." }, { "code": null, "e": 27034, "s": 27012, "text": "Common Anode Method :" }, { "code": null, "e": 27252, "s": 27034, "text": "Here we are using a common anode display therefore 0 logic is needed to activate the segment. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated." }, { "code": null, "e": 27296, "s": 27252, "text": "The instructions to execute it is given as," }, { "code": null, "e": 27312, "s": 27296, "text": "MVI A,99\nOUT AE" }, { "code": null, "e": 27401, "s": 27312, "text": "First, we are storing the 99H in the accumulator i.e. 10010000 by using MVI instruction." }, { "code": null, "e": 27486, "s": 27401, "text": "By OUT instruction we are sending the data stored in the accumulator to the port AFH" }, { "code": null, "e": 27510, "s": 27486, "text": "Common Cathode Method :" }, { "code": null, "e": 27709, "s": 27510, "text": "Here we are using common cathode 1 logic is needed to activate the signal. Suppose to display number 9 at the seven-segment display, therefore the segments F, G, B, A, C, and D have to be activated." }, { "code": null, "e": 27753, "s": 27709, "text": "The instructions to execute it is given as," }, { "code": null, "e": 27770, "s": 27753, "text": "MVI A,6F \nOUT AE" }, { "code": null, "e": 27859, "s": 27770, "text": "First, we are storing the 6FH in the accumulator i.e.01101111 by using MVI instruction." }, { "code": null, "e": 27944, "s": 27859, "text": "By OUT instruction we are sending the data stored in the accumulator to the port AFH" }, { "code": null, "e": 27959, "s": 27944, "text": "microprocessor" }, { "code": null, "e": 27998, "s": 27959, "text": "Computer Organization and Architecture" }, { "code": null, "e": 28013, "s": 27998, "text": "microprocessor" }, { "code": null, "e": 28111, "s": 28013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28149, "s": 28111, "text": "Advanced RISC Machine (ARM) Processor" }, { "code": null, "e": 28207, "s": 28149, "text": "Difference between Cache Coherence and Memory Consistency" }, { "code": null, "e": 28243, "s": 28207, "text": "Basic Cache Optimization Techniques" }, { "code": null, "e": 28287, "s": 28243, "text": "Difference between Hardware and Peripherals" }, { "code": null, "e": 28329, "s": 28287, "text": "Advantages and disadvantages of Hard Disk" }, { "code": null, "e": 28372, "s": 28329, "text": "Factors affecting Cache Memory Performance" }, { "code": null, "e": 28410, "s": 28372, "text": "Representing Instructions in Computer" }, { "code": null, "e": 28455, "s": 28410, "text": "Simultaneous and Hierarchical Cache Accesses" }, { "code": null, "e": 28524, "s": 28455, "text": "8085 program to find 2's complement of the contents of Flag Register" } ]
Boolean compareTo() method in Java with examples - GeeksforGeeks
08 Oct, 2018 The compareTo() method of Boolean class is a built in method in Java which is used to compare the given Boolean instance with the current instance. Syntax: BooleanObject.compareTo(Boolean a) Parameters: It takes a Boolean value a as parameter which is to be compared with the current instance. Return Type: The return type of the function is int. It returns: 0 if ‘a’ is equal to ‘b’, a negative value if ‘a’is false and ‘b’ is true, a positive value if ‘a’ is true and ‘b’ is false. Below are programs to illustrate the compareTo() method of Boolean class: Program 1: // Java code to implement// compareTo() method of Boolean class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + " comparing with " + b + " = " + a.compareTo(b)); }} true comparing with true = 0 Program 2: // Java code to implement// compareTo() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(false); // compare method System.out.println(a + " comparing with " + b + " = " + a.compareTo(b)); }} true comparing with false = 1 Program 3: // Java code to implement// compareTo() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(false); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + " comparing with " + b + " = " + a.compareTo(b)); }} false comparing with true = -1 Java - util package Java-Byte Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n08 Oct, 2018" }, { "code": null, "e": 25385, "s": 25237, "text": "The compareTo() method of Boolean class is a built in method in Java which is used to compare the given Boolean instance with the current instance." }, { "code": null, "e": 25393, "s": 25385, "text": "Syntax:" }, { "code": null, "e": 25428, "s": 25393, "text": "BooleanObject.compareTo(Boolean a)" }, { "code": null, "e": 25531, "s": 25428, "text": "Parameters: It takes a Boolean value a as parameter which is to be compared with the current instance." }, { "code": null, "e": 25596, "s": 25531, "text": "Return Type: The return type of the function is int. It returns:" }, { "code": null, "e": 25622, "s": 25596, "text": "0 if ‘a’ is equal to ‘b’," }, { "code": null, "e": 25671, "s": 25622, "text": "a negative value if ‘a’is false and ‘b’ is true," }, { "code": null, "e": 25721, "s": 25671, "text": "a positive value if ‘a’ is true and ‘b’ is false." }, { "code": null, "e": 25795, "s": 25721, "text": "Below are programs to illustrate the compareTo() method of Boolean class:" }, { "code": null, "e": 25806, "s": 25795, "text": "Program 1:" }, { "code": "// Java code to implement// compareTo() method of Boolean class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.compareTo(b)); }}", "e": 26231, "s": 25806, "text": null }, { "code": null, "e": 26261, "s": 26231, "text": "true comparing with true = 0\n" }, { "code": null, "e": 26272, "s": 26261, "text": "Program 2:" }, { "code": "// Java code to implement// compareTo() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(false); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.compareTo(b)); }}", "e": 26695, "s": 26272, "text": null }, { "code": null, "e": 26726, "s": 26695, "text": "true comparing with false = 1\n" }, { "code": null, "e": 26737, "s": 26726, "text": "Program 3:" }, { "code": "// Java code to implement// compareTo() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(false); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.compareTo(b)); }}", "e": 27160, "s": 26737, "text": null }, { "code": null, "e": 27192, "s": 27160, "text": "false comparing with true = -1\n" }, { "code": null, "e": 27212, "s": 27192, "text": "Java - util package" }, { "code": null, "e": 27222, "s": 27212, "text": "Java-Byte" }, { "code": null, "e": 27237, "s": 27222, "text": "Java-Functions" }, { "code": null, "e": 27242, "s": 27237, "text": "Java" }, { "code": null, "e": 27247, "s": 27242, "text": "Java" }, { "code": null, "e": 27345, "s": 27247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27360, "s": 27345, "text": "Stream In Java" }, { "code": null, "e": 27381, "s": 27360, "text": "Constructors in Java" }, { "code": null, "e": 27400, "s": 27381, "text": "Exceptions in Java" }, { "code": null, "e": 27430, "s": 27400, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27476, "s": 27430, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27493, "s": 27476, "text": "Generics in Java" }, { "code": null, "e": 27514, "s": 27493, "text": "Introduction to Java" }, { "code": null, "e": 27557, "s": 27514, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27579, "s": 27557, "text": "PriorityQueue in Java" } ]
AB Testing With R Programming - GeeksforGeeks
23 Oct, 2020 Split testing is another name of A/B testing and it’s a common or general methodology. It’s used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two web pages by representing variants A and B for them, as the number of visitors is similar the conversion rate given by the variant becomes better. Overall, it’s an experiment where two or more variations of the same web page are compared against together by showcasing them to real-time visitors, and through that determines which one performs better for a given goal. A/B testing is not only used or limited by web pages only, it can be used in emails, popups, sign-up forms, apps, and more. Let’s look into the example of a case study. So let’s implement AB testing in the R language. Let’s imagine we have results of A/B tests from two hotel booking websites, (Note: the data is not the real one ). First, we need to conduct a test analysis of the data; second, we need to draw conclusions from the data which we obtained from the first step, and in the final step, we make recommendations or suggestions to the product or management teams. Download the data set from here. Variant A is from the control group which tells the existing features or products on a website. Variant B is from the experimental group to check the new version of a feature or product to see if users like it or if it increases the conversions(bookings). Converted is based on the data set given, there are two categories defined by logical value. It’s going to show true when the customer completes bookings and it’s going to show false when the customer visits the sites but not makes a booking. Null Hypothesis: Both versions A and B have an equal probability of conversion or driving customer booking. In other words, there is no difference or no effect between A and B versions Alternative Hypothesis: Versions both A and B possess different probability of conversion or driving customer booking and there is a difference between A and B version. Version B is better than version A in driving customer bookings. PExp_B! = Pcont_A. 1. Prepare the dataset and load the tidyverse library which contains the relevant packages used for the analysis. R # load the librarylibrary(tidyverse) # set up your own directorysetwd(“~egot_\\Projects\\ABTest”) # Using read.csv base import function ABTest <- read.csv("Website Results.csv", header = TRUE) # save in your own directorysave(ABTest, file = "~rda\\ABTest.rda") 2. Let’s filter conversions for variants A & B and compute their corresponding conversion rates R # Let's filter out conversions for variant_A conversion_subset_A <- ABTest %>% filter(variant == "A" & converted == "TRUE") # Total Number of Conversions for variant_Aconversions_A <- nrow(conversion_subset_A) # Number of Visitors for variant_Avisitors_A <- nrow(ABTest %>% filter(variant == "A")) # Conversion_rate_Aconv_rate_A <- (conversions_A/visitors_A) print(conv_rate_A) # 0.02773925 # Let's take a subset of conversions for variant_Bconversion_subset_B <- ABTest %>% filter(variant == "B" & converted == "TRUE") # Number of Conversions for variant_Bconversions_B <- nrow(conversion_subset_B) # Number of Visitors for variant_Bvisitors_B <- nrow(ABTest %>% filter(variant == "B")) # Conversion_rate_Bconv_rate_B <- (conversions_B/visitors_B) print(conv_rate_B) # 0.05068493 Output: 0.02773925 0.05068493 3. Let’s compute the relative uplift using conversion rates A & B. The uplift is a percentage of the increase R uplift <- (conv_rate_B - conv_rate_A) / conv_rate_A * 100uplift # 82.72% Output: 82.72% B is better than A by 83%. This is high enough to decide a winner. 4. Let’s compute the pooled probability, standard error, the margin of error, and difference in proportion (point estimate) for variants A & B R # Pooled sample proportion for variants A & Bp_pool <- (conversions_A + conversions_B) / (visitors_A + visitors_B)print(p_pool) # 0.03928325 # Let's compute Standard error for variants A & B (SE_pool)SE_pool <- sqrt(p_pool * (1 - p_pool) * ((1 / visitors_A) + (1 / visitors_B)))print(SE_pool) # 0.01020014 # Let's compute the margin of error for the poolMOE <- SE_pool * qnorm(0.975)print(MOE) # 0.0199919 # Point Estimate or Difference in proportiond_hat <- conv_rate_B - conv_rate_A Output: 0.03928325 0.01020014 0.0199919 5. Let’s compute the z-score R # Compute the Z-score so we# can determine the p-valuez_score <- d_hat / SE_poolprint(z_score) # 2.249546 Output: 2.249546 6. Using this z-score, we can quickly determine the p-value via a look-up table, or using the code below: R # Let's compute p_value # using the z_score valuep_value <- pnorm(q = -z_score, mean = 0, sd = 1) * 2print(p_value) # 0.02447777 Output: 0.02447777 7. Let’s compute the confidence interval for the pool R # Let's compute Confidence interval for the # pool using pre-calculated resultsci <- c(d_hat - MOE, d_hat + MOE) ci # 0.002953777 0.042937584 # Using same steps as already shown, # let's compute the confidence # interval for variants A separatelyX_hat_A <- conversions_A / visitors_Ase_hat_A <- sqrt(X_hat_A * (1 - X_hat_A) / visitors_A) ci_A <- c(X_hat_A - qnorm(0.975) * se_hat_A, X_hat_A + qnorm(0.975) * se_hat_A) print(ci_A) # 0.01575201 0.03972649 # Using same steps as already shown, # let's compute the confidence # interval for variants B separately X_hat_B <- conversions_B / visitors_Bse_hat_B <- sqrt(X_hat_B * (1 - X_hat_B) / visitors_B) ci_B <- c(X_hat_B - qnorm(0.975) * se_hat_B, X_hat_B + qnorm(0.975) * se_hat_B) print(ci_B) # 0.03477269 0.06659717 Output: 0.002953777 0.042937584 0.01575201 0.03972649 0.03477269 0.06659717 8. Let’s visualize the results computed so far in a dataframe (table): R vis_result_pool <- data.frame( metric = c( 'Estimated Difference', 'Relative Uplift(%)', 'pooled sample proportion', 'Standard Error of Difference', 'z_score', 'p-value', 'Margin of Error', 'CI-lower', 'CI-upper'), value = c( conv_rate_B - conv_rate_A, uplift, p_pool, SE_pool, z_score, p_value, MOE, ci_lower, ci_upper ))vis_result_pool Output: metric value 1 Estimated Difference 0.02294568 2 Relative Uplift(%) 82.71917808 3 pooled sample proportion 0.03928325 4 Standard Error of Difference 0.01020014 5 z_score 2.24954609 6 p-value 0.02447777 7 Margin of Error 0.01999190 8 CI-lower 0.00000000 9 CI-upper 0.04589136 Variant A has 20 conversions and 721 hits whereas Variant B has 37 conversions and 730 hits. Relative uplift of 82.72% based on a variant A conversion rate is 2.77% and for B is 5.07%. Hence, variant B is better than A by 82.72%. For this analysis P-value computed was 0.02448. Hence, there is strong statistical significance in test results. From the above results that depict strong statistical significance. You should reject the null hypothesis and proceed with the launch. Therefore, Accept Variant B and you can roll it to the users for 100%. If you want to know the full analysis and datasets details then please click on this Github link. It is one of the tools for conversion optimization and it’s not an independent solution and it’s not going to fix all the conversion issues of ours and it can’t fix the issues as you get with messy data and you need to perform more than just an A/B test to improve on conversions. Picked R Data-science R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Logistic Regression in R Programming How to change the order of bars in bar chart in R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Data Visualization in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n23 Oct, 2020" }, { "code": null, "e": 26098, "s": 25162, "text": "Split testing is another name of A/B testing and it’s a common or general methodology. It’s used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two web pages by representing variants A and B for them, as the number of visitors is similar the conversion rate given by the variant becomes better. Overall, it’s an experiment where two or more variations of the same web page are compared against together by showcasing them to real-time visitors, and through that determines which one performs better for a given goal. A/B testing is not only used or limited by web pages only, it can be used in emails, popups, sign-up forms, apps, and more. Let’s look into the example of a case study. So let’s implement AB testing in the R language." }, { "code": null, "e": 26455, "s": 26098, "text": "Let’s imagine we have results of A/B tests from two hotel booking websites, (Note: the data is not the real one ). First, we need to conduct a test analysis of the data; second, we need to draw conclusions from the data which we obtained from the first step, and in the final step, we make recommendations or suggestions to the product or management teams." }, { "code": null, "e": 26488, "s": 26455, "text": "Download the data set from here." }, { "code": null, "e": 26584, "s": 26488, "text": "Variant A is from the control group which tells the existing features or products on a website." }, { "code": null, "e": 26744, "s": 26584, "text": "Variant B is from the experimental group to check the new version of a feature or product to see if users like it or if it increases the conversions(bookings)." }, { "code": null, "e": 26987, "s": 26744, "text": "Converted is based on the data set given, there are two categories defined by logical value. It’s going to show true when the customer completes bookings and it’s going to show false when the customer visits the sites but not makes a booking." }, { "code": null, "e": 27172, "s": 26987, "text": "Null Hypothesis: Both versions A and B have an equal probability of conversion or driving customer booking. In other words, there is no difference or no effect between A and B versions" }, { "code": null, "e": 27425, "s": 27172, "text": "Alternative Hypothesis: Versions both A and B possess different probability of conversion or driving customer booking and there is a difference between A and B version. Version B is better than version A in driving customer bookings. PExp_B! = Pcont_A." }, { "code": null, "e": 27539, "s": 27425, "text": "1. Prepare the dataset and load the tidyverse library which contains the relevant packages used for the analysis." }, { "code": null, "e": 27541, "s": 27539, "text": "R" }, { "code": "# load the librarylibrary(tidyverse) # set up your own directorysetwd(“~egot_\\\\Projects\\\\ABTest”) # Using read.csv base import function ABTest <- read.csv(\"Website Results.csv\", header = TRUE) # save in your own directorysave(ABTest, file = \"~rda\\\\ABTest.rda\")", "e": 27826, "s": 27541, "text": null }, { "code": null, "e": 27922, "s": 27826, "text": "2. Let’s filter conversions for variants A & B and compute their corresponding conversion rates" }, { "code": null, "e": 27924, "s": 27922, "text": "R" }, { "code": "# Let's filter out conversions for variant_A conversion_subset_A <- ABTest %>% filter(variant == \"A\" & converted == \"TRUE\") # Total Number of Conversions for variant_Aconversions_A <- nrow(conversion_subset_A) # Number of Visitors for variant_Avisitors_A <- nrow(ABTest %>% filter(variant == \"A\")) # Conversion_rate_Aconv_rate_A <- (conversions_A/visitors_A) print(conv_rate_A) # 0.02773925 # Let's take a subset of conversions for variant_Bconversion_subset_B <- ABTest %>% filter(variant == \"B\" & converted == \"TRUE\") # Number of Conversions for variant_Bconversions_B <- nrow(conversion_subset_B) # Number of Visitors for variant_Bvisitors_B <- nrow(ABTest %>% filter(variant == \"B\")) # Conversion_rate_Bconv_rate_B <- (conversions_B/visitors_B) print(conv_rate_B) # 0.05068493", "e": 28731, "s": 27924, "text": null }, { "code": null, "e": 28739, "s": 28731, "text": "Output:" }, { "code": null, "e": 28763, "s": 28739, "text": "0.02773925\n0.05068493\n\n" }, { "code": null, "e": 28873, "s": 28763, "text": "3. Let’s compute the relative uplift using conversion rates A & B. The uplift is a percentage of the increase" }, { "code": null, "e": 28875, "s": 28873, "text": "R" }, { "code": "uplift <- (conv_rate_B - conv_rate_A) / conv_rate_A * 100uplift # 82.72%", "e": 28948, "s": 28875, "text": null }, { "code": null, "e": 28956, "s": 28948, "text": "Output:" }, { "code": null, "e": 28965, "s": 28956, "text": "82.72%\n\n" }, { "code": null, "e": 29032, "s": 28965, "text": "B is better than A by 83%. This is high enough to decide a winner." }, { "code": null, "e": 29175, "s": 29032, "text": "4. Let’s compute the pooled probability, standard error, the margin of error, and difference in proportion (point estimate) for variants A & B" }, { "code": null, "e": 29177, "s": 29175, "text": "R" }, { "code": "# Pooled sample proportion for variants A & Bp_pool <- (conversions_A + conversions_B) / (visitors_A + visitors_B)print(p_pool) # 0.03928325 # Let's compute Standard error for variants A & B (SE_pool)SE_pool <- sqrt(p_pool * (1 - p_pool) * ((1 / visitors_A) + (1 / visitors_B)))print(SE_pool) # 0.01020014 # Let's compute the margin of error for the poolMOE <- SE_pool * qnorm(0.975)print(MOE) # 0.0199919 # Point Estimate or Difference in proportiond_hat <- conv_rate_B - conv_rate_A", "e": 29750, "s": 29177, "text": null }, { "code": null, "e": 29758, "s": 29750, "text": "Output:" }, { "code": null, "e": 29792, "s": 29758, "text": "0.03928325\n0.01020014\n0.0199919\n\n" }, { "code": null, "e": 29821, "s": 29792, "text": "5. Let’s compute the z-score" }, { "code": null, "e": 29823, "s": 29821, "text": "R" }, { "code": "# Compute the Z-score so we# can determine the p-valuez_score <- d_hat / SE_poolprint(z_score) # 2.249546", "e": 29929, "s": 29823, "text": null }, { "code": null, "e": 29937, "s": 29929, "text": "Output:" }, { "code": null, "e": 29948, "s": 29937, "text": "2.249546\n\n" }, { "code": null, "e": 30054, "s": 29948, "text": "6. Using this z-score, we can quickly determine the p-value via a look-up table, or using the code below:" }, { "code": null, "e": 30056, "s": 30054, "text": "R" }, { "code": "# Let's compute p_value # using the z_score valuep_value <- pnorm(q = -z_score, mean = 0, sd = 1) * 2print(p_value) # 0.02447777", "e": 30219, "s": 30056, "text": null }, { "code": null, "e": 30227, "s": 30219, "text": "Output:" }, { "code": null, "e": 30240, "s": 30227, "text": "0.02447777\n\n" }, { "code": null, "e": 30294, "s": 30240, "text": "7. Let’s compute the confidence interval for the pool" }, { "code": null, "e": 30296, "s": 30294, "text": "R" }, { "code": "# Let's compute Confidence interval for the # pool using pre-calculated resultsci <- c(d_hat - MOE, d_hat + MOE) ci # 0.002953777 0.042937584 # Using same steps as already shown, # let's compute the confidence # interval for variants A separatelyX_hat_A <- conversions_A / visitors_Ase_hat_A <- sqrt(X_hat_A * (1 - X_hat_A) / visitors_A) ci_A <- c(X_hat_A - qnorm(0.975) * se_hat_A, X_hat_A + qnorm(0.975) * se_hat_A) print(ci_A) # 0.01575201 0.03972649 # Using same steps as already shown, # let's compute the confidence # interval for variants B separately X_hat_B <- conversions_B / visitors_Bse_hat_B <- sqrt(X_hat_B * (1 - X_hat_B) / visitors_B) ci_B <- c(X_hat_B - qnorm(0.975) * se_hat_B, X_hat_B + qnorm(0.975) * se_hat_B) print(ci_B) # 0.03477269 0.06659717", "e": 31116, "s": 30296, "text": null }, { "code": null, "e": 31124, "s": 31116, "text": "Output:" }, { "code": null, "e": 31194, "s": 31124, "text": "0.002953777 0.042937584\n0.01575201 0.03972649\n0.03477269 0.06659717\n\n" }, { "code": null, "e": 31265, "s": 31194, "text": "8. Let’s visualize the results computed so far in a dataframe (table):" }, { "code": null, "e": 31267, "s": 31265, "text": "R" }, { "code": "vis_result_pool <- data.frame( metric = c( 'Estimated Difference', 'Relative Uplift(%)', 'pooled sample proportion', 'Standard Error of Difference', 'z_score', 'p-value', 'Margin of Error', 'CI-lower', 'CI-upper'), value = c( conv_rate_B - conv_rate_A, uplift, p_pool, SE_pool, z_score, p_value, MOE, ci_lower, ci_upper ))vis_result_pool", "e": 31662, "s": 31267, "text": null }, { "code": null, "e": 31670, "s": 31662, "text": "Output:" }, { "code": null, "e": 32099, "s": 31670, "text": " metric value\n1 Estimated Difference 0.02294568\n2 Relative Uplift(%) 82.71917808\n3 pooled sample proportion 0.03928325\n4 Standard Error of Difference 0.01020014\n5 z_score 2.24954609\n6 p-value 0.02447777\n7 Margin of Error 0.01999190\n8 CI-lower 0.00000000\n9 CI-upper 0.04589136\n\n" }, { "code": null, "e": 32192, "s": 32099, "text": "Variant A has 20 conversions and 721 hits whereas Variant B has 37 conversions and 730 hits." }, { "code": null, "e": 32329, "s": 32192, "text": "Relative uplift of 82.72% based on a variant A conversion rate is 2.77% and for B is 5.07%. Hence, variant B is better than A by 82.72%." }, { "code": null, "e": 32442, "s": 32329, "text": "For this analysis P-value computed was 0.02448. Hence, there is strong statistical significance in test results." }, { "code": null, "e": 32577, "s": 32442, "text": "From the above results that depict strong statistical significance. You should reject the null hypothesis and proceed with the launch." }, { "code": null, "e": 32648, "s": 32577, "text": "Therefore, Accept Variant B and you can roll it to the users for 100%." }, { "code": null, "e": 32747, "s": 32648, "text": "If you want to know the full analysis and datasets details then please click on this Github link. " }, { "code": null, "e": 33029, "s": 32747, "text": "It is one of the tools for conversion optimization and it’s not an independent solution and it’s not going to fix all the conversion issues of ours and it can’t fix the issues as you get with messy data and you need to perform more than just an A/B test to improve on conversions. " }, { "code": null, "e": 33036, "s": 33029, "text": "Picked" }, { "code": null, "e": 33051, "s": 33036, "text": "R Data-science" }, { "code": null, "e": 33062, "s": 33051, "text": "R Language" }, { "code": null, "e": 33160, "s": 33062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33169, "s": 33160, "text": "Comments" }, { "code": null, "e": 33182, "s": 33169, "text": "Old Comments" }, { "code": null, "e": 33234, "s": 33182, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 33272, "s": 33234, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 33307, "s": 33272, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 33365, "s": 33307, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 33414, "s": 33365, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 33451, "s": 33414, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 33503, "s": 33451, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 33553, "s": 33503, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 33596, "s": 33553, "text": "Replace Specific Characters in String in R" } ]
Check if subtree | Practice | GeeksforGeeks
Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T. A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1. Example 1: Input: T: 1 S: 3 / \ / 2 3 4 / \ / N N 4 Output: 1 Explanation: S is present in T Example 2: Input: T: 26 S: 26 / \ / \ 10 N 10 N / \ / \ 20 30 20 30 / \ / \ 40 60 40 60 Output: 1 Explanation: S and T are both same. Hence, it can be said that S is a subtree of T. Your Task: You don't need to read input or print anything. Your task is to complete the function isSubtree() that takes root node of S and T as parameters and returns 1 if S is a subtree of T else 0. Note: The nodes can have the duplicate values. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= Number of nodes <= 105 1 <= Value of nodes <= 104 0 devanshuz3 days ago 0.69 JAVA Solution 10 Lines public static boolean isSubtree(Node T, Node S) { if (T == null) return false; if (isIdentical(T, S)) return true; return isSubtree(T.left, S) || isSubtree(T.right, S); } public static boolean isIdentical(Node T, Node S){ if (T == null || S == null){ return T == S; } return T.data == S.data && isIdentical(T.left, S.left) && isIdentical(T.right, S.right); } +1 shubham211019971 week ago static boolean helper(Node r1,Node r2){ if(r1==null&& r2==null)return true; if(r1==null||r2==null)return false; return ((r1.data==r2.data)&&helper(r1.left,r2.left)&&helper(r1.right,r2.right)); } public static boolean isSubtree(Node r1, Node r2) { if(r1==null && r2==null)return true; if(r1==null&&r2!=null)return false; return (helper(r1,r2)||isSubtree(r1.left,r2)||isSubtree(r1.right,r2)); } 0 aayushwas1 week ago 0.78/1.95 C++ //aretreessame checks if two trees are same bool aretreessame(Node* t, Node* s){ if(t==NULL&&s!=NULL || t!=NULL&&s==NULL) return false; if(t==NULL&&s==NULL) return true; if(t->data!=s->data) return false; bool a = aretreessame(t->left,s->left); bool b = aretreessame(t->right,s->right); return a&&b; } // checks if s subtree exists in T bool isSubTree(Node* T, Node* S) { if(T==NULL&&S!=NULL || T!=NULL&&S==NULL) return false; if(T==NULL&&S==NULL) return true; if(T->data==S->data&&aretreessame(T,S)==true){ return true; } bool l = isSubTree(T->left,S); bool r = isSubTree(T->right,S); return l||r; } +1 tarunkanade2 weeks ago 0.69/1.94 Java O(n), O(h) with explanation public static boolean isSubtree(Node T, Node S) { // add code here. if(T == null){ return false; } if(T.data == S.data){ // 3 // / \ // 3 5 // / \ // 4 6 for eg: this is "T" // and we want to find: // 3 // / \ // 4 6 // As here 3 is present 2 times in T, and "S" is the subtree with // root as 3 which is the later one (in T) we can see from the visualization // so in such conditions if we simply return checkIfSame(T, S) // then our code will not check subsequent subtrees after the first // encounter with 3 (in T) and will return false as a result which is wrong // So for keep searching the subtrees we are again checking if // checkIfSame(T, S) == true then only return (true) otherwise keep searching if(checkIfSame(T, S)){ return true; } } if(isSubtree(T.left, S) == true || isSubtree(T.right, S) == true){ return true; } else{ return false; } } // method for checking if 2 trees are identical private static boolean checkIfSame(Node root1, Node root2){ if(root1 == null && root2 == null){ return true; } else if((root1 == null && root2 != null) || (root1 != null && root2 == null)){ return false; } else if(root1.data != root2.data){ return false; } else{ if(checkIfSame(root1.left, root2.left) == true && checkIfSame(root1.right, root2.right) == true){ return true; } else{ return false; } } } +3 akashkhurana283 weeks ago JAVA SOLUTION class Solution { public static boolean check(Node root,Node subroot) { if(root==null && subroot==null) { return true; } if(root==null || subroot==null) { return false; } if(root.data==subroot.data) { return check(root.left,subroot.left) && check(root.right,subroot.right); } return false; } public static boolean isSubtree(Node T, Node S) { // add code here. if(S==null) { return true; } if(T==null) { return false; } if(T.data==S.data) { if(check(T,S)) { return true; } } return isSubtree(T.left,S) || isSubtree(T.right,S); }} 0 mohit negi3 weeks ago c++ simple solution O(N) int checkSub(Node *t,Node *s) { if(t==NULL && s==NULL) return 1; if(!t||!s) return 0; if(t->data!=s->data) return 0; else { int a=checkSub(t->left,s->left); int b=checkSub(t->right,s->right); return a&b; } } void check(Node* t, Node* s,int &is) { if(t==NULL) return; else if(!is) { if(t->data==s->data) { is= checkSub(t,s); if(is) return; } check(t->left,s,is); check(t->right,s,is); } } bool isSubTree(Node* T, Node* S) { int is=0; check(T,S,is); return is; } 0 himanshujain4573 weeks ago No rocket Science:Simple Solution class Solution { static void storeRoot(Node r,Node s, ArrayList<Node>ans){ if(r==null)return ; if(r.data==s.data) ans.add(r); storeRoot(r.left,s,ans); storeRoot(r.right,s,ans); } static boolean check(Node r,Node s){ if(r==null&&s==null)return true; if(r==null &&s!=null)return false; if(r!=null&&s==null)return false; if(r.data!=s.data)return false; if(check(r.left,s.left)&&check(r.right,s.right))return true; return false; } public static boolean isSubtree(Node T, Node S) { ArrayList<Node>ans=new ArrayList<>(); if(T==null&&S==null)return true; if(T==null&&S!=null)return false; if(T!=null &&S==null)return true; storeRoot(T,S,ans); for(Node e:ans){ if(check(e,S)) return true; } return false; }} 0 nikhilchakravarthy091 month ago void findSubTreeNode(Node* t, Node* s,vector<Node*>& temp){ if(t==NULL) return; if(t->data == s->data) temp.push_back(t); findSubTreeNode(t->left,s,temp); findSubTreeNode(t->right,s,temp); } bool checkSubTree(Node* sub, Node* s){ if(s==NULL && sub==NULL) return true; if((sub==NULL && s!=NULL) || (sub!=NULL && s==NULL))return false; if(sub->data == s->data){ return (checkSubTree(sub->left,s->left) && checkSubTree(sub->right,s->right)); } return false; } bool isSubTree(Node* T, Node* S) { Node* sub=NULL; vector<Node*> temp; findSubTreeNode(T,S,temp); for(int i=0;i<temp.size();i++) if (checkSubTree(temp[i],S)) return true; return false; } 0 harrypotter02 months ago def isSubTree(self, s, t): def convert(p): return "^" + str(p.data) + "#" + convert(p.left) + convert(p.right) if p else "$" return convert(t) in convert(s) 0 adityapratapsingh0820172 months ago python solution not accepted why? class Solution: def isSubTree(self, T, S): # Code here if not T: return False if not S: return True if mirror(T,S): return True return (self.isSubTree(T.left,S) or self.isSubTree(T.right,S)) def mirror(t,s): if not s or not t: return t==s return (t.data==s.data) and mirror(t.left,s.left) and mirror(t.right,s.right) We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 467, "s": 238, "text": "Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.\nA subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1." }, { "code": null, "e": 478, "s": 467, "text": "Example 1:" }, { "code": null, "e": 629, "s": 478, "text": "Input:\nT: 1 S: 3\n / \\ /\n 2 3 4\n / \\ /\n N N 4\nOutput: 1 \nExplanation: S is present in T\n\n" }, { "code": null, "e": 640, "s": 629, "text": "Example 2:" }, { "code": null, "e": 928, "s": 640, "text": "Input:\nT: 26 S: 26\n / \\ / \\\n 10 N 10 N\n / \\ / \\\n 20 30 20 30\n / \\ / \\\n 40 60 40 60\nOutput: 1 \nExplanation: \nS and T are both same. Hence, \nit can be said that S is a subtree \nof T.\n" }, { "code": null, "e": 1128, "s": 928, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isSubtree() that takes root node of S and T as parameters and returns 1 if S is a subtree of T else 0." }, { "code": null, "e": 1175, "s": 1128, "text": "Note: The nodes can have the duplicate values." }, { "code": null, "e": 1240, "s": 1175, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1310, "s": 1240, "text": "Constraints:\n1 <= Number of nodes <= 105\n1 <= Value of nodes <= 104\n " }, { "code": null, "e": 1312, "s": 1310, "text": "0" }, { "code": null, "e": 1332, "s": 1312, "text": "devanshuz3 days ago" }, { "code": null, "e": 1360, "s": 1332, "text": "0.69 JAVA Solution 10 Lines" }, { "code": null, "e": 1808, "s": 1360, "text": "public static boolean isSubtree(Node T, Node S) {\n if (T == null) return false;\n if (isIdentical(T, S))\n return true;\n return isSubtree(T.left, S) || isSubtree(T.right, S);\n }\n \n public static boolean isIdentical(Node T, Node S){\n if (T == null || S == null){\n return T == S;\n }\n return T.data == S.data && isIdentical(T.left, S.left) && isIdentical(T.right, S.right);\n }" }, { "code": null, "e": 1811, "s": 1808, "text": "+1" }, { "code": null, "e": 1837, "s": 1811, "text": "shubham211019971 week ago" }, { "code": null, "e": 2296, "s": 1837, "text": "static boolean helper(Node r1,Node r2){\n if(r1==null&& r2==null)return true;\n if(r1==null||r2==null)return false;\n return ((r1.data==r2.data)&&helper(r1.left,r2.left)&&helper(r1.right,r2.right));\n }\n public static boolean isSubtree(Node r1, Node r2) {\n if(r1==null && r2==null)return true;\n if(r1==null&&r2!=null)return false;\n return (helper(r1,r2)||isSubtree(r1.left,r2)||isSubtree(r1.right,r2));\n \n }" }, { "code": null, "e": 2298, "s": 2296, "text": "0" }, { "code": null, "e": 2318, "s": 2298, "text": "aayushwas1 week ago" }, { "code": null, "e": 2332, "s": 2318, "text": "0.78/1.95 C++" }, { "code": null, "e": 3105, "s": 2332, "text": "//aretreessame checks if two trees are same\n\tbool aretreessame(Node* t, Node* s){\n if(t==NULL&&s!=NULL || t!=NULL&&s==NULL) \t\t\t\t\t\t return false;\n if(t==NULL&&s==NULL) return true;\n if(t->data!=s->data) return false;\n bool a = aretreessame(t->left,s->left);\n bool b = aretreessame(t->right,s->right);\n \n return a&&b;\n }\n// checks if s subtree exists in T \n bool isSubTree(Node* T, Node* S) \n {\n if(T==NULL&&S!=NULL || T!=NULL&&S==NULL) return false;\n if(T==NULL&&S==NULL) return true;\n \n if(T->data==S->data&&aretreessame(T,S)==true){\n return true;\n }\n bool l = isSubTree(T->left,S);\n bool r = isSubTree(T->right,S);\n return l||r;\n \n }" }, { "code": null, "e": 3108, "s": 3105, "text": "+1" }, { "code": null, "e": 3131, "s": 3108, "text": "tarunkanade2 weeks ago" }, { "code": null, "e": 3174, "s": 3131, "text": "0.69/1.94 Java O(n), O(h) with explanation" }, { "code": null, "e": 5089, "s": 3174, "text": "public static boolean isSubtree(Node T, Node S) {\n // add code here.\n if(T == null){\n return false;\n }\n \n if(T.data == S.data){\n // 3\n // / \\\n // 3 5\n // / \\\n // 4 6 for eg: this is \"T\"\n // and we want to find:\n // 3\n // / \\\n // 4 6\n // As here 3 is present 2 times in T, and \"S\" is the subtree with\n // root as 3 which is the later one (in T) we can see from the visualization\n // so in such conditions if we simply return checkIfSame(T, S)\n // then our code will not check subsequent subtrees after the first\n // encounter with 3 (in T) and will return false as a result which is wrong\n // So for keep searching the subtrees we are again checking if \n // checkIfSame(T, S) == true then only return (true) otherwise keep searching\n if(checkIfSame(T, S)){\n return true;\n }\n }\n \n if(isSubtree(T.left, S) == true || isSubtree(T.right, S) == true){\n return true;\n }\n else{\n return false;\n }\n }\n \n // method for checking if 2 trees are identical\n private static boolean checkIfSame(Node root1, Node root2){\n if(root1 == null && root2 == null){\n return true;\n }\n else if((root1 == null && root2 != null) || (root1 != null && root2 == null)){\n return false;\n }\n else if(root1.data != root2.data){\n return false;\n }\n else{\n if(checkIfSame(root1.left, root2.left) == true && \n checkIfSame(root1.right, root2.right) == true){\n return true;\n }\n else{\n return false;\n }\n }\n }" }, { "code": null, "e": 5092, "s": 5089, "text": "+3" }, { "code": null, "e": 5118, "s": 5092, "text": "akashkhurana283 weeks ago" }, { "code": null, "e": 5132, "s": 5118, "text": "JAVA SOLUTION" }, { "code": null, "e": 5860, "s": 5132, "text": "class Solution { public static boolean check(Node root,Node subroot) { if(root==null && subroot==null) { return true; } if(root==null || subroot==null) { return false; } if(root.data==subroot.data) { return check(root.left,subroot.left) && check(root.right,subroot.right); } return false; } public static boolean isSubtree(Node T, Node S) { // add code here. if(S==null) { return true; } if(T==null) { return false; } if(T.data==S.data) { if(check(T,S)) { return true; } } return isSubtree(T.left,S) || isSubtree(T.right,S); }}" }, { "code": null, "e": 5862, "s": 5860, "text": "0" }, { "code": null, "e": 5884, "s": 5862, "text": "mohit negi3 weeks ago" }, { "code": null, "e": 6601, "s": 5884, "text": "c++ simple solution O(N) int checkSub(Node *t,Node *s) { if(t==NULL && s==NULL) return 1; if(!t||!s) return 0; if(t->data!=s->data) return 0; else { int a=checkSub(t->left,s->left); int b=checkSub(t->right,s->right); return a&b; } } void check(Node* t, Node* s,int &is) { if(t==NULL) return; else if(!is) { if(t->data==s->data) { is= checkSub(t,s); if(is) return; } check(t->left,s,is); check(t->right,s,is); } } bool isSubTree(Node* T, Node* S) { int is=0; check(T,S,is); return is; }" }, { "code": null, "e": 6603, "s": 6601, "text": "0" }, { "code": null, "e": 6630, "s": 6603, "text": "himanshujain4573 weeks ago" }, { "code": null, "e": 6664, "s": 6630, "text": "No rocket Science:Simple Solution" }, { "code": null, "e": 7501, "s": 6664, "text": "class Solution { static void storeRoot(Node r,Node s, ArrayList<Node>ans){ if(r==null)return ; if(r.data==s.data) ans.add(r); storeRoot(r.left,s,ans); storeRoot(r.right,s,ans); } static boolean check(Node r,Node s){ if(r==null&&s==null)return true; if(r==null &&s!=null)return false; if(r!=null&&s==null)return false; if(r.data!=s.data)return false; if(check(r.left,s.left)&&check(r.right,s.right))return true; return false; } public static boolean isSubtree(Node T, Node S) { ArrayList<Node>ans=new ArrayList<>(); if(T==null&&S==null)return true; if(T==null&&S!=null)return false; if(T!=null &&S==null)return true; storeRoot(T,S,ans); for(Node e:ans){ if(check(e,S)) return true; } return false; }}" }, { "code": null, "e": 7503, "s": 7501, "text": "0" }, { "code": null, "e": 7535, "s": 7503, "text": "nikhilchakravarthy091 month ago" }, { "code": null, "e": 8354, "s": 7535, "text": "void findSubTreeNode(Node* t, Node* s,vector<Node*>& temp){\n if(t==NULL) return;\n if(t->data == s->data) temp.push_back(t);\n findSubTreeNode(t->left,s,temp);\n findSubTreeNode(t->right,s,temp);\n }\n bool checkSubTree(Node* sub, Node* s){\n if(s==NULL && sub==NULL) return true;\n if((sub==NULL && s!=NULL) || (sub!=NULL && s==NULL))return false;\n if(sub->data == s->data){\n return (checkSubTree(sub->left,s->left) && checkSubTree(sub->right,s->right)); \n }\n return false;\n }\n bool isSubTree(Node* T, Node* S) \n {\n Node* sub=NULL;\n vector<Node*> temp;\n findSubTreeNode(T,S,temp);\n \n for(int i=0;i<temp.size();i++)\n if (checkSubTree(temp[i],S)) return true;\n return false;\n }" }, { "code": null, "e": 8356, "s": 8354, "text": "0" }, { "code": null, "e": 8381, "s": 8356, "text": "harrypotter02 months ago" }, { "code": null, "e": 8576, "s": 8381, "text": " def isSubTree(self, s, t):\n def convert(p):\n return \"^\" + str(p.data) + \"#\" + convert(p.left) + convert(p.right) if p else \"$\"\n \n return convert(t) in convert(s)\n" }, { "code": null, "e": 8578, "s": 8576, "text": "0" }, { "code": null, "e": 8614, "s": 8578, "text": "adityapratapsingh0820172 months ago" }, { "code": null, "e": 8648, "s": 8614, "text": "python solution not accepted why?" }, { "code": null, "e": 9063, "s": 8648, "text": "class Solution:\n def isSubTree(self, T, S):\n # Code here\n if not T:\n return False\n if not S:\n return True\n if mirror(T,S):\n return True\n return (self.isSubTree(T.left,S) or self.isSubTree(T.right,S))\n\n\ndef mirror(t,s):\n if not s or not t:\n return t==s\n return (t.data==s.data) and mirror(t.left,s.left) and mirror(t.right,s.right)" }, { "code": null, "e": 9209, "s": 9063, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 9245, "s": 9209, "text": " Login to access your submissions. " }, { "code": null, "e": 9255, "s": 9245, "text": "\nProblem\n" }, { "code": null, "e": 9265, "s": 9255, "text": "\nContest\n" }, { "code": null, "e": 9328, "s": 9265, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9476, "s": 9328, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9684, "s": 9476, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9790, "s": 9684, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
stat() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint int stat(const char *path, struct stat *buf); int fstat(int filedes, struct stat *buf); int lstat(const char *path, struct stat *buf); These functions return information about a file. No permissions are required on the file itself, but — in the case of stat() and lstat() — execute (search) permission is required on all of the directories in path that lead to the file. stat() stats the file pointed to by path and fills in buf. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor filedes. All of these system calls return a stat structure, which contains the following fields: struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for filesystem I/O */ blkcnt_t st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ }; The st_dev field describes the device on which this file resides. The st_rdev field describes the device that this file (inode) represents. The st_size field gives the size of the file (if it is a regular file or a symbolic link) in bytes. The size of a symlink is the length of the pathname it contains, without a trailing null byte. The st_blocks field indicates the number of blocks allocated to the file, 512-byte units. (This may be smaller than st_size/512, for example, when the file has holes.) The st_blksize field gives the "preferred" blocksize for efficient file system I/O. (Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.) Not all of the Linux filesystems implement all of the time fields. Some file system types allow mounting in such a way that file accesses do not cause an update of the st_atime field. (See ‘noatime’ in mount(8).) The field st_atime is changed by file accesses, e.g. by execve(2), mknod(2), pipe(2), utime(2) and read(2) (of more than zero bytes). Other routines, like mmap(2), may or may not update st_atime. The field st_mtime is changed by file modifications, e.g. by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes). Moreover, st_mtime of a directory is changed by the creation or deletion of files in that directory. The st_mtime field is not changed for changes in owner, group, hard link count, or mode. The field st_ctime is changed by writing or by setting inode information (i.e., owner, group, link count, mode, etc.). The following POSIX macros are defined to check the file type using the st_mode field: The following flags are defined for the st_mode field: The set-group-ID bit (S_ISGID) has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking. The ‘sticky’ bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by a privileged process. For most files under the /proc directory, stat() does not return the file size in the st_size field; instead the field is returned with the value 0. Use of the st_blocks and st_blksize fields may be less portable. (They were introduced in BSD. The interpretation differs between systems, and possibly on a single system when NFS mounts are involved.) POSIX does not describe the S_IFMT, S_IFSOCK, S_IFLNK, S_IFREG, S_IFBLK, S_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX bits, but instead demands the use of the macros S_ISDIR(), etc. The S_ISLNK and S_ISSOCK macros are not in POSIX.1-1996, but both are present in POSIX.1-2001; the former is from SVID 4, the latter from SUSv2. Unix V7 (and later systems) had S_IREAD, S_IWRITE, S_IEXEC, where POSIX prescribes the synonyms S_IRUSR, S_IWUSR, S_IXUSR. A sticky command appeared in Version 32V AT&T UNIX. access (2) access (2) chmod (2) chmod (2) chown (2) chown (2) fstatat (2) fstatat (2) readlink (2) readlink (2) utime (2) utime (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2458, "s": 2319, "text": "\nint stat(const char *path, struct stat *buf); \nint fstat(int filedes, struct stat *buf); \nint lstat(const char *path, struct stat *buf); " }, { "code": null, "e": 2696, "s": 2458, "text": "\nThese functions return information about a file.\nNo permissions are required on the file itself, but — in the case of\nstat() and\nlstat() —\nexecute (search) permission is required on all of the directories in\npath that lead to the file.\n" }, { "code": null, "e": 2757, "s": 2696, "text": "\nstat() stats the file pointed to by\npath and fills in\nbuf. " }, { "code": null, "e": 2896, "s": 2757, "text": "\nlstat() is identical to\nstat(), except that if\npath is a symbolic link, then the link itself is stat-ed,\nnot the file that it refers to.\n" }, { "code": null, "e": 3010, "s": 2896, "text": "\nfstat() is identical to\nstat(), except that the file to be stat-ed is specified by the file descriptor\nfiledes. " }, { "code": null, "e": 3100, "s": 3010, "text": "\nAll of these system calls return a\nstat structure, which contains the following fields:\n" }, { "code": null, "e": 3823, "s": 3102, "text": "struct stat {\n dev_t st_dev; /* ID of device containing file */\n ino_t st_ino; /* inode number */\n mode_t st_mode; /* protection */\n nlink_t st_nlink; /* number of hard links */\n uid_t st_uid; /* user ID of owner */\n gid_t st_gid; /* group ID of owner */\n dev_t st_rdev; /* device ID (if special file) */\n off_t st_size; /* total size, in bytes */\n blksize_t st_blksize; /* blocksize for filesystem I/O */\n blkcnt_t st_blocks; /* number of blocks allocated */\n time_t st_atime; /* time of last access */\n time_t st_mtime; /* time of last modification */\n time_t st_ctime; /* time of last status change */\n};\n" }, { "code": null, "e": 3891, "s": 3823, "text": "\nThe\nst_dev field describes the device on which this file resides.\n" }, { "code": null, "e": 3967, "s": 3891, "text": "\nThe\nst_rdev field describes the device that this file (inode) represents.\n" }, { "code": null, "e": 4164, "s": 3967, "text": "\nThe\nst_size field gives the size of the file (if it is a regular\nfile or a symbolic link) in bytes.\nThe size of a symlink is the length of the pathname\nit contains, without a trailing null byte.\n" }, { "code": null, "e": 4334, "s": 4164, "text": "\nThe\nst_blocks field indicates the number of blocks allocated to the file, 512-byte units.\n(This may be smaller than\nst_size/512, for example, when the file has holes.)\n" }, { "code": null, "e": 4504, "s": 4334, "text": "\nThe\nst_blksize field gives the \"preferred\" blocksize for efficient file system I/O.\n(Writing to a file in smaller chunks may cause\nan inefficient read-modify-rewrite.)\n" }, { "code": null, "e": 4719, "s": 4504, "text": "\nNot all of the Linux filesystems implement all of the time fields.\nSome file system types allow mounting in such a way that file\naccesses do not cause an update of the\nst_atime field. (See ‘noatime’ in\nmount(8).)\n" }, { "code": null, "e": 4917, "s": 4719, "text": "\nThe field\nst_atime is changed by file accesses, e.g. by\nexecve(2),\nmknod(2),\npipe(2),\nutime(2)\nand\nread(2)\n(of more than zero bytes). Other routines, like\nmmap(2),\nmay or may not update\nst_atime. " }, { "code": null, "e": 5242, "s": 4917, "text": "\nThe field\nst_mtime is changed by file modifications, e.g. by\nmknod(2),\ntruncate(2),\nutime(2)\nand\nwrite(2)\n(of more than zero bytes).\nMoreover,\nst_mtime of a directory is changed by the creation or deletion of files\nin that directory.\nThe\nst_mtime field is\nnot changed for changes in owner, group, hard link count, or mode.\n" }, { "code": null, "e": 5363, "s": 5242, "text": "\nThe field\nst_ctime is changed by writing or by setting inode information\n(i.e., owner, group, link count, mode, etc.).\n" }, { "code": null, "e": 5452, "s": 5363, "text": "\nThe following POSIX macros are defined to check the file type using the\nst_mode field:\n" }, { "code": null, "e": 5509, "s": 5452, "text": "\nThe following flags are defined for the\nst_mode field:\n" }, { "code": null, "e": 5966, "s": 5509, "text": "\nThe set-group-ID bit (S_ISGID) has several special uses.\nFor a directory it indicates that BSD semantics is to be used\nfor that directory: files created there inherit their group ID from\nthe directory, not from the effective group ID of the creating process,\nand directories created there will also get the S_ISGID bit set.\nFor a file that does not have the group execution bit (S_IXGRP) set,\nthe set-group-ID bit indicates mandatory file/record locking.\n" }, { "code": null, "e": 6163, "s": 5966, "text": "\nThe ‘sticky’ bit (S_ISVTX) on a directory means that a file\nin that directory can be renamed or deleted only by the owner\nof the file, by the owner of the directory, and by a privileged\nprocess.\n" }, { "code": null, "e": 6314, "s": 6163, "text": "\nFor most files under the\n/proc directory,\nstat() does not return the file size in the\nst_size field; instead the field is returned with the value 0.\n" }, { "code": null, "e": 6518, "s": 6314, "text": "\nUse of the\nst_blocks and\nst_blksize fields may be less portable. (They were introduced in BSD.\nThe interpretation differs between\nsystems, and possibly on a single system when NFS mounts are involved.)\n" }, { "code": null, "e": 6837, "s": 6518, "text": "\nPOSIX does not describe the S_IFMT, S_IFSOCK, S_IFLNK, S_IFREG, S_IFBLK,\nS_IFDIR, S_IFCHR, S_IFIFO, S_ISVTX bits, but instead demands the use of\nthe macros S_ISDIR(), etc.\nThe S_ISLNK and S_ISSOCK macros are not in\nPOSIX.1-1996, but both are present in POSIX.1-2001;\nthe former is from SVID 4, the latter from SUSv2.\n" }, { "code": null, "e": 6962, "s": 6837, "text": "\nUnix V7 (and later systems) had S_IREAD, S_IWRITE, S_IEXEC, where POSIX\nprescribes the synonyms S_IRUSR, S_IWUSR, S_IXUSR.\n" }, { "code": null, "e": 7018, "s": 6964, "text": "\nA sticky command appeared in Version 32V AT&T UNIX.\n" }, { "code": null, "e": 7029, "s": 7018, "text": "access (2)" }, { "code": null, "e": 7040, "s": 7029, "text": "access (2)" }, { "code": null, "e": 7050, "s": 7040, "text": "chmod (2)" }, { "code": null, "e": 7060, "s": 7050, "text": "chmod (2)" }, { "code": null, "e": 7070, "s": 7060, "text": "chown (2)" }, { "code": null, "e": 7080, "s": 7070, "text": "chown (2)" }, { "code": null, "e": 7092, "s": 7080, "text": "fstatat (2)" }, { "code": null, "e": 7104, "s": 7092, "text": "fstatat (2)" }, { "code": null, "e": 7117, "s": 7104, "text": "readlink (2)" }, { "code": null, "e": 7130, "s": 7117, "text": "readlink (2)" }, { "code": null, "e": 7140, "s": 7130, "text": "utime (2)" }, { "code": null, "e": 7150, "s": 7140, "text": "utime (2)" }, { "code": null, "e": 7167, "s": 7150, "text": "\nAdvertisements\n" }, { "code": null, "e": 7202, "s": 7167, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 7230, "s": 7202, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7264, "s": 7230, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7281, "s": 7264, "text": " Frahaan Hussain" }, { "code": null, "e": 7314, "s": 7281, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 7325, "s": 7314, "text": " Pradeep D" }, { "code": null, "e": 7360, "s": 7325, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7376, "s": 7360, "text": " Musab Zayadneh" }, { "code": null, "e": 7409, "s": 7376, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 7421, "s": 7409, "text": " GUHARAJANM" }, { "code": null, "e": 7453, "s": 7421, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 7461, "s": 7453, "text": " Uplatz" }, { "code": null, "e": 7468, "s": 7461, "text": " Print" }, { "code": null, "e": 7479, "s": 7468, "text": " Add Notes" } ]
How to track the color in OpenCV using C++?
Color tracking is similar to color detection. For tracking purpose, we added extra few lines to calculate the area of the detected object and then track the current position of that area and finally used line() function of OpenCV to show the object's path of motion. The following program demonstrates how to track the color in OpenCV using C++. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main(int argc, char** argv) { VideoCapture video_load(0);//capturing video from default camera// namedWindow("Adjust");//declaring window to show the image// int Hue_Low= 0;//lower range of hue// int Hue_high = 22;//upper range of hue// int Sat_Low =99;//lower range of saturation// int Sat_high = 255;//upper range of saturation// int Val_Low = 0;//lower range of value// int Val_high = 255;//upper range of value// createTrackbar("LowH", "Adjust", &Hue_Low, 179);//track-bar for min hue// createTrackbar("HighH","Adjust", &Hue_high, 179);//track-bar for max hue// createTrackbar("LowS", "Adjust", &Sat_Low, 255);//track-bar for min saturation// createTrackbar("HighS", "Adjust", &Sat_high, 255);// track-bar for max saturation// createTrackbar("LowV", "Adjust", &Val_Low,255);//track-bar for min value// createTrackbar("HighV", "Adjust", &Val_high, 255);// track - bar for max value// int Horizontal_Last = -1;//initial horizontal position// int vertical_Last = -1;//initial vertical position// Mat temp;//declaring a matrix to load frames from video stream// video_load.read(temp);//loading frames from video stream// Mat track_motion = Mat::zeros(temp.size(), CV_8UC3);//creating black matrix for detection// while (true) { Mat actual_Image;//declaring a ,atrix for actual image// bool temp_load= video_load.read(actual_Image);//loading frames from video to the matrix// Mat converted_to_HSV;//declaring a matrix to store converted image// cvtColor(actual_Image, converted_to_HSV, COLOR_BGR2HSV);//converting BGR image to HSV// Mat adjusted_frame;//declaring a matrix to detected color// inRange(converted_to_HSV,Scalar(Hue_Low, Sat_Low, Val_Low), Scalar(Hue_high, Sat_high, Val_high), adjusted_frame);//applying change of values of track-bars// erode(adjusted_frame,adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small objects from foreground// dilate(adjusted_frame, adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small object from foreground// dilate(adjusted_frame, adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground// erode(adjusted_frame, adjusted_frame, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground// Moments detecting_object = moments(adjusted_frame);//creating an object from detected color frame// double vertical_moment = detecting_object.m01;//getting value of vertical position// double horizontal_moment = detecting_object.m10;//getting value of horizontal position// double tracking_area = detecting_object.m00;//getting area of the object// if (tracking_area > 10000){ //when area of the object is greater than 10000 pixels// int posX = horizontal_moment / tracking_area;//calculate the horizontal position of the object// int posY = vertical_moment / tracking_area;//calculate the vertical position of the object// if (Horizontal_Last >= 0 && vertical_Last >= 0 && posX >= 0 && posY >= 0){ //when the detected object moves// line(track_motion, Point(posX, posY), Point(Horizontal_Last, vertical_Last), Scalar(0, 0, 255), 2);//draw lines of red color on the path of detected object;s motion// } Horizontal_Last = posX;//getting new horizontal position// vertical_Last = posY;// getting new vertical position value// } imshow("Detected_Object", adjusted_frame);//showing detected object// actual_Image = actual_Image + track_motion;//drawing continuous line in original video frames// imshow("Actual",actual_Image);//showing original video// cout << "position of the object is:" << Horizontal_Last << "," << vertical_Last << endl;//showing tracked co-ordinated values// if(waitKey(30)==27){ //if esc is pressed loop will break// cout << "esc key is pressed by user" << endl; break; } } return 0; }
[ { "code": null, "e": 1329, "s": 1062, "text": "Color tracking is similar to color detection. For tracking purpose, we added extra few lines to calculate the area of the detected object and then track the current position of that area and finally used line() function of OpenCV to show the object's path of motion." }, { "code": null, "e": 1408, "s": 1329, "text": "The following program demonstrates how to track the color in OpenCV using C++." }, { "code": null, "e": 5722, "s": 1408, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace std;\nusing namespace cv;\nint main(int argc, char** argv) {\n VideoCapture video_load(0);//capturing video from default camera//\n namedWindow(\"Adjust\");//declaring window to show the image//\n int Hue_Low= 0;//lower range of hue//\n int Hue_high = 22;//upper range of hue//\n int Sat_Low =99;//lower range of saturation//\n int Sat_high = 255;//upper range of saturation//\n int Val_Low = 0;//lower range of value//\n int Val_high = 255;//upper range of value//\n createTrackbar(\"LowH\", \"Adjust\", &Hue_Low, 179);//track-bar for min hue//\n createTrackbar(\"HighH\",\"Adjust\", &Hue_high, 179);//track-bar for max hue//\n createTrackbar(\"LowS\", \"Adjust\", &Sat_Low, 255);//track-bar for min saturation//\n createTrackbar(\"HighS\", \"Adjust\", &Sat_high, 255);// track-bar for max saturation//\n createTrackbar(\"LowV\", \"Adjust\", &Val_Low,255);//track-bar for min value//\n createTrackbar(\"HighV\", \"Adjust\", &Val_high, 255);// track - bar for max value// \n int Horizontal_Last = -1;//initial horizontal position//\n int vertical_Last = -1;//initial vertical position//\n Mat temp;//declaring a matrix to load frames from video stream//\n video_load.read(temp);//loading frames from video stream//\n Mat track_motion = Mat::zeros(temp.size(), CV_8UC3);//creating black matrix for detection//\n while (true) {\n Mat actual_Image;//declaring a ,atrix for actual image//\n bool temp_load= video_load.read(actual_Image);//loading frames from video to the matrix//\n Mat converted_to_HSV;//declaring a matrix to store converted image//\n cvtColor(actual_Image, converted_to_HSV, COLOR_BGR2HSV);//converting BGR image to HSV//\n Mat adjusted_frame;//declaring a matrix to detected color//\n inRange(converted_to_HSV,Scalar(Hue_Low, Sat_Low, Val_Low),\n Scalar(Hue_high, Sat_high, Val_high), adjusted_frame);//applying change of values of track-bars// \n erode(adjusted_frame,adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small objects from foreground//\n dilate(adjusted_frame, adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological opening for removing small object from foreground//\n dilate(adjusted_frame, adjusted_frame,getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground//\n erode(adjusted_frame, adjusted_frame, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));//morphological closing for filling up small holes in foreground//\n Moments detecting_object = moments(adjusted_frame);//creating an object from detected color frame//\n double vertical_moment = detecting_object.m01;//getting value of vertical position//\n double horizontal_moment = detecting_object.m10;//getting value of horizontal position//\n double tracking_area = detecting_object.m00;//getting area of the object//\n if (tracking_area > 10000){ //when area of the object is greater than 10000 pixels//\n int posX = horizontal_moment / tracking_area;//calculate the horizontal position of the object//\n int posY = vertical_moment / tracking_area;//calculate the vertical position of the object//\n if (Horizontal_Last >= 0 && vertical_Last >= 0 && posX >= 0 && posY >= 0){ //when the detected object moves//\n line(track_motion, Point(posX, posY), Point(Horizontal_Last, vertical_Last), Scalar(0, 0, 255), 2);//draw lines of red color on the path of detected object;s motion//\n }\n Horizontal_Last = posX;//getting new horizontal position//\n vertical_Last = posY;// getting new vertical position value//\n }\n imshow(\"Detected_Object\", adjusted_frame);//showing detected object//\n actual_Image = actual_Image + track_motion;//drawing continuous line in original video frames//\n imshow(\"Actual\",actual_Image);//showing original video//\n cout << \"position of the object is:\" << Horizontal_Last << \",\" << vertical_Last << endl;//showing tracked co-ordinated values//\n if(waitKey(30)==27){ //if esc is pressed loop will break//\n cout << \"esc key is pressed by user\" << endl;\n break;\n }\n }\n return 0;\n}" } ]
Predicting Fake job postings — Part 2 (Predictive Analysis) | by Sharad Jain | Towards Data Science
In Part 1 of this two-part series, I did a detailed exploratory analysis of how fake job postings are different from genuine ones. Below is a link to Part 1 and I would highly recommend you read that first before moving forward! towardsdatascience.com Fake job postings were mostly targeted towards Full-time roles, which had a minimum requirement of a Bachelor’s degree and a Mid-Senior level work experience.These postings were mainly directed towards individuals seeking jobs in the technology sector.45% of these postings gave jobs to candidates without even a single question asked (A vital indicator of a fake posting).The postings in which had no screening process were mostly for Entry level jobs.The fake postings were mostly in the United States, followed by the United Kingdom, Canada, and India.After creating a word cloud, it was found that the job postings had similar behavioral content, but the genuine ones were more specific to the role. Fake job postings were mostly targeted towards Full-time roles, which had a minimum requirement of a Bachelor’s degree and a Mid-Senior level work experience. These postings were mainly directed towards individuals seeking jobs in the technology sector. 45% of these postings gave jobs to candidates without even a single question asked (A vital indicator of a fake posting). The postings in which had no screening process were mostly for Entry level jobs. The fake postings were mostly in the United States, followed by the United Kingdom, Canada, and India. After creating a word cloud, it was found that the job postings had similar behavioral content, but the genuine ones were more specific to the role. Based on these insights, we now know that it is possible to find out which job postings are fake and which are not. But in these unprecedented times, where hundreds of individuals are being laid off every day, job seekers are desperate. The scammers are using this desperation to put out more and more fake job advertisements. Hence, we need more of these algorithms and tools being used on job search websites like LinkedIn, Glassdoor and Indeed so that these fake postings are filtered out, and the job-seekers only see the genuine ones. In the following sections, I will be using machine learning techniques on the data used last time and predict the fake job postings from the genuine ones. So, the data we have used so far in this analysis was compiled by the University of the Aegean, Laboratory of Information & Communications Systems Security (http://emscad.samos.aegean.gr/). This dataset contains 800 fak job descriptions. I have defined the variables which are a part of the dataset initially in Part 1 of the series. I will be mentioning which variables out of the complete list. I will be using for this analysis in the next section. I imported the data on the Jupyter Notebook on my system and worked on Python 3. Since I want this part to be more on insights than code, I have not attached any code gists here but anyone interested in looking at the data cleaning code, feel free to check out my GitHub repository — https://github.com/sharad18/Fake_Job_Posting The initial dataset contained 18,000 postings. After cleaning, the new data has ~11,000 postings. The subset of variables which I will be using for the predictive analysis will be — Title: Title of the job posting.Description: Job description + Company profile + RequirementsTelecommuting: Tru for telecommuting positions.Has_company_logo: True if the company logo is present.Has_questions: True if screening questions are present.Employment_type: Full-time, Part-time, Contract, etc.Required_experience: Executive, Entry-level, Intern, etc.Required_education: Doctorate, Master’s degree, Bachelor’s, etc.Industry: Automotive, IT, Health care, Real estate, etc.Function: Consulting, Engineering, Research, Sales, etc.Fraudulent (Target Variable): 1 if fake posting else 0.City: The city mentioned in the job posting.Country_name: Name of the country mentioned in the job posting. Title: Title of the job posting. Description: Job description + Company profile + Requirements Telecommuting: Tru for telecommuting positions. Has_company_logo: True if the company logo is present. Has_questions: True if screening questions are present. Employment_type: Full-time, Part-time, Contract, etc. Required_experience: Executive, Entry-level, Intern, etc. Required_education: Doctorate, Master’s degree, Bachelor’s, etc. Industry: Automotive, IT, Health care, Real estate, etc. Function: Consulting, Engineering, Research, Sales, etc. Fraudulent (Target Variable): 1 if fake posting else 0. City: The city mentioned in the job posting. Country_name: Name of the country mentioned in the job posting. Let’s start working on this cleaned data! I imported the following libraries for now which are the essential libraries anyone needs to perform analysis in Python, import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport numpy as nppd.set_option('display.max_columns', None) Let’s look at the data, df = pd.read_csv('Clean_data.csv')df.head() Now, we try to study the column ‘description’ in detail. From the cleaned data file I imported, the ‘description’ column is the combination of ‘description’ + ‘requirements’ and ‘company profile.’ An example of how the data in ‘description’ looks like — Next, we will try to look at the Top 20 most common words being used in both fake postings as well as good job postings. import spacynlp = spacy.load('en_core_web_lg')import base64import stringimport refrom collections import Counterfrom nltk.corpus import stopwordsstopwords = stopwords.words('english')punctuations = string.punctuationdef cleanup_text(docs, logging = False): texts = [] for doc in docs: doc = nlp(doc, disable = ['parser', 'ner']) tokens = [tok.lemma_.lower().strip() for tok in doc if tok.lemma_ != '-PRON-'] tokens = [tok for tok in tokens if tok not in stopwords and tok not in punctuations] tokens = ' '.join(tokens) texts.append(tokens)return pd.Series(texts) For fraudulent job postings, Fraud_1 = [text for text in df1[df1['fraudulent'] == 1]['description']]Fraud_1_clean = cleanup_text(Fraud_1)Fraud_1_clean = ' '.join(Fraud_1_clean).split()Fraud_1_counts = Counter(Fraud_1_clean)Fraud_1_common_words = [word[0] for word in Fraud_1_counts.most_common(20)]Fraud_1_common_counts = [word[1] for word in Fraud_1_counts.most_common(20)]fig = plt.figure(figsize = (20, 10))pal = sns.color_palette("cubehelix", 20)sns.barplot(x = Fraud_1_common_words, y = Fraud_1_common_counts, palette=pal)plt.title('Most Common Words used in Fake job postings')plt.ylabel("Frequency of words")plt.xlabel("Words")plt.show() For genuine job postings, Fraud_0 = [text for text in df1[df1['fraudulent'] == 0]['description']]Fraud_0_clean = cleanup_text(Fraud_0)Fraud_0_clean = ' '.join(Fraud_0_clean).split()Fraud_0_counts = Counter(Fraud_0_clean)Fraud_0_common_words = [word[0] for word in Fraud_0_counts.most_common(20)]Fraud_0_common_counts = [word[1] for word in Fraud_0_counts.most_common(20)]fig = plt.figure(figsize = (20, 10))pal = sns.color_palette("cubehelix", 20)sns.barplot(x = Fraud_0_common_words, y = Fraud_0_common_counts, palette=pal)plt.title('Most Common Words used in Genuine job postings')plt.ylabel("Frequency of words")plt.xlabel("Words")plt.show() In both the figures above, most frequent words are almost alike, and it is tough to differentiate between the two. Hence, the variable ‘description’ alone cannot help us with predicting, and therefore the complete set of variables is significant. One more noteworthy thing to point out is, when an individual sees a job posting on the internet, these additional features which I have mentioned in the ‘Data Cleaning’ section are not directly provided. These variables have only been acquired after a job posting was reported as fraudulent. In such a case, it becomes imperative that if one finds such a fake posting, they inform the concerned authorities as well as to other job-seekers in their network. Before splitting the data, we need to make some final changes to the data, after which we will be splitting it. The ‘description’ column had to be cleaned into tokens. This is done with the help of spacy and nltk libraries. In the following piece of code, the ‘description’ column has been converted into tokens, and those tokens have been used to create one hot column using sklearn’s CountVectorizer. Also, categorical columns like ‘employment_type,’ ‘required_eduacation,’ ‘required_experience,’ ‘industry,’ and ‘function’ have been converted into one-hot vectors. STOPLIST = set(stopwords.words('english') + list(ENGLISH_STOP_WORDS))SYMBOLS = " ".join(string.punctuation).split(" ")def tokenizetext(sample): text = sample.strip().replace("\n", " ").replace("\r", " ") text = text.lower() tokens = parser(text) lemmas = [] for tok in tokens: lemmas.append(tok.lemma_.lower().strip() if tok.lemma_ != "-PRON-" else tok.lower_) tokens = lemmas tokens = [tok for tok in tokens if tok not in STOPLIST] tokens = [tok for tok in tokens if tok not in SYMBOLS] return tokensvectorizer = CountVectorizer(tokenizer = tokenizetext, ngram_range = (1,3), min_df = 0.06)vectorizer_features = vectorizer.fit_transform(df1['description'])vectorized_df = pd.DataFrame(vectorizer_features.todense(), columns = vectorizer.get_feature_names())df_final = pd.concat([df1, vectorized_df], axis = 1)df_final.drop('description', axis = 1, inplace = True)df_final.dropna(inplace=True)columns_to_1_hot = ['employment_type', 'required_experience', 'required_education', 'industry', 'function']for column in columns_to_1_hot: encoded = pd.get_dummies(df_final[column]) df_final = pd.concat([df_final, encoded], axis = 1)columns_to_1_hot += ['title', 'city', 'country_name']df_final.drop(columns_to_1_hot, axis = 1, inplace = True) Next, we split the data into train and test — target = df_vectorized['fraudulent']features = df_vectorized.drop('fraudulent', axis = 1)X_train, X_test, y_train, y_test = train_test_split(features, target, test_size = 0.1, stratify = target, random_state=42)print (X_train.shape)print (y_train.shape)print (X_test.shape)print (y_test.shape) We get the following output — (10144, 857)(10144,)(1128, 857)(1128,) We have everything place now. Let’s start with machine learning! Libraries we will use in subsequent sections — from sklearn.model_selection import GridSearchCVfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNearestNeighborsfrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.neural_network import MLPClassifierfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score log_reg = LogisticRegression()c_values = [0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000]penalty_options = ['l1', 'l2']param_grid = dict(C = c_values, penalty = penalty_options)grid_tfidf = GridSearchCV(log_reg, param_grid = param_grid, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose=1)grid.fit(X_train, y_train)log_reg_pred = grid.predict(X_test)print (roc_auc_score(y_test, log_reg_pred))print (classification_report(y_test, log_reg_pred)) We get the following results — Out of Sample roc_auc score = 0.7795 and for classification report we get — Predictions with the most basic model, Logistic Regression, gives us a 0.7795 ROC-AUC score, which is a good score given the imbalance of the data. In subsequent sections, we’ll see more sophisticated models. knn = KNeighborsClassifier()k_range = list(np.arange(2, 23, 2))param_grid_knn = dict(n_neighbors = k_range)print (param_grid_knn)grid_knn = GridSearchCV(knn, param_grid_knn, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 1)grid_knn.fit(X_train, y_train)knn_pred = grid_knn.predict(X_test)print (roc_auc_score(y_test, knn_pred))print (classification_report(y_test, knn_pred)) Out of Sample ROC-AUC score for KNN — 0.5995. For classification report we get — From the image on the left, we can see that KNN performed very poorly as compared to Logistic Regression. svc = SVC()kernel = ['linear', 'rbf']param_grid_knn = dict(kernel = kernel)print (param_grid_knn)grid_svc = GridSearchCV(svc, param_grid_knn, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 2)grid_svc.fit(X_train, y_train)svc_pred = grid_svc.predict(X_test)print (roc_auc_score(y_test, svc_pred))print (classification_report(y_test, svc_pred)) The out of sample score reported here is 0.8195 ~ 0.82. The classification report is as follows — SVC has the best score yet with 0.82, which is significantly better than the last two methods. rf = RandomForestClassifier()n_estimators_range = [1, 2, 4, 8, 16, 32, 64, 100, 200]param_grid_rf = dict(n_estimators = n_estimators_range)grid_rf = GridSearchCV(rf, param_grid_rf, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 1)grid_rf.fit(X_train, y_train)print (grid_rf.best_score_)print (grid_rf.best_params_)rf_pred = grid_rf.predict(X_test)print (roc_auc_score(y_test, rf_pred))print (classification_report(y_test, rf_pred)) For the Random Forest model, the ROC-AUC score reported is 0.74. The classification report is as follows — To be honest, I expected Random Forest to perform better than SVC, but so far, SVC has the best result. mlp = MLPClassifier(solver = 'sgd', activation = 'relu', hidden_layer_sizes = (100, 50, 30), max_iter = 1000)mlp.fit(X_train, y_train)mlp_pred = mlp.predict(X_test)print (roc_auc_score(y_test, mlp_pred))print (classification_report(y_test, mlp_pred)) ROC-AUC score, in this case, is 0.7786. And the classification report — The MLP Classifier with ‘sgd’ solver performs slightly better than the Random Forest model but is still worse than what SVC reported. mlp = MLPClassifier(solver = 'adam', activation = 'relu', hidden_layer_sizes = (100, 50, 30), max_iter = 1000)mlp.fit(X_train, y_train)mlp_pred = mlp.predict(X_test)print (roc_auc_score(y_test, mlp_pred))print (classification_report(y_test, mlp_pred)) The out of sample ROC-AUC score reported for this model is 0.8595 ~ 0.86. The classification report is as follows — This is the highest score yet reported, and based on this model, we will be able to predict correctly if a job posting is fake 86% of the time. From the above image, we can see that Sklearn’s MLP Classifier based on Neural Network with ‘adam’ optimizer performs the best followed by the same model with ‘sgd’ solver and Support Vector Machine Classifier. So based on MLP Classifier’s out of sample performance metric, ROC-AUC score, we can safely say that we can predict if a job posting is fake or not 86% of the time. This predictive analysis is very much useful for job search websites like LinkedIn and Glassdoor, which can help them filter such fak job postings. Currently, we live in times which none of us ever expected. Coronavirus has not only brought health emergencies to nations but also accelerated an impending recession. Many employees are being laid off every day, and the demand for jobs is way higher than the number of posts available in the market. Through this series of articles, I have tried to put forward an issue that is creeping through the job market. Turmoil and chaos are the perfect proponents for scammers, and currently, cyber scam attacks are on the rise. In the previous part, I provided a detailed analysis of how to differentiate between a fake posting and a genuine one and what are the characteristics of a fraudulent job posting. In this part, I have provided a detailed analysis of how we can apply machine learning to predict the occurrences of such fake postings. As I have mentioned throughout the two parts, rather than any model or analysis, it is the responsibility of us as users of the internet and job-seekers to let the authorities and our network know if we come across such a fake job posting. Thank you for reading the two parts. I wish everyone a great day ahead & please maintain social distance so that we can get over such times faster and more efficiently! Working on this project was a great learning experience for me. Hopefully, you all found it helpful and informative. The entire code for this article is there on my GitHub repository for this analysis — https://github.com/sharad18/Fake_Job_Posting. I would love to hear your feedback in the comments section. You can also connect with me on LinkedIn — https://www.linkedin.com/in/sharad-jain/
[ { "code": null, "e": 401, "s": 172, "text": "In Part 1 of this two-part series, I did a detailed exploratory analysis of how fake job postings are different from genuine ones. Below is a link to Part 1 and I would highly recommend you read that first before moving forward!" }, { "code": null, "e": 424, "s": 401, "text": "towardsdatascience.com" }, { "code": null, "e": 1128, "s": 424, "text": "Fake job postings were mostly targeted towards Full-time roles, which had a minimum requirement of a Bachelor’s degree and a Mid-Senior level work experience.These postings were mainly directed towards individuals seeking jobs in the technology sector.45% of these postings gave jobs to candidates without even a single question asked (A vital indicator of a fake posting).The postings in which had no screening process were mostly for Entry level jobs.The fake postings were mostly in the United States, followed by the United Kingdom, Canada, and India.After creating a word cloud, it was found that the job postings had similar behavioral content, but the genuine ones were more specific to the role." }, { "code": null, "e": 1287, "s": 1128, "text": "Fake job postings were mostly targeted towards Full-time roles, which had a minimum requirement of a Bachelor’s degree and a Mid-Senior level work experience." }, { "code": null, "e": 1382, "s": 1287, "text": "These postings were mainly directed towards individuals seeking jobs in the technology sector." }, { "code": null, "e": 1504, "s": 1382, "text": "45% of these postings gave jobs to candidates without even a single question asked (A vital indicator of a fake posting)." }, { "code": null, "e": 1585, "s": 1504, "text": "The postings in which had no screening process were mostly for Entry level jobs." }, { "code": null, "e": 1688, "s": 1585, "text": "The fake postings were mostly in the United States, followed by the United Kingdom, Canada, and India." }, { "code": null, "e": 1837, "s": 1688, "text": "After creating a word cloud, it was found that the job postings had similar behavioral content, but the genuine ones were more specific to the role." }, { "code": null, "e": 2377, "s": 1837, "text": "Based on these insights, we now know that it is possible to find out which job postings are fake and which are not. But in these unprecedented times, where hundreds of individuals are being laid off every day, job seekers are desperate. The scammers are using this desperation to put out more and more fake job advertisements. Hence, we need more of these algorithms and tools being used on job search websites like LinkedIn, Glassdoor and Indeed so that these fake postings are filtered out, and the job-seekers only see the genuine ones." }, { "code": null, "e": 2532, "s": 2377, "text": "In the following sections, I will be using machine learning techniques on the data used last time and predict the fake job postings from the genuine ones." }, { "code": null, "e": 2770, "s": 2532, "text": "So, the data we have used so far in this analysis was compiled by the University of the Aegean, Laboratory of Information & Communications Systems Security (http://emscad.samos.aegean.gr/). This dataset contains 800 fak job descriptions." }, { "code": null, "e": 2984, "s": 2770, "text": "I have defined the variables which are a part of the dataset initially in Part 1 of the series. I will be mentioning which variables out of the complete list. I will be using for this analysis in the next section." }, { "code": null, "e": 3313, "s": 2984, "text": "I imported the data on the Jupyter Notebook on my system and worked on Python 3. Since I want this part to be more on insights than code, I have not attached any code gists here but anyone interested in looking at the data cleaning code, feel free to check out my GitHub repository — https://github.com/sharad18/Fake_Job_Posting" }, { "code": null, "e": 3411, "s": 3313, "text": "The initial dataset contained 18,000 postings. After cleaning, the new data has ~11,000 postings." }, { "code": null, "e": 3495, "s": 3411, "text": "The subset of variables which I will be using for the predictive analysis will be —" }, { "code": null, "e": 4193, "s": 3495, "text": "Title: Title of the job posting.Description: Job description + Company profile + RequirementsTelecommuting: Tru for telecommuting positions.Has_company_logo: True if the company logo is present.Has_questions: True if screening questions are present.Employment_type: Full-time, Part-time, Contract, etc.Required_experience: Executive, Entry-level, Intern, etc.Required_education: Doctorate, Master’s degree, Bachelor’s, etc.Industry: Automotive, IT, Health care, Real estate, etc.Function: Consulting, Engineering, Research, Sales, etc.Fraudulent (Target Variable): 1 if fake posting else 0.City: The city mentioned in the job posting.Country_name: Name of the country mentioned in the job posting." }, { "code": null, "e": 4226, "s": 4193, "text": "Title: Title of the job posting." }, { "code": null, "e": 4288, "s": 4226, "text": "Description: Job description + Company profile + Requirements" }, { "code": null, "e": 4336, "s": 4288, "text": "Telecommuting: Tru for telecommuting positions." }, { "code": null, "e": 4391, "s": 4336, "text": "Has_company_logo: True if the company logo is present." }, { "code": null, "e": 4447, "s": 4391, "text": "Has_questions: True if screening questions are present." }, { "code": null, "e": 4501, "s": 4447, "text": "Employment_type: Full-time, Part-time, Contract, etc." }, { "code": null, "e": 4559, "s": 4501, "text": "Required_experience: Executive, Entry-level, Intern, etc." }, { "code": null, "e": 4624, "s": 4559, "text": "Required_education: Doctorate, Master’s degree, Bachelor’s, etc." }, { "code": null, "e": 4681, "s": 4624, "text": "Industry: Automotive, IT, Health care, Real estate, etc." }, { "code": null, "e": 4738, "s": 4681, "text": "Function: Consulting, Engineering, Research, Sales, etc." }, { "code": null, "e": 4794, "s": 4738, "text": "Fraudulent (Target Variable): 1 if fake posting else 0." }, { "code": null, "e": 4839, "s": 4794, "text": "City: The city mentioned in the job posting." }, { "code": null, "e": 4903, "s": 4839, "text": "Country_name: Name of the country mentioned in the job posting." }, { "code": null, "e": 4945, "s": 4903, "text": "Let’s start working on this cleaned data!" }, { "code": null, "e": 5066, "s": 4945, "text": "I imported the following libraries for now which are the essential libraries anyone needs to perform analysis in Python," }, { "code": null, "e": 5216, "s": 5066, "text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlineimport numpy as nppd.set_option('display.max_columns', None)" }, { "code": null, "e": 5240, "s": 5216, "text": "Let’s look at the data," }, { "code": null, "e": 5284, "s": 5240, "text": "df = pd.read_csv('Clean_data.csv')df.head()" }, { "code": null, "e": 5538, "s": 5284, "text": "Now, we try to study the column ‘description’ in detail. From the cleaned data file I imported, the ‘description’ column is the combination of ‘description’ + ‘requirements’ and ‘company profile.’ An example of how the data in ‘description’ looks like —" }, { "code": null, "e": 5659, "s": 5538, "text": "Next, we will try to look at the Top 20 most common words being used in both fake postings as well as good job postings." }, { "code": null, "e": 6263, "s": 5659, "text": "import spacynlp = spacy.load('en_core_web_lg')import base64import stringimport refrom collections import Counterfrom nltk.corpus import stopwordsstopwords = stopwords.words('english')punctuations = string.punctuationdef cleanup_text(docs, logging = False): texts = [] for doc in docs: doc = nlp(doc, disable = ['parser', 'ner']) tokens = [tok.lemma_.lower().strip() for tok in doc if tok.lemma_ != '-PRON-'] tokens = [tok for tok in tokens if tok not in stopwords and tok not in punctuations] tokens = ' '.join(tokens) texts.append(tokens)return pd.Series(texts)" }, { "code": null, "e": 6292, "s": 6263, "text": "For fraudulent job postings," }, { "code": null, "e": 6908, "s": 6292, "text": "Fraud_1 = [text for text in df1[df1['fraudulent'] == 1]['description']]Fraud_1_clean = cleanup_text(Fraud_1)Fraud_1_clean = ' '.join(Fraud_1_clean).split()Fraud_1_counts = Counter(Fraud_1_clean)Fraud_1_common_words = [word[0] for word in Fraud_1_counts.most_common(20)]Fraud_1_common_counts = [word[1] for word in Fraud_1_counts.most_common(20)]fig = plt.figure(figsize = (20, 10))pal = sns.color_palette(\"cubehelix\", 20)sns.barplot(x = Fraud_1_common_words, y = Fraud_1_common_counts, palette=pal)plt.title('Most Common Words used in Fake job postings')plt.ylabel(\"Frequency of words\")plt.xlabel(\"Words\")plt.show()" }, { "code": null, "e": 6934, "s": 6908, "text": "For genuine job postings," }, { "code": null, "e": 7553, "s": 6934, "text": "Fraud_0 = [text for text in df1[df1['fraudulent'] == 0]['description']]Fraud_0_clean = cleanup_text(Fraud_0)Fraud_0_clean = ' '.join(Fraud_0_clean).split()Fraud_0_counts = Counter(Fraud_0_clean)Fraud_0_common_words = [word[0] for word in Fraud_0_counts.most_common(20)]Fraud_0_common_counts = [word[1] for word in Fraud_0_counts.most_common(20)]fig = plt.figure(figsize = (20, 10))pal = sns.color_palette(\"cubehelix\", 20)sns.barplot(x = Fraud_0_common_words, y = Fraud_0_common_counts, palette=pal)plt.title('Most Common Words used in Genuine job postings')plt.ylabel(\"Frequency of words\")plt.xlabel(\"Words\")plt.show()" }, { "code": null, "e": 8258, "s": 7553, "text": "In both the figures above, most frequent words are almost alike, and it is tough to differentiate between the two. Hence, the variable ‘description’ alone cannot help us with predicting, and therefore the complete set of variables is significant. One more noteworthy thing to point out is, when an individual sees a job posting on the internet, these additional features which I have mentioned in the ‘Data Cleaning’ section are not directly provided. These variables have only been acquired after a job posting was reported as fraudulent. In such a case, it becomes imperative that if one finds such a fake posting, they inform the concerned authorities as well as to other job-seekers in their network." }, { "code": null, "e": 8826, "s": 8258, "text": "Before splitting the data, we need to make some final changes to the data, after which we will be splitting it. The ‘description’ column had to be cleaned into tokens. This is done with the help of spacy and nltk libraries. In the following piece of code, the ‘description’ column has been converted into tokens, and those tokens have been used to create one hot column using sklearn’s CountVectorizer. Also, categorical columns like ‘employment_type,’ ‘required_eduacation,’ ‘required_experience,’ ‘industry,’ and ‘function’ have been converted into one-hot vectors." }, { "code": null, "e": 10103, "s": 8826, "text": "STOPLIST = set(stopwords.words('english') + list(ENGLISH_STOP_WORDS))SYMBOLS = \" \".join(string.punctuation).split(\" \")def tokenizetext(sample): text = sample.strip().replace(\"\\n\", \" \").replace(\"\\r\", \" \") text = text.lower() tokens = parser(text) lemmas = [] for tok in tokens: lemmas.append(tok.lemma_.lower().strip() if tok.lemma_ != \"-PRON-\" else tok.lower_) tokens = lemmas tokens = [tok for tok in tokens if tok not in STOPLIST] tokens = [tok for tok in tokens if tok not in SYMBOLS] return tokensvectorizer = CountVectorizer(tokenizer = tokenizetext, ngram_range = (1,3), min_df = 0.06)vectorizer_features = vectorizer.fit_transform(df1['description'])vectorized_df = pd.DataFrame(vectorizer_features.todense(), columns = vectorizer.get_feature_names())df_final = pd.concat([df1, vectorized_df], axis = 1)df_final.drop('description', axis = 1, inplace = True)df_final.dropna(inplace=True)columns_to_1_hot = ['employment_type', 'required_experience', 'required_education', 'industry', 'function']for column in columns_to_1_hot: encoded = pd.get_dummies(df_final[column]) df_final = pd.concat([df_final, encoded], axis = 1)columns_to_1_hot += ['title', 'city', 'country_name']df_final.drop(columns_to_1_hot, axis = 1, inplace = True)" }, { "code": null, "e": 10149, "s": 10103, "text": "Next, we split the data into train and test —" }, { "code": null, "e": 10443, "s": 10149, "text": "target = df_vectorized['fraudulent']features = df_vectorized.drop('fraudulent', axis = 1)X_train, X_test, y_train, y_test = train_test_split(features, target, test_size = 0.1, stratify = target, random_state=42)print (X_train.shape)print (y_train.shape)print (X_test.shape)print (y_test.shape)" }, { "code": null, "e": 10473, "s": 10443, "text": "We get the following output —" }, { "code": null, "e": 10512, "s": 10473, "text": "(10144, 857)(10144,)(1128, 857)(1128,)" }, { "code": null, "e": 10577, "s": 10512, "text": "We have everything place now. Let’s start with machine learning!" }, { "code": null, "e": 10624, "s": 10577, "text": "Libraries we will use in subsequent sections —" }, { "code": null, "e": 10995, "s": 10624, "text": "from sklearn.model_selection import GridSearchCVfrom sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNearestNeighborsfrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.neural_network import MLPClassifierfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score" }, { "code": null, "e": 11453, "s": 10995, "text": "log_reg = LogisticRegression()c_values = [0.00001, 0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000]penalty_options = ['l1', 'l2']param_grid = dict(C = c_values, penalty = penalty_options)grid_tfidf = GridSearchCV(log_reg, param_grid = param_grid, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose=1)grid.fit(X_train, y_train)log_reg_pred = grid.predict(X_test)print (roc_auc_score(y_test, log_reg_pred))print (classification_report(y_test, log_reg_pred))" }, { "code": null, "e": 11560, "s": 11453, "text": "We get the following results — Out of Sample roc_auc score = 0.7795 and for classification report we get —" }, { "code": null, "e": 11769, "s": 11560, "text": "Predictions with the most basic model, Logistic Regression, gives us a 0.7795 ROC-AUC score, which is a good score given the imbalance of the data. In subsequent sections, we’ll see more sophisticated models." }, { "code": null, "e": 12150, "s": 11769, "text": "knn = KNeighborsClassifier()k_range = list(np.arange(2, 23, 2))param_grid_knn = dict(n_neighbors = k_range)print (param_grid_knn)grid_knn = GridSearchCV(knn, param_grid_knn, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 1)grid_knn.fit(X_train, y_train)knn_pred = grid_knn.predict(X_test)print (roc_auc_score(y_test, knn_pred))print (classification_report(y_test, knn_pred))" }, { "code": null, "e": 12231, "s": 12150, "text": "Out of Sample ROC-AUC score for KNN — 0.5995. For classification report we get —" }, { "code": null, "e": 12337, "s": 12231, "text": "From the image on the left, we can see that KNN performed very poorly as compared to Logistic Regression." }, { "code": null, "e": 12686, "s": 12337, "text": "svc = SVC()kernel = ['linear', 'rbf']param_grid_knn = dict(kernel = kernel)print (param_grid_knn)grid_svc = GridSearchCV(svc, param_grid_knn, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 2)grid_svc.fit(X_train, y_train)svc_pred = grid_svc.predict(X_test)print (roc_auc_score(y_test, svc_pred))print (classification_report(y_test, svc_pred))" }, { "code": null, "e": 12784, "s": 12686, "text": "The out of sample score reported here is 0.8195 ~ 0.82. The classification report is as follows —" }, { "code": null, "e": 12879, "s": 12784, "text": "SVC has the best score yet with 0.82, which is significantly better than the last two methods." }, { "code": null, "e": 13317, "s": 12879, "text": "rf = RandomForestClassifier()n_estimators_range = [1, 2, 4, 8, 16, 32, 64, 100, 200]param_grid_rf = dict(n_estimators = n_estimators_range)grid_rf = GridSearchCV(rf, param_grid_rf, cv = 10, scoring = 'roc_auc', n_jobs = -1, verbose = 1)grid_rf.fit(X_train, y_train)print (grid_rf.best_score_)print (grid_rf.best_params_)rf_pred = grid_rf.predict(X_test)print (roc_auc_score(y_test, rf_pred))print (classification_report(y_test, rf_pred))" }, { "code": null, "e": 13424, "s": 13317, "text": "For the Random Forest model, the ROC-AUC score reported is 0.74. The classification report is as follows —" }, { "code": null, "e": 13528, "s": 13424, "text": "To be honest, I expected Random Forest to perform better than SVC, but so far, SVC has the best result." }, { "code": null, "e": 13779, "s": 13528, "text": "mlp = MLPClassifier(solver = 'sgd', activation = 'relu', hidden_layer_sizes = (100, 50, 30), max_iter = 1000)mlp.fit(X_train, y_train)mlp_pred = mlp.predict(X_test)print (roc_auc_score(y_test, mlp_pred))print (classification_report(y_test, mlp_pred))" }, { "code": null, "e": 13851, "s": 13779, "text": "ROC-AUC score, in this case, is 0.7786. And the classification report —" }, { "code": null, "e": 13985, "s": 13851, "text": "The MLP Classifier with ‘sgd’ solver performs slightly better than the Random Forest model but is still worse than what SVC reported." }, { "code": null, "e": 14237, "s": 13985, "text": "mlp = MLPClassifier(solver = 'adam', activation = 'relu', hidden_layer_sizes = (100, 50, 30), max_iter = 1000)mlp.fit(X_train, y_train)mlp_pred = mlp.predict(X_test)print (roc_auc_score(y_test, mlp_pred))print (classification_report(y_test, mlp_pred))" }, { "code": null, "e": 14353, "s": 14237, "text": "The out of sample ROC-AUC score reported for this model is 0.8595 ~ 0.86. The classification report is as follows —" }, { "code": null, "e": 14497, "s": 14353, "text": "This is the highest score yet reported, and based on this model, we will be able to predict correctly if a job posting is fake 86% of the time." }, { "code": null, "e": 14873, "s": 14497, "text": "From the above image, we can see that Sklearn’s MLP Classifier based on Neural Network with ‘adam’ optimizer performs the best followed by the same model with ‘sgd’ solver and Support Vector Machine Classifier. So based on MLP Classifier’s out of sample performance metric, ROC-AUC score, we can safely say that we can predict if a job posting is fake or not 86% of the time." }, { "code": null, "e": 15021, "s": 14873, "text": "This predictive analysis is very much useful for job search websites like LinkedIn and Glassdoor, which can help them filter such fak job postings." }, { "code": null, "e": 15322, "s": 15021, "text": "Currently, we live in times which none of us ever expected. Coronavirus has not only brought health emergencies to nations but also accelerated an impending recession. Many employees are being laid off every day, and the demand for jobs is way higher than the number of posts available in the market." }, { "code": null, "e": 15860, "s": 15322, "text": "Through this series of articles, I have tried to put forward an issue that is creeping through the job market. Turmoil and chaos are the perfect proponents for scammers, and currently, cyber scam attacks are on the rise. In the previous part, I provided a detailed analysis of how to differentiate between a fake posting and a genuine one and what are the characteristics of a fraudulent job posting. In this part, I have provided a detailed analysis of how we can apply machine learning to predict the occurrences of such fake postings." }, { "code": null, "e": 16100, "s": 15860, "text": "As I have mentioned throughout the two parts, rather than any model or analysis, it is the responsibility of us as users of the internet and job-seekers to let the authorities and our network know if we come across such a fake job posting." }, { "code": null, "e": 16269, "s": 16100, "text": "Thank you for reading the two parts. I wish everyone a great day ahead & please maintain social distance so that we can get over such times faster and more efficiently!" }, { "code": null, "e": 16386, "s": 16269, "text": "Working on this project was a great learning experience for me. Hopefully, you all found it helpful and informative." }, { "code": null, "e": 16578, "s": 16386, "text": "The entire code for this article is there on my GitHub repository for this analysis — https://github.com/sharad18/Fake_Job_Posting. I would love to hear your feedback in the comments section." } ]
Difference between Firm Real-time Tasks and Soft Real-time Tasks - GeeksforGeeks
16 May, 2020 Real-time tasks are generally classified as – Hard and Soft but on a wide range, Real-time tasks are classified as: Hard Real-time TasksFirm Real-time TasksSoft Real-time Tasks Hard Real-time Tasks Firm Real-time Tasks Soft Real-time Tasks 1. Firm Real-time Tasks :Firm real-time tasks are such type of real-time tasks which are associated with time bound and the task need to produce the result within the deadline. Although firm real-time task is different from hard real-time task as in hard real-time once deadline is crossed and task is not completed, system fails but in case of firm real-time task even after the passing of deadline, system does not fail. Example: 1. Video conferencing 2. Satellite based tracking 2. Soft Real-time Tasks :Soft real-time tasks are such type of real-time tasks which are also associated with time bound but here timing constraints are not expressed as absolute values. In soft real-time tasks, even after the deadline result is not considered incorrect and system failure does not occur. Example: 1. Web browsing 2. Railway Ticket Reservation Difference between Firm and Soft Real-time Tasks : Difference Between Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference between Process and Thread Stack vs Heap Memory Allocation Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Program for Round Robin scheduling | Set 1 Semaphores in Process Synchronization
[ { "code": null, "e": 24896, "s": 24868, "text": "\n16 May, 2020" }, { "code": null, "e": 25012, "s": 24896, "text": "Real-time tasks are generally classified as – Hard and Soft but on a wide range, Real-time tasks are classified as:" }, { "code": null, "e": 25073, "s": 25012, "text": "Hard Real-time TasksFirm Real-time TasksSoft Real-time Tasks" }, { "code": null, "e": 25094, "s": 25073, "text": "Hard Real-time Tasks" }, { "code": null, "e": 25115, "s": 25094, "text": "Firm Real-time Tasks" }, { "code": null, "e": 25136, "s": 25115, "text": "Soft Real-time Tasks" }, { "code": null, "e": 25559, "s": 25136, "text": "1. Firm Real-time Tasks :Firm real-time tasks are such type of real-time tasks which are associated with time bound and the task need to produce the result within the deadline. Although firm real-time task is different from hard real-time task as in hard real-time once deadline is crossed and task is not completed, system fails but in case of firm real-time task even after the passing of deadline, system does not fail." }, { "code": null, "e": 25568, "s": 25559, "text": "Example:" }, { "code": null, "e": 25619, "s": 25568, "text": "1. Video conferencing\n2. Satellite based tracking " }, { "code": null, "e": 25925, "s": 25619, "text": "2. Soft Real-time Tasks :Soft real-time tasks are such type of real-time tasks which are also associated with time bound but here timing constraints are not expressed as absolute values. In soft real-time tasks, even after the deadline result is not considered incorrect and system failure does not occur." }, { "code": null, "e": 25934, "s": 25925, "text": "Example:" }, { "code": null, "e": 25981, "s": 25934, "text": "1. Web browsing\n2. Railway Ticket Reservation " }, { "code": null, "e": 26032, "s": 25981, "text": "Difference between Firm and Soft Real-time Tasks :" }, { "code": null, "e": 26051, "s": 26032, "text": "Difference Between" }, { "code": null, "e": 26069, "s": 26051, "text": "Operating Systems" }, { "code": null, "e": 26087, "s": 26069, "text": "Operating Systems" }, { "code": null, "e": 26185, "s": 26087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26246, "s": 26185, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26284, "s": 26246, "text": "Difference between Process and Thread" }, { "code": null, "e": 26316, "s": 26284, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 26384, "s": 26316, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26421, "s": 26384, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 26460, "s": 26421, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 26509, "s": 26460, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26549, "s": 26509, "text": "Program for FCFS CPU Scheduling | Set 1" }, { "code": null, "e": 26592, "s": 26549, "text": "Program for Round Robin scheduling | Set 1" } ]
ES6 - toLowerCase()
This method returns the calling string value converted to lowercase. string.toLowerCase( ) Returns the calling string value converted to lowercase. var str = "Apples are round, and Apples are Juicy."; console.log(str.toLowerCase( )) apples are round, and apples are juicy. 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2346, "s": 2277, "text": "This method returns the calling string value converted to lowercase." }, { "code": null, "e": 2371, "s": 2346, "text": "string.toLowerCase( ) \n" }, { "code": null, "e": 2428, "s": 2371, "text": "Returns the calling string value converted to lowercase." }, { "code": null, "e": 2517, "s": 2428, "text": "var str = \"Apples are round, and Apples are Juicy.\"; \nconsole.log(str.toLowerCase( )) " }, { "code": null, "e": 2559, "s": 2517, "text": "apples are round, and apples are juicy. \n" }, { "code": null, "e": 2594, "s": 2559, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2608, "s": 2594, "text": " Sharad Kumar" }, { "code": null, "e": 2641, "s": 2608, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2659, "s": 2641, "text": " Richa Maheshwari" }, { "code": null, "e": 2692, "s": 2659, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2706, "s": 2692, "text": " Anadi Sharma" }, { "code": null, "e": 2741, "s": 2706, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2758, "s": 2741, "text": " Gowthami Swarna" }, { "code": null, "e": 2791, "s": 2758, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2807, "s": 2791, "text": " Deepti Trivedi" }, { "code": null, "e": 2842, "s": 2807, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2850, "s": 2842, "text": " Shweta" }, { "code": null, "e": 2857, "s": 2850, "text": " Print" }, { "code": null, "e": 2868, "s": 2857, "text": " Add Notes" } ]
K Nearest Neighbours Explained. In this article I will give a general... | by Vatsal | Towards Data Science
In this article I will give a general overview, implementation, drawbacks and resources associated to the K Nearest Neighbours algorithm. Supervised learning is a subsection of machine learning generally associated to classification and regression based problems. Supervised learning implies that you are training a model using a labelled dataset. K Nearest Neighbours (KNN) falls under the supervised learning umbrella and is one of the core algorithms in machine learning. It’s a highly used, simple yet efficient example of a non-parametric, lazy learner classification algorithm. Lazy Learner implies that it doesn’t learn a discriminative function from the training data but rather memorizes the training data instead Non-parametric implies that the algorithm makes no assumptions about the distribution of the data. The KNN algorithm classifies unclassified data points based on their proximity and similarity to other available data points. The underlying assumption this algorithm makes is that similar data points can be found near one another. It’s commonly used to solve problems in various industries because its ease of use, application to classification and regression problems, and the ease of interpretability of the results it generates. K represents the number of nearest neighbours. When K = 1, the algorithm is called the nearest neighbour algorithm. This is the simplest scenario where given an unlabelled position X, the algorithm can predict its label by finding the closest labelled point to X and assigning that as the label. The algorithm works as follows : 1) Choose the number of K and a distance metric used to calculate the proximity2) Find the K nearest neighbours of the point we want to classify3) Assign the point a label by majority vote The choice of K is crucial for the model, if chosen incorrectly it can cause the model to be over / under fit. A K value too small will cause noise in the data to have a high influence on the prediction, however a K value too large will make it computationally expensive. The industry standard for choosing the optimal value of K is by taking the square root of N, where N is the total number of samples. Of course, take this with a grain of salt as it varies from problem to problem. You can experiment with various values of K and their associated accuracies. Common practices to determine the accuracy of a KNN model is to use confusion matrices, cross validation or F1 scores. Below, I’ve listed some of the advantages and disadvantages of using the KNN algorithm. Advantages Simple & intuitive — The algorithm is very easy to understand and implementMemory based approach — Allows it to immediately adapt to new training dataVariety of distance metrics — There is flexibility from the users side to use a distance metric which is best suited for their application (Euclidean, Minkowski, Manhattan distance etc.) Simple & intuitive — The algorithm is very easy to understand and implement Memory based approach — Allows it to immediately adapt to new training data Variety of distance metrics — There is flexibility from the users side to use a distance metric which is best suited for their application (Euclidean, Minkowski, Manhattan distance etc.) Disadvantages Computational complexity — As your training data increases, the speed at which calculations are made rapidly decreasePoor performance on imbalanced data — When majority of the data the model is being trained on represents 1 label then that label will have a high likelihood of being predictedOptimal value of K — If chosen incorrectly, the model will be under or overfitted to the data Computational complexity — As your training data increases, the speed at which calculations are made rapidly decrease Poor performance on imbalanced data — When majority of the data the model is being trained on represents 1 label then that label will have a high likelihood of being predicted Optimal value of K — If chosen incorrectly, the model will be under or overfitted to the data In summation, this article outlines that kNN is a lazy learner and non parametric algorithm. It works by assigning a label to a unlabelled point based on the proximity of the unlabelled point to all the other nearest labelled points. Its main disadvantages are that it is quite computationally inefficient and its difficult to pick the “correct” value of K. However, the advantages of this algorithm is that it is versatile to different calculations of proximity, its very intuitive and that it’s a memory based approach. https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier If you’ve enjoyed this read then check out my other works as well.
[ { "code": null, "e": 756, "s": 172, "text": "In this article I will give a general overview, implementation, drawbacks and resources associated to the K Nearest Neighbours algorithm. Supervised learning is a subsection of machine learning generally associated to classification and regression based problems. Supervised learning implies that you are training a model using a labelled dataset. K Nearest Neighbours (KNN) falls under the supervised learning umbrella and is one of the core algorithms in machine learning. It’s a highly used, simple yet efficient example of a non-parametric, lazy learner classification algorithm." }, { "code": null, "e": 895, "s": 756, "text": "Lazy Learner implies that it doesn’t learn a discriminative function from the training data but rather memorizes the training data instead" }, { "code": null, "e": 994, "s": 895, "text": "Non-parametric implies that the algorithm makes no assumptions about the distribution of the data." }, { "code": null, "e": 1427, "s": 994, "text": "The KNN algorithm classifies unclassified data points based on their proximity and similarity to other available data points. The underlying assumption this algorithm makes is that similar data points can be found near one another. It’s commonly used to solve problems in various industries because its ease of use, application to classification and regression problems, and the ease of interpretability of the results it generates." }, { "code": null, "e": 1723, "s": 1427, "text": "K represents the number of nearest neighbours. When K = 1, the algorithm is called the nearest neighbour algorithm. This is the simplest scenario where given an unlabelled position X, the algorithm can predict its label by finding the closest labelled point to X and assigning that as the label." }, { "code": null, "e": 1756, "s": 1723, "text": "The algorithm works as follows :" }, { "code": null, "e": 1952, "s": 1756, "text": "1) Choose the number of K and a distance metric used to calculate the proximity2) Find the K nearest neighbours of the point we want to classify3) Assign the point a label by majority vote" }, { "code": null, "e": 2224, "s": 1952, "text": "The choice of K is crucial for the model, if chosen incorrectly it can cause the model to be over / under fit. A K value too small will cause noise in the data to have a high influence on the prediction, however a K value too large will make it computationally expensive." }, { "code": null, "e": 2437, "s": 2224, "text": "The industry standard for choosing the optimal value of K is by taking the square root of N, where N is the total number of samples. Of course, take this with a grain of salt as it varies from problem to problem." }, { "code": null, "e": 2633, "s": 2437, "text": "You can experiment with various values of K and their associated accuracies. Common practices to determine the accuracy of a KNN model is to use confusion matrices, cross validation or F1 scores." }, { "code": null, "e": 2721, "s": 2633, "text": "Below, I’ve listed some of the advantages and disadvantages of using the KNN algorithm." }, { "code": null, "e": 2732, "s": 2721, "text": "Advantages" }, { "code": null, "e": 3069, "s": 2732, "text": "Simple & intuitive — The algorithm is very easy to understand and implementMemory based approach — Allows it to immediately adapt to new training dataVariety of distance metrics — There is flexibility from the users side to use a distance metric which is best suited for their application (Euclidean, Minkowski, Manhattan distance etc.)" }, { "code": null, "e": 3145, "s": 3069, "text": "Simple & intuitive — The algorithm is very easy to understand and implement" }, { "code": null, "e": 3221, "s": 3145, "text": "Memory based approach — Allows it to immediately adapt to new training data" }, { "code": null, "e": 3408, "s": 3221, "text": "Variety of distance metrics — There is flexibility from the users side to use a distance metric which is best suited for their application (Euclidean, Minkowski, Manhattan distance etc.)" }, { "code": null, "e": 3422, "s": 3408, "text": "Disadvantages" }, { "code": null, "e": 3808, "s": 3422, "text": "Computational complexity — As your training data increases, the speed at which calculations are made rapidly decreasePoor performance on imbalanced data — When majority of the data the model is being trained on represents 1 label then that label will have a high likelihood of being predictedOptimal value of K — If chosen incorrectly, the model will be under or overfitted to the data" }, { "code": null, "e": 3926, "s": 3808, "text": "Computational complexity — As your training data increases, the speed at which calculations are made rapidly decrease" }, { "code": null, "e": 4102, "s": 3926, "text": "Poor performance on imbalanced data — When majority of the data the model is being trained on represents 1 label then that label will have a high likelihood of being predicted" }, { "code": null, "e": 4196, "s": 4102, "text": "Optimal value of K — If chosen incorrectly, the model will be under or overfitted to the data" }, { "code": null, "e": 4718, "s": 4196, "text": "In summation, this article outlines that kNN is a lazy learner and non parametric algorithm. It works by assigning a label to a unlabelled point based on the proximity of the unlabelled point to all the other nearest labelled points. Its main disadvantages are that it is quite computationally inefficient and its difficult to pick the “correct” value of K. However, the advantages of this algorithm is that it is versatile to different calculations of proximity, its very intuitive and that it’s a memory based approach." }, { "code": null, "e": 4851, "s": 4718, "text": "https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier" } ]
ASP.NET WP - WebGrid
In the previous chapters of databases, we have displayed database data by using a razor code, and doing the HTML markup ourselves. But in ASP.NET Web Pages while using a Razor, we also have an easier way to display data by using the WebGrid helper. This helper can render an HTML table for you that displays data. This helper can render an HTML table for you that displays data. This helper supports options for formatting, for creating a way to page through the data. This helper supports options for formatting, for creating a way to page through the data. In the WebGrid helper you can sort the data just by clicking a column heading. In the WebGrid helper you can sort the data just by clicking a column heading. Let’s have a look into a simple example in which we will display the same data, but this time we will be using the WebGrid helper. In this example, we will create a copy of ListCustomers.cshtml file and then use the WebGrid instead of manually creating the table using HTML markup like <tr> and <td> tags. We will need to create a CSHTML file to start with. Enter CustomersWebGrid.cshtml in the name field and Click OK to continue. Replace the following code in CustomersWebGrid.cshtml file. @{ var db = Database.Open("WebPagesCustomers"); var selectQueryString = "SELECT * FROM Customers ORDER BY FirstName"; var data = db.Query(selectQueryString); var grid = new WebGrid(data); } <!DOCTYPE html> <html> <head> <title>Customers List</title> <style> table, th, td { border: solid 1px #bbbbbb; border-collapse: collapse; padding: 2px; } </style> </head> <body> <h1>Customers List</h1> <div id = "grid"> @grid.GetHtml() </div> </body> </html> As you can see that the code first opens the WebPagesCustomers database file and then creates a simple SQL query. var selectQueryString = "SELECT * FROM Customers ORDER BY FirstName"; A variable named data is populated with the returned data from the SQL Select statement. var data = db.Query(selectQueryString); Then the WebGrid helper is used to create a new grid from data. var grid = new WebGrid(data); This code creates a new WebGrid object and assigns it to the grid variable. In the body of the page, you render the data using the WebGrid helper as shown in the following program. <div id = "grid"> @grid.GetHtml() </div> Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page. As you can see, by using the simplest possible code, the WebGrid helper does a lot of work when displaying and sorting the data. In the above output, you can see that the data is sorted by FirstName, now you can easily sort the data by ID or LastName, etc. just by clicking on the column header. So let’s click on the ID column header and you will see that data is now sorted by ID as shown in the following screenshot. The WebGrid helper can do quite a lot more as well like formatting the columns and styling the whole grid. Let’s have a look into the same example, but this time, we will format the columns. @{ var db = Database.Open("WebPagesCustomers"); var selectQueryString = "SELECT * FROM Customers ORDER BY FirstName"; var data = db.Query(selectQueryString); var grid = new WebGrid(data); } <!DOCTYPE html> <html> <head> <title>Customers List</title> <style> table, th, td { border: solid 1px #bbbbbb; border-collapse: collapse; padding: 2px; } </style> </head> <body> <h1>Customers List</h1> <div id = "grid"> @grid.GetHtml( columns: grid.Columns( grid.Column("FirstName", format:@<i>@item.FirstName</i>), grid.Column("LastName", format:@<i>@item.LastName</i>), grid.Column("Address", format:@<text>[email protected]</text>) ) ) </div> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page. As you can see that the data in the FirstName and LastName columns are now displayed in the italic format. Let’s have a look into another simple example in which we will set the style of the whole grid by defining the CSS classes that specify how the rendered HTML table will look as shown in the following code. @{ var db = Database.Open("WebPagesCustomers"); var selectQueryString = "SELECT * FROM Customers ORDER BY FirstName"; var data = db.Query(selectQueryString); var grid = new WebGrid(data); } <!DOCTYPE html> <html> <head> <title>Customers List</title> <style type = "text/css"> .grid { margin: 4px; border-collapse: collapse; width: 600px; } .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } .alt { background-color: #E8E8E8; color: #000; } .product { width: 200px; font-weight:bold;} </style> </head> <body> <h1>Customers List</h1> <div id = "grid"> @grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("FirstName", format:@<i>@item.FirstName</i>), grid.Column("LastName", format:@<i>@item.LastName</i>), grid.Column("Address", format:@<text>[email protected]</text>) ) ) </div> </body> </html> Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2534, "s": 2285, "text": "In the previous chapters of databases, we have displayed database data by using a razor code, and doing the HTML markup ourselves. But in ASP.NET Web Pages while using a Razor, we also have an easier way to display data by using the WebGrid helper." }, { "code": null, "e": 2599, "s": 2534, "text": "This helper can render an HTML table for you that displays data." }, { "code": null, "e": 2664, "s": 2599, "text": "This helper can render an HTML table for you that displays data." }, { "code": null, "e": 2754, "s": 2664, "text": "This helper supports options for formatting, for creating a way to page through the data." }, { "code": null, "e": 2844, "s": 2754, "text": "This helper supports options for formatting, for creating a way to page through the data." }, { "code": null, "e": 2923, "s": 2844, "text": "In the WebGrid helper you can sort the data just by clicking a column heading." }, { "code": null, "e": 3002, "s": 2923, "text": "In the WebGrid helper you can sort the data just by clicking a column heading." }, { "code": null, "e": 3308, "s": 3002, "text": "Let’s have a look into a simple example in which we will display the same data, but this time we will be using the WebGrid helper. In this example, we will create a copy of ListCustomers.cshtml file and then use the WebGrid instead of manually creating the table using HTML markup like <tr> and <td> tags." }, { "code": null, "e": 3360, "s": 3308, "text": "We will need to create a CSHTML file to start with." }, { "code": null, "e": 3434, "s": 3360, "text": "Enter CustomersWebGrid.cshtml in the name field and Click OK to continue." }, { "code": null, "e": 3494, "s": 3434, "text": "Replace the following code in CustomersWebGrid.cshtml file." }, { "code": null, "e": 4086, "s": 3494, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var selectQueryString = \"SELECT * FROM Customers ORDER BY FirstName\";\n var data = db.Query(selectQueryString);\n var grid = new WebGrid(data);\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Customers List</title>\n <style>\n table, th, td {\n border: solid 1px #bbbbbb;\n border-collapse: collapse;\n padding: 2px;\n }\n </style>\n \n </head>\n <body>\n <h1>Customers List</h1>\n \n <div id = \"grid\">\n @grid.GetHtml()\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 4200, "s": 4086, "text": "As you can see that the code first opens the WebPagesCustomers database file and then creates a simple SQL query." }, { "code": null, "e": 4271, "s": 4200, "text": "var selectQueryString = \"SELECT * FROM Customers ORDER BY FirstName\";\n" }, { "code": null, "e": 4360, "s": 4271, "text": "A variable named data is populated with the returned data from the SQL Select statement." }, { "code": null, "e": 4401, "s": 4360, "text": "var data = db.Query(selectQueryString);\n" }, { "code": null, "e": 4465, "s": 4401, "text": "Then the WebGrid helper is used to create a new grid from data." }, { "code": null, "e": 4496, "s": 4465, "text": "var grid = new WebGrid(data);\n" }, { "code": null, "e": 4677, "s": 4496, "text": "This code creates a new WebGrid object and assigns it to the grid variable. In the body of the page, you render the data using the WebGrid helper as shown in the following program." }, { "code": null, "e": 4721, "s": 4677, "text": "<div id = \"grid\">\n @grid.GetHtml()\n</div>" }, { "code": null, "e": 4864, "s": 4721, "text": "Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page." }, { "code": null, "e": 4993, "s": 4864, "text": "As you can see, by using the simplest possible code, the WebGrid helper does a lot of work when displaying and sorting the data." }, { "code": null, "e": 5160, "s": 4993, "text": "In the above output, you can see that the data is sorted by FirstName, now you can easily sort the data by ID or LastName, etc. just by clicking on the column header." }, { "code": null, "e": 5284, "s": 5160, "text": "So let’s click on the ID column header and you will see that data is now sorted by ID as shown in the following screenshot." }, { "code": null, "e": 5391, "s": 5284, "text": "The WebGrid helper can do quite a lot more as well like formatting the columns and styling the whole grid." }, { "code": null, "e": 5475, "s": 5391, "text": "Let’s have a look into the same example, but this time, we will format the columns." }, { "code": null, "e": 6345, "s": 5475, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var selectQueryString = \"SELECT * FROM Customers ORDER BY FirstName\";\n var data = db.Query(selectQueryString);\n var grid = new WebGrid(data);\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Customers List</title>\n <style>\n table, th, td {\n border: solid 1px #bbbbbb;\n border-collapse: collapse;\n padding: 2px;\n }\n </style>\n \n </head>\n <body>\n <h1>Customers List</h1>\n \n <div id = \"grid\">\n @grid.GetHtml(\n columns: grid.Columns(\n grid.Column(\"FirstName\", format:@<i>@item.FirstName</i>),\n grid.Column(\"LastName\", format:@<i>@item.LastName</i>),\n grid.Column(\"Address\", format:@<text>[email protected]</text>)\n )\n )\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 6488, "s": 6345, "text": "Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page." }, { "code": null, "e": 6595, "s": 6488, "text": "As you can see that the data in the FirstName and LastName columns are now displayed in the italic format." }, { "code": null, "e": 6801, "s": 6595, "text": "Let’s have a look into another simple example in which we will set the style of the whole grid by defining the CSS classes that specify how the rendered HTML table will look as shown in the following code." }, { "code": null, "e": 7989, "s": 6801, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var selectQueryString = \"SELECT * FROM Customers ORDER BY FirstName\";\n var data = db.Query(selectQueryString);\n var grid = new WebGrid(data);\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Customers List</title>\n <style type = \"text/css\">\n .grid { margin: 4px; border-collapse: collapse; width: 600px; }\n .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; }\n .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; }\n .alt { background-color: #E8E8E8; color: #000; }\n .product { width: 200px; font-weight:bold;}\n </style>\n \n </head>\n <body>\n <h1>Customers List</h1>\n \n <div id = \"grid\">\n @grid.GetHtml(\n tableStyle: \"grid\",\n headerStyle: \"head\",\n alternatingRowStyle: \"alt\",\n columns: grid.Columns(\n grid.Column(\"FirstName\", format:@<i>@item.FirstName</i>),\n grid.Column(\"LastName\", format:@<i>@item.LastName</i>),\n grid.Column(\"Address\", format:@<text>[email protected]</text>)\n )\n )\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 8132, "s": 7989, "text": "Now let’s run the application and specify the following url − http://localhost:36905/CustomersWebGrid and you will see the following web page." }, { "code": null, "e": 8167, "s": 8132, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8181, "s": 8167, "text": " Anadi Sharma" }, { "code": null, "e": 8216, "s": 8181, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8239, "s": 8216, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8273, "s": 8239, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8293, "s": 8273, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8328, "s": 8293, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8345, "s": 8328, "text": " University Code" }, { "code": null, "e": 8380, "s": 8345, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8397, "s": 8380, "text": " University Code" }, { "code": null, "e": 8431, "s": 8397, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 8446, "s": 8431, "text": " Bhrugen Patel" }, { "code": null, "e": 8453, "s": 8446, "text": " Print" }, { "code": null, "e": 8464, "s": 8453, "text": " Add Notes" } ]
How to find the length of the StringBuilder in C# - GeeksforGeeks
28 Jan, 2019 StringBuilder.Length Property is used to get or set the length of the current StringBuilder object. Syntax: public int Length { get; set; }It returns the length of the current instance. Exception: This property will give ArgumentOutOfRangeException if the value specified for a set operation is less than zero or greater than MaxCapacity. Below programs illustrate the use of the above-discussed property: Example 1: // C# program to demonstrate// the Length() Propertyusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String passed as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string Console.WriteLine("String = " + str.ToString()); // get length of StringBuilder object int length = str.Length; // print length Console.WriteLine("length of String = " + length); }} String = WelcomeGeeks length of String = 12 Example 2: // C# program to demonstrate// the Length() Propertyusing System;using System.Text; class GFG { public static void Main(String[] args) { // create a StringBuilder object // with a String passed as parameter StringBuilder str = new StringBuilder("India is Great"); // print string Console.WriteLine("String = " + str.ToString()); // get length of StringBuilder object int length = str.Length; // print length Console.WriteLine("length of String = " + length); }} String = India is Great length of String = 14 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.length?view=netframework-4.7.2 CSharp-StringBuilder-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to calculate Electricity Bill C# Dictionary with examples C# | Method Overriding Introduction to .NET Framework HashSet in C# with Examples C# | Replace() Method How to find the length of an Array in C# C# | Dictionary.Add() Method C# Tutorial C# | Class and Object
[ { "code": null, "e": 23609, "s": 23581, "text": "\n28 Jan, 2019" }, { "code": null, "e": 23709, "s": 23609, "text": "StringBuilder.Length Property is used to get or set the length of the current StringBuilder object." }, { "code": null, "e": 23795, "s": 23709, "text": "Syntax: public int Length { get; set; }It returns the length of the current instance." }, { "code": null, "e": 23948, "s": 23795, "text": "Exception: This property will give ArgumentOutOfRangeException if the value specified for a set operation is less than zero or greater than MaxCapacity." }, { "code": null, "e": 24015, "s": 23948, "text": "Below programs illustrate the use of the above-discussed property:" }, { "code": null, "e": 24026, "s": 24015, "text": "Example 1:" }, { "code": "// C# program to demonstrate// the Length() Propertyusing System;using System.Text; class GFG { // Main Method public static void Main(String[] args) { // create a StringBuilder object // with a String passed as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string Console.WriteLine(\"String = \" + str.ToString()); // get length of StringBuilder object int length = str.Length; // print length Console.WriteLine(\"length of String = \" + length); }}", "e": 24641, "s": 24026, "text": null }, { "code": null, "e": 24686, "s": 24641, "text": "String = WelcomeGeeks\nlength of String = 12\n" }, { "code": null, "e": 24697, "s": 24686, "text": "Example 2:" }, { "code": "// C# program to demonstrate// the Length() Propertyusing System;using System.Text; class GFG { public static void Main(String[] args) { // create a StringBuilder object // with a String passed as parameter StringBuilder str = new StringBuilder(\"India is Great\"); // print string Console.WriteLine(\"String = \" + str.ToString()); // get length of StringBuilder object int length = str.Length; // print length Console.WriteLine(\"length of String = \" + length); }}", "e": 25294, "s": 24697, "text": null }, { "code": null, "e": 25341, "s": 25294, "text": "String = India is Great\nlength of String = 14\n" }, { "code": null, "e": 25352, "s": 25341, "text": "Reference:" }, { "code": null, "e": 25453, "s": 25352, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.length?view=netframework-4.7.2" }, { "code": null, "e": 25480, "s": 25453, "text": "CSharp-StringBuilder-Class" }, { "code": null, "e": 25483, "s": 25480, "text": "C#" }, { "code": null, "e": 25581, "s": 25483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25590, "s": 25581, "text": "Comments" }, { "code": null, "e": 25603, "s": 25590, "text": "Old Comments" }, { "code": null, "e": 25641, "s": 25603, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 25669, "s": 25641, "text": "C# Dictionary with examples" }, { "code": null, "e": 25692, "s": 25669, "text": "C# | Method Overriding" }, { "code": null, "e": 25723, "s": 25692, "text": "Introduction to .NET Framework" }, { "code": null, "e": 25751, "s": 25723, "text": "HashSet in C# with Examples" }, { "code": null, "e": 25773, "s": 25751, "text": "C# | Replace() Method" }, { "code": null, "e": 25814, "s": 25773, "text": "How to find the length of an Array in C#" }, { "code": null, "e": 25843, "s": 25814, "text": "C# | Dictionary.Add() Method" }, { "code": null, "e": 25855, "s": 25843, "text": "C# Tutorial" } ]
Predicting Pharmacokinetics with Deterministic Models and Bayesian Statistics | by Georgi Tancev | Towards Data Science
Pharmacokinetics (PK) deals with the distribution and metabolism of xenobiotics in organisms. In drug development and clinical research, one encounters pharmacologists whose job it is to advise physicians the dose of drug(s) to provide to their patients. For this purpose, they often run simulations of so-called pharmacokinetic models which are deterministic, i.e. they consist of ordinary differential equations with respect to a time variable and that describe the following processes (known as LADME): liberation: the process of drug release from the pharmaceutical formulation absorption: the process of a substance entering the blood circulation distribution: the dispersion or dissemination of substances throughout the fluids and tissues of the body metabolism: the recognition by the organism that a foreign substance is present and the irreversible transformation of parent compounds into daughter metabolites elimination: the removal of the substances from the body Such models help determining the optimal dose of drugs as a function of patient attributes like weight, height, age, or sex. In addition, the concentration profile of a drug in the blood plasma over time can be predicted. Furthermore, drug interactions can be monitored. This way, the dosing interval can be defined for an individual patient — paving the way for personalized treatments (visit openPK for more information). Normally, these sets of equations that are part of deterministic models have parameters which are unknown and have to be estimated from experimental data. The body itself is described as a multi-compartment system (organs are compartments) in which subsets of the mentioned processes take place, and drug/metabolite molecules flow from one compartment (organ) to another. It is usually assumed that said compartments are ideally mixed, i.e. incoming molecules are immediately mixed. Note that time-dependent experimental data is usually not available for all compartments, especially not in humans. The way to develop such a model is to formulate a set of differential equations (one example dealing with ethanol metabolism programmed in MATLAB can be found on my GitHub). The equation below is a general formulation of a mass balance with a flow rate Q and a volume V for a compound i in a compartment k. P is a partition coefficient which states how much a compound is retained in a certain tissue. Q and V depend on patient weight, height, age, and sex (modeled with allometric scaling). dc_dt_i_k = (Q_k/V_k)*(c_in_i_(k-1)-c_i_k/P_i_k) Values for Q, V, and P for each compartment can be found in the literature. In addition, drugs are metabolized in the liver compartment and excreted in the kidney compartment. In this case, the equations for the liver and kidneys are modified. dc_dt_i_liver = (1/V_liver)*(Q_liver*(c_in_i-c_i_liver/P_i_liver)-v_max_i*c_i_liver/(K_m_i+c_i_liver))dc_dt_i_kidney = (1/V_kidney)*(Q_kidney*(c_in_i-c_i_kidney/P_i_kidney)-k_r_i*c_i_kidney The term in bold in the liver equation represents the so-called Michaelis-Menten expression for a reaction catalyzed by an enzyme. It limits a reaction to a maximal reaction speed vmax since the amount of active sites for reaction is limited. However, vmax and Km are not readily available in the literature and have to be estimated from experimental data (the same is true for the clearance term kr). Furthermore, competition for active sites with other molecules might occur and the reaction term might need a modification by including an inhibition expression. It is a priori not clear which processes to include in which compartments. For example, a drug is absorbed into the blood within the gastrointestinal tract, but it could also decompose there. The way to go is to formulate an initial model, to estimate its parameters, and to evalute its performance on a test set. If the model performance is insufficient, the model is refined by adding or removing some terms, and the procedure is repeated until convergence. There are different objective functions to be used for the parameter estimation. First, the regular least-squares problem can be minimized (the concentrations are a function of parameters p and so is the objective function J). The concentrations of all compounds i in all compartments k are stacked in one column for this purpose (using a reshape function to avoid a for-loop). The variable c_m refers to the measured concentration, whereas c_p is the predicted concentration. J = (1/N)*(c_m-c_p)'*(c_m-c_p) This function has the disadvantage that it will fit molecules in high concentration better than such of low concentrations as their contribution to the objective is much smaller. Another possibility is to scale the dot product with the inverse of a covariance matrix and reformulate it as a maximum likelihood problem. Of course, the variance matrix E has to be known. J = (1/N)*(c_m-c_p)'*inv(E)*(c_m-c_p) E can, for example, be estimated from the coefficient of variation cv for each compound in each compartment. E = cv'*c_m Finally, by defining a prior distribution over the parameters, the objective function can be expanded and the problem solved in a maximum a posteriori manner, which is a method from Bayesian statistics. In this case, the objective function is again slightly modified assuming normal distribution with zero mean and qI (q times identity matrix variance and neglecting constants). J = (1/N)*(c_m-c_p)'*inv(E)*(c_m-c_p)+q*p'p Lastly, the model has to be wrapped inside the objective function. With the parameters, the model is evaluated and the predicted concentrations are calculated using a solver for differential equations (e.g. ode15s to deal with stiffness), i.e. by a Runge-Kutta method. The objective function is minimized using a solver like fminunc which is based on a Quasi-Newton method implementation (similar to gradient descent, but the gradient is approximated around a current parameter point and scaled proportionally to the magnitude of the second derivate of the objective function, which enhances the performance by allowing bigger steps in flat regions). It’s important to perform a multi-start (different starting points for parameters p) in order to find a global optimum and not to end up with a local one. (Note that a least-squares solution can serve as a starting point for a more sophisticated approach.) The model is best validated using a test set, i.e. data with which the model has not been trained. Mean relative/absolute (squared) error can be used as metrics. In addition, it is important to perform a sensitivity analysis. For this purpose, the partial derivatives of all concentrations (every compound in every compartment) with respect to all parameters are calculated. Note that they are time-dependent as the concentrations are time-dependent. Hence, the influence of one parameter on an output variable can change in time. Very sensitive parameters and the processes they describe have to be further studied. The rank of the sensitivity matrix reveals if all parameters are independent of each other (structural identifiability); if the rank is lower than the number of parameters, the model has to be redefined by removing or readjusting dependent parameters. R = rank(S) Additionally, the confidence intervals of the parameters should be calculated to examine practical identifiability. The variance of the parameters can be calculated using the Fisher information together with the Cramér-Rao bound. E_p = inv(S'*inv(E)*S) The confidence intervals are calculated by a univariate approach using only the diagonal elements of the parameter covariance matrix and the quantiles of Student’s t-distribution. sigma = sqrt(diag(E_p))CI_lb = p_fit-sigma*tinv(0.95, number_points-number_parameters)CI_ub = p_fit+sigma*tinv(0.95, number_points-number_parameters) If a confidence interval includes zero, then a parameter could also be zero, i.e. not taking part in the equations, hence the model should be refined. Note that all parameters should be positive. After several iterations of fitting and refinement, the construction process is certainly finished, a reasonable test set performance is obtained, and the model can be used for prediction.
[ { "code": null, "e": 678, "s": 172, "text": "Pharmacokinetics (PK) deals with the distribution and metabolism of xenobiotics in organisms. In drug development and clinical research, one encounters pharmacologists whose job it is to advise physicians the dose of drug(s) to provide to their patients. For this purpose, they often run simulations of so-called pharmacokinetic models which are deterministic, i.e. they consist of ordinary differential equations with respect to a time variable and that describe the following processes (known as LADME):" }, { "code": null, "e": 754, "s": 678, "text": "liberation: the process of drug release from the pharmaceutical formulation" }, { "code": null, "e": 824, "s": 754, "text": "absorption: the process of a substance entering the blood circulation" }, { "code": null, "e": 930, "s": 824, "text": "distribution: the dispersion or dissemination of substances throughout the fluids and tissues of the body" }, { "code": null, "e": 1092, "s": 930, "text": "metabolism: the recognition by the organism that a foreign substance is present and the irreversible transformation of parent compounds into daughter metabolites" }, { "code": null, "e": 1149, "s": 1092, "text": "elimination: the removal of the substances from the body" }, { "code": null, "e": 1573, "s": 1149, "text": "Such models help determining the optimal dose of drugs as a function of patient attributes like weight, height, age, or sex. In addition, the concentration profile of a drug in the blood plasma over time can be predicted. Furthermore, drug interactions can be monitored. This way, the dosing interval can be defined for an individual patient — paving the way for personalized treatments (visit openPK for more information)." }, { "code": null, "e": 2172, "s": 1573, "text": "Normally, these sets of equations that are part of deterministic models have parameters which are unknown and have to be estimated from experimental data. The body itself is described as a multi-compartment system (organs are compartments) in which subsets of the mentioned processes take place, and drug/metabolite molecules flow from one compartment (organ) to another. It is usually assumed that said compartments are ideally mixed, i.e. incoming molecules are immediately mixed. Note that time-dependent experimental data is usually not available for all compartments, especially not in humans." }, { "code": null, "e": 2664, "s": 2172, "text": "The way to develop such a model is to formulate a set of differential equations (one example dealing with ethanol metabolism programmed in MATLAB can be found on my GitHub). The equation below is a general formulation of a mass balance with a flow rate Q and a volume V for a compound i in a compartment k. P is a partition coefficient which states how much a compound is retained in a certain tissue. Q and V depend on patient weight, height, age, and sex (modeled with allometric scaling)." }, { "code": null, "e": 2713, "s": 2664, "text": "dc_dt_i_k = (Q_k/V_k)*(c_in_i_(k-1)-c_i_k/P_i_k)" }, { "code": null, "e": 2957, "s": 2713, "text": "Values for Q, V, and P for each compartment can be found in the literature. In addition, drugs are metabolized in the liver compartment and excreted in the kidney compartment. In this case, the equations for the liver and kidneys are modified." }, { "code": null, "e": 3147, "s": 2957, "text": "dc_dt_i_liver = (1/V_liver)*(Q_liver*(c_in_i-c_i_liver/P_i_liver)-v_max_i*c_i_liver/(K_m_i+c_i_liver))dc_dt_i_kidney = (1/V_kidney)*(Q_kidney*(c_in_i-c_i_kidney/P_i_kidney)-k_r_i*c_i_kidney" }, { "code": null, "e": 4171, "s": 3147, "text": "The term in bold in the liver equation represents the so-called Michaelis-Menten expression for a reaction catalyzed by an enzyme. It limits a reaction to a maximal reaction speed vmax since the amount of active sites for reaction is limited. However, vmax and Km are not readily available in the literature and have to be estimated from experimental data (the same is true for the clearance term kr). Furthermore, competition for active sites with other molecules might occur and the reaction term might need a modification by including an inhibition expression. It is a priori not clear which processes to include in which compartments. For example, a drug is absorbed into the blood within the gastrointestinal tract, but it could also decompose there. The way to go is to formulate an initial model, to estimate its parameters, and to evalute its performance on a test set. If the model performance is insufficient, the model is refined by adding or removing some terms, and the procedure is repeated until convergence." }, { "code": null, "e": 4648, "s": 4171, "text": "There are different objective functions to be used for the parameter estimation. First, the regular least-squares problem can be minimized (the concentrations are a function of parameters p and so is the objective function J). The concentrations of all compounds i in all compartments k are stacked in one column for this purpose (using a reshape function to avoid a for-loop). The variable c_m refers to the measured concentration, whereas c_p is the predicted concentration." }, { "code": null, "e": 4679, "s": 4648, "text": "J = (1/N)*(c_m-c_p)'*(c_m-c_p)" }, { "code": null, "e": 5048, "s": 4679, "text": "This function has the disadvantage that it will fit molecules in high concentration better than such of low concentrations as their contribution to the objective is much smaller. Another possibility is to scale the dot product with the inverse of a covariance matrix and reformulate it as a maximum likelihood problem. Of course, the variance matrix E has to be known." }, { "code": null, "e": 5086, "s": 5048, "text": "J = (1/N)*(c_m-c_p)'*inv(E)*(c_m-c_p)" }, { "code": null, "e": 5195, "s": 5086, "text": "E can, for example, be estimated from the coefficient of variation cv for each compound in each compartment." }, { "code": null, "e": 5207, "s": 5195, "text": "E = cv'*c_m" }, { "code": null, "e": 5586, "s": 5207, "text": "Finally, by defining a prior distribution over the parameters, the objective function can be expanded and the problem solved in a maximum a posteriori manner, which is a method from Bayesian statistics. In this case, the objective function is again slightly modified assuming normal distribution with zero mean and qI (q times identity matrix variance and neglecting constants)." }, { "code": null, "e": 5630, "s": 5586, "text": "J = (1/N)*(c_m-c_p)'*inv(E)*(c_m-c_p)+q*p'p" }, { "code": null, "e": 6538, "s": 5630, "text": "Lastly, the model has to be wrapped inside the objective function. With the parameters, the model is evaluated and the predicted concentrations are calculated using a solver for differential equations (e.g. ode15s to deal with stiffness), i.e. by a Runge-Kutta method. The objective function is minimized using a solver like fminunc which is based on a Quasi-Newton method implementation (similar to gradient descent, but the gradient is approximated around a current parameter point and scaled proportionally to the magnitude of the second derivate of the objective function, which enhances the performance by allowing bigger steps in flat regions). It’s important to perform a multi-start (different starting points for parameters p) in order to find a global optimum and not to end up with a local one. (Note that a least-squares solution can serve as a starting point for a more sophisticated approach.)" }, { "code": null, "e": 7155, "s": 6538, "text": "The model is best validated using a test set, i.e. data with which the model has not been trained. Mean relative/absolute (squared) error can be used as metrics. In addition, it is important to perform a sensitivity analysis. For this purpose, the partial derivatives of all concentrations (every compound in every compartment) with respect to all parameters are calculated. Note that they are time-dependent as the concentrations are time-dependent. Hence, the influence of one parameter on an output variable can change in time. Very sensitive parameters and the processes they describe have to be further studied." }, { "code": null, "e": 7407, "s": 7155, "text": "The rank of the sensitivity matrix reveals if all parameters are independent of each other (structural identifiability); if the rank is lower than the number of parameters, the model has to be redefined by removing or readjusting dependent parameters." }, { "code": null, "e": 7419, "s": 7407, "text": "R = rank(S)" }, { "code": null, "e": 7650, "s": 7419, "text": "Additionally, the confidence intervals of the parameters should be calculated to examine practical identifiability. The variance of the parameters can be calculated using the Fisher information together with the Cramér-Rao bound." }, { "code": null, "e": 7673, "s": 7650, "text": "E_p = inv(S'*inv(E)*S)" }, { "code": null, "e": 7853, "s": 7673, "text": "The confidence intervals are calculated by a univariate approach using only the diagonal elements of the parameter covariance matrix and the quantiles of Student’s t-distribution." }, { "code": null, "e": 8003, "s": 7853, "text": "sigma = sqrt(diag(E_p))CI_lb = p_fit-sigma*tinv(0.95, number_points-number_parameters)CI_ub = p_fit+sigma*tinv(0.95, number_points-number_parameters)" }, { "code": null, "e": 8199, "s": 8003, "text": "If a confidence interval includes zero, then a parameter could also be zero, i.e. not taking part in the equations, hence the model should be refined. Note that all parameters should be positive." } ]
Print new line and tab in Arduino
In order to print a newline, you can either introduce the '\n' character in your text, or use Serial.println() instead of Serial.print() An example code is given below − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); Serial.print("This is line1\nThis is line2\n"); Serial.println("This is line3"); Serial.println("This is line4"); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output for the above code is − In order to add a tab space, you can introduce '\t' in your code. An example code is given below − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); Serial.print("This is left half\tThis is right half\n"); } void loop() { // put your main code here, to run repeatedly: } The corresponding Serial Monitor output is −
[ { "code": null, "e": 1199, "s": 1062, "text": "In order to print a newline, you can either introduce the '\\n' character in your text, or use Serial.println() instead of Serial.print()" }, { "code": null, "e": 1232, "s": 1199, "text": "An example code is given below −" }, { "code": null, "e": 1531, "s": 1232, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n Serial.print(\"This is line1\\nThis is line2\\n\");\n Serial.println(\"This is line3\");\n Serial.println(\"This is line4\");\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n \n}" }, { "code": null, "e": 1581, "s": 1531, "text": "The Serial Monitor output for the above code is −" }, { "code": null, "e": 1647, "s": 1581, "text": "In order to add a tab space, you can introduce '\\t' in your code." }, { "code": null, "e": 1680, "s": 1647, "text": "An example code is given below −" }, { "code": null, "e": 1916, "s": 1680, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n Serial.print(\"This is left half\\tThis is right half\\n\");\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n \n}" }, { "code": null, "e": 1961, "s": 1916, "text": "The corresponding Serial Monitor output is −" } ]
ReactJS - Create a Component Using Properties
Let us modify our ExpenseEntryItem component and try to use properties. Open our expense-manager application in your favorite editor. Open ExpenseEntryItem file in the src/components folder. Introduce construction function with argument props. constructor(props) { super(props); } Next, change the render method and populate the value from props. render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend date:</b> <em>{this.props.spenddate.tostring()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } Here, name represents the item’s name of type String name represents the item’s name of type String amount represents the item’s amount of type number amount represents the item’s amount of type number spendDate represents the item’s Spend Date of type date spendDate represents the item’s Spend Date of type date category represents the item’s category of type String category represents the item’s category of type String Now, we have successfully updated the component using properties. import React from 'react' import './ExpenseEntryItem.css'; import styles from './ExpenseEntryItem.module.css' class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } export default ExpenseEntryItem; Now, we can use the component by passing all the properties through attributes in the index.js. import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItem from './components/ExpenseEntryItem' const name = "Grape Juice" const amount = 30.00 const spendDate = new Date("2020-10-10") const category = "Food" ReactDOM.render( <React.StrictMode> <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} /> </React.StrictMode>, document.getElementById('root') ); Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React based application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.name}</em></div> <div><b>Amount:</b> <em>{this.props.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.category}</em></div> </div> ); } } const name = "Grape Juice" const amount = 30.00 const spendDate = new Date("2020-10-10") const category = "Food" ReactDOM.render( <ExpenseEntryItem name={name} amount={amount} spendDate={spendDate} category={category} />, document.getElementById('react-app') ); </script> </body> </html> Let us learn how to use JavaScript object as attributes in this chapter. Open our expense-manager application in your favorite editor. Next, open ExpenseEntryItem.js file. Next, change the render() method and access the input object item through this.props.item property. render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em></div> <div><b>Category:</b> <em>{this.props.item.category}</em></div> </div> ); } Next, open index.js and represent the expense entry item in JavaScript object. const item = { id: 1, name : "Grape Juice", amount : 30.5, spendDate: new Date("2020-10-10"), category: "Food" } Next, pass the object to the component using curly brace ({}) syntax in the component attributes. <ExpenseEntryItem item={item} /> The complete code of index.js is as follows − import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItem from './components/ExpenseEntryItem' const item = { id: 1, name : "Grape Juice", amount : 30.5, spendDate: new Date("2020-10-10"), category: "Food" } ReactDOM.render( <React.StrictMode> <ExpenseEntryItem item={item} /> </React.StrictMode>, document.getElementById('root') ); Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The complete code to do it using CDN in a webpage is as follows − <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React based application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> class ExpenseEntryItem extends React.Component { constructor(props) { super(props); } render() { return ( <div> <div><b>Item:</b> <em>{this.props.item.name}</em></div> <div><b>Amount:</b> <em>{this.props.item.amount}</em></div> <div><b>Spend Date:</b> <em>{this.props.item.spendDate.toString()}</em> </div> <div><b>Category:</b> <em>{this.props.item.category}</em> </div> </div> ); } } const item = { id: 1, name : "Grape Juice", amount : 30.5, spendDate: new Date("2020-10-10"), category: "Food" } ReactDOM.render( <ExpenseEntryItem item={item} />, document.getElementById('react-app') ); </script> </body> </html> 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2105, "s": 2033, "text": "Let us modify our ExpenseEntryItem component and try to use properties." }, { "code": null, "e": 2167, "s": 2105, "text": "Open our expense-manager application in your favorite editor." }, { "code": null, "e": 2224, "s": 2167, "text": "Open ExpenseEntryItem file in the src/components folder." }, { "code": null, "e": 2277, "s": 2224, "text": "Introduce construction function with argument props." }, { "code": null, "e": 2319, "s": 2277, "text": "constructor(props) { \n super(props); \n}" }, { "code": null, "e": 2385, "s": 2319, "text": "Next, change the render method and populate the value from props." }, { "code": null, "e": 2728, "s": 2385, "text": "render() {\n return (\n <div>\n <div><b>Item:</b> <em>{this.props.name}</em></div>\n <div><b>Amount:</b> <em>{this.props.amount}</em></div>\n <div><b>Spend date:</b> \n <em>{this.props.spenddate.tostring()}</em></div>\n <div><b>Category:</b> <em>{this.props.category}</em></div>\n </div>\n );\n}" }, { "code": null, "e": 2734, "s": 2728, "text": "Here," }, { "code": null, "e": 2781, "s": 2734, "text": "name represents the item’s name of type String" }, { "code": null, "e": 2828, "s": 2781, "text": "name represents the item’s name of type String" }, { "code": null, "e": 2879, "s": 2828, "text": "amount represents the item’s amount of type number" }, { "code": null, "e": 2930, "s": 2879, "text": "amount represents the item’s amount of type number" }, { "code": null, "e": 2986, "s": 2930, "text": "spendDate represents the item’s Spend Date of type date" }, { "code": null, "e": 3042, "s": 2986, "text": "spendDate represents the item’s Spend Date of type date" }, { "code": null, "e": 3097, "s": 3042, "text": "category represents the item’s category of type String" }, { "code": null, "e": 3152, "s": 3097, "text": "category represents the item’s category of type String" }, { "code": null, "e": 3218, "s": 3152, "text": "Now, we have successfully updated the component using properties." }, { "code": null, "e": 3838, "s": 3218, "text": "import React from 'react'\nimport './ExpenseEntryItem.css';\nimport styles from './ExpenseEntryItem.module.css'\n\nclass ExpenseEntryItem extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <div><b>Item:</b> <em>{this.props.name}</em></div>\n <div><b>Amount:</b> <em>{this.props.amount}</em></div>\n <div><b>Spend Date:</b> \n <em>{this.props.spendDate.toString()}</em></div>\n <div><b>Category:</b> <em>{this.props.category}</em></div>\n </div>\n );\n }\n}\nexport default ExpenseEntryItem;" }, { "code": null, "e": 3934, "s": 3838, "text": "Now, we can use the component by passing all the properties through attributes in the index.js." }, { "code": null, "e": 4405, "s": 3934, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseEntryItem from './components/ExpenseEntryItem'\n\nconst name = \"Grape Juice\"\nconst amount = 30.00\nconst spendDate = new Date(\"2020-10-10\")\nconst category = \"Food\"\n\nReactDOM.render(\n <React.StrictMode>\n <ExpenseEntryItem\n name={name}\n amount={amount}\n spendDate={spendDate}\n category={category} />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 4452, "s": 4405, "text": "Next, serve the application using npm command." }, { "code": null, "e": 4463, "s": 4452, "text": "npm start\n" }, { "code": null, "e": 4554, "s": 4463, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 4620, "s": 4554, "text": "The complete code to do it using CDN in a webpage is as follows −" }, { "code": null, "e": 6124, "s": 4620, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\" />\n <title>React based application</title>\n </head>\n <body>\n <div id=\"react-app\"></div>\n \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/@babel/standalone/babel.min.js\"></script>\n <script type=\"text/babel\">\n class ExpenseEntryItem extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <div><b>Item:</b> <em>{this.props.name}</em></div>\n <div><b>Amount:</b> <em>{this.props.amount}</em></div>\n <div><b>Spend Date:</b> <em>{this.props.spendDate.toString()}</em></div>\n <div><b>Category:</b> <em>{this.props.category}</em></div>\n </div>\n );\n }\n }\n const name = \"Grape Juice\"\n const amount = 30.00\n const spendDate = new Date(\"2020-10-10\")\n const category = \"Food\"\n\n ReactDOM.render(\n <ExpenseEntryItem \n name={name} \n amount={amount} \n spendDate={spendDate} \n category={category} />,\n document.getElementById('react-app') );\n </script>\n </body>\n</html>" }, { "code": null, "e": 6197, "s": 6124, "text": "Let us learn how to use JavaScript object as attributes in this chapter." }, { "code": null, "e": 6259, "s": 6197, "text": "Open our expense-manager application in your favorite editor." }, { "code": null, "e": 6296, "s": 6259, "text": "Next, open ExpenseEntryItem.js file." }, { "code": null, "e": 6396, "s": 6296, "text": "Next, change the render() method and access the input object item through this.props.item property." }, { "code": null, "e": 6759, "s": 6396, "text": "render() {\n return (\n <div>\n <div><b>Item:</b> <em>{this.props.item.name}</em></div>\n <div><b>Amount:</b> <em>{this.props.item.amount}</em></div>\n <div><b>Spend Date:</b> \n <em>{this.props.item.spendDate.toString()}</em></div>\n <div><b>Category:</b> <em>{this.props.item.category}</em></div>\n </div>\n );\n}" }, { "code": null, "e": 6838, "s": 6759, "text": "Next, open index.js and represent the expense entry item in JavaScript object." }, { "code": null, "e": 6972, "s": 6838, "text": "const item = { \n id: 1, \n name : \"Grape Juice\", \n amount : 30.5, \n spendDate: new Date(\"2020-10-10\"), \n category: \"Food\" \n}" }, { "code": null, "e": 7070, "s": 6972, "text": "Next, pass the object to the component using curly brace ({}) syntax in the component attributes." }, { "code": null, "e": 7104, "s": 7070, "text": "<ExpenseEntryItem item={item} />\n" }, { "code": null, "e": 7150, "s": 7104, "text": "The complete code of index.js is as follows −" }, { "code": null, "e": 7543, "s": 7150, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseEntryItem from './components/ExpenseEntryItem'\n\nconst item = {\n id: 1, \n name : \"Grape Juice\", \n amount : 30.5, \n spendDate: new Date(\"2020-10-10\"), \n category: \"Food\" \n}\nReactDOM.render(\n <React.StrictMode>\n <ExpenseEntryItem item={item} />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 7590, "s": 7543, "text": "Next, serve the application using npm command." }, { "code": null, "e": 7601, "s": 7590, "text": "npm start\n" }, { "code": null, "e": 7692, "s": 7601, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 7758, "s": 7692, "text": "The complete code to do it using CDN in a webpage is as follows −" }, { "code": null, "e": 9360, "s": 7758, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\" />\n <title>React based application</title>\n </head>\n <body>\n <div id=\"react-app\"></div>\n \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/@babel/standalone/babel.min.js\"></script>\n <script type=\"text/babel\">\n class ExpenseEntryItem extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <div><b>Item:</b> \n <em>{this.props.item.name}</em></div>\n <div><b>Amount:</b> \n <em>{this.props.item.amount}</em></div>\n <div><b>Spend Date:</b> \n <em>{this.props.item.spendDate.toString()}</em>\n </div>\n <div><b>Category:</b> \n <em>{this.props.item.category}</em>\n </div>\n </div>\n );\n }\n }\n const item = {\n id: 1, \n name : \"Grape Juice\", \n amount : 30.5, \n spendDate: new Date(\"2020-10-10\"), \n category: \"Food\" \n }\n ReactDOM.render(\n <ExpenseEntryItem item={item} />,\n document.getElementById('react-app') \n );\n </script>\n </body>\n</html>" }, { "code": null, "e": 9395, "s": 9360, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9409, "s": 9395, "text": " Anadi Sharma" }, { "code": null, "e": 9444, "s": 9409, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9464, "s": 9444, "text": " Skillbakerystudios" }, { "code": null, "e": 9499, "s": 9464, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 9522, "s": 9499, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 9557, "s": 9522, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 9573, "s": 9557, "text": " TELCOMA Global" }, { "code": null, "e": 9606, "s": 9573, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 9624, "s": 9606, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 9631, "s": 9624, "text": " Print" }, { "code": null, "e": 9642, "s": 9631, "text": " Add Notes" } ]
Palindrome program in Java.
Following is the required program. Live Demo public class Tester { public static void main(String args[]) { int r, sum = 0, temp; int m = 454; int n = m; temp = n; while (n > 0) { r = n % 10; sum = (sum * 10) + r; n = n / 10; } if (temp == sum) { System.out.println(m + " is a palindrome number."); } else { System.out.println(m + "is not a palindrome number."); } } } 454 is a palindrome number.
[ { "code": null, "e": 1097, "s": 1062, "text": "Following is the required program." }, { "code": null, "e": 1107, "s": 1097, "text": "Live Demo" }, { "code": null, "e": 1530, "s": 1107, "text": "public class Tester {\n public static void main(String args[]) {\n int r, sum = 0, temp;\n int m = 454;\n int n = m;\n temp = n;\n while (n > 0) {\n r = n % 10;\n sum = (sum * 10) + r;\n n = n / 10;\n }\n if (temp == sum) {\n System.out.println(m + \" is a palindrome number.\");\n } else {\n System.out.println(m + \"is not a palindrome number.\");\n }\n }\n}" }, { "code": null, "e": 1558, "s": 1530, "text": "454 is a palindrome number." } ]
Advanced Selectors in CSS
The Advanced Selectors in CSS includes Adjacent Sibling selector, attribute selector, direct child selector, nth-of-type selector, etc. It also includes General Sibling Selector, an example is shown below: h1 ~ h3 Example of direct child selector − div > span Following is the code showing advanced selectors in CSS − Live Demo <html> <head> <style> #red { color: red; } .green { background: green; } ul:nth-of-type(1) { background: rgb(0, 174, 255); } ul + h3 { border: 4px solid rgb(19, 0, 128); } a[href="https://www.wikipedia.org"] { font-size: 25px; } h1 ~ h3 { font-size: 40px; } div > span { background-color: DodgerBlue; } </style> </head> <body> <h1>Advanced Selectors Example</h1> <ul> <li>Cow</li> <li>Dog</li> <li>Cat</li> </ul> <ul> <li>Puma</li> <li>Leopard</li> <li>Cheetah</li> </ul> <h3>Animals</h3> <div> <span>Text sample</span> <p> Paragraph Text <span>span text</span> </p> <p class="green">Paragraph Text</p> <p id="red">Paragraph Text.</p> <p class="green">Paragraph Text</p> </div> <a href="https://www.google.com">www.google.com</a> <a href="https://www.wikipedia.org" target="_blank">www.wikipedia.org</a> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1268, "s": 1062, "text": "The Advanced Selectors in CSS includes Adjacent Sibling selector, attribute selector, direct child selector, nth-of-type selector, etc. It also includes General Sibling Selector, an example is shown below:" }, { "code": null, "e": 1276, "s": 1268, "text": "h1 ~ h3" }, { "code": null, "e": 1311, "s": 1276, "text": "Example of direct child selector −" }, { "code": null, "e": 1322, "s": 1311, "text": "div > span" }, { "code": null, "e": 1380, "s": 1322, "text": "Following is the code showing advanced selectors in CSS −" }, { "code": null, "e": 1391, "s": 1380, "text": " Live Demo" }, { "code": null, "e": 2232, "s": 1391, "text": "<html>\n<head>\n<style>\n#red {\n color: red;\n}\n.green {\n background: green;\n}\nul:nth-of-type(1) {\n background: rgb(0, 174, 255);\n}\nul + h3 {\n border: 4px solid rgb(19, 0, 128);\n}\na[href=\"https://www.wikipedia.org\"] {\n font-size: 25px;\n}\nh1 ~ h3 {\n font-size: 40px;\n}\ndiv > span {\n background-color: DodgerBlue;\n}\n</style>\n</head>\n<body>\n<h1>Advanced Selectors Example</h1>\n<ul>\n<li>Cow</li>\n<li>Dog</li>\n<li>Cat</li>\n</ul>\n<ul>\n<li>Puma</li>\n<li>Leopard</li>\n<li>Cheetah</li>\n</ul>\n<h3>Animals</h3>\n<div>\n<span>Text sample</span>\n<p>\nParagraph Text\n<span>span text</span>\n</p>\n<p class=\"green\">Paragraph Text</p>\n<p id=\"red\">Paragraph Text.</p>\n<p class=\"green\">Paragraph Text</p>\n</div>\n<a href=\"https://www.google.com\">www.google.com</a>\n<a href=\"https://www.wikipedia.org\" target=\"_blank\">www.wikipedia.org</a>\n</body>\n</html>" }, { "code": null, "e": 2283, "s": 2232, "text": "The above code will produce the following output −" } ]
DLL - Tools
Several tools are available to help you troubleshoot DLL problems. Some of them are discussed below. The Dependency Walker tool (depends.exe) can recursively scan for all the dependent DLLs that are used by a program. When you open a program in Dependency Walker, the Dependency Walker performs the following checks: Checks for missing DLLs. Checks for program files or DLLs that are not valid. Checks that import functions and export functions match. Checks for circular dependency errors. Checks for modules that are not valid because the modules are for a different operating system. By using Dependency Walker, you can document all the DLLs that a program uses. It may help prevent and correct DLL problems that may occur in the future. Dependency Walker is located in the following directory when you install Microsoft Visual Studio 6.0: drive\Program Files\Microsoft Visual Studio\Common\Tools The DLL Universal Problem Solver (DUPS) tool is used to audit, compare, document, and display DLL information. The following list describes the utilities that make up the DUPS tool: Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file. Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file. Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences. Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences. Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database. Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database. DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility. DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility. Print Add Notes Bookmark this page
[ { "code": null, "e": 1753, "s": 1652, "text": "Several tools are available to help you troubleshoot DLL problems. Some of them are discussed below." }, { "code": null, "e": 1969, "s": 1753, "text": "The Dependency Walker tool (depends.exe) can recursively scan for all the dependent DLLs that are used by a program. When you open a program in Dependency Walker, the Dependency Walker performs the following checks:" }, { "code": null, "e": 1994, "s": 1969, "text": "Checks for missing DLLs." }, { "code": null, "e": 2047, "s": 1994, "text": "Checks for program files or DLLs that are not valid." }, { "code": null, "e": 2104, "s": 2047, "text": "Checks that import functions and export functions match." }, { "code": null, "e": 2143, "s": 2104, "text": "Checks for circular dependency errors." }, { "code": null, "e": 2239, "s": 2143, "text": "Checks for modules that are not valid because the modules are for a different operating system." }, { "code": null, "e": 2495, "s": 2239, "text": "By using Dependency Walker, you can document all the DLLs that a program uses. It may help prevent and correct DLL problems that may occur in the future. Dependency Walker is located in the following directory when you install Microsoft Visual Studio 6.0:" }, { "code": null, "e": 2553, "s": 2495, "text": "drive\\Program Files\\Microsoft Visual Studio\\Common\\Tools\n" }, { "code": null, "e": 2735, "s": 2553, "text": "The DLL Universal Problem Solver (DUPS) tool is used to audit, compare, document, and display DLL information. The following list describes the utilities that make up the DUPS tool:" }, { "code": null, "e": 2865, "s": 2735, "text": "Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file." }, { "code": null, "e": 2995, "s": 2865, "text": "Dlister.exe − This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file." }, { "code": null, "e": 3134, "s": 2995, "text": "Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences." }, { "code": null, "e": 3273, "s": 3134, "text": "Dcomp.exe − This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences." }, { "code": null, "e": 3424, "s": 3273, "text": "Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database." }, { "code": null, "e": 3575, "s": 3424, "text": "Dtxt2DB.exe − This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database." }, { "code": null, "e": 3683, "s": 3575, "text": "DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility." }, { "code": null, "e": 3791, "s": 3683, "text": "DlgDtxt2DB.exe − This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility." }, { "code": null, "e": 3798, "s": 3791, "text": " Print" }, { "code": null, "e": 3809, "s": 3798, "text": " Add Notes" } ]
How to retrieve the value from a table cell with TableModel in Java?
At first, create a table with DefaultTableModel − String data[][] = { {"Australia","5","1"}, {"US","10","2"}, {"Canada","9","3"}, {"India","7","4"}, {"Poland","2","5"}, {"SriLanka","5","6"} }; String col [] = {"Team","Selected Players","Rank"}; DefaultTableModel tableModel = new DefaultTableModel(data,col); JTable table = new JTable(tableModel); Now, use the getModel() to retrieve the value from table cell − Object ob = table.getModel().getValueAt(3, 2); System.out.println("Value = "+ob); The following is an example to retrieve the value from a table cell with TableModel − package my; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { JFrame frame = new JFrame("Demo"); JPanel panel = new JPanel(); String data[][] = { {"Australia","5","1"}, {"US","10","2"}, {"Canada","9","3"}, {"India","7","4"}, {"Poland","2","5"}, {"SriLanka","5","6"} }; String col [] = {"Team","Selected Players","Rank"}; DefaultTableModel tableModel = new DefaultTableModel(data,col); JTable table = new JTable(tableModel); table.getTableHeader().setResizingAllowed(false); Dimension dim = new Dimension(50,2); table.setIntercellSpacing(new Dimension(dim)); Object ob = table.getModel().getValueAt(3, 2); System.out.println("Value = "+ob); JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane); frame.add(panel); frame.setSize(600,400); frame.setUndecorated(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG); frame.setVisible(true); } } The value of the cell would be visible in the Console −
[ { "code": null, "e": 1112, "s": 1062, "text": "At first, create a table with DefaultTableModel −" }, { "code": null, "e": 1428, "s": 1112, "text": "String data[][] = {\n {\"Australia\",\"5\",\"1\"},\n {\"US\",\"10\",\"2\"},\n {\"Canada\",\"9\",\"3\"},\n {\"India\",\"7\",\"4\"},\n {\"Poland\",\"2\",\"5\"},\n {\"SriLanka\",\"5\",\"6\"}\n};\nString col [] = {\"Team\",\"Selected Players\",\"Rank\"};\nDefaultTableModel tableModel = new DefaultTableModel(data,col);\nJTable table = new JTable(tableModel);" }, { "code": null, "e": 1492, "s": 1428, "text": "Now, use the getModel() to retrieve the value from table cell −" }, { "code": null, "e": 1574, "s": 1492, "text": "Object ob = table.getModel().getValueAt(3, 2);\nSystem.out.println(\"Value = \"+ob);" }, { "code": null, "e": 1660, "s": 1574, "text": "The following is an example to retrieve the value from a table cell with TableModel −" }, { "code": null, "e": 3027, "s": 1660, "text": "package my;\nimport java.awt.Dimension;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JRootPane;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n JPanel panel = new JPanel();\n String data[][] = {\n {\"Australia\",\"5\",\"1\"},\n {\"US\",\"10\",\"2\"},\n {\"Canada\",\"9\",\"3\"},\n {\"India\",\"7\",\"4\"},\n {\"Poland\",\"2\",\"5\"},\n {\"SriLanka\",\"5\",\"6\"}\n };\n String col [] = {\"Team\",\"Selected Players\",\"Rank\"};\n DefaultTableModel tableModel = new DefaultTableModel(data,col);\n JTable table = new JTable(tableModel);\n table.getTableHeader().setResizingAllowed(false);\n Dimension dim = new Dimension(50,2);\n table.setIntercellSpacing(new Dimension(dim));\n Object ob = table.getModel().getValueAt(3, 2);\n System.out.println(\"Value = \"+ob);\n JScrollPane scrollPane = new JScrollPane(table);\n panel.add(scrollPane);\n frame.add(panel);\n frame.setSize(600,400);\n frame.setUndecorated(true);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getRootPane().setWindowDecorationStyle(JRootPane.INFORMATION_DIALOG);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 3083, "s": 3027, "text": "The value of the cell would be visible in the Console −" } ]
How to run a Spark application from an EC2 Instance | by Natalie Olivo | Towards Data Science
Why would you do this instead of using EMR? Well, great question. Under certain circumstances, using EC2 might be cheaper than using EMR, but otherwise, EMR may be advisable. In any case, here’s how to run a Spark application from an EC2 instance: I used a Deep Learning AMI (Ubuntu 16.04) Version 25.3 with a p3 instance, for accelerated computing. ssh -i pem_key.pem ubuntu@public_dns_key You type into your EC2 terminal: java -version it returns: openjdk version “1.8.0_222”OpenJDK Runtime Environment (build 1.8.0_222–8u222-b10–1ubuntu1~16.04.1-b10)OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode) Java 8 is what we want for Spark to run, so this is good. My application is written using python so I want to check that it’s installed. python --version It returns: Python 3.6.6 :: Anaconda, Inc. Great! I used the following guidelines: https://datawookie.netlify.com/blog/2017/07/installing-hadoop-on-ubuntu/ Go to the Spark downloads site and see which version of Hadoop it uses: Go to the Spark downloads site and see which version of Hadoop it uses: 2. It uses Hadoop 2.7. Ok now go to the Hadoop mirror site and use wget Right click, copy link to the Hadoop-2.7.7.tar.gz type into your ubuntu terminal (paste what you just copied, I bolded it to let you know that yours may be different): wget http://apache.mirrors.ionfish.org/hadoop/common/hadoop-2.7.7/hadoop-2.7.7.tar.gz 3. Unpack the zipped contents tar -xvf hadoop-2.7.7.tar.gz 4. Find the location of java type -p javac|xargs readlink -f|xargs dirname|xargs dirname It returns: /usr/lib/jvm/java-8-openjdk-amd64 Ok copy your output ^ 5. Ok now edit the Hadoop configuration file so it can interact with java vi hadoop-2.7.7/etc/hadoop/hadoop-env.sh Type i to insert and update the JAVA_HOME variable by pasting that output you copied To exit vim, use ESC + :wq! (wq stands for write and quit, the explanation point is to force it) 6. Set HADOOP_HOME and JAVA_HOME environment variables. The JAVA_HOME environment variable points to the directory where the Java runtime environment (JRE) is installed on your computer. The purpose is to point to where Java is installed. You can do this by using export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64export HADOOP_HOME=/home/ubuntu/hadoop-2.7.7 and update your path: export PATH=$PATH:$HADOOP_HOME/bin/ But this might not save if you shut down your EC2 instance. So I do it by using vim and adding each of these exports to my .bashrc file. vi .bashrc , i for insert, then :wq when you’re done. PS: this is how you remove duplicates in your PATH, you don’t need to, they don’t hurt anything, but in case you were wondering: if [ -n "$PATH" ]; then old_PATH=$PATH:; PATH= while [ -n "$old_PATH" ]; do x=${old_PATH%%:*} # the first remaining entry case $PATH: in *:"$x":*) ;; # already there *) PATH=$PATH:$x;; # not there yet esac old_PATH=${old_PATH#*:} done PATH=${PATH#:} unset old_PATH xfi Source: https://unix.stackexchange.com/questions/40749/remove-duplicate-path-entries-with-awk-command 7. Source your .bashrc file, in your home directory type source .bashrc 8. Now to check version, you can go back to your home directory and type hadoop version, and it should tell you 9. You can remove your zipped tar file from your home directory: rm hadoop-2.7.7.tar.gz https://datawookie.netlify.com/blog/2017/07/installing-spark-on-ubuntu/ 1. Go to this site and copy link address of the first mirror site 2. In your ubuntu terminal type wget and paste the copied link wget http://mirrors.sonic.net/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz 3. Now unpack the zipped tar file tar -xvf spark-2.4.4-bin-hadoop2.7.tgz 4. Add spark to your environment variables export SPARK_HOME=/home/ubuntu/spark-2.4.4-bin-hadoop2.7 5. Install scala. Why do we do it the easy way here? Because we won’t need to peer into the jar files or anything. sudo apt install scala 1. Configure Spark https://stackoverflow.com/questions/58415928/spark-s3-error-java-lang-classnotfoundexception-class-org-apache-hadoop-f a. Navigate to folder ~/spark-2.4.4-bin-hadoop2.7/conf in your EC2 terminal Run code: touch spark_defaults.confvi spark_defaults.conf In here you’re going to want to add the following lines: If 2FA applies to you: make sure your access key and secret key are for a service account (not associated with a username/password) spark.hadoop.fs.s3a.access.key ***your_access_key***spark.hadoop.fs.s3a.secret.key ***your_secret_key***spark.hadoop.fs.s3a.impl org.apache.hadoop.fs.s3a.S3AFileSystemspark.driver.extraClassPath /home/ubuntu/spark-2.4.4-bin-hadoop2.7/jars/hadoop-aws-2.7.3.jar:/home/ubuntu/spark-2.4.4-bin-hadoop2.7/jars/aws-java-sdk-1.7.4.jar b. How do you make sure you have these jar files right?? I bolded them because they may be different for you. So to check, go to your Hadoop jars. Go to the following folder using cd:cd ~/hadoop-2.7.7/share/hadoop/tools/liband check to see which JARS are being used for aws-java-sdk and hadoop-aws, make sure these .jar files match what you just put in spark_defaults.conf. c. Copy these files to the spark jars folder: For the following code to work, be in the ~/hadoop-2.7.7/share/hadoop/tools/lib folder cp hadoop-aws-2.7.3.jar ~/spark-2.4.4-bin-hadoop2.7/jars/cp aws-java-sdk-1.7.4.jar ~/spark-2.4.4-bin-hadoop2.7/jars/ a. Make it so each of your worker nodes can access S3 (since our code reads and writes from S3) https://github.com/CoorpAcademy/docker-pyspark/issues/13 Edit file hadoop-2.7.7/etc/hadoop/core-site.xml to contain the following lines: <configuration><property><name>fs.s3.awsAccessKeyId</name><value>*****</value></property><property><name>fs.s3.awsSecretAccessKey</name><value>*****</value></property></configuration> b. Copy the following jar files to the hadoop-2.7.7/share/hadoop/common/lib directory sudo cp hadoop-2.7.7/share/hadoop/tools/lib/aws-java-sdk-1.7.4.jar hadoop-2.7.7/share/hadoop/common/lib/sudo cp hadoop-2.7.7/share/hadoop/tools/lib/hadoop-aws-2.7.5.jar Hadoop-2.7.7/share/hadoop/common/lib/ git clone path/to/your/repo.git Make sure to add a PYTHONPATH to this folder by adding the following line to your .bashrc file: export PYTHONPATH=$PYTHONPATH:/home/ubuntu/repo PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library. The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages directory). Source: https://www.tutorialspoint.com/What-is-PYTHONPATH-environment-variable-in-Python Happy Sparking! check out Snipe.gg’s blog: medium.com In their case, they found [...] upon checking the EMR Pricing, we realized that EMR adds a pricing overhead of a whopping 25% to the price of the EC2 instances it uses This blog also does a great job of highlighting tools and considerations for productionizing the effort I just outlined.
[ { "code": null, "e": 420, "s": 172, "text": "Why would you do this instead of using EMR? Well, great question. Under certain circumstances, using EC2 might be cheaper than using EMR, but otherwise, EMR may be advisable. In any case, here’s how to run a Spark application from an EC2 instance:" }, { "code": null, "e": 522, "s": 420, "text": "I used a Deep Learning AMI (Ubuntu 16.04) Version 25.3 with a p3 instance, for accelerated computing." }, { "code": null, "e": 563, "s": 522, "text": "ssh -i pem_key.pem ubuntu@public_dns_key" }, { "code": null, "e": 596, "s": 563, "text": "You type into your EC2 terminal:" }, { "code": null, "e": 610, "s": 596, "text": "java -version" }, { "code": null, "e": 622, "s": 610, "text": "it returns:" }, { "code": null, "e": 781, "s": 622, "text": "openjdk version “1.8.0_222”OpenJDK Runtime Environment (build 1.8.0_222–8u222-b10–1ubuntu1~16.04.1-b10)OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)" }, { "code": null, "e": 839, "s": 781, "text": "Java 8 is what we want for Spark to run, so this is good." }, { "code": null, "e": 918, "s": 839, "text": "My application is written using python so I want to check that it’s installed." }, { "code": null, "e": 935, "s": 918, "text": "python --version" }, { "code": null, "e": 947, "s": 935, "text": "It returns:" }, { "code": null, "e": 978, "s": 947, "text": "Python 3.6.6 :: Anaconda, Inc." }, { "code": null, "e": 985, "s": 978, "text": "Great!" }, { "code": null, "e": 1018, "s": 985, "text": "I used the following guidelines:" }, { "code": null, "e": 1091, "s": 1018, "text": "https://datawookie.netlify.com/blog/2017/07/installing-hadoop-on-ubuntu/" }, { "code": null, "e": 1163, "s": 1091, "text": "Go to the Spark downloads site and see which version of Hadoop it uses:" }, { "code": null, "e": 1235, "s": 1163, "text": "Go to the Spark downloads site and see which version of Hadoop it uses:" }, { "code": null, "e": 1307, "s": 1235, "text": "2. It uses Hadoop 2.7. Ok now go to the Hadoop mirror site and use wget" }, { "code": null, "e": 1357, "s": 1307, "text": "Right click, copy link to the Hadoop-2.7.7.tar.gz" }, { "code": null, "e": 1475, "s": 1357, "text": "type into your ubuntu terminal (paste what you just copied, I bolded it to let you know that yours may be different):" }, { "code": null, "e": 1561, "s": 1475, "text": "wget http://apache.mirrors.ionfish.org/hadoop/common/hadoop-2.7.7/hadoop-2.7.7.tar.gz" }, { "code": null, "e": 1591, "s": 1561, "text": "3. Unpack the zipped contents" }, { "code": null, "e": 1620, "s": 1591, "text": "tar -xvf hadoop-2.7.7.tar.gz" }, { "code": null, "e": 1649, "s": 1620, "text": "4. Find the location of java" }, { "code": null, "e": 1709, "s": 1649, "text": "type -p javac|xargs readlink -f|xargs dirname|xargs dirname" }, { "code": null, "e": 1721, "s": 1709, "text": "It returns:" }, { "code": null, "e": 1755, "s": 1721, "text": "/usr/lib/jvm/java-8-openjdk-amd64" }, { "code": null, "e": 1777, "s": 1755, "text": "Ok copy your output ^" }, { "code": null, "e": 1851, "s": 1777, "text": "5. Ok now edit the Hadoop configuration file so it can interact with java" }, { "code": null, "e": 1892, "s": 1851, "text": "vi hadoop-2.7.7/etc/hadoop/hadoop-env.sh" }, { "code": null, "e": 1977, "s": 1892, "text": "Type i to insert and update the JAVA_HOME variable by pasting that output you copied" }, { "code": null, "e": 2074, "s": 1977, "text": "To exit vim, use ESC + :wq! (wq stands for write and quit, the explanation point is to force it)" }, { "code": null, "e": 2313, "s": 2074, "text": "6. Set HADOOP_HOME and JAVA_HOME environment variables. The JAVA_HOME environment variable points to the directory where the Java runtime environment (JRE) is installed on your computer. The purpose is to point to where Java is installed." }, { "code": null, "e": 2338, "s": 2313, "text": "You can do this by using" }, { "code": null, "e": 2433, "s": 2338, "text": "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64export HADOOP_HOME=/home/ubuntu/hadoop-2.7.7" }, { "code": null, "e": 2455, "s": 2433, "text": "and update your path:" }, { "code": null, "e": 2491, "s": 2455, "text": "export PATH=$PATH:$HADOOP_HOME/bin/" }, { "code": null, "e": 2628, "s": 2491, "text": "But this might not save if you shut down your EC2 instance. So I do it by using vim and adding each of these exports to my .bashrc file." }, { "code": null, "e": 2682, "s": 2628, "text": "vi .bashrc , i for insert, then :wq when you’re done." }, { "code": null, "e": 2811, "s": 2682, "text": "PS: this is how you remove duplicates in your PATH, you don’t need to, they don’t hurt anything, but in case you were wondering:" }, { "code": null, "e": 3163, "s": 2811, "text": "if [ -n \"$PATH\" ]; then old_PATH=$PATH:; PATH= while [ -n \"$old_PATH\" ]; do x=${old_PATH%%:*} # the first remaining entry case $PATH: in *:\"$x\":*) ;; # already there *) PATH=$PATH:$x;; # not there yet esac old_PATH=${old_PATH#*:} done PATH=${PATH#:} unset old_PATH xfi" }, { "code": null, "e": 3265, "s": 3163, "text": "Source: https://unix.stackexchange.com/questions/40749/remove-duplicate-path-entries-with-awk-command" }, { "code": null, "e": 3337, "s": 3265, "text": "7. Source your .bashrc file, in your home directory type source .bashrc" }, { "code": null, "e": 3450, "s": 3337, "text": "8. Now to check version, you can go back to your home directory and type hadoop version, and it should tell you" }, { "code": null, "e": 3538, "s": 3450, "text": "9. You can remove your zipped tar file from your home directory: rm hadoop-2.7.7.tar.gz" }, { "code": null, "e": 3610, "s": 3538, "text": "https://datawookie.netlify.com/blog/2017/07/installing-spark-on-ubuntu/" }, { "code": null, "e": 3676, "s": 3610, "text": "1. Go to this site and copy link address of the first mirror site" }, { "code": null, "e": 3739, "s": 3676, "text": "2. In your ubuntu terminal type wget and paste the copied link" }, { "code": null, "e": 3824, "s": 3739, "text": "wget http://mirrors.sonic.net/apache/spark/spark-2.4.4/spark-2.4.4-bin-hadoop2.7.tgz" }, { "code": null, "e": 3858, "s": 3824, "text": "3. Now unpack the zipped tar file" }, { "code": null, "e": 3897, "s": 3858, "text": "tar -xvf spark-2.4.4-bin-hadoop2.7.tgz" }, { "code": null, "e": 3997, "s": 3897, "text": "4. Add spark to your environment variables export SPARK_HOME=/home/ubuntu/spark-2.4.4-bin-hadoop2.7" }, { "code": null, "e": 4112, "s": 3997, "text": "5. Install scala. Why do we do it the easy way here? Because we won’t need to peer into the jar files or anything." }, { "code": null, "e": 4135, "s": 4112, "text": "sudo apt install scala" }, { "code": null, "e": 4273, "s": 4135, "text": "1. Configure Spark https://stackoverflow.com/questions/58415928/spark-s3-error-java-lang-classnotfoundexception-class-org-apache-hadoop-f" }, { "code": null, "e": 4349, "s": 4273, "text": "a. Navigate to folder ~/spark-2.4.4-bin-hadoop2.7/conf in your EC2 terminal" }, { "code": null, "e": 4359, "s": 4349, "text": "Run code:" }, { "code": null, "e": 4407, "s": 4359, "text": "touch spark_defaults.confvi spark_defaults.conf" }, { "code": null, "e": 4596, "s": 4407, "text": "In here you’re going to want to add the following lines: If 2FA applies to you: make sure your access key and secret key are for a service account (not associated with a username/password)" }, { "code": null, "e": 4923, "s": 4596, "text": "spark.hadoop.fs.s3a.access.key ***your_access_key***spark.hadoop.fs.s3a.secret.key ***your_secret_key***spark.hadoop.fs.s3a.impl org.apache.hadoop.fs.s3a.S3AFileSystemspark.driver.extraClassPath /home/ubuntu/spark-2.4.4-bin-hadoop2.7/jars/hadoop-aws-2.7.3.jar:/home/ubuntu/spark-2.4.4-bin-hadoop2.7/jars/aws-java-sdk-1.7.4.jar" }, { "code": null, "e": 5070, "s": 4923, "text": "b. How do you make sure you have these jar files right?? I bolded them because they may be different for you. So to check, go to your Hadoop jars." }, { "code": null, "e": 5297, "s": 5070, "text": "Go to the following folder using cd:cd ~/hadoop-2.7.7/share/hadoop/tools/liband check to see which JARS are being used for aws-java-sdk and hadoop-aws, make sure these .jar files match what you just put in spark_defaults.conf." }, { "code": null, "e": 5343, "s": 5297, "text": "c. Copy these files to the spark jars folder:" }, { "code": null, "e": 5430, "s": 5343, "text": "For the following code to work, be in the ~/hadoop-2.7.7/share/hadoop/tools/lib folder" }, { "code": null, "e": 5547, "s": 5430, "text": "cp hadoop-aws-2.7.3.jar ~/spark-2.4.4-bin-hadoop2.7/jars/cp aws-java-sdk-1.7.4.jar ~/spark-2.4.4-bin-hadoop2.7/jars/" }, { "code": null, "e": 5700, "s": 5547, "text": "a. Make it so each of your worker nodes can access S3 (since our code reads and writes from S3) https://github.com/CoorpAcademy/docker-pyspark/issues/13" }, { "code": null, "e": 5780, "s": 5700, "text": "Edit file hadoop-2.7.7/etc/hadoop/core-site.xml to contain the following lines:" }, { "code": null, "e": 5964, "s": 5780, "text": "<configuration><property><name>fs.s3.awsAccessKeyId</name><value>*****</value></property><property><name>fs.s3.awsSecretAccessKey</name><value>*****</value></property></configuration>" }, { "code": null, "e": 6050, "s": 5964, "text": "b. Copy the following jar files to the hadoop-2.7.7/share/hadoop/common/lib directory" }, { "code": null, "e": 6257, "s": 6050, "text": "sudo cp hadoop-2.7.7/share/hadoop/tools/lib/aws-java-sdk-1.7.4.jar hadoop-2.7.7/share/hadoop/common/lib/sudo cp hadoop-2.7.7/share/hadoop/tools/lib/hadoop-aws-2.7.5.jar Hadoop-2.7.7/share/hadoop/common/lib/" }, { "code": null, "e": 6289, "s": 6257, "text": "git clone path/to/your/repo.git" }, { "code": null, "e": 6385, "s": 6289, "text": "Make sure to add a PYTHONPATH to this folder by adding the following line to your .bashrc file:" }, { "code": null, "e": 6433, "s": 6385, "text": "export PYTHONPATH=$PYTHONPATH:/home/ubuntu/repo" }, { "code": null, "e": 6721, "s": 6433, "text": "PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library." }, { "code": null, "e": 6909, "s": 6721, "text": "The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages directory)." }, { "code": null, "e": 6998, "s": 6909, "text": "Source: https://www.tutorialspoint.com/What-is-PYTHONPATH-environment-variable-in-Python" }, { "code": null, "e": 7014, "s": 6998, "text": "Happy Sparking!" }, { "code": null, "e": 7041, "s": 7014, "text": "check out Snipe.gg’s blog:" }, { "code": null, "e": 7052, "s": 7041, "text": "medium.com" }, { "code": null, "e": 7078, "s": 7052, "text": "In their case, they found" }, { "code": null, "e": 7220, "s": 7078, "text": "[...] upon checking the EMR Pricing, we realized that EMR adds a pricing overhead of a whopping 25% to the price of the EC2 instances it uses" } ]
Find All Live Hosts IP Addresses Connected on Network in Linux - GeeksforGeeks
28 Jul, 2021 As network engineers or penetration testers, we need to find the live hosts on the networks. Today we are going to see how to find live hosts on the network. We are going to use the nmap tool to find the live hosts on the network. Nmap (network mapper) is an open-source command-line tool for network exploration and security auditing. Nmap is used to scan the networks using the raw IP packets. In this article, we are using the nmap to find live hosts on the network. Now let’s see how to install nmap on the different Linux Distros: For Ubuntu/Debian/Kali Linux systems: sudo apt-get install nmap For Arch Linux: sudo pacman -S nmap For CentOS: sudo yum install nmap For Fedora: sudo dnf install nmap Now we have installed the nmap on the system. The syntax for nmap use is: nmap <scan type...> options <target> Here, scan type are the option provided by the nmap. And the target is the IP address or hostname of the network. Now to find a live host first we need to find the IP address and the subnet mask of the target that means we need to find the IP address and its subnet mask of our network. We can find the IP address by following commands: ifconfig or ip addr show Here in this case the IP of the network is 192.1.1.0 and the subnet mask is 255.255. 255.0 i.e. /24. Now we are going to use the following command of nmap to find the live host on our network. Here -sn is an option: This option tells the nmap to do not scan port after host discovery of a live host. By default, the Nmap scans all ports on the discovered host. 192.168.1.0/24 is a target: We are going to scan the live host on this target. nmap -sn 192.168.1.0/24 In the above output, we can see there are two live hosts. To know more about we can use man command or help command like to follow man nmap and nmap --help This is how we can find the live host on our network. linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ 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": 24015, "s": 23987, "text": "\n28 Jul, 2021" }, { "code": null, "e": 24246, "s": 24015, "text": "As network engineers or penetration testers, we need to find the live hosts on the networks. Today we are going to see how to find live hosts on the network. We are going to use the nmap tool to find the live hosts on the network." }, { "code": null, "e": 24485, "s": 24246, "text": "Nmap (network mapper) is an open-source command-line tool for network exploration and security auditing. Nmap is used to scan the networks using the raw IP packets. In this article, we are using the nmap to find live hosts on the network." }, { "code": null, "e": 24551, "s": 24485, "text": "Now let’s see how to install nmap on the different Linux Distros:" }, { "code": null, "e": 24589, "s": 24551, "text": "For Ubuntu/Debian/Kali Linux systems:" }, { "code": null, "e": 24615, "s": 24589, "text": "sudo apt-get install nmap" }, { "code": null, "e": 24631, "s": 24615, "text": "For Arch Linux:" }, { "code": null, "e": 24651, "s": 24631, "text": "sudo pacman -S nmap" }, { "code": null, "e": 24663, "s": 24651, "text": "For CentOS:" }, { "code": null, "e": 24685, "s": 24663, "text": "sudo yum install nmap" }, { "code": null, "e": 24697, "s": 24685, "text": "For Fedora:" }, { "code": null, "e": 24719, "s": 24697, "text": "sudo dnf install nmap" }, { "code": null, "e": 24793, "s": 24719, "text": "Now we have installed the nmap on the system. The syntax for nmap use is:" }, { "code": null, "e": 24834, "s": 24793, "text": " nmap <scan type...> options <target>" }, { "code": null, "e": 24948, "s": 24834, "text": "Here, scan type are the option provided by the nmap. And the target is the IP address or hostname of the network." }, { "code": null, "e": 25171, "s": 24948, "text": "Now to find a live host first we need to find the IP address and the subnet mask of the target that means we need to find the IP address and its subnet mask of our network. We can find the IP address by following commands:" }, { "code": null, "e": 25180, "s": 25171, "text": "ifconfig" }, { "code": null, "e": 25184, "s": 25180, "text": "or " }, { "code": null, "e": 25197, "s": 25184, "text": "ip addr show" }, { "code": null, "e": 25390, "s": 25197, "text": "Here in this case the IP of the network is 192.1.1.0 and the subnet mask is 255.255. 255.0 i.e. /24. Now we are going to use the following command of nmap to find the live host on our network." }, { "code": null, "e": 25558, "s": 25390, "text": "Here -sn is an option: This option tells the nmap to do not scan port after host discovery of a live host. By default, the Nmap scans all ports on the discovered host." }, { "code": null, "e": 25637, "s": 25558, "text": "192.168.1.0/24 is a target: We are going to scan the live host on this target." }, { "code": null, "e": 25662, "s": 25637, "text": " nmap -sn 192.168.1.0/24" }, { "code": null, "e": 25793, "s": 25662, "text": "In the above output, we can see there are two live hosts. To know more about we can use man command or help command like to follow" }, { "code": null, "e": 25802, "s": 25793, "text": "man nmap" }, { "code": null, "e": 25806, "s": 25802, "text": "and" }, { "code": null, "e": 25818, "s": 25806, "text": "nmap --help" }, { "code": null, "e": 25872, "s": 25818, "text": "This is how we can find the live host on our network." }, { "code": null, "e": 25886, "s": 25872, "text": "linux-command" }, { "code": null, "e": 25893, "s": 25886, "text": "Picked" }, { "code": null, "e": 25904, "s": 25893, "text": "Linux-Unix" }, { "code": null, "e": 26002, "s": 25904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26011, "s": 26002, "text": "Comments" }, { "code": null, "e": 26024, "s": 26011, "text": "Old Comments" }, { "code": null, "e": 26059, "s": 26024, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26096, "s": 26059, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26130, "s": 26096, "text": "mv command in Linux with examples" }, { "code": null, "e": 26156, "s": 26130, "text": "Thread functions in C/C++" }, { "code": null, "e": 26182, "s": 26156, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26219, "s": 26182, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26259, "s": 26219, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26288, "s": 26259, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26330, "s": 26288, "text": "Named Pipe or FIFO with example C program" } ]
Python unittest - assertIs() function - GeeksforGeeks
29 Aug, 2020 assertIs() in Python is a unittest library function that is used in unit testing to test whether first and second input value evaluates to the same object or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input evaluates to the same object then assertIs() will return true else return false. Syntax: assertIs(firstValue, secondValue, message) Parameters: assertIs() accept three parameters which are listed below with explanation: firstValue variable of any type which is used in the comparison by function secondValue: variable of any type which is used in the comparison by function message: a string sentence as a message which got displayed when the test case got failed. Listed below are two different examples illustrating the positive and negative test case for given assert function: Example 1: Negative Test case Python3 # unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_negative(self): firstValue = DummyClass() secondValue = DummyClass() # error message in case if test case got failed message = "First value & second value are not evaluated to same object !" # assertIs() to check that if first & second evaluated to same object self.assertIs(firstValue, secondValue, message) if __name__ == '__main__': unittest.main() Output: F ====================================================================== FAIL: test_negative (__main__.TestMethods) ---------------------------------------------------------------------- Traceback (most recent call last): File "p1.py", line 15, in test_negative self.assertIs(firstValue, secondValue, message) AssertionError: <__main__.DummyClass object at 0x7f1d20251b70> is not <__main__.DummyClass object at 0x7f1d20251ba8> : First value and second value are not evaluated to same object! ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (failures=1) Example 2: Positive Test case Python3 # unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_positive(self): firstValue = DummyClass() secondValue = firstValue # error message in case if test case got failed message = "First value and second value are not evaluated to same object !" # assertIs() to check that if first & second evaluated to same object self.assertIs(firstValue, secondValue, message) if __name__ == '__main__': unittest.main() Output: . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK Reference: https://docs.python.org/3/library/unittest.html Python unittest-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24069, "s": 24041, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24441, "s": 24069, "text": "assertIs() in Python is a unittest library function that is used in unit testing to test whether first and second input value evaluates to the same object or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input evaluates to the same object then assertIs() will return true else return false." }, { "code": null, "e": 24492, "s": 24441, "text": "Syntax: assertIs(firstValue, secondValue, message)" }, { "code": null, "e": 24580, "s": 24492, "text": "Parameters: assertIs() accept three parameters which are listed below with explanation:" }, { "code": null, "e": 24657, "s": 24580, "text": "firstValue variable of any type which is used in the comparison by function" }, { "code": null, "e": 24735, "s": 24657, "text": "secondValue: variable of any type which is used in the comparison by function" }, { "code": null, "e": 24826, "s": 24735, "text": "message: a string sentence as a message which got displayed when the test case got failed." }, { "code": null, "e": 24942, "s": 24826, "text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:" }, { "code": null, "e": 24972, "s": 24942, "text": "Example 1: Negative Test case" }, { "code": null, "e": 24980, "s": 24972, "text": "Python3" }, { "code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_negative(self): firstValue = DummyClass() secondValue = DummyClass() # error message in case if test case got failed message = \"First value & second value are not evaluated to same object !\" # assertIs() to check that if first & second evaluated to same object self.assertIs(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()", "e": 25543, "s": 24980, "text": null }, { "code": null, "e": 25551, "s": 25543, "text": "Output:" }, { "code": null, "e": 26168, "s": 25551, "text": "F\n======================================================================\nFAIL: test_negative (__main__.TestMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 15, in test_negative\n self.assertIs(firstValue, secondValue, message)\nAssertionError: <__main__.DummyClass object at 0x7f1d20251b70> is \nnot <__main__.DummyClass object at 0x7f1d20251ba8> :\n First value and second value are not evaluated to same object!\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n\n" }, { "code": null, "e": 26198, "s": 26168, "text": "Example 2: Positive Test case" }, { "code": null, "e": 26206, "s": 26198, "text": "Python3" }, { "code": "# unit test caseimport unittest class DummyClass: x = 5 class TestMethods(unittest.TestCase): # test function to test object equality of two value def test_positive(self): firstValue = DummyClass() secondValue = firstValue # error message in case if test case got failed message = \"First value and second value are not evaluated to same object !\" # assertIs() to check that if first & second evaluated to same object self.assertIs(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()", "e": 26769, "s": 26206, "text": null }, { "code": null, "e": 26777, "s": 26769, "text": "Output:" }, { "code": null, "e": 26878, "s": 26777, "text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n\n" }, { "code": null, "e": 26937, "s": 26878, "text": "Reference: https://docs.python.org/3/library/unittest.html" }, { "code": null, "e": 26961, "s": 26937, "text": "Python unittest-library" }, { "code": null, "e": 26968, "s": 26961, "text": "Python" }, { "code": null, "e": 27066, "s": 26968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27075, "s": 27066, "text": "Comments" }, { "code": null, "e": 27088, "s": 27075, "text": "Old Comments" }, { "code": null, "e": 27106, "s": 27088, "text": "Python Dictionary" }, { "code": null, "e": 27128, "s": 27106, "text": "Enumerate() in Python" }, { "code": null, "e": 27160, "s": 27128, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27202, "s": 27160, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27228, "s": 27202, "text": "Python String | replace()" }, { "code": null, "e": 27253, "s": 27228, "text": "sum() function in Python" }, { "code": null, "e": 27290, "s": 27253, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27346, "s": 27290, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27375, "s": 27346, "text": "*args and **kwargs in Python" } ]
Sort an array of 0s, 1s and 2s (Simple Counting) - GeeksforGeeks
25 Aug, 2021 Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last. Examples: Input : {0, 1, 2, 0, 1, 2} Output : {0, 0, 1, 1, 2, 2} Input : {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output : {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2} Count the number of 0’s, 1’s and 2’s. After Counting, put all 0’s first, then 1’s and lastly 2’s in the array. We traverse the array two times. Time complexity will be O(n). C++ Java Python3 C# Javascript // Simple C++ program to sort an array of 0s// 1s and 2s.#include <iostream>using namespace std; void sort012(int* arr, int n){ // Variables to maintain the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0, count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; return;} // Prints the arrayvoid printArray(int* arr, int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;} // Driver codeint main(){ int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); printArray(arr, n); return 0;} // Simple Java program// to sort an array of 0s// 1s and 2s.import java.util.*;import java.lang.*; public class GfG{ public static void sort012(int arr[], int n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0; int count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array public static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver function public static void main(String args[]) { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = 12; sort012(arr, n); }} // This code is contributed by Sagar Shukla # Python C++ program to sort an array of 0s# 1s and 2s.import math def sort012(arr, n): # Variables to maintain the count of 0's, # 1's and 2's in the array count0 = 0 count1 = 0 count2 = 0 for i in range(0,n): if (arr[i] == 0): count0=count0+1 if (arr[i] == 1): count1=count1+1 if (arr[i] == 2): count2=count2+1 # Putting the 0's in the array in starting. for i in range(0,count0): arr[i] = 0 # Putting the 1's in the array after the 0's. for i in range( count0, (count0 + count1)) : arr[i] = 1 # Putting the 2's in the array after the 1's for i in range((count0 + count1),n) : arr[i] = 2 return # Prints the arraydef printArray( arr, n): for i in range(0,n): print( arr[i] , end=" ") print() # Driver codearr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]n = len(arr)sort012(arr, n)printArray(arr, n) # This code is contributed by Gitanjali. // Simple C# program// to sort an array of 0s// 1s and 2s.using System; public class GfG{ public static void sort012(int []arr, int n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0; int count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array public static void printArray(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver function public static void Main() { int []arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = 12; sort012(arr, n); }} // This code is contributed by vt_m <script> // JavaScript program// to sort an array of 0s// 1s and 2s. function sort012(arr, n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array let count0 = 0, count1 = 0; let count2 = 0; for (let i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (let i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (let i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (let i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array function printArray(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); document.write(); } // Driver code let arr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]; let n = 12; sort012(arr, n); </script> 0 0 0 0 0 1 1 1 1 1 2 2 Problems with the above solution.: It requires two traversals of array.This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one. It requires two traversals of array. This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one. Another Approach: Java Python3 C# Javascript import java.util.ArrayList;import java.util.List; // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2]class GFG { static int[] inputArray = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; static List<Integer> outputArray = new ArrayList<>(); static int indexOfOne = 0; static void print() { for (int item : inputArray) if (item == 2) outputArray.add(item); else if (item == 1) { outputArray.add(indexOfOne, item); indexOfOne += 1; } else if (item == 0) { outputArray.add(0, item); indexOfOne += 1; } else { System.out.println(" wrong value - Aborting "); continue; } } public static void main(String[] args) { print(); for (int item : outputArray) System.out.print(item+", "); }}// This code is contributed by Amit Katiyar # Example## input = [0, 1, 2, 2, 0, 0]# output = [0, 0, 0, 1, 2, 2] inputArray = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]outputArray = []indexOfOne = 0for item in inputArray: if item == 2: outputArray.append(item) elif item == 1: outputArray.insert(indexOfOne, item) indexOfOne += 1 elif item == 0: outputArray.insert(0, item) indexOfOne += 1 else: print(" wrong value - Aborting ") continueprint(outputArray) using System;using System.Collections.Generic; // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2] class GFG{ static int[] inputArray = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };static List<int> outputArray = new List<int>();static int indexOfOne = 0; static void print(){ foreach (int item in inputArray) if (item == 2) outputArray.Add(item); else if (item == 1) { outputArray.Insert(indexOfOne, item); indexOfOne += 1; } else if (item == 0) { outputArray.Insert(0, item); indexOfOne += 1; } else { Console.WriteLine(" wrong value - Aborting "); continue; }} // Driver codepublic static void Main(String[] args){ print(); foreach(int item in outputArray) Console.Write(item + ", ");}} // This code is contributed by 29AjayKumar <script> // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2]let inputArray=[ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let outputArray = [];let indexOfOne = 0; function print(){ for (let item of inputArray.values()) if (item == 2) outputArray.push(item); else if (item == 1) { outputArray.splice(indexOfOne,0, item); indexOfOne += 1; } else if (item == 0) { outputArray.splice(0,0, item); indexOfOne += 1; } else { document.write(" wrong value - Aborting "); continue; }} print();for (let item of outputArray.values()) document.write(item+", "); // This code is contributed by rag2127</script> Output: 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, Optimal Solution that handles above issues : Sort an array of 0s, 1s and 2s (Dutch National Flag Algorithm) kishandewangan splevel62 amit143katiyar 29AjayKumar rag2127 kshitijsauravnik counting-sort limited-range-elements Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments k largest(or smallest) elements in an array Merge two sorted arrays Python Program for Bubble Sort Bucket Sort Most frequent element in an array sort() in Python Python List sort() method Python Program for QuickSort C++ Program for QuickSort Merge Sort for Linked Lists
[ { "code": null, "e": 24939, "s": 24911, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25088, "s": 24939, "text": "Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s and all 2s in last." }, { "code": null, "e": 25099, "s": 25088, "text": "Examples: " }, { "code": null, "e": 25248, "s": 25099, "text": "Input : {0, 1, 2, 0, 1, 2}\nOutput : {0, 0, 1, 1, 2, 2}\n\nInput : {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}\nOutput : {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}" }, { "code": null, "e": 25423, "s": 25248, "text": "Count the number of 0’s, 1’s and 2’s. After Counting, put all 0’s first, then 1’s and lastly 2’s in the array. We traverse the array two times. Time complexity will be O(n). " }, { "code": null, "e": 25427, "s": 25423, "text": "C++" }, { "code": null, "e": 25432, "s": 25427, "text": "Java" }, { "code": null, "e": 25440, "s": 25432, "text": "Python3" }, { "code": null, "e": 25443, "s": 25440, "text": "C#" }, { "code": null, "e": 25454, "s": 25443, "text": "Javascript" }, { "code": "// Simple C++ program to sort an array of 0s// 1s and 2s.#include <iostream>using namespace std; void sort012(int* arr, int n){ // Variables to maintain the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0, count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; return;} // Prints the arrayvoid printArray(int* arr, int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << endl;} // Driver codeint main(){ int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); printArray(arr, n); return 0;}", "e": 26553, "s": 25454, "text": null }, { "code": "// Simple Java program// to sort an array of 0s// 1s and 2s.import java.util.*;import java.lang.*; public class GfG{ public static void sort012(int arr[], int n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0; int count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array public static void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver function public static void main(String args[]) { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = 12; sort012(arr, n); }} // This code is contributed by Sagar Shukla", "e": 28007, "s": 26553, "text": null }, { "code": "# Python C++ program to sort an array of 0s# 1s and 2s.import math def sort012(arr, n): # Variables to maintain the count of 0's, # 1's and 2's in the array count0 = 0 count1 = 0 count2 = 0 for i in range(0,n): if (arr[i] == 0): count0=count0+1 if (arr[i] == 1): count1=count1+1 if (arr[i] == 2): count2=count2+1 # Putting the 0's in the array in starting. for i in range(0,count0): arr[i] = 0 # Putting the 1's in the array after the 0's. for i in range( count0, (count0 + count1)) : arr[i] = 1 # Putting the 2's in the array after the 1's for i in range((count0 + count1),n) : arr[i] = 2 return # Prints the arraydef printArray( arr, n): for i in range(0,n): print( arr[i] , end=\" \") print() # Driver codearr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]n = len(arr)sort012(arr, n)printArray(arr, n) # This code is contributed by Gitanjali.", "e": 28998, "s": 28007, "text": null }, { "code": "// Simple C# program// to sort an array of 0s// 1s and 2s.using System; public class GfG{ public static void sort012(int []arr, int n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array int count0 = 0, count1 = 0; int count2 = 0; for (int i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (int i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (int i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (int i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array public static void printArray(int []arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver function public static void Main() { int []arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = 12; sort012(arr, n); }} // This code is contributed by vt_m", "e": 30400, "s": 28998, "text": null }, { "code": "<script> // JavaScript program// to sort an array of 0s// 1s and 2s. function sort012(arr, n) { // Variables to maintain // the count of 0's, // 1's and 2's in the array let count0 = 0, count1 = 0; let count2 = 0; for (let i = 0; i < n; i++) { if (arr[i] == 0) count0++; if (arr[i] == 1) count1++; if (arr[i] == 2) count2++; } // Putting the 0's in the // array in starting. for (let i = 0; i < count0; i++) arr[i] = 0; // Putting the 1's in the // array after the 0's. for (let i = count0; i < (count0 + count1); i++) arr[i] = 1; // Putting the 2's in the // array after the 1's for (let i = (count0 + count1); i < n; i++) arr[i] = 2; printArray(arr, n); } // Prints the array function printArray(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); document.write(); } // Driver code let arr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]; let n = 12; sort012(arr, n); </script>", "e": 31684, "s": 30400, "text": null }, { "code": null, "e": 31709, "s": 31684, "text": "0 0 0 0 0 1 1 1 1 1 2 2 " }, { "code": null, "e": 31744, "s": 31709, "text": "Problems with the above solution.:" }, { "code": null, "e": 32127, "s": 31744, "text": "It requires two traversals of array.This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one." }, { "code": null, "e": 32164, "s": 32127, "text": "It requires two traversals of array." }, { "code": null, "e": 32511, "s": 32164, "text": "This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one." }, { "code": null, "e": 32529, "s": 32511, "text": "Another Approach:" }, { "code": null, "e": 32534, "s": 32529, "text": "Java" }, { "code": null, "e": 32542, "s": 32534, "text": "Python3" }, { "code": null, "e": 32545, "s": 32542, "text": "C#" }, { "code": null, "e": 32556, "s": 32545, "text": "Javascript" }, { "code": "import java.util.ArrayList;import java.util.List; // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2]class GFG { static int[] inputArray = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; static List<Integer> outputArray = new ArrayList<>(); static int indexOfOne = 0; static void print() { for (int item : inputArray) if (item == 2) outputArray.add(item); else if (item == 1) { outputArray.add(indexOfOne, item); indexOfOne += 1; } else if (item == 0) { outputArray.add(0, item); indexOfOne += 1; } else { System.out.println(\" wrong value - Aborting \"); continue; } } public static void main(String[] args) { print(); for (int item : outputArray) System.out.print(item+\", \"); }}// This code is contributed by Amit Katiyar", "e": 33505, "s": 32556, "text": null }, { "code": "# Example## input = [0, 1, 2, 2, 0, 0]# output = [0, 0, 0, 1, 2, 2] inputArray = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]outputArray = []indexOfOne = 0for item in inputArray: if item == 2: outputArray.append(item) elif item == 1: outputArray.insert(indexOfOne, item) indexOfOne += 1 elif item == 0: outputArray.insert(0, item) indexOfOne += 1 else: print(\" wrong value - Aborting \") continueprint(outputArray)", "e": 33972, "s": 33505, "text": null }, { "code": "using System;using System.Collections.Generic; // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2] class GFG{ static int[] inputArray = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };static List<int> outputArray = new List<int>();static int indexOfOne = 0; static void print(){ foreach (int item in inputArray) if (item == 2) outputArray.Add(item); else if (item == 1) { outputArray.Insert(indexOfOne, item); indexOfOne += 1; } else if (item == 0) { outputArray.Insert(0, item); indexOfOne += 1; } else { Console.WriteLine(\" wrong value - Aborting \"); continue; }} // Driver codepublic static void Main(String[] args){ print(); foreach(int item in outputArray) Console.Write(item + \", \");}} // This code is contributed by 29AjayKumar", "e": 34912, "s": 33972, "text": null }, { "code": "<script> // Example//// input = [0, 1, 2, 2, 0, 0]// output = [0, 0, 0, 1, 2, 2]let inputArray=[ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ];let outputArray = [];let indexOfOne = 0; function print(){ for (let item of inputArray.values()) if (item == 2) outputArray.push(item); else if (item == 1) { outputArray.splice(indexOfOne,0, item); indexOfOne += 1; } else if (item == 0) { outputArray.splice(0,0, item); indexOfOne += 1; } else { document.write(\" wrong value - Aborting \"); continue; }} print();for (let item of outputArray.values()) document.write(item+\", \"); // This code is contributed by rag2127</script>", "e": 35687, "s": 34912, "text": null }, { "code": null, "e": 35695, "s": 35687, "text": "Output:" }, { "code": null, "e": 35732, "s": 35695, "text": "0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, " }, { "code": null, "e": 35841, "s": 35732, "text": "Optimal Solution that handles above issues : Sort an array of 0s, 1s and 2s (Dutch National Flag Algorithm) " }, { "code": null, "e": 35856, "s": 35841, "text": "kishandewangan" }, { "code": null, "e": 35866, "s": 35856, "text": "splevel62" }, { "code": null, "e": 35881, "s": 35866, "text": "amit143katiyar" }, { "code": null, "e": 35893, "s": 35881, "text": "29AjayKumar" }, { "code": null, "e": 35901, "s": 35893, "text": "rag2127" }, { "code": null, "e": 35918, "s": 35901, "text": "kshitijsauravnik" }, { "code": null, "e": 35932, "s": 35918, "text": "counting-sort" }, { "code": null, "e": 35955, "s": 35932, "text": "limited-range-elements" }, { "code": null, "e": 35963, "s": 35955, "text": "Sorting" }, { "code": null, "e": 35971, "s": 35963, "text": "Sorting" }, { "code": null, "e": 36069, "s": 35971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36078, "s": 36069, "text": "Comments" }, { "code": null, "e": 36091, "s": 36078, "text": "Old Comments" }, { "code": null, "e": 36135, "s": 36091, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 36159, "s": 36135, "text": "Merge two sorted arrays" }, { "code": null, "e": 36190, "s": 36159, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 36202, "s": 36190, "text": "Bucket Sort" }, { "code": null, "e": 36236, "s": 36202, "text": "Most frequent element in an array" }, { "code": null, "e": 36253, "s": 36236, "text": "sort() in Python" }, { "code": null, "e": 36279, "s": 36253, "text": "Python List sort() method" }, { "code": null, "e": 36308, "s": 36279, "text": "Python Program for QuickSort" }, { "code": null, "e": 36334, "s": 36308, "text": "C++ Program for QuickSort" } ]
Bootstrap 4 - Quick Guide
Bootstrap 4 is a powerful and popular mobile first front-end framework for building responsive mobile first sites on the web. It is a latest version of Bootstrap, which uses HTML, CSS and JavaScript. The last stable release of Bootstrap v3.3.7 was in July 2016 and in August 2017, Bootstrap 4.0.0 beta version released. It contains mobile first styles throughout the entire library, instead of using them in the separate files. It contains mobile first styles throughout the entire library, instead of using them in the separate files. With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation. With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation. It is supported by all popular browsers and its responsive CSS adjusts to Desktops, Tablets and Mobiles. It is supported by all popular browsers and its responsive CSS adjusts to Desktops, Tablets and Mobiles. Provides a clean and uniform solution for building an interface for developers. Provides a clean and uniform solution for building an interface for developers. It contains beautiful and functional built-in components which are easy to customize. It contains beautiful and functional built-in components which are easy to customize. It is an open source and provides web based customization. It is an open source and provides web based customization. Bootstrap 4 is a latest version of Bootstrap 3, who's source CSS files are converted into SCSS. It uses the flex modal for grid system and supports all the latest browsers. However, it supports Internet Explorer 9+ and iOS 7+ and dropped support for IE 8 and lesser versions, iOS 6 and lesser versions. For more information on difference between Bootstrap 3 and Bootstrap 4, checkout this chapter. You can start using Bootstrap 4 in your website by including it from CDN(Content Delivery Network) or downloading from getbootstrap.com. The Bootstrap 4 can be used in the website by including it from Content Delivery Network. Use the below compiled Bootstrap's CDN of CSS and JS in your project. <!-- Compiled and Minified Bootstrap CSS --> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity = "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin = "anonymous"> <!-- jQuery Library --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Compiled and Minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous"> </script> Include the CDN versions of jQuery and Popper.js (Bootstrap 4 uses jQuery and Popper.js to make use of JavaScript components such as modals, tooltips, popovers etc) before the minified Bootstrap JavaScript, if you are using the compiled version of JavaScript. Following are some components, which require jQuery − Used for closable alerts Used for closable alerts Toggle the states by using buttons and checkboxes/radio buttons and collapse for toggling content Toggle the states by using buttons and checkboxes/radio buttons and collapse for toggling content Carousel for slides, controls, and indicators Carousel for slides, controls, and indicators Dropdowns (uses the Popper.js for perfect positioning) Dropdowns (uses the Popper.js for perfect positioning) Open and close the Modals Open and close the Modals For collapsing the Navbar For collapsing the Navbar Tooltips and popovers (uses the Popper.js for perfect positioning) Tooltips and popovers (uses the Popper.js for perfect positioning) You can download the Bootstrap 4 from https://getbootstrap.com/docs/4.1/getting-started/download/. When you click on this link, you will get to see a screen as shown below − Here you can see two buttons − Download − Clicking this, you can download the precompiled and minified versions of Bootstrap's CSS and JavaScript. No documentation or original source code files are included. Download − Clicking this, you can download the precompiled and minified versions of Bootstrap's CSS and JavaScript. No documentation or original source code files are included. Download Source − Clicking this, you can get the latest Bootstrap SCSS, JavaScript source code and documentation files. Download Source − Clicking this, you can get the latest Bootstrap SCSS, JavaScript source code and documentation files. For better understanding and ease of use, we shall use precompiled version of Bootstrap throughout the tutorial. As the files are complied and minified, you don't have to bother every time including separate files for individual functionality. Once the compiled version Bootstrap 4 is downloaded, extract the ZIP file, and you will see the following file/directory structure − As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*). If you have downloaded the Bootstrap 4 source code, then the file structure would be as follows − The files under js/ and scss/ are the source code for Bootstrap CSS and JavaScript. The files under js/ and scss/ are the source code for Bootstrap CSS and JavaScript. The dist/ folder include everything listed in the precompiled download section above. The dist/ folder include everything listed in the precompiled download section above. The docs/examples/, includes source code for Bootstrap documentation and examples of Bootstrap usage. The docs/examples/, includes source code for Bootstrap documentation and examples of Bootstrap usage. The below example specifies simple web page of Bootstrap 4 − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width=device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity =" sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <h2>Hello, world!!! Welcome to Tutorialspoint...</h2> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Bootstrap 4 uses container classes to wrap the page's contents. It contains two container classes − .container − It represents a fixed width container. .container − It represents a fixed width container. .container-fluid − It represents a full width container. .container-fluid − It represents a full width container. The .container class is used to wrap the page content with fixed width and content can be placed in the center easily by using the .container class as shown below. <div class = "container"> ... </div> The below example specifies a simple web page with fixed width container − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> <style> .container { background: #a52c644a; text-align: center; padding-top: 100px; padding-bottom: 100px; } </style> </head> <body> <div class = "container"> <h2>Fixed Width Container</h2> This is a simple web page with fixed width container by using <code>.container</code> class. </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − You can create a full width container by using the .container-fluid class as shown below. <div class = "container-fluid"> ... </div> The below example specifies a simple web page with full width container − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> <style> .container-fluid { background: #a52c644a; text-align: center; padding-top: 100px; padding-bottom: 100px; } </style> </head> <body> <div class = "container-fluid"> <h2>Full Width Container</h2> This is a simple web page with full width container by using <code>.container-fluid</code> class. </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity =" sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Bootstrap 4 grid system built with flexbox which is fully responsive and scales up to 12 columns (according to the size of device) by creating layout with rows and columns across the page. It provides responsive, mobile first fluid grid system which scales the columns as the device or viewport size increases. Rows must be placed within a .container class for proper alignment and padding. Rows must be placed within a .container class for proper alignment and padding. For responsive width use .container class and for fixed width across all viewport, use the .container-fluid class. For responsive width use .container class and for fixed width across all viewport, use the .container-fluid class. Use rows to create horizontal groups of columns. Use rows to create horizontal groups of columns. Content should be placed within the columns, and only columns may be the immediate children of rows. Content should be placed within the columns, and only columns may be the immediate children of rows. Columns contain padding for controlling the space between them. Columns contain padding for controlling the space between them. If you place more than 12 columns in a row, then the columns will be placed in a new line. If you place more than 12 columns in a row, then the columns will be placed in a new line. Columns create gaps between column content via padding. Therefore, you can remove the margin from rows and padding from columns with .no-gutters class on the row. Columns create gaps between column content via padding. Therefore, you can remove the margin from rows and padding from columns with .no-gutters class on the row. You can make grid system responsive by using five grid breakpoints such as extra small, small, medium, large, and extra large. You can make grid system responsive by using five grid breakpoints such as extra small, small, medium, large, and extra large. Predefined grid classes like .col-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts. Predefined grid classes like .col-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts. The following table summarizes aspects of how Bootstrap 4 grid system works across multiple devices − 30px (15px on each side of a column) 30px (15px on each side of a column) 30px (15px on each side of a column) 30px (15px on each side of a column) 30px (15px on each side of a column) Following is basic structure of Bootstrap 4 grid − <div class = "container"> <div class = "row"> <div class = "col-*-*"></div> <div class = "col-*-*"></div> </div> <div class = "row"> <div class = "col-*-*"></div> <div class = "col-*-*"></div> <div class = "col-*-*"></div> </div> <div class = "row">...</div> </div> Following is an example of Bootstrap 4 grid system − <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </style> .grid_system div[class^="col"] { border: 1px solid white; background: #e4dcdc; text-align: center; padding-top: 5px; padding-bottom: 5px } </style> </head> <body> <div class = "grid_system"> <div class = "row"> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> <div class = "col-sm-1">.col-sm-1</div> </div> <div class = "row"> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-3">.col-sm-3</div> </div> <div class = "row"> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-4">.col-sm-4</div> </div> <div class = "row"> <div class =" col-sm-3">.col-sm-3</div> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-6">.col-sm-6</div> </div> <div class = "row"> <div class = "col-sm-5">.col-sm-5</div> <div class = "col-sm-7">.col-sm-7</div> </div> <div class = "row"> <div class = "col-sm-6">.col-sm-6</div> <div class = "col-sm-6">.col-sm-6</div> </div> <div class = "row"> <div class = "col-sm-12">.col-sm-12</div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − The following example describes creating two column layouts for small, medium and large devices. On small devices such as mobile phones, columns will automatically become horizontal as default. <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "grid_system"> <div class = "row"> <div class = "col-sm-6">.col-sm-6</div> <div class = "col-sm-6">.col-sm-6</div> </div> <div class = "row"> <div class = "col-sm-7">.col-sm-7</div> <div class = "col-sm-5">.col-sm-5</div> </div> <div class = "row"> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-8">.col-sm-8</div> </div> <div class = "row"> <div class = "col-sm-9">.col-sm-9</div> <div class = "col-sm-3">.col-sm-3</div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − The following example describes creating three column layouts for medium and large devices. If the screen resolution is more than or equal to 992 pixels, then it will display in landscape mode in tablets and as usual, it will display in portrait mode. <html lang = "en"> <head> <!-- Meta tags --> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no"> <!-- Bootstrap CSS --> <link rel = " stylesheet" href = " https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin = "anonymous"> <title>Bootstrap 4 Example</title> </head> <body> <div class = "grid_system"> <div class = "row"> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-4">.col-sm-4</div> </div> <div class = "row"> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-4">.col-sm-4</div> <div class = "col-sm-5">.col-sm-5</div> </div> <div class = "row"> <div class = "col-sm-2">.col-sm-2</div> <div class = "col-sm-8">.col-sm-8</div> <div class = "col-sm-2">.col-sm-2</div> </div> <div class = "row"> <div class = "col-sm-2">.col-sm-2</div> <div class = "col-sm-3">.col-sm-3</div> <div class = "col-sm-7">.col-sm-7</div> </div> </div> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous"> </script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin = "anonymous"> </script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin = "anonymous"> </script> </body> </html> It will produce the following result − Bootstrap 4 uses collection of content methods for displaying the text, blocks of code, responsive images, data in a tabular format etc on the web page. The following table lists down the content methods which you can use to manipulate the Bootstrap 4 − Typography The typography feature creates headings, paragraphs, lists and other inline elements. Code It is used to display inline and multiline blocks of code in the document. Images Bootstrap 4 provides support for images by using <img> tag. Tables Tables are used for displaying the data in a tabular format. Figures The figure element specifies the content along with related images with an optional caption. Bootstrap 4 uses collection of content methods for displaying the text, blocks of code, responsive images, data in a tabular format etc on the web page. The following table lists down the content methods which you can use to manipulate the Bootstrap 4 − Alerts The alert component specifies the predefined message for user actions. Badges Badges are used to highlight the additional information to the content. Breadcrumb It is used to show hierarchy-based information for a site. Buttons Bootstrap provides clickable button to put content such as text and images. Button group Button groups allow multiple buttons to be stacked together on a single line. Cards Card is a content container which displays a bordered box with some padding around it. Carousel Carousel is a flexible, responsive way to add a slider to your site. Collapse It is used to show or hide the content. Dropdowns Dropdown menus can be used for displaying links in a list format. Forms The form element is used to collect input from user. Input group Using input groups you can easily prepend and append text or buttons to the text-based inputs. Jumbotron It increases the size of headings and adds a lot of margin for landing page content. Modal Modal is a child window that is layered over its parent window. Navs Bootstrap provides navigation items for your site in a horizontal menu. Navbar Navbar provides navigation headers for your application or site. Pagination Pagination is used to divide the related content across multiple pages. Popovers Popover is similar to tooltip, offering an extended view complete with a heading. Progress Progress bar shows progress of a process with stacked bars, animated backgrounds, and text labels. Scrollspy Scrollspy is used to indicate currently active link in the menu based on scroll position. Tooltips Tooltips are useful when you need to describe a link. Bootstrap 4 uses collection of utilities for displaying borders, text color, embeding video etc on the web page. The following table lists down the utilities types which you can use to manipulate the Bootstrap 4 − Borders Border utility provides style, color and radius of an element's border. Clearfix and Close Icon Clearfix is used to clear the floated content and close icon for dismissing the content. Colors Use the contextual classes to change the color of text, link and background color of an element. Embed It is used to embed the video in a page by using <iframe> element. Float It is used to float an element to left or right side. Shadows and Spacing Shadow utility adds shadow to the elements and spacing utility provides margin or padding values to an element. Sizing You can make the size of an element wide or tall by using width and height utilities. Text Bootstrap provides text utilities to control text alignment, transform, weight and more. Flex Flex utility can be used to manage the layout, alignment, grid columns, navigation and other components of the page. Bootstrap is a powerful and popular mobile first front-end framework for building responsive mobile first sites on the web by using HTML, CSS and JS framework. The following table shows differences in Bootstrap 3 and Bootstrap 4 − 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 2016, "s": 1816, "text": "Bootstrap 4 is a powerful and popular mobile first front-end framework for building responsive mobile first sites on the web. It is a latest version of Bootstrap, which uses HTML, CSS and JavaScript." }, { "code": null, "e": 2136, "s": 2016, "text": "The last stable release of Bootstrap v3.3.7 was in July 2016 and in August 2017, Bootstrap 4.0.0 beta version released." }, { "code": null, "e": 2244, "s": 2136, "text": "It contains mobile first styles throughout the entire library, instead of using them in the separate files." }, { "code": null, "e": 2352, "s": 2244, "text": "It contains mobile first styles throughout the entire library, instead of using them in the separate files." }, { "code": null, "e": 2490, "s": 2352, "text": "With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation." }, { "code": null, "e": 2628, "s": 2490, "text": "With just the knowledge of HTML and CSS anyone can get started with Bootstrap. Also the Bootstrap official site has a good documentation." }, { "code": null, "e": 2733, "s": 2628, "text": "It is supported by all popular browsers and its responsive CSS adjusts to Desktops, Tablets and Mobiles." }, { "code": null, "e": 2838, "s": 2733, "text": "It is supported by all popular browsers and its responsive CSS adjusts to Desktops, Tablets and Mobiles." }, { "code": null, "e": 2918, "s": 2838, "text": "Provides a clean and uniform solution for building an interface for developers." }, { "code": null, "e": 2998, "s": 2918, "text": "Provides a clean and uniform solution for building an interface for developers." }, { "code": null, "e": 3084, "s": 2998, "text": "It contains beautiful and functional built-in components which are easy to customize." }, { "code": null, "e": 3170, "s": 3084, "text": "It contains beautiful and functional built-in components which are easy to customize." }, { "code": null, "e": 3229, "s": 3170, "text": "It is an open source and provides web based customization." }, { "code": null, "e": 3288, "s": 3229, "text": "It is an open source and provides web based customization." }, { "code": null, "e": 3687, "s": 3288, "text": "Bootstrap 4 is a latest version of Bootstrap 3, who's source CSS files are converted into SCSS. It uses the flex modal for grid system and supports all the latest browsers. However, it supports Internet Explorer 9+ and iOS 7+ and dropped support for IE 8 and lesser versions, iOS 6 and lesser versions. For more information on difference between Bootstrap 3 and Bootstrap 4, checkout this chapter. " }, { "code": null, "e": 3824, "s": 3687, "text": "You can start using Bootstrap 4 in your website by including it from CDN(Content Delivery Network) or downloading from getbootstrap.com." }, { "code": null, "e": 3914, "s": 3824, "text": "The Bootstrap 4 can be used in the website by including it from Content Delivery Network." }, { "code": null, "e": 3984, "s": 3914, "text": "Use the below compiled Bootstrap's CDN of CSS and JS in your project." }, { "code": null, "e": 4984, "s": 3984, "text": "<!-- Compiled and Minified Bootstrap CSS -->\n<link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\"\n integrity = \"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" \n crossorigin = \"anonymous\">\n\n<!-- jQuery Library -->\n<script src = \"https://code.jquery.com/jquery-3.2.1.slim.min.js\" \n integrity = \"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" \n crossorigin = \"anonymous\">\n</script>\n\n<!-- Popper -->\n<script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" \n integrity = \"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" \n crossorigin = \"anonymous\">\n</script>\n\n<!-- Compiled and Minified Bootstrap JavaScript -->\n<script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" \n integrity = \"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" \n crossorigin = \"anonymous\">\n</script>" }, { "code": null, "e": 5244, "s": 4984, "text": "Include the CDN versions of jQuery and Popper.js (Bootstrap 4 uses jQuery and Popper.js to make use of JavaScript components such as modals, tooltips, popovers etc) before the minified Bootstrap JavaScript, if you are using the compiled version of JavaScript." }, { "code": null, "e": 5298, "s": 5244, "text": "Following are some components, which require jQuery −" }, { "code": null, "e": 5323, "s": 5298, "text": "Used for closable alerts" }, { "code": null, "e": 5348, "s": 5323, "text": "Used for closable alerts" }, { "code": null, "e": 5446, "s": 5348, "text": "Toggle the states by using buttons and checkboxes/radio buttons and collapse for toggling content" }, { "code": null, "e": 5544, "s": 5446, "text": "Toggle the states by using buttons and checkboxes/radio buttons and collapse for toggling content" }, { "code": null, "e": 5590, "s": 5544, "text": "Carousel for slides, controls, and indicators" }, { "code": null, "e": 5636, "s": 5590, "text": "Carousel for slides, controls, and indicators" }, { "code": null, "e": 5691, "s": 5636, "text": "Dropdowns (uses the Popper.js for perfect positioning)" }, { "code": null, "e": 5746, "s": 5691, "text": "Dropdowns (uses the Popper.js for perfect positioning)" }, { "code": null, "e": 5772, "s": 5746, "text": "Open and close the Modals" }, { "code": null, "e": 5798, "s": 5772, "text": "Open and close the Modals" }, { "code": null, "e": 5824, "s": 5798, "text": "For collapsing the Navbar" }, { "code": null, "e": 5850, "s": 5824, "text": "For collapsing the Navbar" }, { "code": null, "e": 5917, "s": 5850, "text": "Tooltips and popovers (uses the Popper.js for perfect positioning)" }, { "code": null, "e": 5984, "s": 5917, "text": "Tooltips and popovers (uses the Popper.js for perfect positioning)" }, { "code": null, "e": 6158, "s": 5984, "text": "You can download the Bootstrap 4 from https://getbootstrap.com/docs/4.1/getting-started/download/. When you click on this link, you will get to see a screen as shown below −" }, { "code": null, "e": 6189, "s": 6158, "text": "Here you can see two buttons −" }, { "code": null, "e": 6366, "s": 6189, "text": "Download − Clicking this, you can download the precompiled and minified versions of Bootstrap's CSS and JavaScript. No documentation or original source code files are included." }, { "code": null, "e": 6543, "s": 6366, "text": "Download − Clicking this, you can download the precompiled and minified versions of Bootstrap's CSS and JavaScript. No documentation or original source code files are included." }, { "code": null, "e": 6663, "s": 6543, "text": "Download Source − Clicking this, you can get the latest Bootstrap SCSS, JavaScript source code and documentation files." }, { "code": null, "e": 6783, "s": 6663, "text": "Download Source − Clicking this, you can get the latest Bootstrap SCSS, JavaScript source code and documentation files." }, { "code": null, "e": 7027, "s": 6783, "text": "For better understanding and ease of use, we shall use precompiled version of Bootstrap throughout the tutorial. As the files are complied and minified, you don't have to bother every time including separate files for individual functionality." }, { "code": null, "e": 7160, "s": 7027, "text": "Once the compiled version Bootstrap 4 is downloaded, extract the ZIP file, and you will see the following file/directory structure −" }, { "code": null, "e": 7284, "s": 7160, "text": "As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*)." }, { "code": null, "e": 7382, "s": 7284, "text": "If you have downloaded the Bootstrap 4 source code, then the file structure would be as follows −" }, { "code": null, "e": 7466, "s": 7382, "text": "The files under js/ and scss/ are the source code for Bootstrap CSS and JavaScript." }, { "code": null, "e": 7550, "s": 7466, "text": "The files under js/ and scss/ are the source code for Bootstrap CSS and JavaScript." }, { "code": null, "e": 7636, "s": 7550, "text": "The dist/ folder include everything listed in the precompiled download section above." }, { "code": null, "e": 7722, "s": 7636, "text": "The dist/ folder include everything listed in the precompiled download section above." }, { "code": null, "e": 7824, "s": 7722, "text": "The docs/examples/, includes source code for Bootstrap documentation and examples of Bootstrap usage." }, { "code": null, "e": 7926, "s": 7824, "text": "The docs/examples/, includes source code for Bootstrap documentation and examples of Bootstrap usage." }, { "code": null, "e": 7987, "s": 7926, "text": "The below example specifies simple web page of Bootstrap 4 −" }, { "code": null, "e": 9410, "s": 7987, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"\n integrity =\" sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n \n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <h2>Hello, world!!! Welcome to Tutorialspoint...</h2>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\"\n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 9449, "s": 9410, "text": "It will produce the following result −" }, { "code": null, "e": 9549, "s": 9449, "text": "Bootstrap 4 uses container classes to wrap the page's contents. It contains two container classes −" }, { "code": null, "e": 9601, "s": 9549, "text": ".container − It represents a fixed width container." }, { "code": null, "e": 9653, "s": 9601, "text": ".container − It represents a fixed width container." }, { "code": null, "e": 9710, "s": 9653, "text": ".container-fluid − It represents a full width container." }, { "code": null, "e": 9767, "s": 9710, "text": ".container-fluid − It represents a full width container." }, { "code": null, "e": 9931, "s": 9767, "text": "The .container class is used to wrap the page content with fixed width and content can be placed in the center easily by using the .container class as shown below." }, { "code": null, "e": 9972, "s": 9931, "text": "<div class = \"container\">\n ...\n</div>\n" }, { "code": null, "e": 10047, "s": 9972, "text": "The below example specifies a simple web page with fixed width container −" }, { "code": null, "e": 11806, "s": 10047, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n <style>\n .container {\n background: #a52c644a;\n text-align: center;\n padding-top: 100px;\n padding-bottom: 100px;\n } \n </style>\n </head>\n \n <body>\n <div class = \"container\">\n <h2>Fixed Width Container</h2>\n This is a simple web page with fixed width container by using \n <code>.container</code> class.\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 11845, "s": 11806, "text": "It will produce the following result −" }, { "code": null, "e": 11935, "s": 11845, "text": "You can create a full width container by using the .container-fluid class as shown below." }, { "code": null, "e": 11982, "s": 11935, "text": "<div class = \"container-fluid\">\n ...\n</div>\n" }, { "code": null, "e": 12056, "s": 11982, "text": "The below example specifies a simple web page with full width container −" }, { "code": null, "e": 13832, "s": 12056, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n <style>\n .container-fluid {\n background: #a52c644a;\n text-align: center;\n padding-top: 100px;\n padding-bottom: 100px;\n } \n </style>\n </head>\n \n <body>\n <div class = \"container-fluid\">\n <h2>Full Width Container</h2>\n This is a simple web page with full width container by using \n <code>.container-fluid</code> class.\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity =\" sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 13871, "s": 13832, "text": "It will produce the following result −" }, { "code": null, "e": 14182, "s": 13871, "text": "Bootstrap 4 grid system built with flexbox which is fully responsive and scales up to 12 columns (according to the size of device) by creating layout with rows and columns across the page. It provides responsive, mobile first fluid grid system which scales the columns as the device or viewport size increases." }, { "code": null, "e": 14262, "s": 14182, "text": "Rows must be placed within a .container class for proper alignment and padding." }, { "code": null, "e": 14342, "s": 14262, "text": "Rows must be placed within a .container class for proper alignment and padding." }, { "code": null, "e": 14457, "s": 14342, "text": "For responsive width use .container class and for fixed width across all viewport, use the .container-fluid class." }, { "code": null, "e": 14572, "s": 14457, "text": "For responsive width use .container class and for fixed width across all viewport, use the .container-fluid class." }, { "code": null, "e": 14621, "s": 14572, "text": "Use rows to create horizontal groups of columns." }, { "code": null, "e": 14670, "s": 14621, "text": "Use rows to create horizontal groups of columns." }, { "code": null, "e": 14771, "s": 14670, "text": "Content should be placed within the columns, and only columns may be the immediate children of rows." }, { "code": null, "e": 14872, "s": 14771, "text": "Content should be placed within the columns, and only columns may be the immediate children of rows." }, { "code": null, "e": 14936, "s": 14872, "text": "Columns contain padding for controlling the space between them." }, { "code": null, "e": 15000, "s": 14936, "text": "Columns contain padding for controlling the space between them." }, { "code": null, "e": 15092, "s": 15000, "text": "If you place more than 12 columns in a row, then the columns will be placed in a new line. " }, { "code": null, "e": 15184, "s": 15092, "text": "If you place more than 12 columns in a row, then the columns will be placed in a new line. " }, { "code": null, "e": 15347, "s": 15184, "text": "Columns create gaps between column content via padding. Therefore, you can remove the margin from rows and padding from columns with .no-gutters class on the row." }, { "code": null, "e": 15510, "s": 15347, "text": "Columns create gaps between column content via padding. Therefore, you can remove the margin from rows and padding from columns with .no-gutters class on the row." }, { "code": null, "e": 15637, "s": 15510, "text": "You can make grid system responsive by using five grid breakpoints such as extra small, small, medium, large, and extra large." }, { "code": null, "e": 15764, "s": 15637, "text": "You can make grid system responsive by using five grid breakpoints such as extra small, small, medium, large, and extra large." }, { "code": null, "e": 15903, "s": 15764, "text": "Predefined grid classes like .col-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts." }, { "code": null, "e": 16042, "s": 15903, "text": "Predefined grid classes like .col-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts." }, { "code": null, "e": 16144, "s": 16042, "text": "The following table summarizes aspects of how Bootstrap 4 grid system works across multiple devices −" }, { "code": null, "e": 16149, "s": 16144, "text": "30px" }, { "code": null, "e": 16181, "s": 16149, "text": "(15px on each side of a column)" }, { "code": null, "e": 16186, "s": 16181, "text": "30px" }, { "code": null, "e": 16218, "s": 16186, "text": "(15px on each side of a column)" }, { "code": null, "e": 16223, "s": 16218, "text": "30px" }, { "code": null, "e": 16255, "s": 16223, "text": "(15px on each side of a column)" }, { "code": null, "e": 16260, "s": 16255, "text": "30px" }, { "code": null, "e": 16292, "s": 16260, "text": "(15px on each side of a column)" }, { "code": null, "e": 16297, "s": 16292, "text": "30px" }, { "code": null, "e": 16329, "s": 16297, "text": "(15px on each side of a column)" }, { "code": null, "e": 16380, "s": 16329, "text": "Following is basic structure of Bootstrap 4 grid −" }, { "code": null, "e": 16702, "s": 16380, "text": "<div class = \"container\">\n <div class = \"row\">\n <div class = \"col-*-*\"></div>\n <div class = \"col-*-*\"></div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-*-*\"></div>\n <div class = \"col-*-*\"></div>\n <div class = \"col-*-*\"></div>\t \n </div>\n \n <div class = \"row\">...</div>\n</div>" }, { "code": null, "e": 16755, "s": 16702, "text": "Following is an example of Bootstrap 4 grid system −" }, { "code": null, "e": 20193, "s": 16755, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" \n href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n </style>\n .grid_system div[class^=\"col\"] {\n border: 1px solid white;\n background: #e4dcdc;\n text-align: center;\n padding-top: 5px;\n padding-bottom: 5px\n }\n </style>\n </head>\n \n <body>\n <div class = \"grid_system\">\n <div class = \"row\">\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n <div class = \"col-sm-1\">.col-sm-1</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-4\">.col-sm-4</div>\n </div>\n \n <div class = \"row\">\n <div class =\" col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-6\">.col-sm-6</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-5\">.col-sm-5</div>\n <div class = \"col-sm-7\">.col-sm-7</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-6\">.col-sm-6</div>\n <div class = \"col-sm-6\">.col-sm-6</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-12\">.col-sm-12</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\"\n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 20232, "s": 20193, "text": "It will produce the following result −" }, { "code": null, "e": 20426, "s": 20232, "text": "The following example describes creating two column layouts for small, medium and large devices. On small devices such as mobile phones, columns will automatically become horizontal as default." }, { "code": null, "e": 22446, "s": 20426, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" \n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"grid_system\">\n <div class = \"row\">\n <div class = \"col-sm-6\">.col-sm-6</div>\n <div class = \"col-sm-6\">.col-sm-6</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-7\">.col-sm-7</div>\n <div class = \"col-sm-5\">.col-sm-5</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-8\">.col-sm-8</div>\n </div>\n\t\t \n <div class = \"row\">\n <div class = \"col-sm-9\">.col-sm-9</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 22485, "s": 22446, "text": "It will produce the following result −" }, { "code": null, "e": 22737, "s": 22485, "text": "The following example describes creating three column layouts for medium and large devices. If the screen resolution is more than or equal to 992 pixels, then it will display in landscape mode in tablets and as usual, it will display in portrait mode." }, { "code": null, "e": 24965, "s": 22737, "text": "<html lang = \"en\">\n <head>\n <!-- Meta tags -->\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, shrink-to-fit = no\">\n \n <!-- Bootstrap CSS -->\n <link rel = \" stylesheet\" href = \" https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" \n integrity = \"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\"\n crossorigin = \"anonymous\">\n <title>Bootstrap 4 Example</title>\n </head>\n \n <body>\n <div class = \"grid_system\">\n <div class = \"row\">\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-4\">.col-sm-4</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-4\">.col-sm-4</div>\n <div class = \"col-sm-5\">.col-sm-5</div>\n </div>\n \n <div class = \"row\">\n <div class = \"col-sm-2\">.col-sm-2</div>\n <div class = \"col-sm-8\">.col-sm-8</div>\n <div class = \"col-sm-2\">.col-sm-2</div>\n </div>\n\t\t\n <div class = \"row\">\n <div class = \"col-sm-2\">.col-sm-2</div>\n <div class = \"col-sm-3\">.col-sm-3</div>\n <div class = \"col-sm-7\">.col-sm-7</div>\n </div>\n </div>\n \n <!-- jQuery first, then Popper.js, then Bootstrap JS -->\n <script src = \"https://code.jquery.com/jquery-3.3.1.slim.min.js\" \n integrity = \"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" \n integrity = \"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" \n crossorigin = \"anonymous\">\n </script>\n \n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" \n integrity = \"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" \n crossorigin = \"anonymous\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 25004, "s": 24965, "text": "It will produce the following result −" }, { "code": null, "e": 25157, "s": 25004, "text": "Bootstrap 4 uses collection of content methods for displaying the text, blocks of code, responsive images, data in a tabular format etc on the web page." }, { "code": null, "e": 25258, "s": 25157, "text": "The following table lists down the content methods which you can use to manipulate the Bootstrap 4 −" }, { "code": null, "e": 25269, "s": 25258, "text": "Typography" }, { "code": null, "e": 25355, "s": 25269, "text": "The typography feature creates headings, paragraphs, lists and other inline elements." }, { "code": null, "e": 25360, "s": 25355, "text": "Code" }, { "code": null, "e": 25435, "s": 25360, "text": "It is used to display inline and multiline blocks of code in the document." }, { "code": null, "e": 25442, "s": 25435, "text": "Images" }, { "code": null, "e": 25502, "s": 25442, "text": "Bootstrap 4 provides support for images by using <img> tag." }, { "code": null, "e": 25509, "s": 25502, "text": "Tables" }, { "code": null, "e": 25570, "s": 25509, "text": "Tables are used for displaying the data in a tabular format." }, { "code": null, "e": 25578, "s": 25570, "text": "Figures" }, { "code": null, "e": 25671, "s": 25578, "text": "The figure element specifies the content along with related images with an optional caption." }, { "code": null, "e": 25824, "s": 25671, "text": "Bootstrap 4 uses collection of content methods for displaying the text, blocks of code, responsive images, data in a tabular format etc on the web page." }, { "code": null, "e": 25925, "s": 25824, "text": "The following table lists down the content methods which you can use to manipulate the Bootstrap 4 −" }, { "code": null, "e": 25932, "s": 25925, "text": "Alerts" }, { "code": null, "e": 26003, "s": 25932, "text": "The alert component specifies the predefined message for user actions." }, { "code": null, "e": 26010, "s": 26003, "text": "Badges" }, { "code": null, "e": 26082, "s": 26010, "text": "Badges are used to highlight the additional information to the content." }, { "code": null, "e": 26093, "s": 26082, "text": "Breadcrumb" }, { "code": null, "e": 26152, "s": 26093, "text": "It is used to show hierarchy-based information for a site." }, { "code": null, "e": 26160, "s": 26152, "text": "Buttons" }, { "code": null, "e": 26236, "s": 26160, "text": "Bootstrap provides clickable button to put content such as text and images." }, { "code": null, "e": 26249, "s": 26236, "text": "Button group" }, { "code": null, "e": 26327, "s": 26249, "text": "Button groups allow multiple buttons to be stacked together on a single line." }, { "code": null, "e": 26333, "s": 26327, "text": "Cards" }, { "code": null, "e": 26420, "s": 26333, "text": "Card is a content container which displays a bordered box with some padding around it." }, { "code": null, "e": 26429, "s": 26420, "text": "Carousel" }, { "code": null, "e": 26498, "s": 26429, "text": "Carousel is a flexible, responsive way to add a slider to your site." }, { "code": null, "e": 26507, "s": 26498, "text": "Collapse" }, { "code": null, "e": 26547, "s": 26507, "text": "It is used to show or hide the content." }, { "code": null, "e": 26557, "s": 26547, "text": "Dropdowns" }, { "code": null, "e": 26623, "s": 26557, "text": "Dropdown menus can be used for displaying links in a list format." }, { "code": null, "e": 26629, "s": 26623, "text": "Forms" }, { "code": null, "e": 26682, "s": 26629, "text": "The form element is used to collect input from user." }, { "code": null, "e": 26694, "s": 26682, "text": "Input group" }, { "code": null, "e": 26789, "s": 26694, "text": "Using input groups you can easily prepend and append text or buttons to the text-based inputs." }, { "code": null, "e": 26799, "s": 26789, "text": "Jumbotron" }, { "code": null, "e": 26884, "s": 26799, "text": "It increases the size of headings and adds a lot of margin for landing page content." }, { "code": null, "e": 26890, "s": 26884, "text": "Modal" }, { "code": null, "e": 26954, "s": 26890, "text": "Modal is a child window that is layered over its parent window." }, { "code": null, "e": 26959, "s": 26954, "text": "Navs" }, { "code": null, "e": 27031, "s": 26959, "text": "Bootstrap provides navigation items for your site in a horizontal menu." }, { "code": null, "e": 27038, "s": 27031, "text": "Navbar" }, { "code": null, "e": 27103, "s": 27038, "text": "Navbar provides navigation headers for your application or site." }, { "code": null, "e": 27114, "s": 27103, "text": "Pagination" }, { "code": null, "e": 27186, "s": 27114, "text": "Pagination is used to divide the related content across multiple pages." }, { "code": null, "e": 27195, "s": 27186, "text": "Popovers" }, { "code": null, "e": 27277, "s": 27195, "text": "Popover is similar to tooltip, offering an extended view complete with a heading." }, { "code": null, "e": 27286, "s": 27277, "text": "Progress" }, { "code": null, "e": 27385, "s": 27286, "text": "Progress bar shows progress of a process with stacked bars, animated backgrounds, and text labels." }, { "code": null, "e": 27395, "s": 27385, "text": "Scrollspy" }, { "code": null, "e": 27485, "s": 27395, "text": "Scrollspy is used to indicate currently active link in the menu based on scroll position." }, { "code": null, "e": 27494, "s": 27485, "text": "Tooltips" }, { "code": null, "e": 27548, "s": 27494, "text": "Tooltips are useful when you need to describe a link." }, { "code": null, "e": 27661, "s": 27548, "text": "Bootstrap 4 uses collection of utilities for displaying borders, text color, embeding video etc on the web page." }, { "code": null, "e": 27762, "s": 27661, "text": "The following table lists down the utilities types which you can use to manipulate the Bootstrap 4 −" }, { "code": null, "e": 27770, "s": 27762, "text": "Borders" }, { "code": null, "e": 27842, "s": 27770, "text": "Border utility provides style, color and radius of an element's border." }, { "code": null, "e": 27866, "s": 27842, "text": "Clearfix and Close Icon" }, { "code": null, "e": 27955, "s": 27866, "text": "Clearfix is used to clear the floated content and close icon for dismissing the content." }, { "code": null, "e": 27962, "s": 27955, "text": "Colors" }, { "code": null, "e": 28059, "s": 27962, "text": "Use the contextual classes to change the color of text, link and background color of an element." }, { "code": null, "e": 28065, "s": 28059, "text": "Embed" }, { "code": null, "e": 28132, "s": 28065, "text": "It is used to embed the video in a page by using <iframe> element." }, { "code": null, "e": 28138, "s": 28132, "text": "Float" }, { "code": null, "e": 28192, "s": 28138, "text": "It is used to float an element to left or right side." }, { "code": null, "e": 28212, "s": 28192, "text": "Shadows and Spacing" }, { "code": null, "e": 28324, "s": 28212, "text": "Shadow utility adds shadow to the elements and spacing utility provides margin or padding values to an element." }, { "code": null, "e": 28331, "s": 28324, "text": "Sizing" }, { "code": null, "e": 28417, "s": 28331, "text": "You can make the size of an element wide or tall by using width and height utilities." }, { "code": null, "e": 28422, "s": 28417, "text": "Text" }, { "code": null, "e": 28511, "s": 28422, "text": "Bootstrap provides text utilities to control text alignment, transform, weight and more." }, { "code": null, "e": 28516, "s": 28511, "text": "Flex" }, { "code": null, "e": 28633, "s": 28516, "text": "Flex utility can be used to manage the layout, alignment, grid columns, navigation and other components of the page." }, { "code": null, "e": 28793, "s": 28633, "text": "Bootstrap is a powerful and popular mobile first front-end framework for building responsive mobile first sites on the web by using HTML, CSS and JS framework." }, { "code": null, "e": 28864, "s": 28793, "text": "The following table shows differences in Bootstrap 3 and Bootstrap 4 −" }, { "code": null, "e": 28897, "s": 28864, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 28911, "s": 28897, "text": " Anadi Sharma" }, { "code": null, "e": 28946, "s": 28911, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 28963, "s": 28946, "text": " Frahaan Hussain" }, { "code": null, "e": 29000, "s": 28963, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 29028, "s": 29000, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 29061, "s": 29028, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 29073, "s": 29061, "text": " Azaz Patel" }, { "code": null, "e": 29108, "s": 29073, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 29125, "s": 29108, "text": " Muhammad Ismail" }, { "code": null, "e": 29158, "s": 29125, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 29178, "s": 29158, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 29185, "s": 29178, "text": " Print" }, { "code": null, "e": 29196, "s": 29185, "text": " Add Notes" } ]
Generating OTP (One time Password) in PHP
10 Oct, 2018 Now these days, OTP (one time password) is mandatory in almost each and every service. A developer can generate OTP in many ways but the challenge is not to be predictive as any one can predict the OTP and can exploit the service. Some of popular format of OTPs are: 4 or 6 digit Numeric OTP. 4 or 6 alphabetic (lowercase / uppercase) OTP. 4 or 6 digit alphanumeric OTP. Examples for n-digit numeric OTP: Input : n = 4 Output : 8723 Input : n = 8 Output : 23914072 Note: The output of program will be different in every execution. One of the best way to generate OTP is to use random function. But using random function directly can be dangerous. So here is an method which uses random function and some algorithm for generating the n-digit numeric OTP. Program: <?php // Function to generate OTPfunction generateNumericOTP($n) { // Take a generator string which consist of // all numeric digits $generator = "1357902468"; // Iterate for n-times and pick a single character // from generator and append it to $result // Login for generating a random character from generator // ---generate a random number // ---take modulus of same with length of generator (say i) // ---append the character at place (i) from generator to result $result = ""; for ($i = 1; $i <= $n; $i++) { $result .= substr($generator, (rand()%(strlen($generator))), 1); } // Return result return $result;} // Main program$n = 6;print_r(generateNumericOTP($n)); ?> 561862 Algorithms PHP PHP Programs Randomized Algorithms PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Oct, 2018" }, { "code": null, "e": 285, "s": 54, "text": "Now these days, OTP (one time password) is mandatory in almost each and every service. A developer can generate OTP in many ways but the challenge is not to be predictive as any one can predict the OTP and can exploit the service." }, { "code": null, "e": 321, "s": 285, "text": "Some of popular format of OTPs are:" }, { "code": null, "e": 347, "s": 321, "text": "4 or 6 digit Numeric OTP." }, { "code": null, "e": 394, "s": 347, "text": "4 or 6 alphabetic (lowercase / uppercase) OTP." }, { "code": null, "e": 425, "s": 394, "text": "4 or 6 digit alphanumeric OTP." }, { "code": null, "e": 459, "s": 425, "text": "Examples for n-digit numeric OTP:" }, { "code": null, "e": 521, "s": 459, "text": "Input : n = 4\nOutput : 8723\n\nInput : n = 8\nOutput : 23914072\n" }, { "code": null, "e": 587, "s": 521, "text": "Note: The output of program will be different in every execution." }, { "code": null, "e": 810, "s": 587, "text": "One of the best way to generate OTP is to use random function. But using random function directly can be dangerous. So here is an method which uses random function and some algorithm for generating the n-digit numeric OTP." }, { "code": null, "e": 819, "s": 810, "text": "Program:" }, { "code": "<?php // Function to generate OTPfunction generateNumericOTP($n) { // Take a generator string which consist of // all numeric digits $generator = \"1357902468\"; // Iterate for n-times and pick a single character // from generator and append it to $result // Login for generating a random character from generator // ---generate a random number // ---take modulus of same with length of generator (say i) // ---append the character at place (i) from generator to result $result = \"\"; for ($i = 1; $i <= $n; $i++) { $result .= substr($generator, (rand()%(strlen($generator))), 1); } // Return result return $result;} // Main program$n = 6;print_r(generateNumericOTP($n)); ?>", "e": 1575, "s": 819, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "561862\n" }, { "code": null, "e": 1594, "s": 1583, "text": "Algorithms" }, { "code": null, "e": 1598, "s": 1594, "text": "PHP" }, { "code": null, "e": 1611, "s": 1598, "text": "PHP Programs" }, { "code": null, "e": 1622, "s": 1611, "text": "Randomized" }, { "code": null, "e": 1633, "s": 1622, "text": "Algorithms" }, { "code": null, "e": 1637, "s": 1633, "text": "PHP" } ]
LocalStorage and SessionStorage | Web Storage APIs
23 May, 2022 SessionStorage and LocalStorage are known as the web storage API. Data can be stored on the client side by using these APIs. SessionStorage: SessionStorage is used for storing data on the client side. Maximum limit of data saving in SessionStorage is about 5 MB. Data in the SessionStorage exist till the current tab is open if we close the current tab then our data will also erase automatically from the SessionStorage. Note: If after closing the current tab we press ctrl+shift+T for restoring that tab, then ideally in SessionStorage data should not be there but we can see that SessionStorage is maintained in the chrome, firefox but not in the safari browser while restoring the tab. It is the browser dependent feature while restoring the tab. LocalStorage: Like SessionStorage, LocalStorage also used for storing the data on the client side. Maximum limit of data saving is about 5 MB in LocalStorage also. LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it. This is the only difference between LocalStorage and SessionStorage Below are some details about SessionStorage and LocalStorage: Both are Object type: Format of storing data in SessionStorage and LocalStorage: Data must be stored in key-value pair in the SessionStorage and LocalStorage and key-value must be either number or string Here it can be seen that till we are inserting data in the form of string or number, we are able to get data correcrly! In the second last attempt we are going to inserting a plain object into key geek and when we get that item it return [object, object] LocalStorage.setItem("geek", { "key":"value" }) undefined LocalStorage.getItem("geek") "[object Object]" If we want to store object or something else except string/number then it must be in the form of string that is what we have done in the last attempt. LocalStorage.setItem("geeks", JSON.stringify({ "key":"value" })) undefined LocalStorage.getItem("geeks") "{"key":"value"}" In this attempt we use JSON.stringify() method to convert an object into string. Common methods in LocalStorage and SessionStorage: For storing data in web storage: LocalStorage.setItem("key", "value"); //key and value both should be string or number; SessionStorage.setItem("key", "value"); //key and value both should be string or number; For getting data from web storage: LocalStorage.getItem("key"); SessionStorage.getItem("key"); Here we will pass the key and it will return value. For Getting the length of web storage object: LocalStorage.length; SessionStorage.length; For deleting a particular key-value pair: LocalStorage.removeItem("key"); SessionStorage.removeItem("key"); when we pass key in method, it will erase the complete data related to that key. For clearing complete storage: LocalStorage.clear(); SessionStorage.clear(); For getting nth key name from web storage we will pass the number n: LocalStorage.key(n); SessionStorage.key(n); Note: Web storage security is a big concern. it is highly recommended never to store sensitive information in web storage as it always stores the data in the plain text format, and anyone can steal the data easily. so never store password or payment credentials with web storage.Web storage can only store the data on the client side, only client side or our javascript can play with that data. To be saved data on the server-side, Cookies is the better option. Web storage security is a big concern. it is highly recommended never to store sensitive information in web storage as it always stores the data in the plain text format, and anyone can steal the data easily. so never store password or payment credentials with web storage. Web storage can only store the data on the client side, only client side or our javascript can play with that data. To be saved data on the server-side, Cookies is the better option. Storing Non-String values with JSON: localStrorage can use only the String values and if we want to store object or arrays as values in localStorage then we can use the JSON.stringify() to convert them into the String. When the creating or updating key/value pairs in localStorage then we can use JSON.stringify() with the object or array as the argument: let gfgObj = { name: 'GeeksForGeeks', Score: '100' }; localStorage.setItem(key, JSON.stringify(gfgObj));//Here Object is store as the String Although gfgObj is an object, JSON.stringify(gfgObj) converts into a string. So gfgObj is now a valid localStorage value. To read and return Stringified values, use the JSON.parse() method. The JSON.parse() method takes JSON strings and converts them into JavaScript objects. JSON.parse() takes .getItem() as it’s argument: let item = JSON.parse(localStorage.getItem(key)); This is also same for the sessionStorage. sameerhakeentc2019 Web technologies JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 154, "s": 28, "text": "SessionStorage and LocalStorage are known as the web storage API. Data can be stored on the client side by using these APIs. " }, { "code": null, "e": 170, "s": 154, "text": "SessionStorage:" }, { "code": null, "e": 230, "s": 170, "text": "SessionStorage is used for storing data on the client side." }, { "code": null, "e": 292, "s": 230, "text": "Maximum limit of data saving in SessionStorage is about 5 MB." }, { "code": null, "e": 451, "s": 292, "text": "Data in the SessionStorage exist till the current tab is open if we close the current tab then our data will also erase automatically from the SessionStorage." }, { "code": null, "e": 781, "s": 451, "text": "Note: If after closing the current tab we press ctrl+shift+T for restoring that tab, then ideally in SessionStorage data should not be there but we can see that SessionStorage is maintained in the chrome, firefox but not in the safari browser while restoring the tab. It is the browser dependent feature while restoring the tab. " }, { "code": null, "e": 795, "s": 781, "text": "LocalStorage:" }, { "code": null, "e": 880, "s": 795, "text": "Like SessionStorage, LocalStorage also used for storing the data on the client side." }, { "code": null, "e": 945, "s": 880, "text": "Maximum limit of data saving is about 5 MB in LocalStorage also." }, { "code": null, "e": 1117, "s": 945, "text": "LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it. This is the only difference between LocalStorage and SessionStorage" }, { "code": null, "e": 1179, "s": 1117, "text": "Below are some details about SessionStorage and LocalStorage:" }, { "code": null, "e": 1202, "s": 1179, "text": "Both are Object type: " }, { "code": null, "e": 1384, "s": 1202, "text": "Format of storing data in SessionStorage and LocalStorage: Data must be stored in key-value pair in the SessionStorage and LocalStorage and key-value must be either number or string" }, { "code": null, "e": 1642, "s": 1387, "text": "Here it can be seen that till we are inserting data in the form of string or number, we are able to get data correcrly! In the second last attempt we are going to inserting a plain object into key geek and when we get that item it return [object, object]" }, { "code": null, "e": 1747, "s": 1642, "text": "LocalStorage.setItem(\"geek\", {\n\"key\":\"value\"\n})\nundefined\nLocalStorage.getItem(\"geek\")\n\"[object Object]\"" }, { "code": null, "e": 1898, "s": 1747, "text": "If we want to store object or something else except string/number then it must be in the form of string that is what we have done in the last attempt." }, { "code": null, "e": 2021, "s": 1898, "text": "LocalStorage.setItem(\"geeks\", JSON.stringify({\n\"key\":\"value\"\n}))\nundefined\nLocalStorage.getItem(\"geeks\")\n\"{\"key\":\"value\"}\"" }, { "code": null, "e": 2102, "s": 2021, "text": "In this attempt we use JSON.stringify() method to convert an object into string." }, { "code": null, "e": 2153, "s": 2102, "text": "Common methods in LocalStorage and SessionStorage:" }, { "code": null, "e": 2186, "s": 2153, "text": "For storing data in web storage:" }, { "code": null, "e": 2364, "s": 2186, "text": "LocalStorage.setItem(\"key\", \"value\"); //key and value both should be string or number;\nSessionStorage.setItem(\"key\", \"value\"); //key and value both should be string or number;" }, { "code": null, "e": 2399, "s": 2364, "text": "For getting data from web storage:" }, { "code": null, "e": 2512, "s": 2399, "text": "LocalStorage.getItem(\"key\");\nSessionStorage.getItem(\"key\");\n\nHere we will pass the key and it will return value." }, { "code": null, "e": 2558, "s": 2512, "text": "For Getting the length of web storage object:" }, { "code": null, "e": 2603, "s": 2558, "text": "LocalStorage.length; \nSessionStorage.length;" }, { "code": null, "e": 2645, "s": 2603, "text": "For deleting a particular key-value pair:" }, { "code": null, "e": 2793, "s": 2645, "text": "LocalStorage.removeItem(\"key\");\nSessionStorage.removeItem(\"key\");\n\nwhen we pass key in method,\nit will erase the complete data related to that key." }, { "code": null, "e": 2824, "s": 2793, "text": "For clearing complete storage:" }, { "code": null, "e": 2870, "s": 2824, "text": "LocalStorage.clear();\nSessionStorage.clear();" }, { "code": null, "e": 2939, "s": 2870, "text": "For getting nth key name from web storage we will pass the number n:" }, { "code": null, "e": 2983, "s": 2939, "text": "LocalStorage.key(n);\nSessionStorage.key(n);" }, { "code": null, "e": 2989, "s": 2983, "text": "Note:" }, { "code": null, "e": 3445, "s": 2989, "text": "Web storage security is a big concern. it is highly recommended never to store sensitive information in web storage as it always stores the data in the plain text format, and anyone can steal the data easily. so never store password or payment credentials with web storage.Web storage can only store the data on the client side, only client side or our javascript can play with that data. To be saved data on the server-side, Cookies is the better option." }, { "code": null, "e": 3719, "s": 3445, "text": "Web storage security is a big concern. it is highly recommended never to store sensitive information in web storage as it always stores the data in the plain text format, and anyone can steal the data easily. so never store password or payment credentials with web storage." }, { "code": null, "e": 3902, "s": 3719, "text": "Web storage can only store the data on the client side, only client side or our javascript can play with that data. To be saved data on the server-side, Cookies is the better option." }, { "code": null, "e": 3939, "s": 3902, "text": "Storing Non-String values with JSON:" }, { "code": null, "e": 4121, "s": 3939, "text": "localStrorage can use only the String values and if we want to store object or arrays as values in localStorage then we can use the JSON.stringify() to convert them into the String." }, { "code": null, "e": 4260, "s": 4121, "text": "When the creating or updating key/value pairs in localStorage then we can use JSON.stringify() with the object or array as the argument:" }, { "code": null, "e": 4401, "s": 4260, "text": "let gfgObj = { name: 'GeeksForGeeks', Score: '100' };\nlocalStorage.setItem(key, JSON.stringify(gfgObj));//Here Object is store as the String" }, { "code": null, "e": 4525, "s": 4401, "text": "Although gfgObj is an object, JSON.stringify(gfgObj) converts into a string. So gfgObj is now a valid localStorage value." }, { "code": null, "e": 4727, "s": 4525, "text": "To read and return Stringified values, use the JSON.parse() method. The JSON.parse() method takes JSON strings and converts them into JavaScript objects. JSON.parse() takes .getItem() as it’s argument:" }, { "code": null, "e": 4777, "s": 4727, "text": "let item = JSON.parse(localStorage.getItem(key));" }, { "code": null, "e": 4819, "s": 4777, "text": "This is also same for the sessionStorage." }, { "code": null, "e": 4838, "s": 4819, "text": "sameerhakeentc2019" }, { "code": null, "e": 4855, "s": 4838, "text": "Web technologies" }, { "code": null, "e": 4866, "s": 4855, "text": "JavaScript" }, { "code": null, "e": 4883, "s": 4866, "text": "Web Technologies" }, { "code": null, "e": 4981, "s": 4883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5042, "s": 4981, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5114, "s": 5042, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5154, "s": 5114, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5196, "s": 5154, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5237, "s": 5196, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5270, "s": 5237, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5332, "s": 5270, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5393, "s": 5332, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5443, "s": 5393, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
ScheduledExecutorService Interface in Java
19 Oct, 2020 The ScheduledExecutorService interface in Java is a sub-interface of ExecutorService interface defined in java.util.concurrent package. This interface is used to run the given tasks periodically or once after a given delay. The ScheduledExecutorService interface has declared some useful methods to schedule the given tasks. These methods are implemented by the ScheduledThreadPoolExecutor class. Declaration public interface ScheduledExecutorService extends ExecutorService The Hierarchy of ScheduledExecutorService Implementing class The implementing class of ScheduledExecutorService is ScheduledThreadPoolExecutor. Creating a ScheduledExecutorService object Since ScheduledExecutorService is an interface, so it can not be instantiated. But the Executors class, defined in java.util.concurrent package, provides some factory methods that return ScheduledExecutorService objects( objects of its implementing classes ) public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. This object can be used to run tasks after a given delay or to execute periodically. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize , ThreadFactory threadFactory) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. The second argument is a ThreadFactory object that is used when a new thread is created. Example of ScheduledExecutorService interface : Java // Java Program to demonstrate// SchedulerExecutorService import java.util.concurrent.*;import java.util.*;import java.io.*; class SchedulerExecutorServiceExample { public static void main(String[] args) { System.out.println( "A count-down-clock program that counts from 10 to 0"); // creating a ScheduledExecutorService object ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); // printing the current time System.out.println( "Current time : " + Calendar.getInstance().get(Calendar.SECOND)); // Scheduling the tasks for (int i = 10; i >= 0; i--) { scheduler.schedule(new Task(i), 10 - i, TimeUnit.SECONDS); } // remember to shutdown the scheduler // so that it no longer accepts // any new tasks scheduler.shutdown(); }} class Task implements Runnable { private int num; public Task(int num) { this.num = num; } public void run() { System.out.println( "Number " + num + " Current time : " + Calendar.getInstance().get(Calendar.SECOND)); }} Output: A count-down-clock program that counts from 10 to 0 Current time : 28 Number 10 Current time : 28 Number 9 Current time : 29 Number 8 Current time : 30 Number 7 Current time : 31 Number 6 Current time : 32 Number 5 Current time : 33 Number 4 Current time : 34 Number 3 Current time : 35 Number 2 Current time : 36 Number 1 Current time : 37 Number 0 Current time : 38 This is a Countdown Clock that counts from 10 to 0. The ScheduledExexutorService object i.e; scheduler is created using the Executors.newScheduledThreadPool(int corePoolSize) method. Note: All the tasks executed after (10 – i) seconds delay from the invocation of schedule() method. The value of the current time may vary in the output based on the time of execution. METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION Java-concurrent-package 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": "\n19 Oct, 2020" }, { "code": null, "e": 425, "s": 28, "text": "The ScheduledExecutorService interface in Java is a sub-interface of ExecutorService interface defined in java.util.concurrent package. This interface is used to run the given tasks periodically or once after a given delay. The ScheduledExecutorService interface has declared some useful methods to schedule the given tasks. These methods are implemented by the ScheduledThreadPoolExecutor class." }, { "code": null, "e": 437, "s": 425, "text": "Declaration" }, { "code": null, "e": 504, "s": 437, "text": "public interface ScheduledExecutorService extends ExecutorService\n" }, { "code": null, "e": 546, "s": 504, "text": "The Hierarchy of ScheduledExecutorService" }, { "code": null, "e": 565, "s": 546, "text": "Implementing class" }, { "code": null, "e": 648, "s": 565, "text": "The implementing class of ScheduledExecutorService is ScheduledThreadPoolExecutor." }, { "code": null, "e": 692, "s": 648, "text": "Creating a ScheduledExecutorService object " }, { "code": null, "e": 951, "s": 692, "text": "Since ScheduledExecutorService is an interface, so it can not be instantiated. But the Executors class, defined in java.util.concurrent package, provides some factory methods that return ScheduledExecutorService objects( objects of its implementing classes )" }, { "code": null, "e": 1307, "s": 951, "text": "public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. This object can be used to run tasks after a given delay or to execute periodically. " }, { "code": null, "e": 1696, "s": 1307, "text": "public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize , ThreadFactory threadFactory) : Creates a new scheduled thread pool with a given core pool size (corePoolSize) and returns a ScheduledExecutorService object which can be downcasted to ScheduledThreadPoolExecutor object. The second argument is a ThreadFactory object that is used when a new thread is created." }, { "code": null, "e": 1745, "s": 1696, "text": "Example of ScheduledExecutorService interface : " }, { "code": null, "e": 1750, "s": 1745, "text": "Java" }, { "code": "// Java Program to demonstrate// SchedulerExecutorService import java.util.concurrent.*;import java.util.*;import java.io.*; class SchedulerExecutorServiceExample { public static void main(String[] args) { System.out.println( \"A count-down-clock program that counts from 10 to 0\"); // creating a ScheduledExecutorService object ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(11); // printing the current time System.out.println( \"Current time : \" + Calendar.getInstance().get(Calendar.SECOND)); // Scheduling the tasks for (int i = 10; i >= 0; i--) { scheduler.schedule(new Task(i), 10 - i, TimeUnit.SECONDS); } // remember to shutdown the scheduler // so that it no longer accepts // any new tasks scheduler.shutdown(); }} class Task implements Runnable { private int num; public Task(int num) { this.num = num; } public void run() { System.out.println( \"Number \" + num + \" Current time : \" + Calendar.getInstance().get(Calendar.SECOND)); }}", "e": 2955, "s": 1750, "text": null }, { "code": null, "e": 2963, "s": 2955, "text": "Output:" }, { "code": null, "e": 3332, "s": 2963, "text": "A count-down-clock program that counts from 10 to 0\nCurrent time : 28\nNumber 10 Current time : 28\nNumber 9 Current time : 29\nNumber 8 Current time : 30\nNumber 7 Current time : 31\nNumber 6 Current time : 32\nNumber 5 Current time : 33\nNumber 4 Current time : 34\nNumber 3 Current time : 35\nNumber 2 Current time : 36\nNumber 1 Current time : 37\nNumber 0 Current time : 38\n" }, { "code": null, "e": 3516, "s": 3332, "text": "This is a Countdown Clock that counts from 10 to 0. The ScheduledExexutorService object i.e; scheduler is created using the Executors.newScheduledThreadPool(int corePoolSize) method. " }, { "code": null, "e": 3701, "s": 3516, "text": "Note: All the tasks executed after (10 – i) seconds delay from the invocation of schedule() method. The value of the current time may vary in the output based on the time of execution." }, { "code": null, "e": 3708, "s": 3701, "text": "METHOD" }, { "code": null, "e": 3720, "s": 3708, "text": "DESCRIPTION" }, { "code": null, "e": 3727, "s": 3720, "text": "METHOD" }, { "code": null, "e": 3739, "s": 3727, "text": "DESCRIPTION" }, { "code": null, "e": 3746, "s": 3739, "text": "METHOD" }, { "code": null, "e": 3758, "s": 3746, "text": "DESCRIPTION" }, { "code": null, "e": 3782, "s": 3758, "text": "Java-concurrent-package" }, { "code": null, "e": 3787, "s": 3782, "text": "Java" }, { "code": null, "e": 3792, "s": 3787, "text": "Java" } ]
JavaScript String toUpperCase() Method
23 Dec, 2021 Below is the example of the String toUpperCase() Method. Example: JavaScript <script>function func() { var str = 'geeksforgeeks'; var string = str.toUpperCase(); document.write(string);}func();</script> Output: GEEKSFORGEEKS str.toUpperCase() method converts the entire string to Upper case. This method does not affect any of the special characters, digits, and the alphabets that are already in the upper case. Syntax: str.toUpperCase() Return value: This method returns a new string in which all the lower case letters are converted to upper case.Examples for the above method are provided below:Example 1: var str = 'It iS a Great Day.'; var string = str.toUpperCase(); print(string); Output: IT IS A GREAT DAY. In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Example 2: var str = 'It iS a 5r&e@@t Day.' var string = str.toUpperCase(); print(string); Output: IT IS A 5R&AMP;E@@T DAY. In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Codes for the above method are provided below:Program 1: JavaScript <script>// JavaScript to illustrate .toUpperCase() function func() { // Original string var str = 'It iS a Great Day.'; // String converted to Upper Case var string = str.toUpperCase(); document.write(string);} func();</script> Output: IT IS A GREAT DAY. Program 2: JavaScript <script>// JavaScript to illustrate .toUpperCase() function func() { //Original string var str = 'It iS a 5r&:ampe@@t Day.' //String converted to Upper Case var string = str.toUpperCase(); document.write(string);} func();</script> Output: IT IS A 5R&:AMPE@@T DAY. Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 3 and above Opera 3 and above Safari 1 and above ysachin2314 JavaScript-Methods javascript-string 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": "\n23 Dec, 2021" }, { "code": null, "e": 85, "s": 28, "text": "Below is the example of the String toUpperCase() Method." }, { "code": null, "e": 96, "s": 85, "text": "Example: " }, { "code": null, "e": 107, "s": 96, "text": "JavaScript" }, { "code": "<script>function func() { var str = 'geeksforgeeks'; var string = str.toUpperCase(); document.write(string);}func();</script>", "e": 242, "s": 107, "text": null }, { "code": null, "e": 252, "s": 242, "text": "Output: " }, { "code": null, "e": 266, "s": 252, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 464, "s": 266, "text": "str.toUpperCase() method converts the entire string to Upper case. This method does not affect any of the special characters, digits, and the alphabets that are already in the upper case. Syntax: " }, { "code": null, "e": 482, "s": 464, "text": "str.toUpperCase()" }, { "code": null, "e": 655, "s": 482, "text": "Return value: This method returns a new string in which all the lower case letters are converted to upper case.Examples for the above method are provided below:Example 1: " }, { "code": null, "e": 734, "s": 655, "text": "var str = 'It iS a Great Day.';\nvar string = str.toUpperCase();\nprint(string);" }, { "code": null, "e": 744, "s": 734, "text": "Output: " }, { "code": null, "e": 763, "s": 744, "text": "IT IS A GREAT DAY." }, { "code": null, "e": 944, "s": 763, "text": "In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Example 2: " }, { "code": null, "e": 1024, "s": 944, "text": "var str = 'It iS a 5r&e@@t Day.'\nvar string = str.toUpperCase();\nprint(string);" }, { "code": null, "e": 1034, "s": 1024, "text": "Output: " }, { "code": null, "e": 1059, "s": 1034, "text": "IT IS A 5R&AMP;E@@T DAY." }, { "code": null, "e": 1285, "s": 1059, "text": "In this example the method toUpperCase() converts all the lower case alphabets to their upper case equivalents without affecting the special characters and the digits. Codes for the above method are provided below:Program 1: " }, { "code": null, "e": 1296, "s": 1285, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate .toUpperCase() function func() { // Original string var str = 'It iS a Great Day.'; // String converted to Upper Case var string = str.toUpperCase(); document.write(string);} func();</script>", "e": 1554, "s": 1296, "text": null }, { "code": null, "e": 1564, "s": 1554, "text": "Output: " }, { "code": null, "e": 1583, "s": 1564, "text": "IT IS A GREAT DAY." }, { "code": null, "e": 1595, "s": 1583, "text": "Program 2: " }, { "code": null, "e": 1606, "s": 1595, "text": "JavaScript" }, { "code": "<script>// JavaScript to illustrate .toUpperCase() function func() { //Original string var str = 'It iS a 5r&:ampe@@t Day.' //String converted to Upper Case var string = str.toUpperCase(); document.write(string);} func();</script>", "e": 1865, "s": 1606, "text": null }, { "code": null, "e": 1875, "s": 1865, "text": "Output: " }, { "code": null, "e": 1900, "s": 1875, "text": "IT IS A 5R&:AMPE@@T DAY." }, { "code": null, "e": 1921, "s": 1902, "text": "Supported Browser:" }, { "code": null, "e": 1940, "s": 1921, "text": "Chrome 1 and above" }, { "code": null, "e": 1958, "s": 1940, "text": "Edge 12 and above" }, { "code": null, "e": 1978, "s": 1958, "text": "Firefox 1 and above" }, { "code": null, "e": 2008, "s": 1978, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 2026, "s": 2008, "text": "Opera 3 and above" }, { "code": null, "e": 2045, "s": 2026, "text": "Safari 1 and above" }, { "code": null, "e": 2057, "s": 2045, "text": "ysachin2314" }, { "code": null, "e": 2076, "s": 2057, "text": "JavaScript-Methods" }, { "code": null, "e": 2094, "s": 2076, "text": "javascript-string" }, { "code": null, "e": 2105, "s": 2094, "text": "JavaScript" }, { "code": null, "e": 2122, "s": 2105, "text": "Web Technologies" } ]
deque::push_back() in C++ STL
06 Oct, 2021 Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. push_back() function is used to push elements into a deque from the back. The new value is inserted into the deque at the end, before the current last element and the container size is increased by 1.Syntax : dequename.push_back(value) Parameters : The value to be added in the back is passed as the parameter Result : Adds the value mentioned as the parameter to the back of the deque named as dequename Examples: Input : deque{1, 2, 3, 4, 5}; deque.push_back(6); Output : 1, 2, 3, 4, 5, 6 Input : deque{5, 4, 3, 2, 1}; deque.push_back(6); Output : 5, 4, 3, 2, 1, 6 Errors and Exceptions1. Strong exception guarantee – if an exception is thrown, there are no changes in the container. 2. If the value passed as argument is not supported by the deque, it shows undefined behavior. CPP // CPP program to illustrate// push_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; mydeque.push_back(6); // deque becomes 1, 2, 3, 4, 5, 6 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;} Output: 1 2 3 4 5 6 Time Complexity : O(1)Application Given an empty deque, add integers to it using push_back() function and then calculate sum of all its elements. Input : 11, 2, 5, 3, 7, 1 Output : 29 Algorithm 1. Add elements to the deque using push_back() function. 2. Check if the size of the deque is 0, if not, add the front element to the sum variable initialized as 0, and pop the front element. 3. Repeat this step until the size of the deque becomes 0. 4. Print the final value of the variable. CPP // CPP program to illustrate// Application of push_back() function#include <iostream>#include <deque>using namespace std; int main(){ int sum = 0; deque<int> mydeque; mydeque.push_back(11); mydeque.push_back(2); mydeque.push_back(5); mydeque.push_back(3); mydeque.push_back(7); mydeque.push_back(1); while (!mydeque.empty()) { sum = sum + mydeque.front(); mydeque.pop_front(); } cout << sum; return 0;} Output: 29 akshaydharsey hritikbhatnagar2182 cpp-deque STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Oct, 2021" }, { "code": null, "e": 374, "s": 53, "text": "Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. " }, { "code": null, "e": 585, "s": 374, "text": "push_back() function is used to push elements into a deque from the back. The new value is inserted into the deque at the end, before the current last element and the container size is increased by 1.Syntax : " }, { "code": null, "e": 783, "s": 585, "text": "dequename.push_back(value)\nParameters :\nThe value to be added in the back is \npassed as the parameter\nResult :\nAdds the value mentioned as the parameter \nto the back of the deque named as dequename" }, { "code": null, "e": 794, "s": 783, "text": "Examples: " }, { "code": null, "e": 963, "s": 794, "text": "Input : deque{1, 2, 3, 4, 5};\n deque.push_back(6);\nOutput : 1, 2, 3, 4, 5, 6\n\nInput : deque{5, 4, 3, 2, 1};\n deque.push_back(6);\nOutput : 5, 4, 3, 2, 1, 6" }, { "code": null, "e": 1178, "s": 963, "text": "Errors and Exceptions1. Strong exception guarantee – if an exception is thrown, there are no changes in the container. 2. If the value passed as argument is not supported by the deque, it shows undefined behavior. " }, { "code": null, "e": 1182, "s": 1178, "text": "CPP" }, { "code": "// CPP program to illustrate// push_back() function#include <iostream>#include <deque>using namespace std; int main(){ deque<int> mydeque{ 1, 2, 3, 4, 5 }; mydeque.push_back(6); // deque becomes 1, 2, 3, 4, 5, 6 for (auto it = mydeque.begin(); it != mydeque.end(); ++it) cout << ' ' << *it;}", "e": 1508, "s": 1182, "text": null }, { "code": null, "e": 1517, "s": 1508, "text": "Output: " }, { "code": null, "e": 1529, "s": 1517, "text": "1 2 3 4 5 6" }, { "code": null, "e": 1676, "s": 1529, "text": "Time Complexity : O(1)Application Given an empty deque, add integers to it using push_back() function and then calculate sum of all its elements. " }, { "code": null, "e": 1715, "s": 1676, "text": "Input : 11, 2, 5, 3, 7, 1\nOutput : 29" }, { "code": null, "e": 2019, "s": 1715, "text": "Algorithm 1. Add elements to the deque using push_back() function. 2. Check if the size of the deque is 0, if not, add the front element to the sum variable initialized as 0, and pop the front element. 3. Repeat this step until the size of the deque becomes 0. 4. Print the final value of the variable. " }, { "code": null, "e": 2023, "s": 2019, "text": "CPP" }, { "code": "// CPP program to illustrate// Application of push_back() function#include <iostream>#include <deque>using namespace std; int main(){ int sum = 0; deque<int> mydeque; mydeque.push_back(11); mydeque.push_back(2); mydeque.push_back(5); mydeque.push_back(3); mydeque.push_back(7); mydeque.push_back(1); while (!mydeque.empty()) { sum = sum + mydeque.front(); mydeque.pop_front(); } cout << sum; return 0;}", "e": 2476, "s": 2023, "text": null }, { "code": null, "e": 2486, "s": 2476, "text": "Output: " }, { "code": null, "e": 2489, "s": 2486, "text": "29" }, { "code": null, "e": 2505, "s": 2491, "text": "akshaydharsey" }, { "code": null, "e": 2525, "s": 2505, "text": "hritikbhatnagar2182" }, { "code": null, "e": 2535, "s": 2525, "text": "cpp-deque" }, { "code": null, "e": 2539, "s": 2535, "text": "STL" }, { "code": null, "e": 2543, "s": 2539, "text": "C++" }, { "code": null, "e": 2547, "s": 2543, "text": "STL" }, { "code": null, "e": 2551, "s": 2547, "text": "CPP" } ]
JavaScript String split() Method
17 May, 2022 Below is the example of the String split() Method. Example: JavaScript <script>// JavaScript Program to illustrate split() function function func() { //Original string var str = 'Geeks for Geeks' var array = str.split("for"); document.write(array);} func();</script> Output: Geeks , Geeks str.split() method is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.Syntax: str.split(separator, limit) separator: It is used to specified the character, or the regular expression, to use for splitting the string. If the separator is unspecified then the entire string becomes one single array element. The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated. limit: Defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached then it is not reported in the array. Return value This function returns an array of strings that is formed after splitting the given string at each point where the separator occurs.Examples for the above function are provided below:Example 1: var str = 'It iS a 5r&e@@t Day.' var array = str.split(" "); print(array); Output: [It,iS,a,5r&e@@t,Day.] In this example the function split() creates an array of strings by splitting str wherever ” “ occurs.Example 2: var str = 'It iS a 5r&e@@t Day.' var array = str.split(" ",2); print(array); Output: [It,iS] In this example the function split() creates an array of strings by splitting str wherever ” “ occurs. The second argument 2 limits the number of such splits to only 2.Codes for the above function are provided below:Program 1: JavaScript <script>// JavaScript Program to illustrate split() function function func() { //Original string var str = 'It iS a 5r&e@@t Day.' var array = str.split(" "); document.write(array); } func();</script> Output: [It,iS,a,5r&e@@t,Day.] Program 2: JavaScript <script>// JavaScript Program to illustrate split() function function func() { // Original string var str = 'It iS a 5r&e@@t Day.' // Splitting up to 2 terms var array = str.split(" ",2); document.write(array);} func();</script> Output: [It,iS] Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 3 and above Safari 1 and above JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. shubham_singh ysachin2314 surinderdawra388 JavaScript-Methods javascript-string 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": "\n17 May, 2022" }, { "code": null, "e": 81, "s": 28, "text": "Below is the example of the String split() Method. " }, { "code": null, "e": 92, "s": 81, "text": "Example: " }, { "code": null, "e": 103, "s": 92, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate split() function function func() { //Original string var str = 'Geeks for Geeks' var array = str.split(\"for\"); document.write(array);} func();</script>", "e": 311, "s": 103, "text": null }, { "code": null, "e": 321, "s": 311, "text": "Output: " }, { "code": null, "e": 335, "s": 321, "text": "Geeks , Geeks" }, { "code": null, "e": 506, "s": 335, "text": "str.split() method is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.Syntax: " }, { "code": null, "e": 534, "s": 506, "text": "str.split(separator, limit)" }, { "code": null, "e": 896, "s": 536, "text": "separator: It is used to specified the character, or the regular expression, to use for splitting the string. If the separator is unspecified then the entire string becomes one single array element. The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated." }, { "code": null, "e": 1081, "s": 896, "text": "limit: Defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached then it is not reported in the array." }, { "code": null, "e": 1289, "s": 1081, "text": "Return value This function returns an array of strings that is formed after splitting the given string at each point where the separator occurs.Examples for the above function are provided below:Example 1: " }, { "code": null, "e": 1364, "s": 1289, "text": "var str = 'It iS a 5r&e@@t Day.'\nvar array = str.split(\" \");\nprint(array);" }, { "code": null, "e": 1374, "s": 1364, "text": "Output: " }, { "code": null, "e": 1397, "s": 1374, "text": "[It,iS,a,5r&e@@t,Day.]" }, { "code": null, "e": 1512, "s": 1397, "text": "In this example the function split() creates an array of strings by splitting str wherever ” “ occurs.Example 2: " }, { "code": null, "e": 1589, "s": 1512, "text": "var str = 'It iS a 5r&e@@t Day.'\nvar array = str.split(\" \",2);\nprint(array);" }, { "code": null, "e": 1599, "s": 1589, "text": "Output: " }, { "code": null, "e": 1607, "s": 1599, "text": "[It,iS]" }, { "code": null, "e": 1835, "s": 1607, "text": "In this example the function split() creates an array of strings by splitting str wherever ” “ occurs. The second argument 2 limits the number of such splits to only 2.Codes for the above function are provided below:Program 1: " }, { "code": null, "e": 1846, "s": 1835, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate split() function function func() { //Original string var str = 'It iS a 5r&e@@t Day.' var array = str.split(\" \"); document.write(array); } func();</script>", "e": 2058, "s": 1846, "text": null }, { "code": null, "e": 2068, "s": 2058, "text": "Output: " }, { "code": null, "e": 2091, "s": 2068, "text": "[It,iS,a,5r&e@@t,Day.]" }, { "code": null, "e": 2103, "s": 2091, "text": "Program 2: " }, { "code": null, "e": 2114, "s": 2103, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate split() function function func() { // Original string var str = 'It iS a 5r&e@@t Day.' // Splitting up to 2 terms var array = str.split(\" \",2); document.write(array);} func();</script>", "e": 2360, "s": 2114, "text": null }, { "code": null, "e": 2370, "s": 2360, "text": "Output: " }, { "code": null, "e": 2378, "s": 2370, "text": "[It,iS]" }, { "code": null, "e": 2397, "s": 2378, "text": "Supported Browser:" }, { "code": null, "e": 2416, "s": 2397, "text": "Chrome 1 and above" }, { "code": null, "e": 2434, "s": 2416, "text": "Edge 12 and above" }, { "code": null, "e": 2454, "s": 2434, "text": "Firefox 1 and above" }, { "code": null, "e": 2484, "s": 2454, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 2502, "s": 2484, "text": "Opera 3 and above" }, { "code": null, "e": 2523, "s": 2502, "text": "Safari 1 and above " }, { "code": null, "e": 2742, "s": 2523, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 2758, "s": 2744, "text": "shubham_singh" }, { "code": null, "e": 2770, "s": 2758, "text": "ysachin2314" }, { "code": null, "e": 2787, "s": 2770, "text": "surinderdawra388" }, { "code": null, "e": 2806, "s": 2787, "text": "JavaScript-Methods" }, { "code": null, "e": 2824, "s": 2806, "text": "javascript-string" }, { "code": null, "e": 2835, "s": 2824, "text": "JavaScript" }, { "code": null, "e": 2852, "s": 2835, "text": "Web Technologies" } ]
Early Fire detection system using deep learning and OpenCV | by Dhruvil Shah | Towards Data Science
Recent advancements in embedded processing have allowed vision-based systems to detect fire using Convolutional Neural Networks during surveillance. In this article, two custom CNN models have been implemented for a cost-effective fire detection CNN architecture for surveillance videos. The first model is a customized basic CNN architecture inspired by AlexNet architecture. We will implement and see its output and limitations and create a customized InceptionV3 model. To balance the efficiency and accuracy, the model is fine-tuned considering the nature of the target problem and fire data. We are going to use three different datasets for training our models. The links for the datasets are available at the end of this article. Let’s get to the coding part. We are going to use TensorFlow API Keras for building our model. Let’s first create our ImageDataGenerator for labeling our data. [1] and [2] datasets are used here for training. Finally, we will have 980 images for training and 239 images for validation. We are going to use data augmentation as well. import tensorflow as tfimport keras_preprocessingfrom keras_preprocessing import imagefrom keras_preprocessing.image import ImageDataGeneratorTRAINING_DIR = "Train"training_datagen = ImageDataGenerator(rescale = 1./255, horizontal_flip=True, rotation_range=30, height_shift_range=0.2, fill_mode='nearest')VALIDATION_DIR = "Validation"validation_datagen = ImageDataGenerator(rescale = 1./255)train_generator = training_datagen.flow_from_directory(TRAINING_DIR, target_size=(224,224), class_mode='categorical', batch_size = 64)validation_generator = validation_datagen.flow_from_directory( VALIDATION_DIR, target_size=(224,224), class_mode='categorical', batch_size= 16) In the above code, 3 data augmentation techniques are applied — horizontal flipping, rotation, and height shifting. Now, we will create our CNN model. The model contains three Conv2D-MaxPooling2D layers pairs followed by 3 Dense layers. To overcome the problem of overfitting we will also add dropout layers. The last layer is the softmax layer which will give us the probability distribution for both the classes — Fire and Nonfire. One can also use ‘sigmoid’ activation function at the last layer by changing the number of classes to 1. from tensorflow.keras.optimizers import Adammodel = tf.keras.models.Sequential([tf.keras.layers.Conv2D(96, (11,11), strides=(4,4), activation='relu', input_shape=(224, 224, 3)), tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Conv2D(256, (5,5), activation='relu'),tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Conv2D(384, (5,5), activation='relu'),tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Flatten(),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(2048, activation='relu'),tf.keras.layers.Dropout(0.25),tf.keras.layers.Dense(1024, activation='relu'),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(2, activation='softmax')])model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001),metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 15,epochs = 50,validation_data = validation_generator,validation_steps = 15) We will use Adam as an optimizer with a learning rate of 0.0001. After training for 50 epochs, we get the training accuracy of 96.83 and validation accuracy of 94.98. The training and validation loss is 0.09 and 0.13 respectively. Let’s test our model for any image and see if it can guess it right. For testing, I have selected 3 images that include a fire-image, a non-fire image, and a photo of me that contains the fire-like colors and shades. Here, we can see that our above-created model is making a mistake in classifying my image. The model is 52% sure that the image has fire in it. This is because of the dataset it has been trained on. There are very few images in the dataset that teaches a model about indoor fires. So, the model only knows about outdoor fires and hence it errs when given an indoor fire-like shaded image. Another reason is that our model is not a complex one that can learn complex features of fire. What we will do next is, use a standard InceptionV3 model and customize it. A complex model is capable of learning the complex features from the images. We will use a different dataset [3] this time, the one which contains outdoor as well as indoor fire images. I have trained our previous CNN model in this dataset and the result was that it overfitted, as it could not handle this comparatively larger dataset and learn complex features from the images. Let’s start with creating the ImageDataGenerator for our customized InceptionV3. The dataset contains 3 classes but for this article, we will only use 2 classes. It contains 1800 images for training and 200 images for validation. Also, I added 8 images of my living room to add some noise in the dataset. import tensorflow as tfimport keras_preprocessingfrom keras_preprocessing import imagefrom keras_preprocessing.image import ImageDataGeneratorTRAINING_DIR = "Train"training_datagen = ImageDataGenerator(rescale=1./255,zoom_range=0.15,horizontal_flip=True,fill_mode='nearest')VALIDATION_DIR = "/content/FIRE-SMOKE-DATASET/Test"validation_datagen = ImageDataGenerator(rescale = 1./255)train_generator = training_datagen.flow_from_directory(TRAINING_DIR,target_size=(224,224),shuffle = True,class_mode='categorical',batch_size = 128)validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,target_size=(224,224),class_mode='categorical',shuffle = True,batch_size= 14) To make training even more accurate we can use data augmentation techniques. In the above code, 2 data augmentation techniques are applied — horizontal flipping and zooming. Let’s import our InceptionV3 model from the Keras API. We will add our layers at the top of the InceptionV3 model as shown below. We will add a global spatial average pooling layer followed by 2 dense layers and 2 dropout layers to ensure that our model does not overfit. At last, we will add a softmax activated dense layer for 2 classes. Next, we will first train only the layers that we added and are randomly initialized. We will use RMSprop as an optimizer here. from tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.preprocessing import imagefrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Input, Dropoutinput_tensor = Input(shape=(224, 224, 3))base_model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=False)x = base_model.outputx = GlobalAveragePooling2D()(x)x = Dense(2048, activation='relu')(x)x = Dropout(0.25)(x)x = Dense(1024, activation='relu')(x)x = Dropout(0.2)(x)predictions = Dense(2, activation='softmax')(x)model = Model(inputs=base_model.input, outputs=predictions)for layer in base_model.layers: layer.trainable = Falsemodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 14,epochs = 20,validation_data = validation_generator,validation_steps = 14) After training our top layers for 20 epochs, we will freeze the first 249 layers of the models and train the rest i.e the top 2 inception blocks. Here, we will use SGD as an optimizer with a learning rate of 0.0001. #To train the top 2 inception blocks, freeze the first 249 layers and unfreeze the rest.for layer in model.layers[:249]: layer.trainable = Falsefor layer in model.layers[249:]: layer.trainable = True#Recompile the model for these modifications to take effectfrom tensorflow.keras.optimizers import SGDmodel.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 14,epochs = 10,validation_data = validation_generator,validation_steps = 14) After training for 10 epochs, we get a training accuracy of 98.04 and a validation accuracy of 96.43. The training and validation losses are 0.063 and 0.118 respectively. Let’s test our model for the same images and see if it can guess it right. This time our model can get all three predictions correct. It is 96% sure that my image does not contain any fire. The other two images that I am using for testing are: Now, our model is ready to be tested with real scenarios. Below is the sample code for using OpenCV to access our webcam and predicting whether each frame contains fire or not. If a frame contains fire in it, we want to change the color of that frame to B&W. import cv2import numpy as npfrom PIL import Imageimport tensorflow as tffrom keras.preprocessing import image#Load the saved modelmodel = tf.keras.models.load_model('InceptionV3.h5')video = cv2.VideoCapture(0)while True: _, frame = video.read()#Convert the captured frame into RGB im = Image.fromarray(frame, 'RGB')#Resizing into 224x224 because we trained the model with this image size. im = im.resize((224,224)) img_array = image.img_to_array(im) img_array = np.expand_dims(img_array, axis=0) / 255 probabilities = model.predict(img_array)[0] #Calling the predict method on model to predict 'fire' on the image prediction = np.argmax(probabilities) #if prediction is 0, which means there is fire in the frame. if prediction == 0: frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) print(probabilities[prediction])cv2.imshow("Capturing", frame) key=cv2.waitKey(1) if key == ord('q'): breakvideo.release()cv2.destroyAllWindows() Below is the live output of the above code. The Github’s link for this project is here. You can find the dataset and all of the code above from there. You can connect with me on LinkedIn from here. If any query arises drop a response here or in my LinkedIn inbox. Using smart cameras you can identify various suspicious incidents such as collisions, medical emergencies, and fires. Of such, fire is the most dangerous abnormal occurrence, because failure to control it at an early stage can lead to huge disasters, leading to human, ecological and economic losses. Inspired by the great potential of CNNs, we can detect fire from images or videos at an early stage. This article shows two custom models for fire detection. Considering the fair fire detection accuracy of the CNN model, it can be of assistance to disaster management teams in managing fire disasters on time, thus preventing huge losses.
[ { "code": null, "e": 937, "s": 171, "text": "Recent advancements in embedded processing have allowed vision-based systems to detect fire using Convolutional Neural Networks during surveillance. In this article, two custom CNN models have been implemented for a cost-effective fire detection CNN architecture for surveillance videos. The first model is a customized basic CNN architecture inspired by AlexNet architecture. We will implement and see its output and limitations and create a customized InceptionV3 model. To balance the efficiency and accuracy, the model is fine-tuned considering the nature of the target problem and fire data. We are going to use three different datasets for training our models. The links for the datasets are available at the end of this article. Let’s get to the coding part." }, { "code": null, "e": 1240, "s": 937, "text": "We are going to use TensorFlow API Keras for building our model. Let’s first create our ImageDataGenerator for labeling our data. [1] and [2] datasets are used here for training. Finally, we will have 980 images for training and 239 images for validation. We are going to use data augmentation as well." }, { "code": null, "e": 2335, "s": 1240, "text": "import tensorflow as tfimport keras_preprocessingfrom keras_preprocessing import imagefrom keras_preprocessing.image import ImageDataGeneratorTRAINING_DIR = \"Train\"training_datagen = ImageDataGenerator(rescale = 1./255, horizontal_flip=True, rotation_range=30, height_shift_range=0.2, fill_mode='nearest')VALIDATION_DIR = \"Validation\"validation_datagen = ImageDataGenerator(rescale = 1./255)train_generator = training_datagen.flow_from_directory(TRAINING_DIR, target_size=(224,224), class_mode='categorical', batch_size = 64)validation_generator = validation_datagen.flow_from_directory( VALIDATION_DIR, target_size=(224,224), class_mode='categorical', batch_size= 16)" }, { "code": null, "e": 2451, "s": 2335, "text": "In the above code, 3 data augmentation techniques are applied — horizontal flipping, rotation, and height shifting." }, { "code": null, "e": 2874, "s": 2451, "text": "Now, we will create our CNN model. The model contains three Conv2D-MaxPooling2D layers pairs followed by 3 Dense layers. To overcome the problem of overfitting we will also add dropout layers. The last layer is the softmax layer which will give us the probability distribution for both the classes — Fire and Nonfire. One can also use ‘sigmoid’ activation function at the last layer by changing the number of classes to 1." }, { "code": null, "e": 3824, "s": 2874, "text": "from tensorflow.keras.optimizers import Adammodel = tf.keras.models.Sequential([tf.keras.layers.Conv2D(96, (11,11), strides=(4,4), activation='relu', input_shape=(224, 224, 3)), tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Conv2D(256, (5,5), activation='relu'),tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Conv2D(384, (5,5), activation='relu'),tf.keras.layers.MaxPooling2D(pool_size = (3,3), strides=(2,2)),tf.keras.layers.Flatten(),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(2048, activation='relu'),tf.keras.layers.Dropout(0.25),tf.keras.layers.Dense(1024, activation='relu'),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(2, activation='softmax')])model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001),metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 15,epochs = 50,validation_data = validation_generator,validation_steps = 15)" }, { "code": null, "e": 4055, "s": 3824, "text": "We will use Adam as an optimizer with a learning rate of 0.0001. After training for 50 epochs, we get the training accuracy of 96.83 and validation accuracy of 94.98. The training and validation loss is 0.09 and 0.13 respectively." }, { "code": null, "e": 4272, "s": 4055, "text": "Let’s test our model for any image and see if it can guess it right. For testing, I have selected 3 images that include a fire-image, a non-fire image, and a photo of me that contains the fire-like colors and shades." }, { "code": null, "e": 4756, "s": 4272, "text": "Here, we can see that our above-created model is making a mistake in classifying my image. The model is 52% sure that the image has fire in it. This is because of the dataset it has been trained on. There are very few images in the dataset that teaches a model about indoor fires. So, the model only knows about outdoor fires and hence it errs when given an indoor fire-like shaded image. Another reason is that our model is not a complex one that can learn complex features of fire." }, { "code": null, "e": 4909, "s": 4756, "text": "What we will do next is, use a standard InceptionV3 model and customize it. A complex model is capable of learning the complex features from the images." }, { "code": null, "e": 5212, "s": 4909, "text": "We will use a different dataset [3] this time, the one which contains outdoor as well as indoor fire images. I have trained our previous CNN model in this dataset and the result was that it overfitted, as it could not handle this comparatively larger dataset and learn complex features from the images." }, { "code": null, "e": 5517, "s": 5212, "text": "Let’s start with creating the ImageDataGenerator for our customized InceptionV3. The dataset contains 3 classes but for this article, we will only use 2 classes. It contains 1800 images for training and 200 images for validation. Also, I added 8 images of my living room to add some noise in the dataset." }, { "code": null, "e": 6201, "s": 5517, "text": "import tensorflow as tfimport keras_preprocessingfrom keras_preprocessing import imagefrom keras_preprocessing.image import ImageDataGeneratorTRAINING_DIR = \"Train\"training_datagen = ImageDataGenerator(rescale=1./255,zoom_range=0.15,horizontal_flip=True,fill_mode='nearest')VALIDATION_DIR = \"/content/FIRE-SMOKE-DATASET/Test\"validation_datagen = ImageDataGenerator(rescale = 1./255)train_generator = training_datagen.flow_from_directory(TRAINING_DIR,target_size=(224,224),shuffle = True,class_mode='categorical',batch_size = 128)validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,target_size=(224,224),class_mode='categorical',shuffle = True,batch_size= 14)" }, { "code": null, "e": 6375, "s": 6201, "text": "To make training even more accurate we can use data augmentation techniques. In the above code, 2 data augmentation techniques are applied — horizontal flipping and zooming." }, { "code": null, "e": 6715, "s": 6375, "text": "Let’s import our InceptionV3 model from the Keras API. We will add our layers at the top of the InceptionV3 model as shown below. We will add a global spatial average pooling layer followed by 2 dense layers and 2 dropout layers to ensure that our model does not overfit. At last, we will add a softmax activated dense layer for 2 classes." }, { "code": null, "e": 6843, "s": 6715, "text": "Next, we will first train only the layers that we added and are randomly initialized. We will use RMSprop as an optimizer here." }, { "code": null, "e": 7752, "s": 6843, "text": "from tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.preprocessing import imagefrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Input, Dropoutinput_tensor = Input(shape=(224, 224, 3))base_model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=False)x = base_model.outputx = GlobalAveragePooling2D()(x)x = Dense(2048, activation='relu')(x)x = Dropout(0.25)(x)x = Dense(1024, activation='relu')(x)x = Dropout(0.2)(x)predictions = Dense(2, activation='softmax')(x)model = Model(inputs=base_model.input, outputs=predictions)for layer in base_model.layers: layer.trainable = Falsemodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 14,epochs = 20,validation_data = validation_generator,validation_steps = 14)" }, { "code": null, "e": 7968, "s": 7752, "text": "After training our top layers for 20 epochs, we will freeze the first 249 layers of the models and train the rest i.e the top 2 inception blocks. Here, we will use SGD as an optimizer with a learning rate of 0.0001." }, { "code": null, "e": 8505, "s": 7968, "text": "#To train the top 2 inception blocks, freeze the first 249 layers and unfreeze the rest.for layer in model.layers[:249]: layer.trainable = Falsefor layer in model.layers[249:]: layer.trainable = True#Recompile the model for these modifications to take effectfrom tensorflow.keras.optimizers import SGDmodel.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['acc'])history = model.fit(train_generator,steps_per_epoch = 14,epochs = 10,validation_data = validation_generator,validation_steps = 14)" }, { "code": null, "e": 8676, "s": 8505, "text": "After training for 10 epochs, we get a training accuracy of 98.04 and a validation accuracy of 96.43. The training and validation losses are 0.063 and 0.118 respectively." }, { "code": null, "e": 8751, "s": 8676, "text": "Let’s test our model for the same images and see if it can guess it right." }, { "code": null, "e": 8920, "s": 8751, "text": "This time our model can get all three predictions correct. It is 96% sure that my image does not contain any fire. The other two images that I am using for testing are:" }, { "code": null, "e": 9179, "s": 8920, "text": "Now, our model is ready to be tested with real scenarios. Below is the sample code for using OpenCV to access our webcam and predicting whether each frame contains fire or not. If a frame contains fire in it, we want to change the color of that frame to B&W." }, { "code": null, "e": 10235, "s": 9179, "text": "import cv2import numpy as npfrom PIL import Imageimport tensorflow as tffrom keras.preprocessing import image#Load the saved modelmodel = tf.keras.models.load_model('InceptionV3.h5')video = cv2.VideoCapture(0)while True: _, frame = video.read()#Convert the captured frame into RGB im = Image.fromarray(frame, 'RGB')#Resizing into 224x224 because we trained the model with this image size. im = im.resize((224,224)) img_array = image.img_to_array(im) img_array = np.expand_dims(img_array, axis=0) / 255 probabilities = model.predict(img_array)[0] #Calling the predict method on model to predict 'fire' on the image prediction = np.argmax(probabilities) #if prediction is 0, which means there is fire in the frame. if prediction == 0: frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) print(probabilities[prediction])cv2.imshow(\"Capturing\", frame) key=cv2.waitKey(1) if key == ord('q'): breakvideo.release()cv2.destroyAllWindows()" }, { "code": null, "e": 10279, "s": 10235, "text": "Below is the live output of the above code." }, { "code": null, "e": 10499, "s": 10279, "text": "The Github’s link for this project is here. You can find the dataset and all of the code above from there. You can connect with me on LinkedIn from here. If any query arises drop a response here or in my LinkedIn inbox." } ]
How to create a temperature converter with HTML and JavaScript?
To create a temperature converter with HTML and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <style> body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } input,span{ font-size: 20px; } </style> </head> <body> <h1>Temperature Converter</h1> <h2>Type Temperature in celcius to convert it into fahrenheit</h2> <p> <label>Celcius</label> <input id="inputKG" type="number" placeholder="Celcius" oninput="CtoFConverter(this.value)" onchange="CtoFConverter(this.value)"> </p> <p>Fahrenheit: <span class="fahrenheit"></span></p> <script> function CtoFConverter(temp) { document.querySelector(".fahrenheit").innerHTML=(temp-32)/1.8; } </script> </body> </html> The above code will produce the following output − On entering temperature in celcius −
[ { "code": null, "e": 1147, "s": 1062, "text": "To create a temperature converter with HTML and JavaScript, the code is as follows −" }, { "code": null, "e": 1158, "s": 1147, "text": " Live Demo" }, { "code": null, "e": 1800, "s": 1158, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body{\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n }\n input,span{\n font-size: 20px;\n }\n</style>\n</head>\n<body>\n<h1>Temperature Converter</h1>\n<h2>Type Temperature in celcius to convert it into fahrenheit</h2>\n<p>\n<label>Celcius</label>\n<input id=\"inputKG\" type=\"number\" placeholder=\"Celcius\"\noninput=\"CtoFConverter(this.value)\" onchange=\"CtoFConverter(this.value)\">\n</p>\n<p>Fahrenheit: <span class=\"fahrenheit\"></span></p>\n<script>\n function CtoFConverter(temp) {\n document.querySelector(\".fahrenheit\").innerHTML=(temp-32)/1.8;\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 1851, "s": 1800, "text": "The above code will produce the following output −" }, { "code": null, "e": 1888, "s": 1851, "text": "On entering temperature in celcius −" } ]
How to Disable Browser Back Button using jQuery ? - GeeksforGeeks
10 Aug, 2021 While working with some privacy-related projects, we have to make sure that our programming doesn’t have any kind of loopholes. In this article, we will see how we can disable the back button of the browser intentionally so that users cannot get back and access the content. We have many scenarios where we could use this kind of functionality. For example, in the payment gateways pages, we can disable the back button so that if the user unintentionally clicks on the back button the payment does not get canceled. For implementing this feature on our page we will toggle through two pages and after that, we will restrict users to get back on the first page. Example: Create two HTML files in the same folder as we use page1.html and page2.html. In page1.html, add the following code. index.html <!DOCTYPE html><html> <head> <title>Disabling browser back button</title> <script src= "https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <a href="test2.html">Next page</a> <script> $(document).ready(function() { function disableBack() { window.history.forward() } window.onload = disableBack(); window.onpageshow = function(e) { if (e.persisted) disableBack(); } }); </script></body> </html> On the second page, page2.html add the following code. The second page could be anything, first page is important because we are using the script on the first page. test2.html <!DOCTYPE html><html> <body> Click on back button of browser or use the backspace key on keyboard.</body> </html> Output: You can also block the browser’s back button by using Vanilla JavaScript for that you can follow this How to stop the browser back button using JavaScript article. jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? How to get a DOM Element from a jQuery Selector ? How to get the value in an input text box using jQuery ? How to generate a simple popup using jQuery ? Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25675, "s": 25647, "text": "\n10 Aug, 2021" }, { "code": null, "e": 26021, "s": 25675, "text": "While working with some privacy-related projects, we have to make sure that our programming doesn’t have any kind of loopholes. In this article, we will see how we can disable the back button of the browser intentionally so that users cannot get back and access the content. We have many scenarios where we could use this kind of functionality. " }, { "code": null, "e": 26338, "s": 26021, "text": "For example, in the payment gateways pages, we can disable the back button so that if the user unintentionally clicks on the back button the payment does not get canceled. For implementing this feature on our page we will toggle through two pages and after that, we will restrict users to get back on the first page." }, { "code": null, "e": 26464, "s": 26338, "text": "Example: Create two HTML files in the same folder as we use page1.html and page2.html. In page1.html, add the following code." }, { "code": null, "e": 26475, "s": 26464, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <title>Disabling browser back button</title> <script src= \"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script></head> <body> <a href=\"test2.html\">Next page</a> <script> $(document).ready(function() { function disableBack() { window.history.forward() } window.onload = disableBack(); window.onpageshow = function(e) { if (e.persisted) disableBack(); } }); </script></body> </html>", "e": 27140, "s": 26475, "text": null }, { "code": null, "e": 27307, "s": 27142, "text": "On the second page, page2.html add the following code. The second page could be anything, first page is important because we are using the script on the first page." }, { "code": null, "e": 27318, "s": 27307, "text": "test2.html" }, { "code": "<!DOCTYPE html><html> <body> Click on back button of browser or use the backspace key on keyboard.</body> </html>", "e": 27441, "s": 27318, "text": null }, { "code": null, "e": 27449, "s": 27441, "text": "Output:" }, { "code": null, "e": 27613, "s": 27449, "text": "You can also block the browser’s back button by using Vanilla JavaScript for that you can follow this How to stop the browser back button using JavaScript article." }, { "code": null, "e": 27628, "s": 27613, "text": "jQuery-Methods" }, { "code": null, "e": 27645, "s": 27628, "text": "jQuery-Questions" }, { "code": null, "e": 27652, "s": 27645, "text": "Picked" }, { "code": null, "e": 27659, "s": 27652, "text": "JQuery" }, { "code": null, "e": 27676, "s": 27659, "text": "Web Technologies" }, { "code": null, "e": 27774, "s": 27676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27783, "s": 27774, "text": "Comments" }, { "code": null, "e": 27796, "s": 27783, "text": "Old Comments" }, { "code": null, "e": 27819, "s": 27796, "text": "jQuery | ajax() Method" }, { "code": null, "e": 27892, "s": 27819, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 27942, "s": 27892, "text": "How to get a DOM Element from a jQuery Selector ?" }, { "code": null, "e": 27999, "s": 27942, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 28045, "s": 27999, "text": "How to generate a simple popup using jQuery ?" }, { "code": null, "e": 28078, "s": 28045, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28120, "s": 28078, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28163, "s": 28120, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28225, "s": 28163, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Tailwind CSS overscroll Behavior - GeeksforGeeks
23 Mar, 2022 This class accepts more than one value in tailwind CSS. It is the alternative to the CSS Overscroll-behavior property. This class is used to set the behavior of the browser when the boundary of a scrolling area is reached. This property can be used to prevent unwanted scrolling in pages where there are multiple scroll areas. There is separate property in CSS for CSS Overscroll-behavior-x and CSS Overflow-behavior-y, but we will cover it in this single article. Overscroll Behavior class: overscroll-auto overscroll-contain overscroll-none overscroll-y-auto overscroll-y-contain overscroll-y-none overscroll-x-auto overscroll-x-contain overscroll-x-none overscroll-auto: It is used to set the scrolling behavior to default. The whole page along with the element will scroll even if the boundary of the element is reached. It is the default value. Syntax: <element class="overscroll-auto">...</element> Example: HTML <!DOCTYPE html><head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-auto overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div> </center></body> </html> Output: overscroll-contain: It is used to set the scrolling behavior to default only on the element used. Scrolling the element further after it has reached the boundary will not scroll the elements behind it. No scroll-chaining would occur in the neighboring scrolling areas. Syntax: <element class="overscroll-contain">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-contain overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: overscroll-none: It is used to prevent scroll-chaining on all elements. The default scroll overflow behavior is also prevented. Syntax: <element class="overscroll-none">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-none overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: Overscroll-behavior-y: This class is used to set the behavior of the browser when the vertical boundary of a scrolling area is reached. This can be used in websites where there are multiple scrolling areas and scrolling one area does not affect the page as a whole. This effect is known as scroll-chaining which can be enabled or disabled accordingly. overscroll-y-auto: This is used to set the scrolling behavior on the y-axis to default on all the elements. The whole page will scroll even if the boundary of the element is reached. It is the default value. Syntax: <element class="overscroll-y-auto">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-y-auto overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: overscroll-y-contain: It is used to set the scrolling behavior on the y-axis to default only on the element used. No scroll-chaining would occur on the neighboring scrolling areas and the elements behind will not scroll. Syntax: <element class="overscroll-y-contain">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-y-contain overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: overscroll-y-none: It is used to prevent scroll-chaining on the y-axis on all elements. The default scroll overflow behavior is also prevented. Syntax: <element class="overscroll-y-none">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-y-none overflow-y-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: Overscroll-behavior-x: This class used to set the behavior of the browser when the horizontal boundary of a scrolling area is reached. This can be used in websites where there are multiple scrolling areas and scrolling one area does not affect the page as a whole. overscroll-x-auto: It is used to set the scrolling behavior on the x-axis to default on all the elements. The whole page will scroll even if the boundary of the element is reached. It is the default value. Syntax: <element class="overscroll-x-auto">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-x-auto overflow-x-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: overscroll-x-contain: It is used to set the scrolling behavior on the x-axis to default only on the element used. No scroll-chaining would occur on the neighboring scrolling areas and the elements behind will not scroll. Syntax: <element class="overscroll-x-contain">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-x-contain overflow-x-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: overscroll-x-none: It is used to prevent scroll-chaining on the x-axis on all elements. The default scroll overflow behavior is also prevented. Syntax: <element class="overscroll-x-none">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <center> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class="flex"> <div class="overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class="overscroll-behavior-x-none overflow-x-scroll bg-green-400 p-2 w-1/4 h-24"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html> Output: Tailwind CSS Tailwind-Layout CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 35749, "s": 35721, "text": "\n23 Mar, 2022" }, { "code": null, "e": 36077, "s": 35749, "text": "This class accepts more than one value in tailwind CSS. It is the alternative to the CSS Overscroll-behavior property. This class is used to set the behavior of the browser when the boundary of a scrolling area is reached. This property can be used to prevent unwanted scrolling in pages where there are multiple scroll areas. " }, { "code": null, "e": 36215, "s": 36077, "text": "There is separate property in CSS for CSS Overscroll-behavior-x and CSS Overflow-behavior-y, but we will cover it in this single article." }, { "code": null, "e": 36242, "s": 36215, "text": "Overscroll Behavior class:" }, { "code": null, "e": 36258, "s": 36242, "text": "overscroll-auto" }, { "code": null, "e": 36277, "s": 36258, "text": "overscroll-contain" }, { "code": null, "e": 36293, "s": 36277, "text": "overscroll-none" }, { "code": null, "e": 36311, "s": 36293, "text": "overscroll-y-auto" }, { "code": null, "e": 36332, "s": 36311, "text": "overscroll-y-contain" }, { "code": null, "e": 36350, "s": 36332, "text": "overscroll-y-none" }, { "code": null, "e": 36368, "s": 36350, "text": "overscroll-x-auto" }, { "code": null, "e": 36389, "s": 36368, "text": "overscroll-x-contain" }, { "code": null, "e": 36407, "s": 36389, "text": "overscroll-x-none" }, { "code": null, "e": 36601, "s": 36407, "text": "overscroll-auto: It is used to set the scrolling behavior to default. The whole page along with the element will scroll even if the boundary of the element is reached. It is the default value." }, { "code": null, "e": 36609, "s": 36601, "text": "Syntax:" }, { "code": null, "e": 36656, "s": 36609, "text": "<element class=\"overscroll-auto\">...</element>" }, { "code": null, "e": 36665, "s": 36656, "text": "Example:" }, { "code": null, "e": 36670, "s": 36665, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-auto overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div> </center></body> </html>", "e": 38068, "s": 36670, "text": null }, { "code": null, "e": 38076, "s": 38068, "text": "Output:" }, { "code": null, "e": 38345, "s": 38076, "text": "overscroll-contain: It is used to set the scrolling behavior to default only on the element used. Scrolling the element further after it has reached the boundary will not scroll the elements behind it. No scroll-chaining would occur in the neighboring scrolling areas." }, { "code": null, "e": 38353, "s": 38345, "text": "Syntax:" }, { "code": null, "e": 38403, "s": 38353, "text": "<element class=\"overscroll-contain\">...</element>" }, { "code": null, "e": 38412, "s": 38403, "text": "Example:" }, { "code": null, "e": 38417, "s": 38412, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-contain overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 39613, "s": 38417, "text": null }, { "code": null, "e": 39621, "s": 39613, "text": "Output:" }, { "code": null, "e": 39749, "s": 39621, "text": "overscroll-none: It is used to prevent scroll-chaining on all elements. The default scroll overflow behavior is also prevented." }, { "code": null, "e": 39757, "s": 39749, "text": "Syntax:" }, { "code": null, "e": 39804, "s": 39757, "text": "<element class=\"overscroll-none\">...</element>" }, { "code": null, "e": 39813, "s": 39804, "text": "Example:" }, { "code": null, "e": 39818, "s": 39813, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Overscroll Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-none overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 41011, "s": 39818, "text": null }, { "code": null, "e": 41019, "s": 41011, "text": "Output:" }, { "code": null, "e": 41371, "s": 41019, "text": "Overscroll-behavior-y: This class is used to set the behavior of the browser when the vertical boundary of a scrolling area is reached. This can be used in websites where there are multiple scrolling areas and scrolling one area does not affect the page as a whole. This effect is known as scroll-chaining which can be enabled or disabled accordingly." }, { "code": null, "e": 41579, "s": 41371, "text": "overscroll-y-auto: This is used to set the scrolling behavior on the y-axis to default on all the elements. The whole page will scroll even if the boundary of the element is reached. It is the default value." }, { "code": null, "e": 41587, "s": 41579, "text": "Syntax:" }, { "code": null, "e": 41636, "s": 41587, "text": "<element class=\"overscroll-y-auto\">...</element>" }, { "code": null, "e": 41645, "s": 41636, "text": "Example:" }, { "code": null, "e": 41650, "s": 41645, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-y-auto overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 42865, "s": 41650, "text": null }, { "code": null, "e": 42873, "s": 42865, "text": "Output:" }, { "code": null, "e": 43094, "s": 42873, "text": "overscroll-y-contain: It is used to set the scrolling behavior on the y-axis to default only on the element used. No scroll-chaining would occur on the neighboring scrolling areas and the elements behind will not scroll." }, { "code": null, "e": 43102, "s": 43094, "text": "Syntax:" }, { "code": null, "e": 43154, "s": 43102, "text": "<element class=\"overscroll-y-contain\">...</element>" }, { "code": null, "e": 43163, "s": 43154, "text": "Example:" }, { "code": null, "e": 43168, "s": 43163, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-y-contain overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 44386, "s": 43168, "text": null }, { "code": null, "e": 44394, "s": 44386, "text": "Output:" }, { "code": null, "e": 44538, "s": 44394, "text": "overscroll-y-none: It is used to prevent scroll-chaining on the y-axis on all elements. The default scroll overflow behavior is also prevented." }, { "code": null, "e": 44546, "s": 44538, "text": "Syntax:" }, { "code": null, "e": 44595, "s": 44546, "text": "<element class=\"overscroll-y-none\">...</element>" }, { "code": null, "e": 44604, "s": 44595, "text": "Example:" }, { "code": null, "e": 44609, "s": 44604, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-y Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-y-none overflow-y-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 45824, "s": 44609, "text": null }, { "code": null, "e": 45832, "s": 45824, "text": "Output:" }, { "code": null, "e": 46097, "s": 45832, "text": "Overscroll-behavior-x: This class used to set the behavior of the browser when the horizontal boundary of a scrolling area is reached. This can be used in websites where there are multiple scrolling areas and scrolling one area does not affect the page as a whole." }, { "code": null, "e": 46304, "s": 46097, "text": "overscroll-x-auto: It is used to set the scrolling behavior on the x-axis to default on all the elements. The whole page will scroll even if the boundary of the element is reached. It is the default value." }, { "code": null, "e": 46312, "s": 46304, "text": "Syntax:" }, { "code": null, "e": 46361, "s": 46312, "text": "<element class=\"overscroll-x-auto\">...</element>" }, { "code": null, "e": 46370, "s": 46361, "text": "Example:" }, { "code": null, "e": 46375, "s": 46370, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-x-auto overflow-x-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 47590, "s": 46375, "text": null }, { "code": null, "e": 47598, "s": 47590, "text": "Output:" }, { "code": null, "e": 47819, "s": 47598, "text": "overscroll-x-contain: It is used to set the scrolling behavior on the x-axis to default only on the element used. No scroll-chaining would occur on the neighboring scrolling areas and the elements behind will not scroll." }, { "code": null, "e": 47827, "s": 47819, "text": "Syntax:" }, { "code": null, "e": 47879, "s": 47827, "text": "<element class=\"overscroll-x-contain\">...</element>" }, { "code": null, "e": 47888, "s": 47879, "text": "Example:" }, { "code": null, "e": 47893, "s": 47888, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-x-contain overflow-x-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 49111, "s": 47893, "text": null }, { "code": null, "e": 49119, "s": 49111, "text": "Output:" }, { "code": null, "e": 49263, "s": 49119, "text": "overscroll-x-none: It is used to prevent scroll-chaining on the x-axis on all elements. The default scroll overflow behavior is also prevented." }, { "code": null, "e": 49271, "s": 49263, "text": "Syntax:" }, { "code": null, "e": 49320, "s": 49271, "text": "<element class=\"overscroll-x-none\">...</element>" }, { "code": null, "e": 49329, "s": 49320, "text": "Example:" }, { "code": null, "e": 49334, "s": 49329, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <center> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS overscroll-behavior-x Class</b> <div class=\"flex\"> <div class=\"overscroll-contain bg-green-200 p-4 mx-24 w-1/3 text-justify\"> This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </div> <div class=\"overscroll-behavior-x-none overflow-x-scroll bg-green-400 p-2 w-1/4 h-24\"> This is a smaller element that is also scrollable. The overscroll behavior can be used to control if the main content behind would scroll when this element's vertical boundary is reached. </div> </div></center></body> </html>", "e": 50549, "s": 49334, "text": null }, { "code": null, "e": 50557, "s": 50549, "text": "Output:" }, { "code": null, "e": 50570, "s": 50557, "text": "Tailwind CSS" }, { "code": null, "e": 50586, "s": 50570, "text": "Tailwind-Layout" }, { "code": null, "e": 50590, "s": 50586, "text": "CSS" }, { "code": null, "e": 50607, "s": 50590, "text": "Web Technologies" }, { "code": null, "e": 50705, "s": 50607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50714, "s": 50705, "text": "Comments" }, { "code": null, "e": 50727, "s": 50714, "text": "Old Comments" }, { "code": null, "e": 50789, "s": 50727, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 50839, "s": 50789, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 50897, "s": 50839, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 50945, "s": 50897, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 50982, "s": 50945, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 51038, "s": 50982, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 51071, "s": 51038, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 51133, "s": 51071, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 51176, "s": 51133, "text": "How to fetch data from an API in ReactJS ?" } ]
How to match one of the two given expressions using Java RegEx?
Using the or logical operator | of Java regular expressions you can match either of two given expressions. For example, if you need your regular expression should match more than one expression you can do so by separating the required expressions by “|”. import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression to match string that starts with hello or ends with bye String regex = "^hello|bye$"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } } Enter a String hello how are you Match occurred Enter a String This is a sample string Match not occurred import java.util.Scanner; public class RegexExample { public static void main( String args[] ) { //Regular expression to match either yes or no String regex = "yes|no"; System.out.println("Enter input value: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); boolean bool = input.matches(regex); if(bool) { System.out.println("match occurred"); } else { System.out.println("match not accepted"); } } } Enter input value: yes match occurred Enter input value: hello match not accepted
[ { "code": null, "e": 1169, "s": 1062, "text": "Using the or logical operator | of Java regular expressions you can match either of two given expressions." }, { "code": null, "e": 1317, "s": 1169, "text": "For example, if you need your regular expression should match more than one expression you can do so by separating the required expressions by “|”." }, { "code": null, "e": 2079, "s": 1317, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n //Regular expression to match string that starts with hello or ends with bye\n String regex = \"^hello|bye$\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n if(matcher.find()) {\n System.out.println(\"Match occurred\");\n } else {\n System.out.println(\"Match not occurred\");\n }\n }\n}" }, { "code": null, "e": 2127, "s": 2079, "text": "Enter a String\nhello how are you\nMatch occurred" }, { "code": null, "e": 2185, "s": 2127, "text": "Enter a String\nThis is a sample string\nMatch not occurred" }, { "code": null, "e": 2679, "s": 2185, "text": "import java.util.Scanner;\npublic class RegexExample {\n public static void main( String args[] ) {\n //Regular expression to match either yes or no String regex = \"yes|no\";\n System.out.println(\"Enter input value: \");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n boolean bool = input.matches(regex);\n if(bool) {\n System.out.println(\"match occurred\");\n } else {\n System.out.println(\"match not accepted\");\n }\n }\n}" }, { "code": null, "e": 2717, "s": 2679, "text": "Enter input value:\nyes\nmatch occurred" }, { "code": null, "e": 2761, "s": 2717, "text": "Enter input value:\nhello\nmatch not accepted" } ]
Create a temporary table in a MySQL procedure?
To create a temporary table in a MySQL procedure, following is the syntax − CREATE PROCEDURE yourProcedureName() BEGIN CREATE TEMPORARY TABLE yourTemporaryTableName SELECT yourValue; END Let us implement the above syntax to create a temporary table and insert some records in the table. Following is the query to create a stored procedure and a temporary table in it − mysql> DELIMITER // mysql> CREATE PROCEDURE create_Temporary_Table() -> BEGIN -> CREATE TEMPORARY TABLE tmpDemoTable SELECT 500; -> END// Query OK, 0 rows affected (0.15 sec) Following is the query to insert record in the table − mysql> CREATE PROCEDURE insert_Record_InTempTable() -> BEGIN -> INSERT INTO tmpDemoTable VALUES (300); -> END// Query OK, 0 rows affected (0.06 sec) mysql> DELIMITER Now you can call the above stored procedure to create a temporary table − mysql> call create_Temporary_Table(); Query OK, 1 row affected (0.00 sec) mysql> call insert_Record_InTempTable(); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select *from tmpDemoTable; This will produce the following output − +-----+ | 500 | +-----+ | 500 | | 300 | +-----+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "To create a temporary table in a MySQL procedure, following is the syntax −" }, { "code": null, "e": 1261, "s": 1138, "text": "CREATE PROCEDURE yourProcedureName()\n BEGIN\n CREATE TEMPORARY TABLE yourTemporaryTableName SELECT yourValue;\n END" }, { "code": null, "e": 1443, "s": 1261, "text": "Let us implement the above syntax to create a temporary table and insert some records in the table. Following is the query to create a stored procedure and a temporary table in it −" }, { "code": null, "e": 1630, "s": 1443, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE create_Temporary_Table()\n -> BEGIN\n -> CREATE TEMPORARY TABLE tmpDemoTable SELECT 500;\n -> END//\nQuery OK, 0 rows affected (0.15 sec)" }, { "code": null, "e": 1685, "s": 1630, "text": "Following is the query to insert record in the table −" }, { "code": null, "e": 1846, "s": 1685, "text": "mysql> CREATE PROCEDURE insert_Record_InTempTable()\n -> BEGIN\n -> INSERT INTO tmpDemoTable VALUES (300);\n -> END//\nQuery OK, 0 rows affected (0.06 sec)" }, { "code": null, "e": 1863, "s": 1846, "text": "mysql> DELIMITER" }, { "code": null, "e": 1937, "s": 1863, "text": "Now you can call the above stored procedure to create a temporary table −" }, { "code": null, "e": 2089, "s": 1937, "text": "mysql> call create_Temporary_Table();\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> call insert_Record_InTempTable();\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 2149, "s": 2089, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2183, "s": 2149, "text": "mysql> select *from tmpDemoTable;" }, { "code": null, "e": 2224, "s": 2183, "text": "This will produce the following output −" }, { "code": null, "e": 2297, "s": 2224, "text": "+-----+\n| 500 |\n+-----+\n| 500 |\n| 300 |\n+-----+\n2 rows in set (0.00 sec)" } ]
C++ Program to Check Leap Year
A leap year contains one additional day that is added to keep the calendar year synchronized with the astronomical year. A year that is divisible by 4 is known as a leap year. However, years divisible by 100 are not leap years while those divisible by 400 are. The program that checks if a year is leap year or not is as follows − Live Demo #include<iostream> using namespace std; int main() { int year = 2016; if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) cout<<year<<" is a leap year"; else cout<<year<<" is not a leap year"; return 0; } 2016 is a leap year In the above program, if a year is divisible by 4 and not divisible by 100, then it is a leap year. Also, if a year is divisible by 400, it is a leap year. This is demonstrated by the following code snippet. if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) cout<<year<<" is a leap year"; else cout<<year<<" is not a leap year"; The program to check if a year is leap year or not can also be written using nested if statements. This is given as follows − Live Demo #include <iostream> using namespace std; int main() { int year = 2020; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) cout << year << " is a leap year"; else cout << year << " is not a leap year"; } else cout << year << " is a leap year"; } else cout << year << " is not a leap year"; return 0; } 2020 is a leap year In the above program, if the year is divisible by 4, then it is checked if it is divisible by 100. If it is divisible by 100, then it is checked if it is divisible by 400. It yes, then the year is a leap year.Otherwise, it is not. If the year is not divisible by 100, it is a leap year. If the year is not divisible by 4, it is not a leap year. This is demonstrated by the following code snippet − if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) cout << year << " is a leap year"; else cout << year << " is not a leap year"; } else cout << year << " is a leap year"; } else cout << year << " is not a leap year";
[ { "code": null, "e": 1183, "s": 1062, "text": "A leap year contains one additional day that is added to keep the calendar year synchronized with the astronomical year." }, { "code": null, "e": 1323, "s": 1183, "text": "A year that is divisible by 4 is known as a leap year. However, years divisible by 100 are not leap years while those divisible by 400 are." }, { "code": null, "e": 1393, "s": 1323, "text": "The program that checks if a year is leap year or not is as follows −" }, { "code": null, "e": 1404, "s": 1393, "text": " Live Demo" }, { "code": null, "e": 1640, "s": 1404, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int year = 2016;\n if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))\n cout<<year<<\" is a leap year\";\n else\n cout<<year<<\" is not a leap year\";\n return 0;\n}" }, { "code": null, "e": 1660, "s": 1640, "text": "2016 is a leap year" }, { "code": null, "e": 1816, "s": 1660, "text": "In the above program, if a year is divisible by 4 and not divisible by 100, then it is a leap year. Also, if a year is divisible by 400, it is a leap year." }, { "code": null, "e": 1868, "s": 1816, "text": "This is demonstrated by the following code snippet." }, { "code": null, "e": 2004, "s": 1868, "text": "if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))\ncout<<year<<\" is a leap year\";\nelse\ncout<<year<<\" is not a leap year\";" }, { "code": null, "e": 2130, "s": 2004, "text": "The program to check if a year is leap year or not can also be written using nested if statements. This is given as follows −" }, { "code": null, "e": 2141, "s": 2130, "text": " Live Demo" }, { "code": null, "e": 2525, "s": 2141, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int year = 2020;\n if (year % 4 == 0) {\n if (year % 100 == 0) {\n if (year % 400 == 0)\n cout << year << \" is a leap year\";\n else\n cout << year << \" is not a leap year\";\n } else\n cout << year << \" is a leap year\";\n } else\n cout << year << \" is not a leap year\";\n return 0;\n}" }, { "code": null, "e": 2545, "s": 2525, "text": "2020 is a leap year" }, { "code": null, "e": 2890, "s": 2545, "text": "In the above program, if the year is divisible by 4, then it is checked if it is divisible by 100. If it is divisible by 100, then it is checked if it is divisible by 400. It yes, then the year is a leap year.Otherwise, it is not. If the year is not divisible by 100, it is a leap year. If the year is not divisible by 4, it is not a leap year." }, { "code": null, "e": 2943, "s": 2890, "text": "This is demonstrated by the following code snippet −" }, { "code": null, "e": 3208, "s": 2943, "text": "if (year % 4 == 0) {\n if (year % 100 == 0) {\n if (year % 400 == 0)\n cout << year << \" is a leap year\";\n else\n cout << year << \" is not a leap year\";\n } else\n cout << year << \" is a leap year\";\n} else\ncout << year << \" is not a leap year\";" } ]
Exchange Rate Prediction: Machine Learning with 5 Regression Models | by Andrew Nguyen | Towards Data Science
If you have missed my 1st part on this end-to-end project about Exchange Rate Prediction, feel free to check it out here. As a recap, this project aims to analyze the historical pattern of exchange rates across different country currencies against USD and therefore to forecast the values in 2020. In order to bring out the best model, I have divided the project into 3 parts which, I hope, will possibly cover what is needed for the prediction: Part 1: Explanatory Data Analysis (EDA) & Data Visualisation (Bonus: Hypothesis Testing)Part 2: Machine Learning with 4 Regression ModelsPart 3: Machine Learning (cont.) with ARIMA Part 1: Explanatory Data Analysis (EDA) & Data Visualisation (Bonus: Hypothesis Testing) Part 2: Machine Learning with 4 Regression Models Part 3: Machine Learning (cont.) with ARIMA Today, I will bring you through the 2nd part which deploys Machine Learning with the aim of finding the line that best fits the pattern of exchange rates over the years. That being said, Linear Regression would seemingly be the right model or, at least, the foundation for our analysis. Beyond it, I have also tested out other linear regression models before deciding which to use for the forecasting (part 3): Linear Regression Multiple Linear Regression Polynomial Regression Ridge Regression (L2 Regularization) Lasso Regression (L1 Regularization) Let’s get started! According to Investopedia, there are 3 common ways to forecast exchange rates: Purchasing Power Parity (PPP), Relative Economic Strength, and Econometric Model. Among the three, I decided to go with the third as it involves a multitude of factors that affect currency movements. www.investopedia.com “The factors used in econometric models are typically based on economic theory, but any variable can be added if it is believed to significantly influence the exchange rate.” — Investopedia, by Joseph Nguyen. This method greatly aligns with the direction that employs “any independent variable” that is influential on the dependent variable — linear regression. Therefore, the factors I wanted to test out are interest rate differential, GDP growth rates, and income growth rate, sequentially yet accumulatively. For this project, I used the exchange rate of AUD/USD for the analysis. Let’s kick off our Linear Regression model with one independent variable: Interest Rate Differential. If you are keen to explore, please refer to this data source. ir_df = pd.read_csv("aud usd interest carry trade.csv")ir_df.head() Above is the table of interest rate differential of AUD/USD from 2017 to 2019. If you want to know more what “long carry” and “short carry” are, check out this article on Investopedia about Carry Trade and another on FXCM about Interest-Rate Carry Trade. In short, Interest-rate carry trades are a form of arbitrage, in which someone makes use of the difference that exists between two markets in order to turn a profit. As such, let’s transform this data for the analysis (in this case, I used Long Carry Interest Rate): x_ir = ir_df['Long Carry'].astype(str)x_ir = x_ir.replace({'%':''}, regex = True)x_ir = x_ir.astype(float)x_ir = np.array(x_ir).reshape(-1,1)aud_usd_fx = df_groupby_aud[(df_groupby_aud['month_year'] >= '2017-01') & (df_groupby_aud['month_year'] <='2019-12')].reset_index(drop=True)aud_usd = aud_usd_fx['AUD_USD']y_fx = aud_usd Here, x_ir refers to the independent variable that affects our exchange rate. For easier use, I removed the “%” from the numbers with regex replace, and converted them to float. As 2D array data is required in the regression model, we need to convert our 1D x_ir to 2D by using .reshape(-1, 1). And if you recall from the 1st part, we have cleaned up the entire dataset, so it’s now easier for us to pick up the AUD/USD data (y_fx) as the dependent variable. Please note that I only used a short period of time (from 2017 to 2019, 36 months) in this project for the sake of simplicity. There you go, let’s run our 1st machine learning model by importing relevant functions from Scikit-learn library! from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression As you might have known, in order to test the accuracy of our model, we are advised to split the dataset into training and testing sets. Essentially, we train the model on the training set and then predict the values with the testing set. x_train, x_test, y_train, y_test = train_test_split(x_ir, y_fx, train_size=0.8, test_size=0.2, random_state=1)model = LinearRegression()model.fit(x_train, y_train)y_predict = model.predict(x_test)print(model.score(x_train, y_train))print(model.score(x_test, y_test)) Here, I split the data into 80% training and 20% test, meaning that the model will learn the pattern by 80% training data, and then predict the y values with 20% testing data. .score() tells us the percentage of a dependent variable (exchange rate) being explained by the independent variable (interest rate differential) or as we know, R-squared. As you can see, the percentage between training and testing data is pretty much close, meaning that the accuracy of the model is relatively good. However, from my observation, the size of the dataset is relatively small (n=36 as we only cover 2017 to 2019), I wanted to see whether I’m able to NOT split the data into training and testing sets or not, for the sake of simplicity. model = LinearRegression()model.fit(x_ir, y_fx)y_fx_predict = model.predict(x_ir)print(model.score(x_ir, y_fx)) The difference in the R-squared between split and no-split is minimal, probably due to the small dataset size. Hence, I will NOT split the data and use the entire dataset. Let’s see how well our model does in creating the “best-fit” line: month_year = aud_usd_fx['month_year']month_year = month_year.astype(str)plt.figure(figsize=(12,6))plt.scatter(month_year, y_fx, alpha=0.4)plt.plot(month_year, y_fx_predict)plt.title("Linear Regression: AUD/USD Exchange Rate (1 var: Interest Rate)")plt.xlabel("Month-Year")plt.ylabel("Exchange Rate")plt.xticks(fontsize=4)plt.show() Combined with the R-squared, the line seems to be able to portray the exchange rate to some extent (R-squared is 72%). Let’s add another variable to see how far our R-squared improves, with Multiple Linear Regression. As shared from the beginning of the article, we are able to add additional variables to the model as long as they are influential on the dependent variable. This leads us to the second Linear Regression model, which includes more than 1 independent variable. Let’s add GDP Growth Rate to our dataset, which can be found from this domain. aus_gdp = pd.read_csv("AUS GDP.csv")usa_gdp = pd.read_csv("USA GDP.csv")aus_gdp = aus_gdp.rename(columns={'GDP': 'AUS_GDP'})aus_usa_gdp = pd.merge(aus_gdp, usa_gdp, on="month_year", how="inner")aus_usa_gdp = aus_usa_gdp.rename(columns={'GDP': 'USA_GDP'})aus_usa_gdp['GDP_diff'] = aus_usa_gdp['AUS_GDP'] - aus_usa_gdp['USA_GDP']aus_usa_gdp_20172019 = aus_usa_gdp[(aus_usa_gdp['month_year'] >= '2017-01') & (aus_usa_gdp['month_year'] <='2019-12')].reset_index(drop=True)gdp_diff = ["%.4f" %num for num in aus_usa_gdp_20172019['GDP_diff']] After loading the data, I applied EDA to clean up and extracted gdp_diff from the dataframe to a list, so as to combine with x_ir variable for our Multiple Linear Regression. x_ir_gdp = np.array(list(zip(x_ir, gdp_diff)))x_ir_gdp = x_ir_gdp.astype(np.float)model.fit(x_ir_gdp, y_fx)y_fx_predict_2 = model.predict(x_ir_gdp)print(model.score(x_ir_gdp, y_fx)) After adding another variable to the model, R-squared has improved quite significantly, from 72% to 87.2%. Let’s compare it visually against the first line we created: Looks good, right! Okay, let’s try adding another independent variable to our model, Consumer Price Index (CPI). Again, the dataset can be found from this domain. cpi = pd.read_csv("aus usa cpi difference.csv")cpi_diff = cpi['CPI_diff']x_ir_gdp_cpi = np.array(list(zip(x_ir, gdp_diff, cpi_diff)))x_ir_gdp_cpi = x_ir_gdp_cpi.astype(np.float)model.fit(x_ir_gdp_cpi, y_fx)y_fx_predict_4 = model.predict(x_ir_gdp_cpi)print(model.score(x_ir_gdp_cpi, y_fx)) This time, R-squared increased really slightly, from 87.2% to 87.3%. This means CPI does not significantly affect the movement of exchange rate nor help improve our model. Visually, there’s no difference either. Let’s replace CPI variable with another, Unemployment Rate (UER) and see whether this improves our model or not. unemployment_rate = pd.read_csv("aus usa unemployment rate.csv")unemployment_rate['uer_diff'] = unemployment_rate['aus_unemployment rate'] - unemployment_rate['usa_unemployment rate']uer_diff_all = unemployment_rate['uer_diff']uer_diff = ["%.4f" % num for num in uer_diff_all]x_ir_gdp_uer = np.array(list(zip(x_ir, gdp_diff, uer_diff)))x_ir_gdp_uer = x_ir_gdp_uer.astype(np.float)model.fit(x_ir_gdp_uer, y_fx)y_fx_predict_3 = model.predict(x_ir_gdp_uer)print(model.score(x_ir_gdp_uer, y_fx)) Okay, R-squared has improved a bit better, from 87.2% to 88.9%. Not too bad, statistically and visually. You can continue to add some more variables to the model, but be careful with overfitting! For me, instead of adding more independent variables, I decided to test out another regression model to find a better-fit line: Polynomial Regression. What is Polynomial Regression? It’s still one kind of Linear Regression but a much more “adaptable” version. Traditionally, Linear Regression aims to find the best linear line that fits all your data points, which might not always be the case. Therefore, Polynomial Regression acts as another form that draws the line from coordinates (x, y) with y modeled as the nth degree polynomial. Let’s import the function from Sciki-learn library and build our model: from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=4)x_poly = poly.fit_transform(x_ir_gdp_uer)model_poly = LinearRegression()model_poly.fit(x_poly, y_fx)y_pred = model_poly.predict(x_poly)print(model_poly.score(x_poly, y_fx)) The only difference in the function between Linear and Polynomial Regression is the degree parameter. Before getting to the result, let me briefly explain: .fit_transform() is to convert your independent variables from linearly to polynomially. The rest of the function stays the same. Here, I randomly selected the degree of 4 and R-squared is nearly perfect: 99.9%! You may want to see it visually? The black line represents the fit that Polynomial Regression found with the degree of 4. How amazing? But the question is: “Which degree is the best, to neither overfit nor underfit the data?” We know that we aim to find R-squared as high as possible, as it well explains the fact that the dependent variable (exchange rate) is affected by the independent variable(s). Apart from it, there is another metric that is able to evaluate the accuracy of our model: Mean Squared Error (MSE). To find the best degree, I decided to test a range of degrees, from 1 to 10 on our model separately with a for loop and visualize it: from sklearn.metrics import mean_squared_errorr_squared_list = []mse_list = []a = range(1,10,1)for i in a: poly = PolynomialFeatures(degree=i) x_poly = poly.fit_transform(x_ir_gdp_uer) model_poly = LinearRegression() model_poly.fit(x_poly, y_fx) y_pred = model_poly.predict(x_poly) r_squared = model_poly.score(x_poly, y_fx) mse = mean_squared_error(y_pred, y_fx) r_squared_list.append(r_squared) mse_list.append(mse) As you can see in both charts, as the line increases from degrees of 1 to 4, the R-Squared and MSE improve significantly (the higher the better for R-Squared, the lower the better for MSE). However, it peaks at degree of 4 and no further improvement is seen since the degree of 5. This means that degree of 4 brings out the best accuracy score for our model! So let’s stick with 4 then! Yay! We finally got the line that best fits the exchange rate over the years, thanks to Polynomial Regression! These final two are my latest experiment in the “ecosystem” of linear regression models as I have heard about somewhere before. Oh yes, it regards L1 & L2 Regularisation! As such, I wanted to test out these two models in my project as well to see how they perform against the above models. However, before jumping into them, let’s quickly point out the origin of these models, Regularisation, and the roles they play against what we might commonly know about Linear Regression. It all started with Overfitting. In a nutshell, overfitting occurs when a machine learning model is too tailored to a certain dataset (especially with too many independent variables/features) and hence unable to generalise to other datasets. Hence, regularisation was introduced to prevent this phenomenon. Essentially, what regularisation does is: Reduce the complexity of the model while maintaining the number of independent variables/features Technically, reduce the magnitude of the coefficients as penalty term to the loss function If you want to deep dive into how it works, mathematically, check out this article on Towards Data Science for more details. Ridge Regression and Lasso Regression were developed from this concept of Regularisation. The only difference between the two is: Ridge Regression uses L2 Regularisation technique, which shrinks the coefficients to zero, but NOT absolute zero Lasso Regression uses L1 Regularisation technique, which shrinks the coefficients to absolute zero This is because Ridge keeps all variables/features while Lasso only keeps the important ones that matter, hence voted as the variable/feature selection technique when our dataset has TOO MANY variables/features. Okay, back to our dataset! Even though our model does not have too many variables (in this case, 3), I still wanted to see how Ridge and Lasso Regression perform on my dataset. from sklearn.linear_model import Ridge, Lassoridge = Ridge(alpha=0.001)ridge.fit(x_ir_gdp_uer, y_fx)y_fx_ridge = ridge.predict(x_ir_gdp_uer)print(ridge.score(x_ir_gdp_uer, y_fx))lasso = Lasso(alpha=0.001)lasso.fit(x_ir_gdp_uer, y_fx)y_fx_lasso = lasso.predict(x_ir_gdp_uer)print(lasso.score(x_ir_gdp_uer, y_fx)) R-Squared of Ridge is 88% while of Lasso is 87%. Not too bad when we compare these numbers with our Multiple Linear Regression (88.9%). This proves that overfitting does not occur to our model! WOW! That’s a wrap for the 2nd part of this project! Too much to absorb, isn’t it? But I do hope you have found this article informative and actionable. In short, we have found the line that best fits our dataset, greatly explaining the pattern of exchange rates over the years! What’s next? Again, do look out for the final part of my project which will cover how I forecasted the exchange rates of 2020 using the regression line we have just discovered. In the meantime, give me a clap if you find this helpful and feel free to check out my Github here for the complete repository: Github: https://github.com/andrewnguyen07LinkedIn: www.linkedin.com/in/andrewnguyen07
[ { "code": null, "e": 294, "s": 172, "text": "If you have missed my 1st part on this end-to-end project about Exchange Rate Prediction, feel free to check it out here." }, { "code": null, "e": 618, "s": 294, "text": "As a recap, this project aims to analyze the historical pattern of exchange rates across different country currencies against USD and therefore to forecast the values in 2020. In order to bring out the best model, I have divided the project into 3 parts which, I hope, will possibly cover what is needed for the prediction:" }, { "code": null, "e": 799, "s": 618, "text": "Part 1: Explanatory Data Analysis (EDA) & Data Visualisation (Bonus: Hypothesis Testing)Part 2: Machine Learning with 4 Regression ModelsPart 3: Machine Learning (cont.) with ARIMA" }, { "code": null, "e": 888, "s": 799, "text": "Part 1: Explanatory Data Analysis (EDA) & Data Visualisation (Bonus: Hypothesis Testing)" }, { "code": null, "e": 938, "s": 888, "text": "Part 2: Machine Learning with 4 Regression Models" }, { "code": null, "e": 982, "s": 938, "text": "Part 3: Machine Learning (cont.) with ARIMA" }, { "code": null, "e": 1393, "s": 982, "text": "Today, I will bring you through the 2nd part which deploys Machine Learning with the aim of finding the line that best fits the pattern of exchange rates over the years. That being said, Linear Regression would seemingly be the right model or, at least, the foundation for our analysis. Beyond it, I have also tested out other linear regression models before deciding which to use for the forecasting (part 3):" }, { "code": null, "e": 1411, "s": 1393, "text": "Linear Regression" }, { "code": null, "e": 1438, "s": 1411, "text": "Multiple Linear Regression" }, { "code": null, "e": 1460, "s": 1438, "text": "Polynomial Regression" }, { "code": null, "e": 1497, "s": 1460, "text": "Ridge Regression (L2 Regularization)" }, { "code": null, "e": 1534, "s": 1497, "text": "Lasso Regression (L1 Regularization)" }, { "code": null, "e": 1553, "s": 1534, "text": "Let’s get started!" }, { "code": null, "e": 1832, "s": 1553, "text": "According to Investopedia, there are 3 common ways to forecast exchange rates: Purchasing Power Parity (PPP), Relative Economic Strength, and Econometric Model. Among the three, I decided to go with the third as it involves a multitude of factors that affect currency movements." }, { "code": null, "e": 1853, "s": 1832, "text": "www.investopedia.com" }, { "code": null, "e": 2062, "s": 1853, "text": "“The factors used in econometric models are typically based on economic theory, but any variable can be added if it is believed to significantly influence the exchange rate.” — Investopedia, by Joseph Nguyen." }, { "code": null, "e": 2438, "s": 2062, "text": "This method greatly aligns with the direction that employs “any independent variable” that is influential on the dependent variable — linear regression. Therefore, the factors I wanted to test out are interest rate differential, GDP growth rates, and income growth rate, sequentially yet accumulatively. For this project, I used the exchange rate of AUD/USD for the analysis." }, { "code": null, "e": 2602, "s": 2438, "text": "Let’s kick off our Linear Regression model with one independent variable: Interest Rate Differential. If you are keen to explore, please refer to this data source." }, { "code": null, "e": 2670, "s": 2602, "text": "ir_df = pd.read_csv(\"aud usd interest carry trade.csv\")ir_df.head()" }, { "code": null, "e": 2935, "s": 2670, "text": "Above is the table of interest rate differential of AUD/USD from 2017 to 2019. If you want to know more what “long carry” and “short carry” are, check out this article on Investopedia about Carry Trade and another on FXCM about Interest-Rate Carry Trade. In short," }, { "code": null, "e": 3091, "s": 2935, "text": "Interest-rate carry trades are a form of arbitrage, in which someone makes use of the difference that exists between two markets in order to turn a profit." }, { "code": null, "e": 3192, "s": 3091, "text": "As such, let’s transform this data for the analysis (in this case, I used Long Carry Interest Rate):" }, { "code": null, "e": 3519, "s": 3192, "text": "x_ir = ir_df['Long Carry'].astype(str)x_ir = x_ir.replace({'%':''}, regex = True)x_ir = x_ir.astype(float)x_ir = np.array(x_ir).reshape(-1,1)aud_usd_fx = df_groupby_aud[(df_groupby_aud['month_year'] >= '2017-01') & (df_groupby_aud['month_year'] <='2019-12')].reset_index(drop=True)aud_usd = aud_usd_fx['AUD_USD']y_fx = aud_usd" }, { "code": null, "e": 3978, "s": 3519, "text": "Here, x_ir refers to the independent variable that affects our exchange rate. For easier use, I removed the “%” from the numbers with regex replace, and converted them to float. As 2D array data is required in the regression model, we need to convert our 1D x_ir to 2D by using .reshape(-1, 1). And if you recall from the 1st part, we have cleaned up the entire dataset, so it’s now easier for us to pick up the AUD/USD data (y_fx) as the dependent variable." }, { "code": null, "e": 4105, "s": 3978, "text": "Please note that I only used a short period of time (from 2017 to 2019, 36 months) in this project for the sake of simplicity." }, { "code": null, "e": 4219, "s": 4105, "text": "There you go, let’s run our 1st machine learning model by importing relevant functions from Scikit-learn library!" }, { "code": null, "e": 4321, "s": 4219, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression" }, { "code": null, "e": 4560, "s": 4321, "text": "As you might have known, in order to test the accuracy of our model, we are advised to split the dataset into training and testing sets. Essentially, we train the model on the training set and then predict the values with the testing set." }, { "code": null, "e": 4827, "s": 4560, "text": "x_train, x_test, y_train, y_test = train_test_split(x_ir, y_fx, train_size=0.8, test_size=0.2, random_state=1)model = LinearRegression()model.fit(x_train, y_train)y_predict = model.predict(x_test)print(model.score(x_train, y_train))print(model.score(x_test, y_test))" }, { "code": null, "e": 5175, "s": 4827, "text": "Here, I split the data into 80% training and 20% test, meaning that the model will learn the pattern by 80% training data, and then predict the y values with 20% testing data. .score() tells us the percentage of a dependent variable (exchange rate) being explained by the independent variable (interest rate differential) or as we know, R-squared." }, { "code": null, "e": 5321, "s": 5175, "text": "As you can see, the percentage between training and testing data is pretty much close, meaning that the accuracy of the model is relatively good." }, { "code": null, "e": 5555, "s": 5321, "text": "However, from my observation, the size of the dataset is relatively small (n=36 as we only cover 2017 to 2019), I wanted to see whether I’m able to NOT split the data into training and testing sets or not, for the sake of simplicity." }, { "code": null, "e": 5667, "s": 5555, "text": "model = LinearRegression()model.fit(x_ir, y_fx)y_fx_predict = model.predict(x_ir)print(model.score(x_ir, y_fx))" }, { "code": null, "e": 5839, "s": 5667, "text": "The difference in the R-squared between split and no-split is minimal, probably due to the small dataset size. Hence, I will NOT split the data and use the entire dataset." }, { "code": null, "e": 5906, "s": 5839, "text": "Let’s see how well our model does in creating the “best-fit” line:" }, { "code": null, "e": 6238, "s": 5906, "text": "month_year = aud_usd_fx['month_year']month_year = month_year.astype(str)plt.figure(figsize=(12,6))plt.scatter(month_year, y_fx, alpha=0.4)plt.plot(month_year, y_fx_predict)plt.title(\"Linear Regression: AUD/USD Exchange Rate (1 var: Interest Rate)\")plt.xlabel(\"Month-Year\")plt.ylabel(\"Exchange Rate\")plt.xticks(fontsize=4)plt.show()" }, { "code": null, "e": 6456, "s": 6238, "text": "Combined with the R-squared, the line seems to be able to portray the exchange rate to some extent (R-squared is 72%). Let’s add another variable to see how far our R-squared improves, with Multiple Linear Regression." }, { "code": null, "e": 6715, "s": 6456, "text": "As shared from the beginning of the article, we are able to add additional variables to the model as long as they are influential on the dependent variable. This leads us to the second Linear Regression model, which includes more than 1 independent variable." }, { "code": null, "e": 6794, "s": 6715, "text": "Let’s add GDP Growth Rate to our dataset, which can be found from this domain." }, { "code": null, "e": 7331, "s": 6794, "text": "aus_gdp = pd.read_csv(\"AUS GDP.csv\")usa_gdp = pd.read_csv(\"USA GDP.csv\")aus_gdp = aus_gdp.rename(columns={'GDP': 'AUS_GDP'})aus_usa_gdp = pd.merge(aus_gdp, usa_gdp, on=\"month_year\", how=\"inner\")aus_usa_gdp = aus_usa_gdp.rename(columns={'GDP': 'USA_GDP'})aus_usa_gdp['GDP_diff'] = aus_usa_gdp['AUS_GDP'] - aus_usa_gdp['USA_GDP']aus_usa_gdp_20172019 = aus_usa_gdp[(aus_usa_gdp['month_year'] >= '2017-01') & (aus_usa_gdp['month_year'] <='2019-12')].reset_index(drop=True)gdp_diff = [\"%.4f\" %num for num in aus_usa_gdp_20172019['GDP_diff']]" }, { "code": null, "e": 7506, "s": 7331, "text": "After loading the data, I applied EDA to clean up and extracted gdp_diff from the dataframe to a list, so as to combine with x_ir variable for our Multiple Linear Regression." }, { "code": null, "e": 7688, "s": 7506, "text": "x_ir_gdp = np.array(list(zip(x_ir, gdp_diff)))x_ir_gdp = x_ir_gdp.astype(np.float)model.fit(x_ir_gdp, y_fx)y_fx_predict_2 = model.predict(x_ir_gdp)print(model.score(x_ir_gdp, y_fx))" }, { "code": null, "e": 7856, "s": 7688, "text": "After adding another variable to the model, R-squared has improved quite significantly, from 72% to 87.2%. Let’s compare it visually against the first line we created:" }, { "code": null, "e": 8019, "s": 7856, "text": "Looks good, right! Okay, let’s try adding another independent variable to our model, Consumer Price Index (CPI). Again, the dataset can be found from this domain." }, { "code": null, "e": 8308, "s": 8019, "text": "cpi = pd.read_csv(\"aus usa cpi difference.csv\")cpi_diff = cpi['CPI_diff']x_ir_gdp_cpi = np.array(list(zip(x_ir, gdp_diff, cpi_diff)))x_ir_gdp_cpi = x_ir_gdp_cpi.astype(np.float)model.fit(x_ir_gdp_cpi, y_fx)y_fx_predict_4 = model.predict(x_ir_gdp_cpi)print(model.score(x_ir_gdp_cpi, y_fx))" }, { "code": null, "e": 8520, "s": 8308, "text": "This time, R-squared increased really slightly, from 87.2% to 87.3%. This means CPI does not significantly affect the movement of exchange rate nor help improve our model. Visually, there’s no difference either." }, { "code": null, "e": 8633, "s": 8520, "text": "Let’s replace CPI variable with another, Unemployment Rate (UER) and see whether this improves our model or not." }, { "code": null, "e": 9125, "s": 8633, "text": "unemployment_rate = pd.read_csv(\"aus usa unemployment rate.csv\")unemployment_rate['uer_diff'] = unemployment_rate['aus_unemployment rate'] - unemployment_rate['usa_unemployment rate']uer_diff_all = unemployment_rate['uer_diff']uer_diff = [\"%.4f\" % num for num in uer_diff_all]x_ir_gdp_uer = np.array(list(zip(x_ir, gdp_diff, uer_diff)))x_ir_gdp_uer = x_ir_gdp_uer.astype(np.float)model.fit(x_ir_gdp_uer, y_fx)y_fx_predict_3 = model.predict(x_ir_gdp_uer)print(model.score(x_ir_gdp_uer, y_fx))" }, { "code": null, "e": 9321, "s": 9125, "text": "Okay, R-squared has improved a bit better, from 87.2% to 88.9%. Not too bad, statistically and visually. You can continue to add some more variables to the model, but be careful with overfitting!" }, { "code": null, "e": 9472, "s": 9321, "text": "For me, instead of adding more independent variables, I decided to test out another regression model to find a better-fit line: Polynomial Regression." }, { "code": null, "e": 9581, "s": 9472, "text": "What is Polynomial Regression? It’s still one kind of Linear Regression but a much more “adaptable” version." }, { "code": null, "e": 9859, "s": 9581, "text": "Traditionally, Linear Regression aims to find the best linear line that fits all your data points, which might not always be the case. Therefore, Polynomial Regression acts as another form that draws the line from coordinates (x, y) with y modeled as the nth degree polynomial." }, { "code": null, "e": 9931, "s": 9859, "text": "Let’s import the function from Sciki-learn library and build our model:" }, { "code": null, "e": 10191, "s": 9931, "text": "from sklearn.preprocessing import PolynomialFeaturespoly = PolynomialFeatures(degree=4)x_poly = poly.fit_transform(x_ir_gdp_uer)model_poly = LinearRegression()model_poly.fit(x_poly, y_fx)y_pred = model_poly.predict(x_poly)print(model_poly.score(x_poly, y_fx))" }, { "code": null, "e": 10477, "s": 10191, "text": "The only difference in the function between Linear and Polynomial Regression is the degree parameter. Before getting to the result, let me briefly explain: .fit_transform() is to convert your independent variables from linearly to polynomially. The rest of the function stays the same." }, { "code": null, "e": 10592, "s": 10477, "text": "Here, I randomly selected the degree of 4 and R-squared is nearly perfect: 99.9%! You may want to see it visually?" }, { "code": null, "e": 10785, "s": 10592, "text": "The black line represents the fit that Polynomial Regression found with the degree of 4. How amazing? But the question is: “Which degree is the best, to neither overfit nor underfit the data?”" }, { "code": null, "e": 11078, "s": 10785, "text": "We know that we aim to find R-squared as high as possible, as it well explains the fact that the dependent variable (exchange rate) is affected by the independent variable(s). Apart from it, there is another metric that is able to evaluate the accuracy of our model: Mean Squared Error (MSE)." }, { "code": null, "e": 11212, "s": 11078, "text": "To find the best degree, I decided to test a range of degrees, from 1 to 10 on our model separately with a for loop and visualize it:" }, { "code": null, "e": 11669, "s": 11212, "text": "from sklearn.metrics import mean_squared_errorr_squared_list = []mse_list = []a = range(1,10,1)for i in a: poly = PolynomialFeatures(degree=i) x_poly = poly.fit_transform(x_ir_gdp_uer) model_poly = LinearRegression() model_poly.fit(x_poly, y_fx) y_pred = model_poly.predict(x_poly) r_squared = model_poly.score(x_poly, y_fx) mse = mean_squared_error(y_pred, y_fx) r_squared_list.append(r_squared) mse_list.append(mse)" }, { "code": null, "e": 12056, "s": 11669, "text": "As you can see in both charts, as the line increases from degrees of 1 to 4, the R-Squared and MSE improve significantly (the higher the better for R-Squared, the lower the better for MSE). However, it peaks at degree of 4 and no further improvement is seen since the degree of 5. This means that degree of 4 brings out the best accuracy score for our model! So let’s stick with 4 then!" }, { "code": null, "e": 12167, "s": 12056, "text": "Yay! We finally got the line that best fits the exchange rate over the years, thanks to Polynomial Regression!" }, { "code": null, "e": 12457, "s": 12167, "text": "These final two are my latest experiment in the “ecosystem” of linear regression models as I have heard about somewhere before. Oh yes, it regards L1 & L2 Regularisation! As such, I wanted to test out these two models in my project as well to see how they perform against the above models." }, { "code": null, "e": 12645, "s": 12457, "text": "However, before jumping into them, let’s quickly point out the origin of these models, Regularisation, and the roles they play against what we might commonly know about Linear Regression." }, { "code": null, "e": 12994, "s": 12645, "text": "It all started with Overfitting. In a nutshell, overfitting occurs when a machine learning model is too tailored to a certain dataset (especially with too many independent variables/features) and hence unable to generalise to other datasets. Hence, regularisation was introduced to prevent this phenomenon. Essentially, what regularisation does is:" }, { "code": null, "e": 13092, "s": 12994, "text": "Reduce the complexity of the model while maintaining the number of independent variables/features" }, { "code": null, "e": 13183, "s": 13092, "text": "Technically, reduce the magnitude of the coefficients as penalty term to the loss function" }, { "code": null, "e": 13308, "s": 13183, "text": "If you want to deep dive into how it works, mathematically, check out this article on Towards Data Science for more details." }, { "code": null, "e": 13438, "s": 13308, "text": "Ridge Regression and Lasso Regression were developed from this concept of Regularisation. The only difference between the two is:" }, { "code": null, "e": 13551, "s": 13438, "text": "Ridge Regression uses L2 Regularisation technique, which shrinks the coefficients to zero, but NOT absolute zero" }, { "code": null, "e": 13650, "s": 13551, "text": "Lasso Regression uses L1 Regularisation technique, which shrinks the coefficients to absolute zero" }, { "code": null, "e": 13862, "s": 13650, "text": "This is because Ridge keeps all variables/features while Lasso only keeps the important ones that matter, hence voted as the variable/feature selection technique when our dataset has TOO MANY variables/features." }, { "code": null, "e": 13889, "s": 13862, "text": "Okay, back to our dataset!" }, { "code": null, "e": 14039, "s": 13889, "text": "Even though our model does not have too many variables (in this case, 3), I still wanted to see how Ridge and Lasso Regression perform on my dataset." }, { "code": null, "e": 14351, "s": 14039, "text": "from sklearn.linear_model import Ridge, Lassoridge = Ridge(alpha=0.001)ridge.fit(x_ir_gdp_uer, y_fx)y_fx_ridge = ridge.predict(x_ir_gdp_uer)print(ridge.score(x_ir_gdp_uer, y_fx))lasso = Lasso(alpha=0.001)lasso.fit(x_ir_gdp_uer, y_fx)y_fx_lasso = lasso.predict(x_ir_gdp_uer)print(lasso.score(x_ir_gdp_uer, y_fx))" }, { "code": null, "e": 14545, "s": 14351, "text": "R-Squared of Ridge is 88% while of Lasso is 87%. Not too bad when we compare these numbers with our Multiple Linear Regression (88.9%). This proves that overfitting does not occur to our model!" }, { "code": null, "e": 14698, "s": 14545, "text": "WOW! That’s a wrap for the 2nd part of this project! Too much to absorb, isn’t it? But I do hope you have found this article informative and actionable." }, { "code": null, "e": 14837, "s": 14698, "text": "In short, we have found the line that best fits our dataset, greatly explaining the pattern of exchange rates over the years! What’s next?" }, { "code": null, "e": 15129, "s": 14837, "text": "Again, do look out for the final part of my project which will cover how I forecasted the exchange rates of 2020 using the regression line we have just discovered. In the meantime, give me a clap if you find this helpful and feel free to check out my Github here for the complete repository:" } ]
How to save pyttsx3 results to MP3 or WAV file? - GeeksforGeeks
25 Feb, 2021 In this article, we will see how to generate and save pyttsx3 results as mp3 and wav file. Pyttsx3 is a python module that provides a Text to Speech API. We can use this API to convert the text into voice. To use pyttsx3 we have to install espeak and ffmpeg first. sudo apt update sudo apt install espeak sudo apt install ffmpeg Additionally, we need to install the latest version of pyttsx3 python3 -m pip install pyttsx3 We can confirm the installation by importing the module. import pyttsx3 If the above statement runs without error, the environment setup is successful. First, we have to initialize the pyttsx3 engine. The init() method does that for us. Next, we need to create a string with the text we want to convert to audio. The say() method takes the string as a parameter. It will set the string it has to speak. Since the speech will take a while to play on the speaker of the machine, we need to wait for the process to complete. Hence, we need to call the runAndWait() method in order to let the interpreter stop the execution till then. Below is the code for the above steps: Python3 # Import the required moduleimport pyttsx3 # Create a stringstring = "Lorem Ipsum is simply dummy text " \ + "of the prting and typesetting industry." # Initialize the Pyttsx3 engineengine = pyttsx3.init() # Command it to speak the given stringengine.say(string) # Wait until above command is not finished.engine.runAndWait() Output: Note that we need to have ffmpeg in our system. So make sure that the environment setup was done correctly. Pyttsx3 comes with a save_to_file() method which takes the text to speak and the file path as an argument. This method saves the given file in the path. However, this module is in development state, so in some operating systems, the volume and rate options may not work properly. We have to keep the library updated to its latest version. Install the module using: sudo apt install git python3 -m pip install git+https://github.com/nateshmbhat/pyttsx3 This will directly install the latest version available. Below is the code to do the same: Python3 # Import the required moduleimport pyttsx3 # Create a stringstring = "Lorem Ipsum is simply dummy text " \ + "of the prting and typesetting industry." # Initialize the Pyttsx3 engineengine = pyttsx3.init() # We can use file extension as mp3 and wav, both will workengine.save_to_file(string, 'speech.mp3') # Wait until above command is not finished.engine.runAndWait() Output: Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n25 Feb, 2021" }, { "code": null, "e": 24132, "s": 23925, "text": "In this article, we will see how to generate and save pyttsx3 results as mp3 and wav file. Pyttsx3 is a python module that provides a Text to Speech API. We can use this API to convert the text into voice. " }, { "code": null, "e": 24191, "s": 24132, "text": "To use pyttsx3 we have to install espeak and ffmpeg first." }, { "code": null, "e": 24255, "s": 24191, "text": "sudo apt update\nsudo apt install espeak\nsudo apt install ffmpeg" }, { "code": null, "e": 24318, "s": 24255, "text": "Additionally, we need to install the latest version of pyttsx3" }, { "code": null, "e": 24349, "s": 24318, "text": "python3 -m pip install pyttsx3" }, { "code": null, "e": 24406, "s": 24349, "text": "We can confirm the installation by importing the module." }, { "code": null, "e": 24421, "s": 24406, "text": "import pyttsx3" }, { "code": null, "e": 24501, "s": 24421, "text": "If the above statement runs without error, the environment setup is successful." }, { "code": null, "e": 24586, "s": 24501, "text": "First, we have to initialize the pyttsx3 engine. The init() method does that for us." }, { "code": null, "e": 24662, "s": 24586, "text": "Next, we need to create a string with the text we want to convert to audio." }, { "code": null, "e": 24752, "s": 24662, "text": "The say() method takes the string as a parameter. It will set the string it has to speak." }, { "code": null, "e": 24980, "s": 24752, "text": "Since the speech will take a while to play on the speaker of the machine, we need to wait for the process to complete. Hence, we need to call the runAndWait() method in order to let the interpreter stop the execution till then." }, { "code": null, "e": 25019, "s": 24980, "text": "Below is the code for the above steps:" }, { "code": null, "e": 25027, "s": 25019, "text": "Python3" }, { "code": "# Import the required moduleimport pyttsx3 # Create a stringstring = \"Lorem Ipsum is simply dummy text \" \\ + \"of the prting and typesetting industry.\" # Initialize the Pyttsx3 engineengine = pyttsx3.init() # Command it to speak the given stringengine.say(string) # Wait until above command is not finished.engine.runAndWait()", "e": 25360, "s": 25027, "text": null }, { "code": null, "e": 25368, "s": 25360, "text": "Output:" }, { "code": null, "e": 25476, "s": 25368, "text": "Note that we need to have ffmpeg in our system. So make sure that the environment setup was done correctly." }, { "code": null, "e": 25583, "s": 25476, "text": "Pyttsx3 comes with a save_to_file() method which takes the text to speak and the file path as an argument." }, { "code": null, "e": 25756, "s": 25583, "text": "This method saves the given file in the path. However, this module is in development state, so in some operating systems, the volume and rate options may not work properly." }, { "code": null, "e": 25841, "s": 25756, "text": "We have to keep the library updated to its latest version. Install the module using:" }, { "code": null, "e": 25928, "s": 25841, "text": "sudo apt install git\npython3 -m pip install git+https://github.com/nateshmbhat/pyttsx3" }, { "code": null, "e": 25985, "s": 25928, "text": "This will directly install the latest version available." }, { "code": null, "e": 26019, "s": 25985, "text": "Below is the code to do the same:" }, { "code": null, "e": 26027, "s": 26019, "text": "Python3" }, { "code": "# Import the required moduleimport pyttsx3 # Create a stringstring = \"Lorem Ipsum is simply dummy text \" \\ + \"of the prting and typesetting industry.\" # Initialize the Pyttsx3 engineengine = pyttsx3.init() # We can use file extension as mp3 and wav, both will workengine.save_to_file(string, 'speech.mp3') # Wait until above command is not finished.engine.runAndWait()", "e": 26403, "s": 26027, "text": null }, { "code": null, "e": 26411, "s": 26403, "text": "Output:" }, { "code": null, "e": 26418, "s": 26411, "text": "Picked" }, { "code": null, "e": 26433, "s": 26418, "text": "python-utility" }, { "code": null, "e": 26440, "s": 26433, "text": "Python" }, { "code": null, "e": 26538, "s": 26440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26547, "s": 26538, "text": "Comments" }, { "code": null, "e": 26560, "s": 26547, "text": "Old Comments" }, { "code": null, "e": 26592, "s": 26560, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26648, "s": 26592, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26690, "s": 26648, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26732, "s": 26690, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26768, "s": 26732, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26790, "s": 26768, "text": "Defaultdict in Python" }, { "code": null, "e": 26829, "s": 26790, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26856, "s": 26829, "text": "Python Classes and Objects" }, { "code": null, "e": 26887, "s": 26856, "text": "Python | os.path.join() method" } ]
What are Subprograms?
A subprogram is defined as a set of statements that can be reused at multiple places in a program when convenient. This reuse results in multiple types of savings, from memory space to coding time. Such reuse is also an abstraction, for the analysis of subprograms computations are restored in a program by a statement that calls the subprogram. The features of subprograms are as follows − A subprogram has a single entry point. A subprogram has a single entry point. The caller is suspended during the implementation of the called subprogram. The caller is suspended during the implementation of the called subprogram. Control repeatedly returns to the caller when the called subprogram’s execution eliminates. Control repeatedly returns to the caller when the called subprogram’s execution eliminates. There are two types of subprograms which are as follows − Procedures − A procedure is defined as a subprogram that defines parameterized computations. These computations are executed by an individual call statement. Procedures represent new statements. For example, because Pascal does not have a sort statement, a user can develop a procedure to sort arrays of records and use a call to that procedure in place of the unavailable sort statement. Procedures − A procedure is defined as a subprogram that defines parameterized computations. These computations are executed by an individual call statement. Procedures represent new statements. For example, because Pascal does not have a sort statement, a user can develop a procedure to sort arrays of records and use a call to that procedure in place of the unavailable sort statement. The general syntax of a procedure in Pascal is given as PROCEDURE Name of Procedure (formal parameter list); {local declaration section} BEGIN {instruction sequence} END; {end of procedure} The declaration implies that a procedure has two parts as the specification and the body. The procedure specification begins with the keyword PROCEDURE and end with the procedure name or a parameter list. Parameter declarations are optional. Procedures that take no parameters are written without parenthesis. The procedure body begins with the keyword BEGIN and end with the keyword END followed by an optional procedure name. The procedure body has three elements such as a declarative part, an executable part, and an optional exceptional handling part. Functions − A function is a subprogram that evaluates a value. Functions and procedures are structured identical, except thatFunctions are semantically modeled on mathematical functions.Functions have a RETURN clause.Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function. Functions − A function is a subprogram that evaluates a value. Functions and procedures are structured identical, except that Functions are semantically modeled on mathematical functions. Functions are semantically modeled on mathematical functions. Functions have a RETURN clause. Functions have a RETURN clause. Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function. Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function. The general syntax of a function in C is given as RETURN TYPE Name of Function (formal parameter list){ local declaration section ................... ................... instruction sequence } A function has two elements as the specification and the body. The function specification begins with the Return type followed by name of the function and parameter list. The function body begins with {and ends with}. The function body has three parts such as a declaration part, an executable part, and an optional exceptional-handling part.
[ { "code": null, "e": 1408, "s": 1062, "text": "A subprogram is defined as a set of statements that can be reused at multiple places in a program when convenient. This reuse results in multiple types of savings, from memory space to coding time. Such reuse is also an abstraction, for the analysis of subprograms computations are restored in a program by a statement that calls the subprogram." }, { "code": null, "e": 1453, "s": 1408, "text": "The features of subprograms are as follows −" }, { "code": null, "e": 1492, "s": 1453, "text": "A subprogram has a single entry point." }, { "code": null, "e": 1531, "s": 1492, "text": "A subprogram has a single entry point." }, { "code": null, "e": 1607, "s": 1531, "text": "The caller is suspended during the implementation of the called subprogram." }, { "code": null, "e": 1683, "s": 1607, "text": "The caller is suspended during the implementation of the called subprogram." }, { "code": null, "e": 1775, "s": 1683, "text": "Control repeatedly returns to the caller when the called subprogram’s execution eliminates." }, { "code": null, "e": 1867, "s": 1775, "text": "Control repeatedly returns to the caller when the called subprogram’s execution eliminates." }, { "code": null, "e": 1925, "s": 1867, "text": "There are two types of subprograms which are as follows −" }, { "code": null, "e": 2314, "s": 1925, "text": "Procedures − A procedure is defined as a subprogram that defines parameterized computations. These computations are executed by an individual call statement. Procedures represent new statements. For example, because Pascal does not have a sort statement, a user can develop a procedure to sort arrays of records and use a call to that procedure in place of the unavailable sort statement." }, { "code": null, "e": 2703, "s": 2314, "text": "Procedures − A procedure is defined as a subprogram that defines parameterized computations. These computations are executed by an individual call statement. Procedures represent new statements. For example, because Pascal does not have a sort statement, a user can develop a procedure to sort arrays of records and use a call to that procedure in place of the unavailable sort statement." }, { "code": null, "e": 2759, "s": 2703, "text": "The general syntax of a procedure in Pascal is given as" }, { "code": null, "e": 2893, "s": 2759, "text": "PROCEDURE Name of Procedure (formal parameter list); {local declaration section}\nBEGIN\n{instruction sequence}\nEND;\n{end of procedure}" }, { "code": null, "e": 3203, "s": 2893, "text": "The declaration implies that a procedure has two parts as the specification and the body. The procedure specification begins with the keyword PROCEDURE and end with the procedure name or a parameter list. Parameter declarations are optional. Procedures that take no parameters are written without parenthesis." }, { "code": null, "e": 3450, "s": 3203, "text": "The procedure body begins with the keyword BEGIN and end with the keyword END followed by an optional procedure name. The procedure body has three elements such as a declarative part, an executable part, and an optional exceptional handling part." }, { "code": null, "e": 3789, "s": 3450, "text": "Functions − A function is a subprogram that evaluates a value. Functions and procedures are structured identical, except thatFunctions are semantically modeled on mathematical functions.Functions have a RETURN clause.Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function." }, { "code": null, "e": 3915, "s": 3789, "text": "Functions − A function is a subprogram that evaluates a value. Functions and procedures are structured identical, except that" }, { "code": null, "e": 3977, "s": 3915, "text": "Functions are semantically modeled on mathematical functions." }, { "code": null, "e": 4039, "s": 3977, "text": "Functions are semantically modeled on mathematical functions." }, { "code": null, "e": 4071, "s": 4039, "text": "Functions have a RETURN clause." }, { "code": null, "e": 4103, "s": 4071, "text": "Functions have a RETURN clause." }, { "code": null, "e": 4225, "s": 4103, "text": "Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function." }, { "code": null, "e": 4347, "s": 4225, "text": "Functions produce no side effects i.e., it changes neither its parameters nor any variables defined outside the function." }, { "code": null, "e": 4397, "s": 4347, "text": "The general syntax of a function in C is given as" }, { "code": null, "e": 4552, "s": 4397, "text": "RETURN TYPE Name of Function (formal parameter list){\n local declaration section\n ...................\n ...................\n instruction sequence\n}" }, { "code": null, "e": 4895, "s": 4552, "text": "A function has two elements as the specification and the body. The function specification begins with the Return type followed by name of the function and parameter list. The function body begins with {and ends with}. The function body has three parts such as a declaration part, an executable part, and an optional exceptional-handling part." } ]