title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
LDA: Linear Discriminant Analysis — How to Improve Your Models with Supervised Dimensionality Reduction | by Saul Dobilas | Towards Data Science
Linear Discriminant Analysis (LDA) is a commonly used dimensionality reduction technique. However, despite the similarities to Principal Component Analysis (PCA), it differs in one crucial aspect. Instead of finding new axes (dimensions) that maximize the variation in the data, it focuses on maximizing the separability among the known categories (classes) in the target variable. In this article, I give an intuitive explanation of how LDA works while highlighting the differences to PCA. At the same time, I provide a Python example of performing Linear Discriminant Analysis on real-life data. The category of Machine Learning techniques LDA belongs to Intuitive explanation of how LDA works Python example of performing LDA on real-life data Conclusions Unlike Principal Component Analysis (PCA), LDA requires you to provide features and class labels for your target. Hence, despite being a dimensionality reduction technique similar to PCA, it sits within the supervised branch of Machine Learning. The below graph is interactive, so please click on different categories to enlarge and reveal more👇. If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story. The easiest way to grasp the concepts of LDA is by working through an example. Hence, instead of focusing on the maths behind the algorithm, I have created a visual explanation for us to go through. Assume we have collected a bunch of data on apartment prices in the city. We categorized them into “expensive” and “cheap” based on some threshold, say $1M. I.e., <$1M = cheap, and ≥$1M = expensive. We display the data on a scatterplot where the x and y axes represent the latitude and longitude, giving us the apartment’s location. Meanwhile, color represents the category/class (cheap vs. expensive). Note that we have already standardized* the data in this fictitious example, so it is centered around the origin. *Standartization is a data transformation technique that rescales the data so each attribute has a mean of 0 and a standard deviation of 1. This transformation can be described with the following formula: Let’s take a look at the scatterplot of our example data: Now let’s compare the PCA and LDA process to understand how these algorithms work and how they differ. Since PCA is an unsupervised Machine learning technique, we do not need to provide a target variable with category labels. This means that PCA does not care about whether the apartment is part of a “cheap” or “expensive” category. Nevertheless, I have kept the color labels in the below graph to highlight the main difference from LDA. The goal of PCA is to capture the maximum amount of variance, which is achieved by the algorithm finding a line that minimizes the distances from data points to that line. Interestingly, this is equivalent to maximizing the spread of data point projections on that same line, which is why we can capture the maximum amount of variance. As you can see from the graph above, we have done a good job finding a new axis that preserves most of the variance, enabling us to go down from two dimensions to one. This is what it looks like after we map the data to our new single dimension (PC1): You can clearly see that, in this scenario, we were able to preserve most of the variance but still lost some information that would have been useful when trying to separate the two categories (classes). If you would like to get a more in-depth understanding of PCA, you can refer to my previous article: towardsdatascience.com Now let’s go back to our original example data and apply LDA instead of PCA. Quick reminder, the goal of LDA is to maximize the separability of the known categories in our target variable (“cheap”, “expensive”) while at the same time reducing dimensions. Here is what the new axis looks like when we perform LDA: As you can see, the choice of the new axis, in this scenario, is very different from that of PCA. In this case, we end up losing a significant amount of variance by mapping data onto LD1. However, we achieve better separation of the two categories: While the separation is imperfect, it is visibly better, with only a few overlapping observations from the two categories. Two key criteria are used when finding the “best” line for our new axis, which are considered simultaneously. Maximizing the distance (d2).2 categories — when you have two classes in your target variable, the distance refers to the difference between the mean (μ) of class 1 and the mean of class 2. More than 2 categories — when you have three or more classes in your target variable, the algorithm first finds a central point to all of the data and then measures the distance from each category mean (μ) to that central point. Maximizing the distance (d2).2 categories — when you have two classes in your target variable, the distance refers to the difference between the mean (μ) of class 1 and the mean of class 2. More than 2 categories — when you have three or more classes in your target variable, the algorithm first finds a central point to all of the data and then measures the distance from each category mean (μ) to that central point. 2. Minimize the variation, also known as “scatter” in LDA (s2). Let’s illustrate the two criteria on a graph: In practice, the calculations are typically performed with the help of either Singular Value Decomposition (SVD) or Eigenvalue decomposition. Both of these options are available in sklearn’s LDA implementation, which we will use in the next section. Finally, it’s time for the fun stuff where we get to apply LDA using Python. Let’s start by getting the right libraries and data for our analysis. We will use the following data and libraries: House price data from Kaggle Scikit-learn library for1) encoding categorical class labels (OrdinalEncoder);2) feature standardization (StandardScaler);3) performing Principal Component Analysis (PCA);4) performing Linear Discriminant Analysis (LDA);5) creating a decision tree-based prediction model (DecisionTreeClassifier);6) model evaluation (classification_report) Plotly for data visualizations Pandas for data manipulation Let’s import all the libraries: Next, we download an ingest house price data from Kaggle. Here’s a snippet of what the data looks like: For this example, we want to create a multiclass target variable. Hence, we take ‘Y house price of unit area’ and divide it into 3 equal categories. We call them: ‘1.Affordable’ (bottom 33%), ‘2.Mid-range’ (middle 33%), and ‘3.Expensive’ (top 33%). Since we have created categorical labels while the algorithm requires numerical ones, let’s use the Ordinal encoder to convert them to numeric. [Note, we could have directly assigned numeric labels, but the categorical ones will make it easier for us to read the upcoming visualization]. To keep the ability to visualize the data, we will limit ourselves to the first 3 feature variables: ‘X1 transaction date’, ‘X2 house age’, and ‘X3 distance to the nearest MRT station’. Let’s see what the data looks like by plotting these three features on the 3D scatterplot: We can see that the data is scattered significantly. Also, we note that cheaper real estate is located further away from MRT stations, while the expensive ones tend to be much closer to MRT and also newer. One final step in data preparation is the standardization of the features. Note that we should also split our data into train and test samples at this stage, but we’ll work with the entire dataset to keep things simple for this example. For interest, we’ll also perform PCA so we can compare the results of PCA to the results of LDA. Interestingly, explained variance ratios for PC1 and PC2 only cover ~69% of the total variance, meaning that we have lost about 31% of the total variance when going down from 3 dimensions to 2. This is largely due to little correlation between the 3 features. Here is a scatter plot of the resulting 2D plot after applying PCA: While we did lose 31% of the variance, we still managed to keep a lot of the spread across the two new dimensions. However, since PCA only considers features and not the target, the three categories (classes) ended up all mixed together. Next, let’s see how LDA compares to PCA. We will use Eigen decomposition as our solver (sklearn implementation enables you to choose between SVD, LSQR, and Eigen) and set the components parameter (number of dimensions) to 2, leaving all the rest as default. Note that this time we also need to supply our target (y) to the algorithm. As before, we also visualize the results on a 2D scatterplot. There is a notable difference in LDA results when compared to PCA. Since the goal of PCA is to separate target categories instead of maximizing variance, it managed to find new axes that reduced the spread of blue (‘2.Mid-range’) and red (‘3.Expensive’) points, keeping them largely within their own space. Meanwhile, despite the large variance remaining in the green (‘1.Affordable) class, the separation from red and blue is pretty good. To validate what we see in these scatter plots, let’s build a couple of decision tree models and see how well we can predict ‘Price Band’ based on features created using PCA and LDA. Let’s set up a reusable function that we can quickly call to train a model and display the results. Now let’s use it to build a model with PCA-transformed features. Here are the model results: As expected, the results are not great, with accuracy only at 64%. Mixing of the categories (classes) after applying PCA has definitely made it harder to predict the price label. Let’s repeat the same with LDA-transformed features. This time the model seems to be much better, with nearly 79% accuracy. These results support our earlier intuition that LDA has better preserved the information relevant to predicting an apartment’s price when compared to PCA. LDA is a great tool when we want to reduce the dimensionality of our data while keeping as much information relevant to our prediction target. However, the direct comparison of PCA and LDA might not be completely fair because they are two different techniques meant for different purposes. For example, PCA is an unsupervised learning technique, while LDA falls under the supervised branch of ML. Hence, please don’t take the results above as proof of LDA superiority over PCA. Instead, please first assess the applicability of these algorithms to your unique case. I sincerely hope my article has helped you better understand Linear Discriminant Analysis, enabling you to incorporate it into your own Data Science projects. Cheers! 👏Saul Dobilas If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is: solclover.com If you liked this story, here are couple more articles that you might enjoy:
[ { "code": null, "e": 368, "s": 171, "text": "Linear Discriminant Analysis (LDA) is a commonly used dimensionality reduction technique. However, despite the similarities to Principal Component Analysis (PCA), it differs in one crucial aspect." }, { "code": null, "e": 553, "s": 368, "text": "Instead of finding new axes (dimensions) that maximize the variation in the data, it focuses on maximizing the separability among the known categories (classes) in the target variable." }, { "code": null, "e": 769, "s": 553, "text": "In this article, I give an intuitive explanation of how LDA works while highlighting the differences to PCA. At the same time, I provide a Python example of performing Linear Discriminant Analysis on real-life data." }, { "code": null, "e": 828, "s": 769, "text": "The category of Machine Learning techniques LDA belongs to" }, { "code": null, "e": 867, "s": 828, "text": "Intuitive explanation of how LDA works" }, { "code": null, "e": 918, "s": 867, "text": "Python example of performing LDA on real-life data" }, { "code": null, "e": 930, "s": 918, "text": "Conclusions" }, { "code": null, "e": 1176, "s": 930, "text": "Unlike Principal Component Analysis (PCA), LDA requires you to provide features and class labels for your target. Hence, despite being a dimensionality reduction technique similar to PCA, it sits within the supervised branch of Machine Learning." }, { "code": null, "e": 1277, "s": 1176, "text": "The below graph is interactive, so please click on different categories to enlarge and reveal more👇." }, { "code": null, "e": 1390, "s": 1277, "text": "If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story." }, { "code": null, "e": 1589, "s": 1390, "text": "The easiest way to grasp the concepts of LDA is by working through an example. Hence, instead of focusing on the maths behind the algorithm, I have created a visual explanation for us to go through." }, { "code": null, "e": 1746, "s": 1589, "text": "Assume we have collected a bunch of data on apartment prices in the city. We categorized them into “expensive” and “cheap” based on some threshold, say $1M." }, { "code": null, "e": 1789, "s": 1746, "text": "I.e., <$1M = cheap, and ≥$1M = expensive. " }, { "code": null, "e": 2107, "s": 1789, "text": "We display the data on a scatterplot where the x and y axes represent the latitude and longitude, giving us the apartment’s location. Meanwhile, color represents the category/class (cheap vs. expensive). Note that we have already standardized* the data in this fictitious example, so it is centered around the origin." }, { "code": null, "e": 2312, "s": 2107, "text": "*Standartization is a data transformation technique that rescales the data so each attribute has a mean of 0 and a standard deviation of 1. This transformation can be described with the following formula:" }, { "code": null, "e": 2370, "s": 2312, "text": "Let’s take a look at the scatterplot of our example data:" }, { "code": null, "e": 2473, "s": 2370, "text": "Now let’s compare the PCA and LDA process to understand how these algorithms work and how they differ." }, { "code": null, "e": 2704, "s": 2473, "text": "Since PCA is an unsupervised Machine learning technique, we do not need to provide a target variable with category labels. This means that PCA does not care about whether the apartment is part of a “cheap” or “expensive” category." }, { "code": null, "e": 2809, "s": 2704, "text": "Nevertheless, I have kept the color labels in the below graph to highlight the main difference from LDA." }, { "code": null, "e": 3145, "s": 2809, "text": "The goal of PCA is to capture the maximum amount of variance, which is achieved by the algorithm finding a line that minimizes the distances from data points to that line. Interestingly, this is equivalent to maximizing the spread of data point projections on that same line, which is why we can capture the maximum amount of variance." }, { "code": null, "e": 3397, "s": 3145, "text": "As you can see from the graph above, we have done a good job finding a new axis that preserves most of the variance, enabling us to go down from two dimensions to one. This is what it looks like after we map the data to our new single dimension (PC1):" }, { "code": null, "e": 3601, "s": 3397, "text": "You can clearly see that, in this scenario, we were able to preserve most of the variance but still lost some information that would have been useful when trying to separate the two categories (classes)." }, { "code": null, "e": 3702, "s": 3601, "text": "If you would like to get a more in-depth understanding of PCA, you can refer to my previous article:" }, { "code": null, "e": 3725, "s": 3702, "text": "towardsdatascience.com" }, { "code": null, "e": 3980, "s": 3725, "text": "Now let’s go back to our original example data and apply LDA instead of PCA. Quick reminder, the goal of LDA is to maximize the separability of the known categories in our target variable (“cheap”, “expensive”) while at the same time reducing dimensions." }, { "code": null, "e": 4038, "s": 3980, "text": "Here is what the new axis looks like when we perform LDA:" }, { "code": null, "e": 4287, "s": 4038, "text": "As you can see, the choice of the new axis, in this scenario, is very different from that of PCA. In this case, we end up losing a significant amount of variance by mapping data onto LD1. However, we achieve better separation of the two categories:" }, { "code": null, "e": 4410, "s": 4287, "text": "While the separation is imperfect, it is visibly better, with only a few overlapping observations from the two categories." }, { "code": null, "e": 4520, "s": 4410, "text": "Two key criteria are used when finding the “best” line for our new axis, which are considered simultaneously." }, { "code": null, "e": 4939, "s": 4520, "text": "Maximizing the distance (d2).2 categories — when you have two classes in your target variable, the distance refers to the difference between the mean (μ) of class 1 and the mean of class 2. More than 2 categories — when you have three or more classes in your target variable, the algorithm first finds a central point to all of the data and then measures the distance from each category mean (μ) to that central point." }, { "code": null, "e": 5358, "s": 4939, "text": "Maximizing the distance (d2).2 categories — when you have two classes in your target variable, the distance refers to the difference between the mean (μ) of class 1 and the mean of class 2. More than 2 categories — when you have three or more classes in your target variable, the algorithm first finds a central point to all of the data and then measures the distance from each category mean (μ) to that central point." }, { "code": null, "e": 5422, "s": 5358, "text": "2. Minimize the variation, also known as “scatter” in LDA (s2)." }, { "code": null, "e": 5468, "s": 5422, "text": "Let’s illustrate the two criteria on a graph:" }, { "code": null, "e": 5718, "s": 5468, "text": "In practice, the calculations are typically performed with the help of either Singular Value Decomposition (SVD) or Eigenvalue decomposition. Both of these options are available in sklearn’s LDA implementation, which we will use in the next section." }, { "code": null, "e": 5865, "s": 5718, "text": "Finally, it’s time for the fun stuff where we get to apply LDA using Python. Let’s start by getting the right libraries and data for our analysis." }, { "code": null, "e": 5911, "s": 5865, "text": "We will use the following data and libraries:" }, { "code": null, "e": 5940, "s": 5911, "text": "House price data from Kaggle" }, { "code": null, "e": 6280, "s": 5940, "text": "Scikit-learn library for1) encoding categorical class labels (OrdinalEncoder);2) feature standardization (StandardScaler);3) performing Principal Component Analysis (PCA);4) performing Linear Discriminant Analysis (LDA);5) creating a decision tree-based prediction model (DecisionTreeClassifier);6) model evaluation (classification_report)" }, { "code": null, "e": 6311, "s": 6280, "text": "Plotly for data visualizations" }, { "code": null, "e": 6340, "s": 6311, "text": "Pandas for data manipulation" }, { "code": null, "e": 6372, "s": 6340, "text": "Let’s import all the libraries:" }, { "code": null, "e": 6430, "s": 6372, "text": "Next, we download an ingest house price data from Kaggle." }, { "code": null, "e": 6476, "s": 6430, "text": "Here’s a snippet of what the data looks like:" }, { "code": null, "e": 6725, "s": 6476, "text": "For this example, we want to create a multiclass target variable. Hence, we take ‘Y house price of unit area’ and divide it into 3 equal categories. We call them: ‘1.Affordable’ (bottom 33%), ‘2.Mid-range’ (middle 33%), and ‘3.Expensive’ (top 33%)." }, { "code": null, "e": 7013, "s": 6725, "text": "Since we have created categorical labels while the algorithm requires numerical ones, let’s use the Ordinal encoder to convert them to numeric. [Note, we could have directly assigned numeric labels, but the categorical ones will make it easier for us to read the upcoming visualization]." }, { "code": null, "e": 7199, "s": 7013, "text": "To keep the ability to visualize the data, we will limit ourselves to the first 3 feature variables: ‘X1 transaction date’, ‘X2 house age’, and ‘X3 distance to the nearest MRT station’." }, { "code": null, "e": 7290, "s": 7199, "text": "Let’s see what the data looks like by plotting these three features on the 3D scatterplot:" }, { "code": null, "e": 7496, "s": 7290, "text": "We can see that the data is scattered significantly. Also, we note that cheaper real estate is located further away from MRT stations, while the expensive ones tend to be much closer to MRT and also newer." }, { "code": null, "e": 7571, "s": 7496, "text": "One final step in data preparation is the standardization of the features." }, { "code": null, "e": 7733, "s": 7571, "text": "Note that we should also split our data into train and test samples at this stage, but we’ll work with the entire dataset to keep things simple for this example." }, { "code": null, "e": 7830, "s": 7733, "text": "For interest, we’ll also perform PCA so we can compare the results of PCA to the results of LDA." }, { "code": null, "e": 8090, "s": 7830, "text": "Interestingly, explained variance ratios for PC1 and PC2 only cover ~69% of the total variance, meaning that we have lost about 31% of the total variance when going down from 3 dimensions to 2. This is largely due to little correlation between the 3 features." }, { "code": null, "e": 8158, "s": 8090, "text": "Here is a scatter plot of the resulting 2D plot after applying PCA:" }, { "code": null, "e": 8396, "s": 8158, "text": "While we did lose 31% of the variance, we still managed to keep a lot of the spread across the two new dimensions. However, since PCA only considers features and not the target, the three categories (classes) ended up all mixed together." }, { "code": null, "e": 8437, "s": 8396, "text": "Next, let’s see how LDA compares to PCA." }, { "code": null, "e": 8730, "s": 8437, "text": "We will use Eigen decomposition as our solver (sklearn implementation enables you to choose between SVD, LSQR, and Eigen) and set the components parameter (number of dimensions) to 2, leaving all the rest as default. Note that this time we also need to supply our target (y) to the algorithm." }, { "code": null, "e": 8792, "s": 8730, "text": "As before, we also visualize the results on a 2D scatterplot." }, { "code": null, "e": 9232, "s": 8792, "text": "There is a notable difference in LDA results when compared to PCA. Since the goal of PCA is to separate target categories instead of maximizing variance, it managed to find new axes that reduced the spread of blue (‘2.Mid-range’) and red (‘3.Expensive’) points, keeping them largely within their own space. Meanwhile, despite the large variance remaining in the green (‘1.Affordable) class, the separation from red and blue is pretty good." }, { "code": null, "e": 9415, "s": 9232, "text": "To validate what we see in these scatter plots, let’s build a couple of decision tree models and see how well we can predict ‘Price Band’ based on features created using PCA and LDA." }, { "code": null, "e": 9515, "s": 9415, "text": "Let’s set up a reusable function that we can quickly call to train a model and display the results." }, { "code": null, "e": 9580, "s": 9515, "text": "Now let’s use it to build a model with PCA-transformed features." }, { "code": null, "e": 9608, "s": 9580, "text": "Here are the model results:" }, { "code": null, "e": 9787, "s": 9608, "text": "As expected, the results are not great, with accuracy only at 64%. Mixing of the categories (classes) after applying PCA has definitely made it harder to predict the price label." }, { "code": null, "e": 9840, "s": 9787, "text": "Let’s repeat the same with LDA-transformed features." }, { "code": null, "e": 10067, "s": 9840, "text": "This time the model seems to be much better, with nearly 79% accuracy. These results support our earlier intuition that LDA has better preserved the information relevant to predicting an apartment’s price when compared to PCA." }, { "code": null, "e": 10210, "s": 10067, "text": "LDA is a great tool when we want to reduce the dimensionality of our data while keeping as much information relevant to our prediction target." }, { "code": null, "e": 10464, "s": 10210, "text": "However, the direct comparison of PCA and LDA might not be completely fair because they are two different techniques meant for different purposes. For example, PCA is an unsupervised learning technique, while LDA falls under the supervised branch of ML." }, { "code": null, "e": 10633, "s": 10464, "text": "Hence, please don’t take the results above as proof of LDA superiority over PCA. Instead, please first assess the applicability of these algorithms to your unique case." }, { "code": null, "e": 10792, "s": 10633, "text": "I sincerely hope my article has helped you better understand Linear Discriminant Analysis, enabling you to incorporate it into your own Data Science projects." }, { "code": null, "e": 10814, "s": 10792, "text": "Cheers! 👏Saul Dobilas" }, { "code": null, "e": 10947, "s": 10814, "text": "If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is:" }, { "code": null, "e": 10961, "s": 10947, "text": "solclover.com" } ]
Python program to define class for complex number objects
Suppose we want to do complex number tasks by defining a complex number class with following operations − add() to add two complex numbers sub() to subtract two complex numbers mul() to multiply two complex numbers div() to divide two complex numbers mod() to get modulus of complex numbers The complex numbers will be shown in the form (a + bi). We have two complex numbers, will perform these operations on them. Inside the class we overload the add(), sub(), mul() and div() methods so that we can use the operators to perform the operations. We also overload __str__() method to print the complex number in proper form. So, if the input is like c1 = 2+3i c2 = 5-2i, then the output will be (7.00 + 1.00i), (-3.00 + 5.00i), (16.00 + 11.00i), (0.14 + 0.66i), 3.61, 5.39. To solve this, we will follow these steps − Define complex class with real part re and imaginary part im Define a function add(). This will take o return a new Complex object with (re + o.re, im + o.im) Define a function sub() . This will take o return a new Complex object with (re - o.re, im - o.im) Define a function mul() . This will take o return a new Complex object with (re * o.re -im * o.im, re * o.im + im * o.re) Define a function div(). This will take o m := o.re * o.re + o.im * o.im return a new Complex number object with ((re * o.re + im * o.im)/m, (im * o.re - re * o.im)/m) Define a function mod() . This will take return square root of (re * re + im * im) Overload __str__(). if im is same as 0, thenreturn re up to two decimal places return re up to two decimal places if re is same as 0, thenreturn im up to two decimal places return im up to two decimal places if im < 0, thenreturn re - im i, both (re and im are up to two decimal places) return re - im i, both (re and im are up to two decimal places) otherwise,return re + im i, both (re and im are up to two decimal places) return re + im i, both (re and im are up to two decimal places) Let us see the following implementation to get better understanding from math import sqrt class Complex: def __init__(self, real, imag): self.re = real self.im = imag def __add__(self, o): return Complex(self.re+o.re, self.im+o.im) def __sub__(self, o): return Complex(self.re-o.re, self.im-o.im) def __mul__(self, o): return Complex(self.re*o.re-self.im*o.im, self.re * o.im + self.im * o.re) def __truediv__(self, o): m = o.re * o.re + o.im * o.im return Complex((self.re * o.re + self.im * o.im)/m, (self.im * o.re - self.re * o.im)/m) def __str__(self): if self.im == 0: return '%.2f' % self.re if self.re == 0: return '%.2fi' % self.im if self.im < 0: return '%.2f - %.2fi' % (self.re, -self.im) else: return '%.2f + %.2fi' % (self.re, self.im) def mod(self): return sqrt(self.re*self.re+self.im*self.im) def solve(comp1, comp2): print(comp1 + comp2) print(comp1 - comp2) print(comp1 * comp2) print(comp1 / comp2) print('%.2f' % comp1.mod()) print('%.2f' % comp2.mod()) comp1 = Complex(2, 3) comp2 = Complex(5, -2) solve(comp1, comp2) 2, 3 5, -2 7.00 + 1.00i -3.00 + 5.00i 16.00 + 11.00i 0.14 + 0.66i 3.61 5.39
[ { "code": null, "e": 1168, "s": 1062, "text": "Suppose we want to do complex number tasks by defining a complex number class with following operations −" }, { "code": null, "e": 1201, "s": 1168, "text": "add() to add two complex numbers" }, { "code": null, "e": 1239, "s": 1201, "text": "sub() to subtract two complex numbers" }, { "code": null, "e": 1277, "s": 1239, "text": "mul() to multiply two complex numbers" }, { "code": null, "e": 1313, "s": 1277, "text": "div() to divide two complex numbers" }, { "code": null, "e": 1353, "s": 1313, "text": "mod() to get modulus of complex numbers" }, { "code": null, "e": 1686, "s": 1353, "text": "The complex numbers will be shown in the form (a + bi). We have two complex numbers, will perform these operations on them. Inside the class we overload the add(), sub(), mul() and div() methods so that we can use the operators to perform the operations. We also overload __str__() method to print the complex number in proper form." }, { "code": null, "e": 1835, "s": 1686, "text": "So, if the input is like c1 = 2+3i c2 = 5-2i, then the output will be (7.00 + 1.00i), (-3.00 + 5.00i), (16.00 + 11.00i), (0.14 + 0.66i), 3.61, 5.39." }, { "code": null, "e": 1879, "s": 1835, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1940, "s": 1879, "text": "Define complex class with real part re and imaginary part im" }, { "code": null, "e": 1982, "s": 1940, "text": "Define a function add(). This will take o" }, { "code": null, "e": 2038, "s": 1982, "text": "return a new Complex object with (re + o.re, im + o.im)" }, { "code": null, "e": 2081, "s": 2038, "text": "Define a function sub() . This will take o" }, { "code": null, "e": 2137, "s": 2081, "text": "return a new Complex object with (re - o.re, im - o.im)" }, { "code": null, "e": 2180, "s": 2137, "text": "Define a function mul() . This will take o" }, { "code": null, "e": 2259, "s": 2180, "text": "return a new Complex object with (re * o.re -im * o.im, re * o.im + im * o.re)" }, { "code": null, "e": 2301, "s": 2259, "text": "Define a function div(). This will take o" }, { "code": null, "e": 2332, "s": 2301, "text": "m := o.re * o.re + o.im * o.im" }, { "code": null, "e": 2427, "s": 2332, "text": "return a new Complex number object with ((re * o.re + im * o.im)/m, (im * o.re - re * o.im)/m)" }, { "code": null, "e": 2468, "s": 2427, "text": "Define a function mod() . This will take" }, { "code": null, "e": 2510, "s": 2468, "text": "return square root of (re * re + im * im)" }, { "code": null, "e": 2530, "s": 2510, "text": "Overload __str__()." }, { "code": null, "e": 2589, "s": 2530, "text": "if im is same as 0, thenreturn re up to two decimal places" }, { "code": null, "e": 2624, "s": 2589, "text": "return re up to two decimal places" }, { "code": null, "e": 2683, "s": 2624, "text": "if re is same as 0, thenreturn im up to two decimal places" }, { "code": null, "e": 2718, "s": 2683, "text": "return im up to two decimal places" }, { "code": null, "e": 2797, "s": 2718, "text": "if im < 0, thenreturn re - im i, both (re and im are up to two decimal places)" }, { "code": null, "e": 2861, "s": 2797, "text": "return re - im i, both (re and im are up to two decimal places)" }, { "code": null, "e": 2935, "s": 2861, "text": "otherwise,return re + im i, both (re and im are up to two decimal places)" }, { "code": null, "e": 2999, "s": 2935, "text": "return re + im i, both (re and im are up to two decimal places)" }, { "code": null, "e": 3067, "s": 2999, "text": "Let us see the following implementation to get better understanding" }, { "code": null, "e": 4199, "s": 3067, "text": "from math import sqrt\nclass Complex:\n def __init__(self, real, imag):\n self.re = real\n self.im = imag\n\n def __add__(self, o):\n return Complex(self.re+o.re, self.im+o.im)\n\n def __sub__(self, o):\n return Complex(self.re-o.re, self.im-o.im)\n\n def __mul__(self, o):\n return Complex(self.re*o.re-self.im*o.im, self.re * o.im + self.im * o.re)\n\n def __truediv__(self, o):\n m = o.re * o.re + o.im * o.im\n return Complex((self.re * o.re + self.im * o.im)/m, (self.im * o.re - self.re * o.im)/m)\n\n def __str__(self):\n if self.im == 0:\n return '%.2f' % self.re\n if self.re == 0:\n return '%.2fi' % self.im\n if self.im < 0:\n return '%.2f - %.2fi' % (self.re, -self.im)\n else:\n return '%.2f + %.2fi' % (self.re, self.im)\n def mod(self):\n return sqrt(self.re*self.re+self.im*self.im)\n\ndef solve(comp1, comp2):\n print(comp1 + comp2)\n print(comp1 - comp2)\n print(comp1 * comp2)\n print(comp1 / comp2)\n print('%.2f' % comp1.mod())\n print('%.2f' % comp2.mod())\n\ncomp1 = Complex(2, 3)\ncomp2 = Complex(5, -2)\nsolve(comp1, comp2)" }, { "code": null, "e": 4210, "s": 4199, "text": "2, 3\n5, -2" }, { "code": null, "e": 4275, "s": 4210, "text": "7.00 + 1.00i\n-3.00 + 5.00i\n16.00 + 11.00i\n0.14 + 0.66i\n3.61\n5.39" } ]
Tryit Editor v3.7
Tryit: Text shadow with border
[]
Remove specific word in a comma separated string with MySQL
Let us first create a table − mysql> create table DemoTable836(FirstName SET('John','Chris','Adam')); Query OK, 0 rows affected (0.60 sec) Insert some records in the table using insert command − mysql> insert into DemoTable836 values('John,Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable836 values('John,Chris,Adam'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable836 values('Chris,Adam'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable836 values('John,Adam'); Query OK, 1 row affected (0.37 sec) Display all records from the table using select statement − mysql> select *from DemoTable836; This will produce the following output − +-----------------+ | FirstName | +-----------------+ | John,Chris | | John,Chris,Adam | | Chris,Adam | | John,Adam | +-----------------+ 4 rows in set (0.00 sec) Following is the query to remove a specific word in a comma-separated string − mysql> update DemoTable836 set FirstName = FirstName &~ (1 << FIND_IN_SET('Chris', FirstName) - 1); Query OK, 3 rows affected (0.21 sec) Rows matched: 4 Changed: 3 Warnings: 0 Let us check the table records once again − mysql> select *from DemoTable836; This will produce the following output − +-----------+ | FirstName | +-----------+ | John | | John,Adam | | Adam | | John,Adam | +-----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1201, "s": 1092, "text": "mysql> create table DemoTable836(FirstName SET('John','Chris','Adam'));\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1257, "s": 1201, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1621, "s": 1257, "text": "mysql> insert into DemoTable836 values('John,Chris');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable836 values('John,Chris,Adam');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable836 values('Chris,Adam');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into DemoTable836 values('John,Adam');\nQuery OK, 1 row affected (0.37 sec)" }, { "code": null, "e": 1681, "s": 1621, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1715, "s": 1681, "text": "mysql> select *from DemoTable836;" }, { "code": null, "e": 1756, "s": 1715, "text": "This will produce the following output −" }, { "code": null, "e": 1941, "s": 1756, "text": "+-----------------+\n| FirstName |\n+-----------------+\n| John,Chris |\n| John,Chris,Adam |\n| Chris,Adam |\n| John,Adam |\n+-----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2020, "s": 1941, "text": "Following is the query to remove a specific word in a comma-separated string −" }, { "code": null, "e": 2196, "s": 2020, "text": "mysql> update DemoTable836 set FirstName = FirstName &~ (1 << FIND_IN_SET('Chris', FirstName) - 1);\nQuery OK, 3 rows affected (0.21 sec)\nRows matched: 4 Changed: 3 Warnings: 0" }, { "code": null, "e": 2240, "s": 2196, "text": "Let us check the table records once again −" }, { "code": null, "e": 2274, "s": 2240, "text": "mysql> select *from DemoTable836;" }, { "code": null, "e": 2315, "s": 2274, "text": "This will produce the following output −" }, { "code": null, "e": 2452, "s": 2315, "text": "+-----------+\n| FirstName |\n+-----------+\n| John |\n| John,Adam |\n| Adam |\n| John,Adam |\n+-----------+\n4 rows in set (0.00 sec)" } ]
Ways to Detect and Remove the Outliers | by Natasha Sharma | Towards Data Science
While working on a Data Science project, what is it, that you look for? What is the most important part of the EDA phase? There are certain things which, if are not done in the EDA phase, can affect further statistical/Machine Learning modelling. One of them is finding “Outliers”. In this post we will try to understand what is an outlier? Why is it important to identify the outliers? What are the methods to outliers? Don’t worry, we won’t just go through the theory part but we will do some coding and plotting of the data too. Wikipedia definition, In statistics, an outlier is an observation point that is distant from other observations. The above definition suggests that outlier is something which is separate/different from the crowd. A lot of motivation videos suggest to be different from the crowd, specially Malcolm Gladwell. In respect to statistics, is it also a good thing or not? we are going to find that through this post. As we now know what is an outlier, but, are you also wondering how did an outlier introduce to the population? The Data Science project starts with collection of data and that’s when outliers first introduced to the population. Though, you will not know about the outliers at all in the collection phase. The outliers can be a result of a mistake during data collection or it can be just an indication of variance in your data. Let’s have a look at some examples. Suppose you have been asked to observe the performance of Indian cricket team i.e Run made by each player and collect the data. As you can see from the above collected data that all other players scored 300+ except Player3 who scored 10. This figure can be just a typing mistake or it is showing the variance in your data and indicating that Player3 is performing very bad so, needs improvements. Now that we know outliers can either be a mistake or just variance, how would you decide if they are important or not. Well, it is pretty simple if they are the result of a mistake, then we can ignore them, but if it is just a variance in the data we would need think a bit further. Before we try to understand whether to ignore the outliers or not, we need to know the ways to identify them. Most of you might be thinking, Oh! I can just have a peak of data find the outliers just like we did in the previously mentioned cricket example. Let’s think about a file with 500+ column and 10k+ rows, do you still think outlier can be found manually? To ease the discovery of outliers, we have plenty of methods in statistics, but we will only be discussing few of them. Mostly we will try to see visualization methods(easiest ones) rather mathematical. So, Let’s get start. We will be using Boston House Pricing Dataset which is included in the sklearn dataset API. We will load the dataset and separate out the features and targets. boston = load_boston()x = boston.datay = boston.targetcolumns = boston.feature_names#create the dataframeboston_df = pd.DataFrame(boston.data)boston_df.columns = columnsboston_df.head() Features/independent variable will be used to look for any outlier. Looking at the data above, it s seems, we only have numeric values i.e. we don’t need to do any data formatting.(Sigh!) There are two types of analysis we will follow to find the outliers- Uni-variate(one variable outlier analysis) and Multi-variate(two or more variable outlier analysis). Don’t get confused right, when you will start coding and plotting the data, you will see yourself that how easy it was to detect the outlier. To keep things simple, we will start with the basic method of detecting outliers and slowly move on to the advance methods. Box plot- Wikipedia Definition, In descriptive statistics, a box plot is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending vertically from the boxes (whiskers) indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot and box-and-whisker diagram. Outliers may be plotted as individual points. Above definition suggests, that if there is an outlier it will plotted as point in boxplot but other population will be grouped together and display as boxes. Let’s try and see it ourselves. import seaborn as snssns.boxplot(x=boston_df['DIS']) Above plot shows three points between 10 to 12, these are outliers as there are not included in the box of other observation i.e no where near the quartiles. Here we analysed Uni-variate outlier i.e. we used DIS column only to check the outlier. But we can do multivariate outlier analysis too. Can we do the multivariate analysis with Box plot? Well it depends, if you have a categorical values then you can use that with any continuous variable and do multivariate outlier analysis. As we do not have categorical value in our Boston Housing dataset, we might need to forget about using box plot for multivariate outlier analysis. Scatter plot- Wikipedia Defintion A scatter plot , is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. The data are displayed as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis. As the definition suggests, the scatter plot is the collection of points that shows values for two variables. We can try and draw scatter plot for two variables from our housing dataset. fig, ax = plt.subplots(figsize=(16,8))ax.scatter(boston_df['INDUS'], boston_df['TAX'])ax.set_xlabel('Proportion of non-retail business acres per town')ax.set_ylabel('Full-value property-tax rate per $10,000')plt.show() Looking at the plot above, we can most of data points are lying bottom left side but there are points which are far from the population like top right corner. Z-Score- Wikipedia Definition The Z-score is the signed number of standard deviations by which the value of an observation or data point is above the mean value of what is being observed or measured. The intuition behind Z-score is to describe any data point by finding their relationship with the Standard Deviation and Mean of the group of data points. Z-score is finding the distribution of data where mean is 0 and standard deviation is 1 i.e. normal distribution. You must be wondering that, how does this help in identifying the outliers? Well, while calculating the Z-score we re-scale and center the data and look for data points which are too far from zero. These data points which are way too far from zero will be treated as the outliers. In most of the cases a threshold of 3 or -3 is used i.e if the Z-score value is greater than or less than 3 or -3 respectively, that data point will be identified as outliers. We will use Z-score function defined in scipy library to detect the outliers. from scipy import statsimport numpy as npz = np.abs(stats.zscore(boston_df))print(z) Looking the code and the output above, it is difficult to say which data point is an outlier. Let’s try and define a threshold to identify an outlier. threshold = 3print(np.where(z > 3)) This will give a result as below - Don’t be confused by the results. The first array contains the list of row numbers and second array respective column numbers, which mean z[55][1] have a Z-score higher than 3. print(z[55][1])3.375038763517309 So, the data point — 55th record on column ZN is an outlier. IQR score - Box plot use the IQR method to display data and outliers(shape of the data) but in order to be get a list of identified outlier, we will need to use the mathematical formula and retrieve the outlier data. Wikipedia Definition The interquartile range (IQR), also called the midspread or middle 50%, or technically H-spread, is a measure of statistical dispersion, being equal to the difference between 75th and 25th percentiles, or between upper and lower quartiles, IQR = Q3 − Q1. In other words, the IQR is the first quartile subtracted from the third quartile; these quartiles can be clearly seen on a box plot on the data. It is a measure of the dispersion similar to standard deviation or variance, but is much more robust against outliers. IQR is somewhat similar to Z-score in terms of finding the distribution of data and then keeping some threshold to identify the outlier. Let’s find out we can box plot uses IQR and how we can use it to find the list of outliers as we did using Z-score calculation. First we will calculate IQR, Q1 = boston_df_o1.quantile(0.25)Q3 = boston_df_o1.quantile(0.75)IQR = Q3 - Q1print(IQR) Here we will get IQR for each column. As we now have the IQR scores, it’s time to get hold on outliers. The below code will give an output with some true and false values. The data point where we have False that means these values are valid whereas True indicates presence of an outlier. print(boston_df_o1 < (Q1 - 1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR)) Now that we know how to detect the outliers, it is important to understand if they needs to be removed or corrected. In the next section we will consider a few methods of removing the outliers and if required imputing new values. During data analysis when you detect the outlier one of most difficult decision could be how one should deal with the outlier. Should they remove them or correct them? Before we talk about this, we will have a look at few methods of removing the outliers. Z-Score In the previous section, we saw how one can detect the outlier using Z-score but now we want to remove or filter the outliers and get the clean data. This can be done with just one line code as we have already calculated the Z-score. boston_df_o = boston_df_o[(z < 3).all(axis=1)] So, above code removed around 90+ rows from the dataset i.e. outliers have been removed. IQR Score - Just like Z-score we can use previously calculated IQR score to filter out the outliers by keeping only valid values. boston_df_out = boston_df_o1[~((boston_df_o1 < (Q1 - 1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR))).any(axis=1)]boston_df_out.shape The above code will remove the outliers from the dataset. There are multiple ways to detect and remove the outliers but the methods, we have used for this exercise, are widely used and easy to understand. Whether an outlier should be removed or not. Every data analyst/data scientist might get these thoughts once in every problem they are working on. I have found some good explanations - https://www.researchgate.net/post/When_is_it_justifiable_to_exclude_outlier_data_points_from_statistical_analyses https://www.researchgate.net/post/Which_is_the_best_method_for_removing_outliers_in_a_data_set https://www.theanalysisfactor.com/outliers-to-drop-or-not-to-drop/ To summarize their explanation- bad data, wrong calculation, these can be identified as Outliers and should be dropped but at the same time you might want to correct them too, as they change the level of data i.e. mean which cause issues when you model your data. For ex- 5 people get salary of 10K, 20K, 30K, 40K and 50K and suddenly one of the person start getting salary of 100K. Consider this situation as, you are the employer, the new salary update might be seen as biased and you might need to increase other employee’s salary too, to keep the balance. So, there can be multiple reasons you want to understand and correct the outliers. Throughout this exercise we saw how in data analysis phase one can encounter with some unusual data i.e outlier. We learned about techniques which can be used to detect and remove those outliers. But there was a question raised about assuring if it is okay to remove the outliers. To answer those questions we have found further readings(this links are mentioned in the previous section). Hope this post helped the readers in knowing Outliers. Note- For this exercise, below tools and libaries were used. Framework- Jupyter Notebook, Language- Python, Libraries- sklearn library, Numpy, Panda and Scipy, Plot Lib- Seaborn and Matplot. Boston DatasetGithub RepoKDNuggets outliersDetect outliers
[ { "code": null, "e": 704, "s": 172, "text": "While working on a Data Science project, what is it, that you look for? What is the most important part of the EDA phase? There are certain things which, if are not done in the EDA phase, can affect further statistical/Machine Learning modelling. One of them is finding “Outliers”. In this post we will try to understand what is an outlier? Why is it important to identify the outliers? What are the methods to outliers? Don’t worry, we won’t just go through the theory part but we will do some coding and plotting of the data too." }, { "code": null, "e": 726, "s": 704, "text": "Wikipedia definition," }, { "code": null, "e": 817, "s": 726, "text": "In statistics, an outlier is an observation point that is distant from other observations." }, { "code": null, "e": 1115, "s": 817, "text": "The above definition suggests that outlier is something which is separate/different from the crowd. A lot of motivation videos suggest to be different from the crowd, specially Malcolm Gladwell. In respect to statistics, is it also a good thing or not? we are going to find that through this post." }, { "code": null, "e": 1226, "s": 1115, "text": "As we now know what is an outlier, but, are you also wondering how did an outlier introduce to the population?" }, { "code": null, "e": 1543, "s": 1226, "text": "The Data Science project starts with collection of data and that’s when outliers first introduced to the population. Though, you will not know about the outliers at all in the collection phase. The outliers can be a result of a mistake during data collection or it can be just an indication of variance in your data." }, { "code": null, "e": 1707, "s": 1543, "text": "Let’s have a look at some examples. Suppose you have been asked to observe the performance of Indian cricket team i.e Run made by each player and collect the data." }, { "code": null, "e": 1976, "s": 1707, "text": "As you can see from the above collected data that all other players scored 300+ except Player3 who scored 10. This figure can be just a typing mistake or it is showing the variance in your data and indicating that Player3 is performing very bad so, needs improvements." }, { "code": null, "e": 2369, "s": 1976, "text": "Now that we know outliers can either be a mistake or just variance, how would you decide if they are important or not. Well, it is pretty simple if they are the result of a mistake, then we can ignore them, but if it is just a variance in the data we would need think a bit further. Before we try to understand whether to ignore the outliers or not, we need to know the ways to identify them." }, { "code": null, "e": 2825, "s": 2369, "text": "Most of you might be thinking, Oh! I can just have a peak of data find the outliers just like we did in the previously mentioned cricket example. Let’s think about a file with 500+ column and 10k+ rows, do you still think outlier can be found manually? To ease the discovery of outliers, we have plenty of methods in statistics, but we will only be discussing few of them. Mostly we will try to see visualization methods(easiest ones) rather mathematical." }, { "code": null, "e": 3006, "s": 2825, "text": "So, Let’s get start. We will be using Boston House Pricing Dataset which is included in the sklearn dataset API. We will load the dataset and separate out the features and targets." }, { "code": null, "e": 3192, "s": 3006, "text": "boston = load_boston()x = boston.datay = boston.targetcolumns = boston.feature_names#create the dataframeboston_df = pd.DataFrame(boston.data)boston_df.columns = columnsboston_df.head()" }, { "code": null, "e": 3380, "s": 3192, "text": "Features/independent variable will be used to look for any outlier. Looking at the data above, it s seems, we only have numeric values i.e. we don’t need to do any data formatting.(Sigh!)" }, { "code": null, "e": 3816, "s": 3380, "text": "There are two types of analysis we will follow to find the outliers- Uni-variate(one variable outlier analysis) and Multi-variate(two or more variable outlier analysis). Don’t get confused right, when you will start coding and plotting the data, you will see yourself that how easy it was to detect the outlier. To keep things simple, we will start with the basic method of detecting outliers and slowly move on to the advance methods." }, { "code": null, "e": 3826, "s": 3816, "text": "Box plot-" }, { "code": null, "e": 3848, "s": 3826, "text": "Wikipedia Definition," }, { "code": null, "e": 4225, "s": 3848, "text": "In descriptive statistics, a box plot is a method for graphically depicting groups of numerical data through their quartiles. Box plots may also have lines extending vertically from the boxes (whiskers) indicating variability outside the upper and lower quartiles, hence the terms box-and-whisker plot and box-and-whisker diagram. Outliers may be plotted as individual points." }, { "code": null, "e": 4416, "s": 4225, "text": "Above definition suggests, that if there is an outlier it will plotted as point in boxplot but other population will be grouped together and display as boxes. Let’s try and see it ourselves." }, { "code": null, "e": 4469, "s": 4416, "text": "import seaborn as snssns.boxplot(x=boston_df['DIS'])" }, { "code": null, "e": 4627, "s": 4469, "text": "Above plot shows three points between 10 to 12, these are outliers as there are not included in the box of other observation i.e no where near the quartiles." }, { "code": null, "e": 5101, "s": 4627, "text": "Here we analysed Uni-variate outlier i.e. we used DIS column only to check the outlier. But we can do multivariate outlier analysis too. Can we do the multivariate analysis with Box plot? Well it depends, if you have a categorical values then you can use that with any continuous variable and do multivariate outlier analysis. As we do not have categorical value in our Boston Housing dataset, we might need to forget about using box plot for multivariate outlier analysis." }, { "code": null, "e": 5115, "s": 5101, "text": "Scatter plot-" }, { "code": null, "e": 5135, "s": 5115, "text": "Wikipedia Defintion" }, { "code": null, "e": 5506, "s": 5135, "text": "A scatter plot , is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. The data are displayed as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis." }, { "code": null, "e": 5693, "s": 5506, "text": "As the definition suggests, the scatter plot is the collection of points that shows values for two variables. We can try and draw scatter plot for two variables from our housing dataset." }, { "code": null, "e": 5912, "s": 5693, "text": "fig, ax = plt.subplots(figsize=(16,8))ax.scatter(boston_df['INDUS'], boston_df['TAX'])ax.set_xlabel('Proportion of non-retail business acres per town')ax.set_ylabel('Full-value property-tax rate per $10,000')plt.show()" }, { "code": null, "e": 6071, "s": 5912, "text": "Looking at the plot above, we can most of data points are lying bottom left side but there are points which are far from the population like top right corner." }, { "code": null, "e": 6080, "s": 6071, "text": "Z-Score-" }, { "code": null, "e": 6101, "s": 6080, "text": "Wikipedia Definition" }, { "code": null, "e": 6271, "s": 6101, "text": "The Z-score is the signed number of standard deviations by which the value of an observation or data point is above the mean value of what is being observed or measured." }, { "code": null, "e": 6540, "s": 6271, "text": "The intuition behind Z-score is to describe any data point by finding their relationship with the Standard Deviation and Mean of the group of data points. Z-score is finding the distribution of data where mean is 0 and standard deviation is 1 i.e. normal distribution." }, { "code": null, "e": 6997, "s": 6540, "text": "You must be wondering that, how does this help in identifying the outliers? Well, while calculating the Z-score we re-scale and center the data and look for data points which are too far from zero. These data points which are way too far from zero will be treated as the outliers. In most of the cases a threshold of 3 or -3 is used i.e if the Z-score value is greater than or less than 3 or -3 respectively, that data point will be identified as outliers." }, { "code": null, "e": 7075, "s": 6997, "text": "We will use Z-score function defined in scipy library to detect the outliers." }, { "code": null, "e": 7160, "s": 7075, "text": "from scipy import statsimport numpy as npz = np.abs(stats.zscore(boston_df))print(z)" }, { "code": null, "e": 7311, "s": 7160, "text": "Looking the code and the output above, it is difficult to say which data point is an outlier. Let’s try and define a threshold to identify an outlier." }, { "code": null, "e": 7347, "s": 7311, "text": "threshold = 3print(np.where(z > 3))" }, { "code": null, "e": 7382, "s": 7347, "text": "This will give a result as below -" }, { "code": null, "e": 7559, "s": 7382, "text": "Don’t be confused by the results. The first array contains the list of row numbers and second array respective column numbers, which mean z[55][1] have a Z-score higher than 3." }, { "code": null, "e": 7592, "s": 7559, "text": "print(z[55][1])3.375038763517309" }, { "code": null, "e": 7653, "s": 7592, "text": "So, the data point — 55th record on column ZN is an outlier." }, { "code": null, "e": 7665, "s": 7653, "text": "IQR score -" }, { "code": null, "e": 7870, "s": 7665, "text": "Box plot use the IQR method to display data and outliers(shape of the data) but in order to be get a list of identified outlier, we will need to use the mathematical formula and retrieve the outlier data." }, { "code": null, "e": 7891, "s": 7870, "text": "Wikipedia Definition" }, { "code": null, "e": 8146, "s": 7891, "text": "The interquartile range (IQR), also called the midspread or middle 50%, or technically H-spread, is a measure of statistical dispersion, being equal to the difference between 75th and 25th percentiles, or between upper and lower quartiles, IQR = Q3 − Q1." }, { "code": null, "e": 8291, "s": 8146, "text": "In other words, the IQR is the first quartile subtracted from the third quartile; these quartiles can be clearly seen on a box plot on the data." }, { "code": null, "e": 8410, "s": 8291, "text": "It is a measure of the dispersion similar to standard deviation or variance, but is much more robust against outliers." }, { "code": null, "e": 8547, "s": 8410, "text": "IQR is somewhat similar to Z-score in terms of finding the distribution of data and then keeping some threshold to identify the outlier." }, { "code": null, "e": 8704, "s": 8547, "text": "Let’s find out we can box plot uses IQR and how we can use it to find the list of outliers as we did using Z-score calculation. First we will calculate IQR," }, { "code": null, "e": 8792, "s": 8704, "text": "Q1 = boston_df_o1.quantile(0.25)Q3 = boston_df_o1.quantile(0.75)IQR = Q3 - Q1print(IQR)" }, { "code": null, "e": 8830, "s": 8792, "text": "Here we will get IQR for each column." }, { "code": null, "e": 9080, "s": 8830, "text": "As we now have the IQR scores, it’s time to get hold on outliers. The below code will give an output with some true and false values. The data point where we have False that means these values are valid whereas True indicates presence of an outlier." }, { "code": null, "e": 9154, "s": 9080, "text": "print(boston_df_o1 < (Q1 - 1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR))" }, { "code": null, "e": 9384, "s": 9154, "text": "Now that we know how to detect the outliers, it is important to understand if they needs to be removed or corrected. In the next section we will consider a few methods of removing the outliers and if required imputing new values." }, { "code": null, "e": 9640, "s": 9384, "text": "During data analysis when you detect the outlier one of most difficult decision could be how one should deal with the outlier. Should they remove them or correct them? Before we talk about this, we will have a look at few methods of removing the outliers." }, { "code": null, "e": 9648, "s": 9640, "text": "Z-Score" }, { "code": null, "e": 9882, "s": 9648, "text": "In the previous section, we saw how one can detect the outlier using Z-score but now we want to remove or filter the outliers and get the clean data. This can be done with just one line code as we have already calculated the Z-score." }, { "code": null, "e": 9929, "s": 9882, "text": "boston_df_o = boston_df_o[(z < 3).all(axis=1)]" }, { "code": null, "e": 10018, "s": 9929, "text": "So, above code removed around 90+ rows from the dataset i.e. outliers have been removed." }, { "code": null, "e": 10030, "s": 10018, "text": "IQR Score -" }, { "code": null, "e": 10148, "s": 10030, "text": "Just like Z-score we can use previously calculated IQR score to filter out the outliers by keeping only valid values." }, { "code": null, "e": 10281, "s": 10148, "text": "boston_df_out = boston_df_o1[~((boston_df_o1 < (Q1 - 1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR))).any(axis=1)]boston_df_out.shape" }, { "code": null, "e": 10339, "s": 10281, "text": "The above code will remove the outliers from the dataset." }, { "code": null, "e": 10486, "s": 10339, "text": "There are multiple ways to detect and remove the outliers but the methods, we have used for this exercise, are widely used and easy to understand." }, { "code": null, "e": 10671, "s": 10486, "text": "Whether an outlier should be removed or not. Every data analyst/data scientist might get these thoughts once in every problem they are working on. I have found some good explanations -" }, { "code": null, "e": 10785, "s": 10671, "text": "https://www.researchgate.net/post/When_is_it_justifiable_to_exclude_outlier_data_points_from_statistical_analyses" }, { "code": null, "e": 10880, "s": 10785, "text": "https://www.researchgate.net/post/Which_is_the_best_method_for_removing_outliers_in_a_data_set" }, { "code": null, "e": 10947, "s": 10880, "text": "https://www.theanalysisfactor.com/outliers-to-drop-or-not-to-drop/" }, { "code": null, "e": 11590, "s": 10947, "text": "To summarize their explanation- bad data, wrong calculation, these can be identified as Outliers and should be dropped but at the same time you might want to correct them too, as they change the level of data i.e. mean which cause issues when you model your data. For ex- 5 people get salary of 10K, 20K, 30K, 40K and 50K and suddenly one of the person start getting salary of 100K. Consider this situation as, you are the employer, the new salary update might be seen as biased and you might need to increase other employee’s salary too, to keep the balance. So, there can be multiple reasons you want to understand and correct the outliers." }, { "code": null, "e": 12034, "s": 11590, "text": "Throughout this exercise we saw how in data analysis phase one can encounter with some unusual data i.e outlier. We learned about techniques which can be used to detect and remove those outliers. But there was a question raised about assuring if it is okay to remove the outliers. To answer those questions we have found further readings(this links are mentioned in the previous section). Hope this post helped the readers in knowing Outliers." }, { "code": null, "e": 12095, "s": 12034, "text": "Note- For this exercise, below tools and libaries were used." }, { "code": null, "e": 12225, "s": 12095, "text": "Framework- Jupyter Notebook, Language- Python, Libraries- sklearn library, Numpy, Panda and Scipy, Plot Lib- Seaborn and Matplot." } ]
Difference between Synchronous and Asynchronous Sequential Circuits - GeeksforGeeks
08 Apr, 2022 Sequential Circuits are those which have the notion of an internal state. This notion of Internal State is necessary because in sequential circuits, the output of the circuit is function of both the present input as well as the past inputs. The Internal State of a sequential circuit is nothing but the reflection of the past inputs to the circuit. Now the Internal State of a Sequential Circuit is represented by a number of State Variables. Each state variable can be in 1 of 2 possible states. This is because State Variables are physically implemented with the help of Flip-Flops, and each Flip-Flop can only represent 2 possible states. Therefore, if we have ‘N’ Flip-Flops, we can represent a maximum of 2N states. Max. No. of States with 'N' Flip-Flops = This means that a Sequential Circuit having ‘N’ Flip-Flops can be in at most Internal States. Now let’s illustrate the difference between that of Synchronous and Asynchronous Sequential Circuits with the example of a Synchronous and Asynchronous 2-bit binary UP Counter using T-Flip-Flops. Figure – 2-bit Binary Asynchronous UP CounterFigure – 2-bit Binary Synchronous UP CounterIn both the above circuits are the State Variables denoting the Internal State of each of the above circuits. Since there are 2 state variable the above sequential circuits can be in 4 possible states, and the function of a counter is to cycle through these 4 states in a particular order. Now the difference between Synchronous and Asynchronous Circuits is in how the circuit goes for one Internal State to the Next Internal State. In a Synchronous Sequential Circuit all the State Variables representing the internal state of the circuit change their state simultaneously with a given input clock signal to achieve the next state. On the other hand in case of an Asynchronous Circuit all the State Variables may not change their state simultaneously to achieve the next steady internal state. In other words the state variables are not synchronized with any universal clock signal. Comparisons – nikhatkhan11 Technical Scripter 2018 Difference Between Digital Electronics & Logic Design GATE CS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference between Process and Thread Difference Between Method Overloading and Method Overriding in Java Difference between Clustered and Non-clustered index Differences between Procedural and Object Oriented Programming Full Adder in Digital Logic Program for Decimal to Binary Conversion Introduction of K-Map (Karnaugh Map) Program for Binary To Decimal Conversion 4-bit binary Adder-Subtractor
[ { "code": null, "e": 24638, "s": 24610, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25359, "s": 24638, "text": "Sequential Circuits are those which have the notion of an internal state. This notion of Internal State is necessary because in sequential circuits, the output of the circuit is function of both the present input as well as the past inputs. The Internal State of a sequential circuit is nothing but the reflection of the past inputs to the circuit. Now the Internal State of a Sequential Circuit is represented by a number of State Variables. Each state variable can be in 1 of 2 possible states. This is because State Variables are physically implemented with the help of Flip-Flops, and each Flip-Flop can only represent 2 possible states. Therefore, if we have ‘N’ Flip-Flops, we can represent a maximum of 2N states." }, { "code": null, "e": 25401, "s": 25359, "text": "Max. No. of States with 'N' Flip-Flops = " }, { "code": null, "e": 26678, "s": 25401, "text": "This means that a Sequential Circuit having ‘N’ Flip-Flops can be in at most Internal States. Now let’s illustrate the difference between that of Synchronous and Asynchronous Sequential Circuits with the example of a Synchronous and Asynchronous 2-bit binary UP Counter using T-Flip-Flops. Figure – 2-bit Binary Asynchronous UP CounterFigure – 2-bit Binary Synchronous UP CounterIn both the above circuits are the State Variables denoting the Internal State of each of the above circuits. Since there are 2 state variable the above sequential circuits can be in 4 possible states, and the function of a counter is to cycle through these 4 states in a particular order. Now the difference between Synchronous and Asynchronous Circuits is in how the circuit goes for one Internal State to the Next Internal State. In a Synchronous Sequential Circuit all the State Variables representing the internal state of the circuit change their state simultaneously with a given input clock signal to achieve the next state. On the other hand in case of an Asynchronous Circuit all the State Variables may not change their state simultaneously to achieve the next steady internal state. In other words the state variables are not synchronized with any universal clock signal. Comparisons –" }, { "code": null, "e": 26691, "s": 26678, "text": "nikhatkhan11" }, { "code": null, "e": 26715, "s": 26691, "text": "Technical Scripter 2018" }, { "code": null, "e": 26734, "s": 26715, "text": "Difference Between" }, { "code": null, "e": 26769, "s": 26734, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 26777, "s": 26769, "text": "GATE CS" }, { "code": null, "e": 26796, "s": 26777, "text": "Technical Scripter" }, { "code": null, "e": 26894, "s": 26796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26903, "s": 26894, "text": "Comments" }, { "code": null, "e": 26916, "s": 26903, "text": "Old Comments" }, { "code": null, "e": 26977, "s": 26916, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27015, "s": 26977, "text": "Difference between Process and Thread" }, { "code": null, "e": 27083, "s": 27015, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27136, "s": 27083, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27199, "s": 27136, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 27227, "s": 27199, "text": "Full Adder in Digital Logic" }, { "code": null, "e": 27268, "s": 27227, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 27305, "s": 27268, "text": "Introduction of K-Map (Karnaugh Map)" }, { "code": null, "e": 27346, "s": 27305, "text": "Program for Binary To Decimal Conversion" } ]
stack push() and pop() in C++ STL
In this article we will be discussing the working, syntax, and examples of stack::push() and stack::pop() function in C++ STL. Stacks are the data structure which stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top. stack::push() function is an inbuilt function in C++ STL, which is defined in <stack>header file. push() is used to push or insert an element at the top of the stack container. The content of the new element is copied and initialized. stack_name.push(value_type& val); The function accepts the following parameter(s) − val − Value which we want to push val − Value which we want to push This function returns nothing Input std::stack<int> stack1; stack1.push(1); stack1.push(2); stack1.push(3); Output 3 2 1 Live Demo #include <iostream> #include <stack> using namespace std; int main(){ stack<int>stck; int Product = 1; stck.push(1); stck.push(2); stck.push(3); stck.push(4); stck.push(5); stck.push(6); while (!stck.empty()){ Product = Product * stck.top(); cout<<"\nsize of stack is: "<<stck.size(); stck.pop(); } return 0; } If we run the above code it will generate the following output − size of stack is: 6 size of stack is: 5 size of stack is: 4 size of stack is: 3 size of stack is: 2 size of stack is: 1 stack::pop() function is an inbuilt function in C++ STL, which is defined in <stack>header file. pop() is used to pop or remove an element from the top of the stack container. The content from the top is removed and the size of the container is reduced by 1. stack_name.pop(); The function accepts no parameter(s) − This function returns nothing Input std::stack<int> stack1; stack1.push(1); stack1.push(2); stack1.push(3); stack1.pop(); Output 2 1 Live Demo #include <iostream> #include <stack> using namespace std; int main(){ stack<int> stck; int Product = 1; stck.push(1); stck.push(2); stck.push(3); stck.push(4); stck.push(5); stck.push(6); while (!stck.empty()){ Product = Product * stck.top(); cout<<"\nsize of stack is: "<<stck.size(); stck.pop(); } return 0; } If we run the above code it will generate the following output − size of stack is: 6 size of stack is: 5 size of stack is: 4 size of stack is: 3 size of stack is: 2 size of stack is: 1
[ { "code": null, "e": 1189, "s": 1062, "text": "In this article we will be discussing the working, syntax, and examples of stack::push() and\nstack::pop() function in C++ STL." }, { "code": null, "e": 1525, "s": 1189, "text": "Stacks are the data structure which stores the data in LIFO (Last In First Out) where we do\ninsertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top." }, { "code": null, "e": 1760, "s": 1525, "text": "stack::push() function is an inbuilt function in C++ STL, which is defined in <stack>header file. push() is used to push or insert an element at the top of the stack container. The content of the new element is copied and initialized." }, { "code": null, "e": 1794, "s": 1760, "text": "stack_name.push(value_type& val);" }, { "code": null, "e": 1844, "s": 1794, "text": "The function accepts the following parameter(s) −" }, { "code": null, "e": 1878, "s": 1844, "text": "val − Value which we want to push" }, { "code": null, "e": 1912, "s": 1878, "text": "val − Value which we want to push" }, { "code": null, "e": 1942, "s": 1912, "text": "This function returns nothing" }, { "code": null, "e": 1949, "s": 1942, "text": "Input " }, { "code": null, "e": 2021, "s": 1949, "text": "std::stack<int> stack1;\nstack1.push(1);\nstack1.push(2);\nstack1.push(3);" }, { "code": null, "e": 2029, "s": 2021, "text": "Output " }, { "code": null, "e": 2035, "s": 2029, "text": "3 2 1" }, { "code": null, "e": 2046, "s": 2035, "text": " Live Demo" }, { "code": null, "e": 2408, "s": 2046, "text": "#include <iostream>\n#include <stack>\nusing namespace std;\nint main(){\n stack<int>stck;\n int Product = 1;\n stck.push(1);\n stck.push(2);\n stck.push(3);\n stck.push(4);\n stck.push(5);\n stck.push(6);\n while (!stck.empty()){\n Product = Product * stck.top();\n cout<<\"\\nsize of stack is: \"<<stck.size();\n stck.pop();\n }\n return 0;\n}" }, { "code": null, "e": 2473, "s": 2408, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2593, "s": 2473, "text": "size of stack is: 6\nsize of stack is: 5\nsize of stack is: 4\nsize of stack is: 3\nsize of stack is: 2\nsize of stack is: 1" }, { "code": null, "e": 2852, "s": 2593, "text": "stack::pop() function is an inbuilt function in C++ STL, which is defined in <stack>header file. pop() is used to pop or remove an element from the top of the stack container. The content from the top is removed and the size of the container is reduced by 1." }, { "code": null, "e": 2870, "s": 2852, "text": "stack_name.pop();" }, { "code": null, "e": 2909, "s": 2870, "text": "The function accepts no parameter(s) −" }, { "code": null, "e": 2939, "s": 2909, "text": "This function returns nothing" }, { "code": null, "e": 2946, "s": 2939, "text": "Input " }, { "code": null, "e": 3032, "s": 2946, "text": "std::stack<int> stack1;\nstack1.push(1);\nstack1.push(2);\nstack1.push(3);\nstack1.pop();" }, { "code": null, "e": 3040, "s": 3032, "text": "Output " }, { "code": null, "e": 3044, "s": 3040, "text": "2 1" }, { "code": null, "e": 3055, "s": 3044, "text": " Live Demo" }, { "code": null, "e": 3418, "s": 3055, "text": "#include <iostream>\n#include <stack>\nusing namespace std;\nint main(){\n stack<int> stck;\n int Product = 1;\n stck.push(1);\n stck.push(2);\n stck.push(3);\n stck.push(4);\n stck.push(5);\n stck.push(6);\n while (!stck.empty()){\n Product = Product * stck.top();\n cout<<\"\\nsize of stack is: \"<<stck.size();\n stck.pop();\n }\n return 0;\n}" }, { "code": null, "e": 3483, "s": 3418, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3603, "s": 3483, "text": "size of stack is: 6\nsize of stack is: 5\nsize of stack is: 4\nsize of stack is: 3\nsize of stack is: 2\nsize of stack is: 1" } ]
jQuery - Widget Dialog
The Widget Dialog function can be used with widgets in JqueryUI. Dialog boxes are one of the nice ways of presenting information on an HTML page. A dialog box is a floating window with a title and content area. This window can be moved, resized, and of course, closed using "X" icon by default. Here is the simple syntax to use Dialog − $( "#dialog" ).dialog(); Following is a simple example showing the usage of Dialog − <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Dialog - Default functionality</title> <link rel = "stylesheet" href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <script> $(function() { $( "#dialog" ).dialog(); }); </script> </head> <body> <div id = "dialog" title = "Basic dialog"> <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p> </div> </body> </html> This will produce following result − This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2617, "s": 2322, "text": "The Widget Dialog function can be used with widgets in JqueryUI. Dialog boxes are one of the nice ways of presenting information on an HTML page. A dialog box is a floating window with a title and content area. This window can be moved, resized, and of course, closed using \"X\" icon by default." }, { "code": null, "e": 2659, "s": 2617, "text": "Here is the simple syntax to use Dialog −" }, { "code": null, "e": 2685, "s": 2659, "text": "$( \"#dialog\" ).dialog();\n" }, { "code": null, "e": 2745, "s": 2685, "text": "Following is a simple example showing the usage of Dialog −" }, { "code": null, "e": 3684, "s": 2745, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Dialog - Default functionality</title>\n\t\t\n <link rel = \"stylesheet\" \n href = \"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\t\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n \n <script>\n $(function() {\n $( \"#dialog\" ).dialog();\n });\n </script>\n </head>\n\t\n <body>\n <div id = \"dialog\" title = \"Basic dialog\">\n <p>This is the default dialog which is useful for displaying\n information. The dialog window can be moved, resized and closed with\n the 'x' icon.</p>\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 3721, "s": 3684, "text": "This will produce following result −" }, { "code": null, "e": 3862, "s": 3721, "text": "This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon." }, { "code": null, "e": 3895, "s": 3862, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3909, "s": 3895, "text": " Mahesh Kumar" }, { "code": null, "e": 3944, "s": 3909, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3958, "s": 3944, "text": " Pratik Singh" }, { "code": null, "e": 3993, "s": 3958, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4010, "s": 3993, "text": " Frahaan Hussain" }, { "code": null, "e": 4043, "s": 4010, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4071, "s": 4043, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4104, "s": 4071, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4125, "s": 4104, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4157, "s": 4125, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4174, "s": 4157, "text": " Laurence Svekis" }, { "code": null, "e": 4181, "s": 4174, "text": " Print" }, { "code": null, "e": 4192, "s": 4181, "text": " Add Notes" } ]
Improve your SQL with these templates for formatting and documentation | by Ha Dinh | Towards Data Science
Have you ever come across a complicated SQL query for analysis? Did you struggle to understand the code itself and the business logic underneath? I did. And sometimes, it was with my queries in the past! To save time for everyone who read my code (including myself), I have tried to apply two templates to my query and found that they are very helpful to: Increase the quality of the code itself Reduce code review time And improve knowledge transfer In this article, I will share with you these two templates that I use. Template #1: Document context and assumptions in your SQL query Template #2: Format SQL query To demonstrate their usage, I will go through an example using MySQL to summarize sales before and after COVID-19. I hope these templates come in handy! This is especially when remote work is our new normal after COVID-19 started, increasing the importance of over-communication to make sure everyone is on the same page. List this information before you write a query: Important business context for this queryExpectations for query resultAny assumptions made for the business logic and data Important business context for this query Expectations for query result Any assumptions made for the business logic and data /* CONTEXT: - add a brief description of why we need this queryRESULT EXPECTATION- add a brief description of your expectations for the query resultASSUMPTION:- add assumption about business logic- add assumption about data*/ Apply this template to our sales summary example: /* CONTEXT: - Our company wants to understand if COVID has any impact on sales in stores around Chicago.RESULT EXPECTATION: - This query returns total sales (in USD) for each of our stores in Chicago every month before and after COVID, starting from 2019-03-01.ASSUMPTION:- Dates before 2020-03-01 are considered "Before COVID"- Each transaction has a unique id, so we do not expect duplications in our transaction table- There are some spam transactions we have identified after COVID, so we will filter these out*/ Having a brief description with business context, result expectation, and assumptions before our queries has many benefits: It keeps us focused on the main goal of the query while writing itIt helps readers quickly establish a high-level understanding of the value and expectations of our queriesIt assists code reviewers to create initial tests for the queries based on the expectations It keeps us focused on the main goal of the query while writing it It helps readers quickly establish a high-level understanding of the value and expectations of our queries It assists code reviewers to create initial tests for the queries based on the expectations Remember, this step is an iterating process. We might have to go back and forth to improve the documentation as we write the query. There are many rules out there to format the SQL query. To keep it simple, these are the main rules I follow: Highlight reserved keywords (eg. SELECT, WHERE) using upper-caseClearly show where a query or subquery starts and ends using indentationFor long and complicated query, include a comment before any major sub-queries or joins for contextGive reference for where columns come from with their source table or descriptive table alias Highlight reserved keywords (eg. SELECT, WHERE) using upper-case Clearly show where a query or subquery starts and ends using indentation For long and complicated query, include a comment before any major sub-queries or joins for context Give reference for where columns come from with their source table or descriptive table alias This query is for demonstration only There are many benefits to readability with this query format. Here are some: Understand the overall structure of the query (ie. what columns are chosen, how many joins are there, which filters are applied) Save time to identify the start and end of subqueries for testing, because we can see the opening and closing parentheses of a subquery in the same vertical line Avoid getting lost in a complicated query with comments throughout the query Combining these two templates in our example, we will have: /* CONTEXT: - Our company wants to understand if COVID has any impact on sales in storesaround Chicago.RESULT EXPECTATION- This query returns total sales (in USD) for each of our stores in Chicagoevery month before and after COVID, starting from 2019-03-01.ASSUMPTION:- Dates before 2020-03-01 are considered "Before COVID"- Each transaction has a unique id, so we do not expect duplicationsin our transaction table- There are some spam transactions we have identified after COVID,so we will filter these out*/SELECT store_info.id, store_info.name AS store_name, DATE_FORMAT(transactions.date, "%Y-%m") AS transaction_month, SUM(transactions.total_amount) AS total_amountFROM transactionsLEFT JOIN -- get all stores in Chicago ( SELECT id, name FROM stores WHERE city = 'Chicago' ) AS store_infoON transactions.branch_id = store_info.idWHERE transactions.date >= '2019-03-01' -- filter spam transactions AND transactions.id NOT IN ( SELECT id FROM spam_transactions )GROUP BY store_info.id, store_info.name, DATE_FORMAT(transactions.date, "%Y-%m") These templates are not the only templates out there. Finding out what works best for you and your team is a trial and error process. After you finalize a formatting style, manually styling every query can be tiring. Many SQL IDE has an option to automate this process for you. However, if it still doesn’t meet your need, there are tools out there. Try searching with these keywords: “SQL formatter” For Python users, I’ve been playing around with sqlparse. You can get more information here. Thank you for reading through the whole article! I hope these templates are helpful to you. I’d love to know your thoughts and any other tips to make SQL queries more readable. Feel free to leave your message below, or connect with me on LinkedIn.
[ { "code": null, "e": 236, "s": 172, "text": "Have you ever come across a complicated SQL query for analysis?" }, { "code": null, "e": 318, "s": 236, "text": "Did you struggle to understand the code itself and the business logic underneath?" }, { "code": null, "e": 376, "s": 318, "text": "I did. And sometimes, it was with my queries in the past!" }, { "code": null, "e": 528, "s": 376, "text": "To save time for everyone who read my code (including myself), I have tried to apply two templates to my query and found that they are very helpful to:" }, { "code": null, "e": 568, "s": 528, "text": "Increase the quality of the code itself" }, { "code": null, "e": 592, "s": 568, "text": "Reduce code review time" }, { "code": null, "e": 623, "s": 592, "text": "And improve knowledge transfer" }, { "code": null, "e": 694, "s": 623, "text": "In this article, I will share with you these two templates that I use." }, { "code": null, "e": 758, "s": 694, "text": "Template #1: Document context and assumptions in your SQL query" }, { "code": null, "e": 788, "s": 758, "text": "Template #2: Format SQL query" }, { "code": null, "e": 903, "s": 788, "text": "To demonstrate their usage, I will go through an example using MySQL to summarize sales before and after COVID-19." }, { "code": null, "e": 1110, "s": 903, "text": "I hope these templates come in handy! This is especially when remote work is our new normal after COVID-19 started, increasing the importance of over-communication to make sure everyone is on the same page." }, { "code": null, "e": 1158, "s": 1110, "text": "List this information before you write a query:" }, { "code": null, "e": 1281, "s": 1158, "text": "Important business context for this queryExpectations for query resultAny assumptions made for the business logic and data" }, { "code": null, "e": 1323, "s": 1281, "text": "Important business context for this query" }, { "code": null, "e": 1353, "s": 1323, "text": "Expectations for query result" }, { "code": null, "e": 1406, "s": 1353, "text": "Any assumptions made for the business logic and data" }, { "code": null, "e": 1632, "s": 1406, "text": "/* CONTEXT: - add a brief description of why we need this queryRESULT EXPECTATION- add a brief description of your expectations for the query resultASSUMPTION:- add assumption about business logic- add assumption about data*/" }, { "code": null, "e": 1682, "s": 1632, "text": "Apply this template to our sales summary example:" }, { "code": null, "e": 2201, "s": 1682, "text": "/* CONTEXT: - Our company wants to understand if COVID has any impact on sales in stores around Chicago.RESULT EXPECTATION: - This query returns total sales (in USD) for each of our stores in Chicago every month before and after COVID, starting from 2019-03-01.ASSUMPTION:- Dates before 2020-03-01 are considered \"Before COVID\"- Each transaction has a unique id, so we do not expect duplications in our transaction table- There are some spam transactions we have identified after COVID, so we will filter these out*/" }, { "code": null, "e": 2325, "s": 2201, "text": "Having a brief description with business context, result expectation, and assumptions before our queries has many benefits:" }, { "code": null, "e": 2589, "s": 2325, "text": "It keeps us focused on the main goal of the query while writing itIt helps readers quickly establish a high-level understanding of the value and expectations of our queriesIt assists code reviewers to create initial tests for the queries based on the expectations" }, { "code": null, "e": 2656, "s": 2589, "text": "It keeps us focused on the main goal of the query while writing it" }, { "code": null, "e": 2763, "s": 2656, "text": "It helps readers quickly establish a high-level understanding of the value and expectations of our queries" }, { "code": null, "e": 2855, "s": 2763, "text": "It assists code reviewers to create initial tests for the queries based on the expectations" }, { "code": null, "e": 2987, "s": 2855, "text": "Remember, this step is an iterating process. We might have to go back and forth to improve the documentation as we write the query." }, { "code": null, "e": 3097, "s": 2987, "text": "There are many rules out there to format the SQL query. To keep it simple, these are the main rules I follow:" }, { "code": null, "e": 3426, "s": 3097, "text": "Highlight reserved keywords (eg. SELECT, WHERE) using upper-caseClearly show where a query or subquery starts and ends using indentationFor long and complicated query, include a comment before any major sub-queries or joins for contextGive reference for where columns come from with their source table or descriptive table alias" }, { "code": null, "e": 3491, "s": 3426, "text": "Highlight reserved keywords (eg. SELECT, WHERE) using upper-case" }, { "code": null, "e": 3564, "s": 3491, "text": "Clearly show where a query or subquery starts and ends using indentation" }, { "code": null, "e": 3664, "s": 3564, "text": "For long and complicated query, include a comment before any major sub-queries or joins for context" }, { "code": null, "e": 3758, "s": 3664, "text": "Give reference for where columns come from with their source table or descriptive table alias" }, { "code": null, "e": 3795, "s": 3758, "text": "This query is for demonstration only" }, { "code": null, "e": 3873, "s": 3795, "text": "There are many benefits to readability with this query format. Here are some:" }, { "code": null, "e": 4002, "s": 3873, "text": "Understand the overall structure of the query (ie. what columns are chosen, how many joins are there, which filters are applied)" }, { "code": null, "e": 4164, "s": 4002, "text": "Save time to identify the start and end of subqueries for testing, because we can see the opening and closing parentheses of a subquery in the same vertical line" }, { "code": null, "e": 4241, "s": 4164, "text": "Avoid getting lost in a complicated query with comments throughout the query" }, { "code": null, "e": 4301, "s": 4241, "text": "Combining these two templates in our example, we will have:" }, { "code": null, "e": 5434, "s": 4301, "text": "/* CONTEXT: - Our company wants to understand if COVID has any impact on sales in storesaround Chicago.RESULT EXPECTATION- This query returns total sales (in USD) for each of our stores in Chicagoevery month before and after COVID, starting from 2019-03-01.ASSUMPTION:- Dates before 2020-03-01 are considered \"Before COVID\"- Each transaction has a unique id, so we do not expect duplicationsin our transaction table- There are some spam transactions we have identified after COVID,so we will filter these out*/SELECT store_info.id, store_info.name AS store_name, DATE_FORMAT(transactions.date, \"%Y-%m\") AS transaction_month, SUM(transactions.total_amount) AS total_amountFROM transactionsLEFT JOIN -- get all stores in Chicago ( SELECT id, name FROM stores WHERE city = 'Chicago' ) AS store_infoON transactions.branch_id = store_info.idWHERE transactions.date >= '2019-03-01' -- filter spam transactions AND transactions.id NOT IN ( SELECT id FROM spam_transactions )GROUP BY store_info.id, store_info.name, DATE_FORMAT(transactions.date, \"%Y-%m\")" }, { "code": null, "e": 5568, "s": 5434, "text": "These templates are not the only templates out there. Finding out what works best for you and your team is a trial and error process." }, { "code": null, "e": 5835, "s": 5568, "text": "After you finalize a formatting style, manually styling every query can be tiring. Many SQL IDE has an option to automate this process for you. However, if it still doesn’t meet your need, there are tools out there. Try searching with these keywords: “SQL formatter”" }, { "code": null, "e": 5928, "s": 5835, "text": "For Python users, I’ve been playing around with sqlparse. You can get more information here." } ]
Invoking functions with call() and apply() in JavaScript
Following is the code for invoking functions with call() and apply() in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Invoking functions with call() and apply()</h1> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Click on the above buttons to invoke functions with call() and apply() method</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function addNum(num1, num2, num3, num4) { return num1 + num2 + num3 + num4; } function multiplyNum(num1, num2, num3, num4) { return num1 * num2 * num3 * num4; } let arr = [22, 33, 44, 55]; BtnEle.addEventListener("click", () => { resEle.innerHTML = "Sum of the numbers = " + addNum.call(this, 22, 33, 44, 55) + "<br>"; resEle.innerHTML +="Multiplication of the array elements = " +multiplyNum.apply(this, arr) +"<br>"; }); </script> </body> </html> On clicking the ‘Click Here’ button −
[ { "code": null, "e": 1147, "s": 1062, "text": "Following is the code for invoking functions with call() and apply() in JavaScript −" }, { "code": null, "e": 1158, "s": 1147, "text": " Live Demo" }, { "code": null, "e": 2340, "s": 1158, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Invoking functions with call() and apply()</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">Click Here</button>\n<h3>Click on the above buttons to invoke functions with call() and apply()\nmethod</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function addNum(num1, num2, num3, num4) {\n return num1 + num2 + num3 + num4;\n }\n function multiplyNum(num1, num2, num3, num4) {\n return num1 * num2 * num3 * num4;\n }\n let arr = [22, 33, 44, 55];\n BtnEle.addEventListener(\"click\", () => {\n resEle.innerHTML = \"Sum of the numbers = \" + addNum.call(this, 22, 33, 44, 55) + \"<br>\";\n resEle.innerHTML +=\"Multiplication of the array elements = \" +multiplyNum.apply(this, arr) +\"<br>\";\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2378, "s": 2340, "text": "On clicking the ‘Click Here’ button −" } ]
MS Project - Track Progress
Once your project plan is ready in MS Project, it becomes essential for a project manager to measure the actuals (in terms of work completed, resources used and costs incurred) and to revise and change information about tasks and resources due to any changes to the plans. A Project Manager should not assume that everything is progressing according to plan and should always keep track of each task. Resistance to formal tracking of project management data is normal. You can overcome resistance to tracking by explaining your expectations, explaining the benefits of tracking, and training people to track the task themselves. To evaluate project performance you need to create a baseline against which you will compare the progress. One needs to save the baseline, once a plan is fully developed. Of course, due to rolling wave planning or progressive elaboration needed to manage projects one can always add new tasks, resources, constraints and costs to the plan. Also note, it makes sense to save the baseline before entering any actual values such as percentage of task completion. Note − With MS Project 2013, you can save up to 11 Baselines in a Single plan. These multiple baselines seem contrary to the definition of baseline. You can use this flexibility when − You have a baseline plan for the external customer and another for the internal team. You have a baseline plan for the external customer and another for the internal team. You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery. You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery. You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder. You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder. Click Project Tab → Schedule group → Set Baseline → OK. Click View Tab → Task Views group → Gantt Chart. Click Format Tab → Bars and Styles group → Baseline (that you want to display). You will see Baseline Gantt bars displayed together with the current Gantt bars. As time and work progresses on a project, you might need to change the baseline as well. You have several options for the same − Update the baseline. Update the baseline for selected tasks. Save multiple baselines. This simply replaces the original baseline values with the currently scheduled values. Click Project Tab → Schedule group → Set Baseline → OK. This does not affect the baseline values for other tasks or resource baseline values in the plan. Click Project Tab → Schedule group → Set Baseline → For select Selected tasks → OK. You can save up to 11 baselines in a single plan. The first one is called Baseline, and the rest are Baseline 1 through Baseline 10. Click Project Tab → Schedule group → Set Baseline → click the dropdown box to save any baseline you like. Click OK. An interim plan saves only two kinds of information for each task − Current start dates and Current finish dates. It can be used as a project marker. It is visually easy to see how off-track or on-track the project progress is. Because it only specifies dates, it is simple, clear and easy information. Click Project Tab → Schedule group → Set Baseline → Set interim plan → OK. If all tasks have started and are finished as scheduled, you can record this in the Update Project dialog box. Most of the times, a seasoned project manager understands that this isn’t true. But sometimes this approach might be fine when the actual work and cost values generated are close enough to your baseline schedule. Click Project tab → Status group → Update Project. Switch on the radio button for “Update work as complete through” option, and then Set 0% -100% complete. Select the current date. Click OK. Check marks will appear in the indicators column for tasks that have been completed. On the right in the Chart portion, progress bars are generated in the Gantt bars of each task. Click any Task → Task Tab → Schedule group → either 0%, 25%, 50%, 75% or 100%. Click View tab → Data group → Tables → Tracking. Now for the required Task, click the corresponding % Comp column and enter the required % complete. You can enter the following actual values for your project − Actual Start and finish dates − Project moves the schedule accordingly. Actual Start and finish dates − Project moves the schedule accordingly. Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete. Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete. Click View Tab → Data group → Tables → Work. You will see the % W. Comp. (% work complete) column. This table includes Work (Scheduled work), Actual, and Remaining columns. Click on Task you want to update. In the following example, Task 9’s Actual field is clicked and 24 hours is entered. For this task, initial scheduled Work was 16 hours, because 24 hours is greater. The project marks the task as 100% complete and updates the Work column to 24 hours (from initial 16 hours). In the example, a Baseline is saved, because the Baseline does not change and is used as a comparison. The Baseline is still at 16 hours and a Variance of 8 hours is now calculated by MS Project. Note − Actual work is rolled up and also reflects on the summary task. Click Task whose dates you would like to change. Click Task tab → Schedule group → dropdown menu for Mark on Track → Update Tasks. Change Start or Finish field in Actual group. You can fill Actual duration field as well. 32 Lectures 2.5 hours Pavan Lalwani 18 Lectures 1.5 hours Dr. Saatya Prasad 102 Lectures 10 hours Pavan Lalwani 52 Lectures 4 hours Pavan Lalwani 239 Lectures 33 hours Gowthami Swarna 53 Lectures 5 hours Akshay Magre Print Add Notes Bookmark this page
[ { "code": null, "e": 2510, "s": 1881, "text": "Once your project plan is ready in MS Project, it becomes essential for a project manager to measure the actuals (in terms of work completed, resources used and costs incurred) and to revise and change information about tasks and resources due to any changes to the plans. A Project Manager should not assume that everything is progressing according to plan and should always keep track of each task. Resistance to formal tracking of project management data is normal. You can overcome resistance to tracking by explaining your expectations, explaining the benefits of tracking, and training people to track the task themselves." }, { "code": null, "e": 2850, "s": 2510, "text": "To evaluate project performance you need to create a baseline against which you will compare the progress. One needs to save the baseline, once a plan is fully developed. Of course, due to rolling wave planning or progressive elaboration needed to manage projects one can always add new tasks, resources, constraints and costs to the plan." }, { "code": null, "e": 2970, "s": 2850, "text": "Also note, it makes sense to save the baseline before entering any actual values such as percentage of task completion." }, { "code": null, "e": 3155, "s": 2970, "text": "Note − With MS Project 2013, you can save up to 11 Baselines in a Single plan. These multiple baselines seem contrary to the definition of baseline. You can use this flexibility when −" }, { "code": null, "e": 3241, "s": 3155, "text": "You have a baseline plan for the external customer and another for the internal team." }, { "code": null, "e": 3327, "s": 3241, "text": "You have a baseline plan for the external customer and another for the internal team." }, { "code": null, "e": 3439, "s": 3327, "text": "You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery." }, { "code": null, "e": 3551, "s": 3439, "text": "You are preparing for a risk event. You want to develop separate baseline plans for risk response and recovery." }, { "code": null, "e": 3702, "s": 3551, "text": "You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder." }, { "code": null, "e": 3853, "s": 3702, "text": "You are accommodating a big change request, you might still want to keep the original plan for future reference when communicating with a stakeholder." }, { "code": null, "e": 3910, "s": 3853, "text": "Click Project Tab → Schedule group → Set Baseline → OK.\n" }, { "code": null, "e": 4041, "s": 3910, "text": "Click View Tab → Task Views group → Gantt Chart.\n\nClick Format Tab → Bars and Styles group → Baseline (that you want to display).\n" }, { "code": null, "e": 4122, "s": 4041, "text": "You will see Baseline Gantt bars displayed together with the current Gantt bars." }, { "code": null, "e": 4251, "s": 4122, "text": "As time and work progresses on a project, you might need to change the baseline as well. You have several options for the same −" }, { "code": null, "e": 4272, "s": 4251, "text": "Update the baseline." }, { "code": null, "e": 4312, "s": 4272, "text": "Update the baseline for selected tasks." }, { "code": null, "e": 4337, "s": 4312, "text": "Save multiple baselines." }, { "code": null, "e": 4424, "s": 4337, "text": "This simply replaces the original baseline values with the currently scheduled values." }, { "code": null, "e": 4481, "s": 4424, "text": "Click Project Tab → Schedule group → Set Baseline → OK.\n" }, { "code": null, "e": 4579, "s": 4481, "text": "This does not affect the baseline values for other tasks or resource baseline values in the plan." }, { "code": null, "e": 4664, "s": 4579, "text": "Click Project Tab → Schedule group → Set Baseline → For select Selected tasks → OK.\n" }, { "code": null, "e": 4797, "s": 4664, "text": "You can save up to 11 baselines in a single plan. The first one is called Baseline, and the rest are Baseline 1 through Baseline 10." }, { "code": null, "e": 4920, "s": 4797, "text": "Click Project Tab → Schedule group → Set Baseline → click \n the dropdown box to save any baseline you like.\n\t\nClick OK.\n" }, { "code": null, "e": 5034, "s": 4920, "text": "An interim plan saves only two kinds of information for each task − Current start dates and Current finish dates." }, { "code": null, "e": 5223, "s": 5034, "text": "It can be used as a project marker. It is visually easy to see how off-track or on-track the project progress is. Because it only specifies dates, it is simple, clear and easy information." }, { "code": null, "e": 5299, "s": 5223, "text": "Click Project Tab → Schedule group → Set Baseline → Set interim plan → OK.\n" }, { "code": null, "e": 5623, "s": 5299, "text": "If all tasks have started and are finished as scheduled, you can record this in the Update Project dialog box. Most of the times, a seasoned project manager understands that this isn’t true. But sometimes this approach might be fine when the actual work and cost values generated are close enough to your baseline schedule." }, { "code": null, "e": 5821, "s": 5623, "text": "Click Project tab → Status group → Update Project.\n\nSwitch on the radio button for “Update work as complete through”\n option, and then Set 0% -100% complete. Select the current date.\n\t\nClick OK.\n" }, { "code": null, "e": 6001, "s": 5821, "text": "Check marks will appear in the indicators column for tasks that have been completed. On the right in the Chart portion, progress bars are generated in the Gantt bars of each task." }, { "code": null, "e": 6081, "s": 6001, "text": "Click any Task → Task Tab → Schedule group → either 0%, 25%, 50%, 75% or 100%.\n" }, { "code": null, "e": 6131, "s": 6081, "text": "Click View tab → Data group → Tables → Tracking.\n" }, { "code": null, "e": 6231, "s": 6131, "text": "Now for the required Task, click the corresponding % Comp column and enter the required % complete." }, { "code": null, "e": 6292, "s": 6231, "text": "You can enter the following actual values for your project −" }, { "code": null, "e": 6364, "s": 6292, "text": "Actual Start and finish dates − Project moves the schedule accordingly." }, { "code": null, "e": 6436, "s": 6364, "text": "Actual Start and finish dates − Project moves the schedule accordingly." }, { "code": null, "e": 6527, "s": 6436, "text": "Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete." }, { "code": null, "e": 6618, "s": 6527, "text": "Task’s Actual duration − If equal or greater than schedule duration: task = 100% complete." }, { "code": null, "e": 6664, "s": 6618, "text": "Click View Tab → Data group → Tables → Work.\n" }, { "code": null, "e": 6718, "s": 6664, "text": "You will see the % W. Comp. (% work complete) column." }, { "code": null, "e": 6792, "s": 6718, "text": "This table includes Work (Scheduled work), Actual, and Remaining columns." }, { "code": null, "e": 7296, "s": 6792, "text": "Click on Task you want to update. In the following example, Task 9’s Actual field is clicked and 24 hours is entered. For this task, initial scheduled Work was 16 hours, because 24 hours is greater. The project marks the task as 100% complete and updates the Work column to 24 hours (from initial 16 hours). In the example, a Baseline is saved, because the Baseline does not change and is used as a comparison. The Baseline is still at 16 hours and a Variance of 8 hours is now calculated by MS Project." }, { "code": null, "e": 7367, "s": 7296, "text": "Note − Actual work is rolled up and also reflects on the summary task." }, { "code": null, "e": 7416, "s": 7367, "text": "Click Task whose dates you would like to change." }, { "code": null, "e": 7546, "s": 7416, "text": "Click Task tab → Schedule group → dropdown menu for Mark on Track → Update Tasks.\n\nChange Start or Finish field in Actual group.\n" }, { "code": null, "e": 7590, "s": 7546, "text": "You can fill Actual duration field as well." }, { "code": null, "e": 7625, "s": 7590, "text": "\n 32 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7640, "s": 7625, "text": " Pavan Lalwani" }, { "code": null, "e": 7675, "s": 7640, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7694, "s": 7675, "text": " Dr. Saatya Prasad" }, { "code": null, "e": 7729, "s": 7694, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 7744, "s": 7729, "text": " Pavan Lalwani" }, { "code": null, "e": 7777, "s": 7744, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 7792, "s": 7777, "text": " Pavan Lalwani" }, { "code": null, "e": 7827, "s": 7792, "text": "\n 239 Lectures \n 33 hours \n" }, { "code": null, "e": 7844, "s": 7827, "text": " Gowthami Swarna" }, { "code": null, "e": 7877, "s": 7844, "text": "\n 53 Lectures \n 5 hours \n" }, { "code": null, "e": 7891, "s": 7877, "text": " Akshay Magre" }, { "code": null, "e": 7898, "s": 7891, "text": " Print" }, { "code": null, "e": 7909, "s": 7898, "text": " Add Notes" } ]
Convert the number from Indian system to International system - GeeksforGeeks
04 Jun, 2020 Given an input string N consisting of numerals and separators (, ) in the Indian Numeric System, the task is to print the string after placing separators(, ) based on International Numeric System. Examples: Input: N = “12, 34, 56, 789”Output: 123, 456, 789 Input: N = “90, 05, 00, 00, 000”Output: 90, 050, 000, 000 Approach: Remove all the separators (, ) from the string.Iterate from the end of the string and place a separator(, ) after every third number.Print the result. Remove all the separators (, ) from the string. Iterate from the end of the string and place a separator(, ) after every third number. Print the result. Below is the implementation of the above approach: C++ // C++ Program to convert// the number from Indian system// to International system #include <bits/stdc++.h>using namespace std; // Function to convert Indian Numeric// System to International Numeric Systemstring convert(string input){ // Length of the input string int len = input.length(); // Removing all the separators(, ) // From the input string for (int i = 0; i < len; i++) { if (input[i] == ',') { input.erase(input.begin() + i); len--; i--; } } // Initialize output string string output = ""; int ctr = 0; // Process the input string for (int i = len - 1; i >= 0; i--) { ctr++; output = input[i] + output; // Add a separator(, ) after // every third digit if (ctr % 3 == 0 && ctr < len) { output = ',' + output; } } // Return the output string back // to the main function return output;} // Driver Codeint main(){ string input1 = "12,34,56,789"; string input2 = "90,05,00,00,000"; cout << convert(input1) << endl; cout << convert(input2) << endl;} 123,456,789 90,050,000,000 Related article: Convert the number from International system to Indian system Mathematical School Programming Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25430, "s": 25402, "text": "\n04 Jun, 2020" }, { "code": null, "e": 25627, "s": 25430, "text": "Given an input string N consisting of numerals and separators (, ) in the Indian Numeric System, the task is to print the string after placing separators(, ) based on International Numeric System." }, { "code": null, "e": 25637, "s": 25627, "text": "Examples:" }, { "code": null, "e": 25687, "s": 25637, "text": "Input: N = “12, 34, 56, 789”Output: 123, 456, 789" }, { "code": null, "e": 25745, "s": 25687, "text": "Input: N = “90, 05, 00, 00, 000”Output: 90, 050, 000, 000" }, { "code": null, "e": 25755, "s": 25745, "text": "Approach:" }, { "code": null, "e": 25906, "s": 25755, "text": "Remove all the separators (, ) from the string.Iterate from the end of the string and place a separator(, ) after every third number.Print the result." }, { "code": null, "e": 25954, "s": 25906, "text": "Remove all the separators (, ) from the string." }, { "code": null, "e": 26041, "s": 25954, "text": "Iterate from the end of the string and place a separator(, ) after every third number." }, { "code": null, "e": 26059, "s": 26041, "text": "Print the result." }, { "code": null, "e": 26110, "s": 26059, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26114, "s": 26110, "text": "C++" }, { "code": "// C++ Program to convert// the number from Indian system// to International system #include <bits/stdc++.h>using namespace std; // Function to convert Indian Numeric// System to International Numeric Systemstring convert(string input){ // Length of the input string int len = input.length(); // Removing all the separators(, ) // From the input string for (int i = 0; i < len; i++) { if (input[i] == ',') { input.erase(input.begin() + i); len--; i--; } } // Initialize output string string output = \"\"; int ctr = 0; // Process the input string for (int i = len - 1; i >= 0; i--) { ctr++; output = input[i] + output; // Add a separator(, ) after // every third digit if (ctr % 3 == 0 && ctr < len) { output = ',' + output; } } // Return the output string back // to the main function return output;} // Driver Codeint main(){ string input1 = \"12,34,56,789\"; string input2 = \"90,05,00,00,000\"; cout << convert(input1) << endl; cout << convert(input2) << endl;}", "e": 27248, "s": 26114, "text": null }, { "code": null, "e": 27276, "s": 27248, "text": "123,456,789\n90,050,000,000\n" }, { "code": null, "e": 27355, "s": 27276, "text": "Related article: Convert the number from International system to Indian system" }, { "code": null, "e": 27368, "s": 27355, "text": "Mathematical" }, { "code": null, "e": 27387, "s": 27368, "text": "School Programming" }, { "code": null, "e": 27395, "s": 27387, "text": "Strings" }, { "code": null, "e": 27403, "s": 27395, "text": "Strings" }, { "code": null, "e": 27416, "s": 27403, "text": "Mathematical" }, { "code": null, "e": 27514, "s": 27416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27538, "s": 27514, "text": "Merge two sorted arrays" }, { "code": null, "e": 27580, "s": 27538, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 27623, "s": 27580, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 27637, "s": 27623, "text": "Prime Numbers" }, { "code": null, "e": 27686, "s": 27637, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 27704, "s": 27686, "text": "Python Dictionary" }, { "code": null, "e": 27720, "s": 27704, "text": "Arrays in C/C++" }, { "code": null, "e": 27739, "s": 27720, "text": "Inheritance in C++" }, { "code": null, "e": 27764, "s": 27739, "text": "Reverse a string in Java" } ]
Create a Date Picker Calendar - Tkinter - GeeksforGeeks
19 Oct, 2021 Prerequisite: Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to create a date picker calendar in Tkinter. In Tkinter, there is no in-built method for date picker calendar, here we will use the tkcalendar Module. tkcalendar: tkcalendar is a Python module that provides the Calendar and DateEntry widgets for Tkinter. For installation run this command into your terminal: pip install tkcalendar Approach: First, we will import the required library Then we will create a Calendar Object and pass the default date Pick the year, month, and date from the calendar For getting the value of the picked date value, use the get() method. Syntax: Calendar(master=None, **kw) year: intCode block it initially displayed year, default is the current year. month: int initially displayed month, default is the current month. day: int initially selected day, if month or year is given but not day, no initial selection, otherwise, default is today. Below is the Implementation:- Python3 # Import Required Libraryfrom tkinter import *from tkcalendar import Calendar # Create Objectroot = Tk() # Set geometryroot.geometry("400x400") # Add Calendarcal = Calendar(root, selectmode = 'day', year = 2020, month = 5, day = 22) cal.pack(pady = 20) def grad_date(): date.config(text = "Selected Date is: " + cal.get_date()) # Add Button and LabelButton(root, text = "Get Date", command = grad_date).pack(pady = 20) date = Label(root, text = "")date.pack(pady = 20) # Execute Tkinterroot.mainloop() Output: simranarora5sos adnanirshad158 Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23927, "s": 23899, "text": "\n19 Oct, 2021" }, { "code": null, "e": 23949, "s": 23927, "text": "Prerequisite: Tkinter" }, { "code": null, "e": 24335, "s": 23949, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to create a date picker calendar in Tkinter." }, { "code": null, "e": 24441, "s": 24335, "text": "In Tkinter, there is no in-built method for date picker calendar, here we will use the tkcalendar Module." }, { "code": null, "e": 24546, "s": 24441, "text": "tkcalendar: tkcalendar is a Python module that provides the Calendar and DateEntry widgets for Tkinter. " }, { "code": null, "e": 24600, "s": 24546, "text": "For installation run this command into your terminal:" }, { "code": null, "e": 24623, "s": 24600, "text": "pip install tkcalendar" }, { "code": null, "e": 24633, "s": 24623, "text": "Approach:" }, { "code": null, "e": 24676, "s": 24633, "text": "First, we will import the required library" }, { "code": null, "e": 24740, "s": 24676, "text": "Then we will create a Calendar Object and pass the default date" }, { "code": null, "e": 24789, "s": 24740, "text": "Pick the year, month, and date from the calendar" }, { "code": null, "e": 24859, "s": 24789, "text": "For getting the value of the picked date value, use the get() method." }, { "code": null, "e": 24895, "s": 24859, "text": "Syntax: Calendar(master=None, **kw)" }, { "code": null, "e": 24915, "s": 24895, "text": "year: intCode block" }, { "code": null, "e": 24973, "s": 24915, "text": "it initially displayed year, default is the current year." }, { "code": null, "e": 24984, "s": 24973, "text": "month: int" }, { "code": null, "e": 25041, "s": 24984, "text": "initially displayed month, default is the current month." }, { "code": null, "e": 25050, "s": 25041, "text": "day: int" }, { "code": null, "e": 25164, "s": 25050, "text": "initially selected day, if month or year is given but not day, no initial selection, otherwise, default is today." }, { "code": null, "e": 25194, "s": 25164, "text": "Below is the Implementation:-" }, { "code": null, "e": 25202, "s": 25194, "text": "Python3" }, { "code": "# Import Required Libraryfrom tkinter import *from tkcalendar import Calendar # Create Objectroot = Tk() # Set geometryroot.geometry(\"400x400\") # Add Calendarcal = Calendar(root, selectmode = 'day', year = 2020, month = 5, day = 22) cal.pack(pady = 20) def grad_date(): date.config(text = \"Selected Date is: \" + cal.get_date()) # Add Button and LabelButton(root, text = \"Get Date\", command = grad_date).pack(pady = 20) date = Label(root, text = \"\")date.pack(pady = 20) # Execute Tkinterroot.mainloop()", "e": 25741, "s": 25202, "text": null }, { "code": null, "e": 25749, "s": 25741, "text": "Output:" }, { "code": null, "e": 25765, "s": 25749, "text": "simranarora5sos" }, { "code": null, "e": 25780, "s": 25765, "text": "adnanirshad158" }, { "code": null, "e": 25805, "s": 25780, "text": "Python Tkinter-exercises" }, { "code": null, "e": 25820, "s": 25805, "text": "Python-tkinter" }, { "code": null, "e": 25827, "s": 25820, "text": "Python" }, { "code": null, "e": 25925, "s": 25827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25934, "s": 25925, "text": "Comments" }, { "code": null, "e": 25947, "s": 25934, "text": "Old Comments" }, { "code": null, "e": 25983, "s": 25947, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26006, "s": 25983, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26045, "s": 26006, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26078, "s": 26045, "text": "Python | Convert set into a list" }, { "code": null, "e": 26127, "s": 26078, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26168, "s": 26127, "text": "Python - Call function from another file" }, { "code": null, "e": 26184, "s": 26168, "text": "loops in python" }, { "code": null, "e": 26235, "s": 26184, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26267, "s": 26235, "text": "Python Dictionary keys() method" } ]
Most useful Python functions for Time Series Analysis | by Sivakar Sivarajah | Towards Data Science
These type of data are sequentially ordered data over time and these observations are typically collected at regular intervals, this could be: Every Second/Minute/Hour Daily Monthly Quarterly/Yearly Some Real-life Examples are: Monthly Sales Data Stock Market prices Hourly Weather Data/Wind Speed IoT(Internet of things) Sensors in Industries and Smart Devices Energy Forecasting Trends show the general tendency of the data to increase or decrease during a long period of time. Generally, a trend is a smooth, general, long-term, average tendency. Seasonality: refers to periodic fluctuations. For example, electricity consumption is high during the day and low during the night, similarly online sales go up during Christmas before going down again. Stationarity is a key characteristic of the time series. A time series is said to be stationary if its statistical properties do not change over time. In other words, it has constant mean and variance, and covariance is independent of time. i.e. A Stock price is not a stationary series, since we might see a growing or decreasing trend and its volatility might increase over time(meaning that variance is changing). Ideally, we want to have a stationary time series for modelling. In real-world scenarios, not all of them are stationary, but we can make different transformations to make them stationary. I will use The Daily Delhi Climate recording going over the span from 2013 to 2017. The dataset has got 4 features but for this tutorial, I am going to specifically use only the Humidity Column. As we can see data from the plot above the data looks stationary and there are few ways to check that! let's look at them ADF test is the most commonly used test the Stationarity of the series, where the null hypothesis is the time series possesses a unit root and is non-stationary. So if the p-Value in ADH test is less than the significance level (0.05) we reject the null hypothesis. Null Hypothesis: The series has a unit root (value of a =1) Alternate Hypothesis: The series has no unit root. KPSS((Kwiatkowski-Phillips-Schmidt-Shin) test is another test for checking the stationarity of a time series. However, the null and alternate hypothesis for the KPSS test are opposite that of the ADF test, which often creates confusion. (You could see in the code below the conditions are opposite) Null Hypothesis: The process is trend stationery. Alternate Hypothesis: The series has a unit root (series is not stationary). It’s always better to apply both the tests, so that we are sure that the series is truly stationary. Autocorrelation is important because it can help us discover patterns in our time series, successfully select the best modelling algorithm, correctly evaluate the effectiveness of our model. Specifically, autocorrelation and partial autocorrelation plots are heavily used to summarize the strength and relationship within observations in a time series with observations at prior time steps. When there is a strong seasonal pattern, we can see in the ACF plot usually defined repeated spikes at the multiples of the seasonal window. For instance in most “monthly sales time series ” you should be able to see spikes at around at 12th, 24th, 36th.. lines explaining the rise of sales with the advent of Christmas holidays. Any time series may be split into the following components: Base Level Trend Seasonality Error However, It is not mandatory that all-time series must have a trend and/or seasonality. A time series may not have a distinct trend but have a seasonality. The opposite can also be true.[1] Depending on the nature of the trend and seasonality, a time series can be modelled as an additive or multiplicative, wherein, each observation in the series can be expressed as either a sum or a product of the components: # Actual Values = Addition of (Seasonality + Trend + Residual) The df.resample() function let us resample our time series to our desired frequencies: A number of string aliases are given to use common time series frequencies, these are referred as offset aliases. Let’s have a look at a few resamplings using these offset aliases. Calculates the alegbric difference between one Dataframe element with another element, the default is one meaning it “differences” the element with the prevoius element. Here there is an example with our humidity coloumn As shown above df[:5]. diff(2) takes the difference between the first and third element of the column, consequently the second and fourth element, and so on. Calculate the Percentage change between the current and a prior element. Computes the percentage change from the immediately previous row by default. This is useful in comparing the percentage of change in a time series of elements. Now let's try to calculate the average mean over all the months, years and day of the week. We will apply pct_change to see how the pattern changed compared to the previous. Humidity means over all the months, years and day of the week Note: there is an anomaly in the 2017(“year”) humidity mean! The 2017 data have only one record! therefore this anomaly. fig, (ax1, ax2,ax3) = plt.subplots(3,figsize=(30,30))ax1.plot(week_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='g')ax1.set_title('Weekly Pct_change');ax2.plot(month_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='r')ax2.set_title('Monthly Pct_change ');ax3.plot(year_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='b')ax3.set_title('Yearly Pct_change'); The shift function shifts the data before or after the specified amount of time. Shift index by desired number of periods with an optional time freq. If not specified by default it will shift the data by one day as shown above. if for instance, we want to shift the data by 365 days we could do: df[:5]shift(365) Provide rolling window calculations or i.e Moving average calculations Moving Average is doing the mathematical average of a rolling window of defined width. You should choose the window-width wisely, a large window-size will over-smooth the series. A window-size bigger than or equal to the seasonal duration will effectively nullify the seasonal effect. In the figure below you can see clearly that a window of less than five is likely to be the threshold as we go up with the bigger window sizes, the series is over-smoothed. When choosing the window you have the option to test and chose a different type of Window, Below there is an example with a few types. This provide exponential weighted (EW) functions, weighing more the current values rather than historic values. In this post, I have tried to explain most of the useful pandas and statistical testing functions for time series analysis. If you could run all the code above, you should have some knowledge on how to perform an analysis on a time series use-case. It will take a lot of practice to become proficient at using all these functions! If you already know these functions I am happy to have refreshed your memory and skills. Thanks for reaching until here, if you want to learn more about modelling, analyzing and much more on time series, I highly recommend Youtube channel: AI engineering (by Srivatsan Srinivasan) playlist on Time Series, the latter is rich with a lot of quality information, check it out :) More Reading: towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com References: [1] ML+. 2020. Time Series Analysis In Python — A Comprehensive Guide With Examples — ML+. [online] Available at:https://www.machinelearningplus.com/time-series/time-series-analysis-python/ .
[ { "code": null, "e": 315, "s": 172, "text": "These type of data are sequentially ordered data over time and these observations are typically collected at regular intervals, this could be:" }, { "code": null, "e": 340, "s": 315, "text": "Every Second/Minute/Hour" }, { "code": null, "e": 346, "s": 340, "text": "Daily" }, { "code": null, "e": 354, "s": 346, "text": "Monthly" }, { "code": null, "e": 371, "s": 354, "text": "Quarterly/Yearly" }, { "code": null, "e": 400, "s": 371, "text": "Some Real-life Examples are:" }, { "code": null, "e": 419, "s": 400, "text": "Monthly Sales Data" }, { "code": null, "e": 439, "s": 419, "text": "Stock Market prices" }, { "code": null, "e": 470, "s": 439, "text": "Hourly Weather Data/Wind Speed" }, { "code": null, "e": 534, "s": 470, "text": "IoT(Internet of things) Sensors in Industries and Smart Devices" }, { "code": null, "e": 553, "s": 534, "text": "Energy Forecasting" }, { "code": null, "e": 722, "s": 553, "text": "Trends show the general tendency of the data to increase or decrease during a long period of time. Generally, a trend is a smooth, general, long-term, average tendency." }, { "code": null, "e": 925, "s": 722, "text": "Seasonality: refers to periodic fluctuations. For example, electricity consumption is high during the day and low during the night, similarly online sales go up during Christmas before going down again." }, { "code": null, "e": 1342, "s": 925, "text": "Stationarity is a key characteristic of the time series. A time series is said to be stationary if its statistical properties do not change over time. In other words, it has constant mean and variance, and covariance is independent of time. i.e. A Stock price is not a stationary series, since we might see a growing or decreasing trend and its volatility might increase over time(meaning that variance is changing)." }, { "code": null, "e": 1531, "s": 1342, "text": "Ideally, we want to have a stationary time series for modelling. In real-world scenarios, not all of them are stationary, but we can make different transformations to make them stationary." }, { "code": null, "e": 1726, "s": 1531, "text": "I will use The Daily Delhi Climate recording going over the span from 2013 to 2017. The dataset has got 4 features but for this tutorial, I am going to specifically use only the Humidity Column." }, { "code": null, "e": 1848, "s": 1726, "text": "As we can see data from the plot above the data looks stationary and there are few ways to check that! let's look at them" }, { "code": null, "e": 2114, "s": 1848, "text": "ADF test is the most commonly used test the Stationarity of the series, where the null hypothesis is the time series possesses a unit root and is non-stationary. So if the p-Value in ADH test is less than the significance level (0.05) we reject the null hypothesis." }, { "code": null, "e": 2174, "s": 2114, "text": "Null Hypothesis: The series has a unit root (value of a =1)" }, { "code": null, "e": 2225, "s": 2174, "text": "Alternate Hypothesis: The series has no unit root." }, { "code": null, "e": 2335, "s": 2225, "text": "KPSS((Kwiatkowski-Phillips-Schmidt-Shin) test is another test for checking the stationarity of a time series." }, { "code": null, "e": 2524, "s": 2335, "text": "However, the null and alternate hypothesis for the KPSS test are opposite that of the ADF test, which often creates confusion. (You could see in the code below the conditions are opposite)" }, { "code": null, "e": 2574, "s": 2524, "text": "Null Hypothesis: The process is trend stationery." }, { "code": null, "e": 2651, "s": 2574, "text": "Alternate Hypothesis: The series has a unit root (series is not stationary)." }, { "code": null, "e": 2752, "s": 2651, "text": "It’s always better to apply both the tests, so that we are sure that the series is truly stationary." }, { "code": null, "e": 3143, "s": 2752, "text": "Autocorrelation is important because it can help us discover patterns in our time series, successfully select the best modelling algorithm, correctly evaluate the effectiveness of our model. Specifically, autocorrelation and partial autocorrelation plots are heavily used to summarize the strength and relationship within observations in a time series with observations at prior time steps." }, { "code": null, "e": 3473, "s": 3143, "text": "When there is a strong seasonal pattern, we can see in the ACF plot usually defined repeated spikes at the multiples of the seasonal window. For instance in most “monthly sales time series ” you should be able to see spikes at around at 12th, 24th, 36th.. lines explaining the rise of sales with the advent of Christmas holidays." }, { "code": null, "e": 3533, "s": 3473, "text": "Any time series may be split into the following components:" }, { "code": null, "e": 3544, "s": 3533, "text": "Base Level" }, { "code": null, "e": 3550, "s": 3544, "text": "Trend" }, { "code": null, "e": 3562, "s": 3550, "text": "Seasonality" }, { "code": null, "e": 3568, "s": 3562, "text": "Error" }, { "code": null, "e": 3758, "s": 3568, "text": "However, It is not mandatory that all-time series must have a trend and/or seasonality. A time series may not have a distinct trend but have a seasonality. The opposite can also be true.[1]" }, { "code": null, "e": 3981, "s": 3758, "text": "Depending on the nature of the trend and seasonality, a time series can be modelled as an additive or multiplicative, wherein, each observation in the series can be expressed as either a sum or a product of the components:" }, { "code": null, "e": 4044, "s": 3981, "text": "# Actual Values = Addition of (Seasonality + Trend + Residual)" }, { "code": null, "e": 4312, "s": 4044, "text": "The df.resample() function let us resample our time series to our desired frequencies: A number of string aliases are given to use common time series frequencies, these are referred as offset aliases. Let’s have a look at a few resamplings using these offset aliases." }, { "code": null, "e": 4533, "s": 4312, "text": "Calculates the alegbric difference between one Dataframe element with another element, the default is one meaning it “differences” the element with the prevoius element. Here there is an example with our humidity coloumn" }, { "code": null, "e": 4691, "s": 4533, "text": "As shown above df[:5]. diff(2) takes the difference between the first and third element of the column, consequently the second and fourth element, and so on." }, { "code": null, "e": 4764, "s": 4691, "text": "Calculate the Percentage change between the current and a prior element." }, { "code": null, "e": 4924, "s": 4764, "text": "Computes the percentage change from the immediately previous row by default. This is useful in comparing the percentage of change in a time series of elements." }, { "code": null, "e": 5098, "s": 4924, "text": "Now let's try to calculate the average mean over all the months, years and day of the week. We will apply pct_change to see how the pattern changed compared to the previous." }, { "code": null, "e": 5160, "s": 5098, "text": "Humidity means over all the months, years and day of the week" }, { "code": null, "e": 5281, "s": 5160, "text": "Note: there is an anomaly in the 2017(“year”) humidity mean! The 2017 data have only one record! therefore this anomaly." }, { "code": null, "e": 5764, "s": 5281, "text": "fig, (ax1, ax2,ax3) = plt.subplots(3,figsize=(30,30))ax1.plot(week_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='g')ax1.set_title('Weekly Pct_change');ax2.plot(month_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='r')ax2.set_title('Monthly Pct_change ');ax3.plot(year_mean_df.Percentage_increase,marker='o', linestyle='--', linewidth=5,markersize=30, color='b')ax3.set_title('Yearly Pct_change');" }, { "code": null, "e": 5845, "s": 5764, "text": "The shift function shifts the data before or after the specified amount of time." }, { "code": null, "e": 5992, "s": 5845, "text": "Shift index by desired number of periods with an optional time freq. If not specified by default it will shift the data by one day as shown above." }, { "code": null, "e": 6060, "s": 5992, "text": "if for instance, we want to shift the data by 365 days we could do:" }, { "code": null, "e": 6077, "s": 6060, "text": "df[:5]shift(365)" }, { "code": null, "e": 6148, "s": 6077, "text": "Provide rolling window calculations or i.e Moving average calculations" }, { "code": null, "e": 6433, "s": 6148, "text": "Moving Average is doing the mathematical average of a rolling window of defined width. You should choose the window-width wisely, a large window-size will over-smooth the series. A window-size bigger than or equal to the seasonal duration will effectively nullify the seasonal effect." }, { "code": null, "e": 6606, "s": 6433, "text": "In the figure below you can see clearly that a window of less than five is likely to be the threshold as we go up with the bigger window sizes, the series is over-smoothed." }, { "code": null, "e": 6741, "s": 6606, "text": "When choosing the window you have the option to test and chose a different type of Window, Below there is an example with a few types." }, { "code": null, "e": 6853, "s": 6741, "text": "This provide exponential weighted (EW) functions, weighing more the current values rather than historic values." }, { "code": null, "e": 7273, "s": 6853, "text": "In this post, I have tried to explain most of the useful pandas and statistical testing functions for time series analysis. If you could run all the code above, you should have some knowledge on how to perform an analysis on a time series use-case. It will take a lot of practice to become proficient at using all these functions! If you already know these functions I am happy to have refreshed your memory and skills." }, { "code": null, "e": 7560, "s": 7273, "text": "Thanks for reaching until here, if you want to learn more about modelling, analyzing and much more on time series, I highly recommend Youtube channel: AI engineering (by Srivatsan Srinivasan) playlist on Time Series, the latter is rich with a lot of quality information, check it out :)" }, { "code": null, "e": 7574, "s": 7560, "text": "More Reading:" }, { "code": null, "e": 7597, "s": 7574, "text": "towardsdatascience.com" }, { "code": null, "e": 7620, "s": 7597, "text": "towardsdatascience.com" }, { "code": null, "e": 7643, "s": 7620, "text": "towardsdatascience.com" }, { "code": null, "e": 7666, "s": 7643, "text": "towardsdatascience.com" }, { "code": null, "e": 7678, "s": 7666, "text": "References:" } ]
Calculate sine of a value in R Programming - sin() Function - GeeksforGeeks
01 Jun, 2020 sin() function in R Language is used to calculate the sine value of the numeric value passed to it as argument. Syntax: sin(x) Parameter:x: Numeric value Example 1: # R code to calculate sine of a value # Assigning values to variablesx1 <- -90x2 <- -30 # Using sin() Functionsin(x1)sin(x2) Output: [1] -0.8939967 [1] 0.9880316 Example 2: # R code to calculate sine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using sin() Functionsin(x1)sin(x2) Output: [1] 1.224647e-16 [1] 0.8660254 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Control Statements in R Programming How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr Data Visualization in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Logistic Regression in R Programming Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 24419, "s": 24391, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24531, "s": 24419, "text": "sin() function in R Language is used to calculate the sine value of the numeric value passed to it as argument." }, { "code": null, "e": 24546, "s": 24531, "text": "Syntax: sin(x)" }, { "code": null, "e": 24573, "s": 24546, "text": "Parameter:x: Numeric value" }, { "code": null, "e": 24584, "s": 24573, "text": "Example 1:" }, { "code": "# R code to calculate sine of a value # Assigning values to variablesx1 <- -90x2 <- -30 # Using sin() Functionsin(x1)sin(x2)", "e": 24711, "s": 24584, "text": null }, { "code": null, "e": 24719, "s": 24711, "text": "Output:" }, { "code": null, "e": 24748, "s": 24719, "text": "[1] -0.8939967\n[1] 0.9880316" }, { "code": null, "e": 24759, "s": 24748, "text": "Example 2:" }, { "code": "# R code to calculate sine of a value # Assigning values to variablesx1 <- pix2 <- pi / 3 # Using sin() Functionsin(x1)sin(x2)", "e": 24888, "s": 24759, "text": null }, { "code": null, "e": 24896, "s": 24888, "text": "Output:" }, { "code": null, "e": 24927, "s": 24896, "text": "[1] 1.224647e-16\n[1] 0.8660254" }, { "code": null, "e": 24943, "s": 24927, "text": "R Math-Function" }, { "code": null, "e": 24954, "s": 24943, "text": "R Language" }, { "code": null, "e": 25052, "s": 24954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25061, "s": 25052, "text": "Comments" }, { "code": null, "e": 25074, "s": 25061, "text": "Old Comments" }, { "code": null, "e": 25110, "s": 25074, "text": "Control Statements in R Programming" }, { "code": null, "e": 25168, "s": 25110, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25200, "s": 25168, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25252, "s": 25200, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25287, "s": 25252, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25311, "s": 25287, "text": "Data Visualization in R" }, { "code": null, "e": 25355, "s": 25311, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25393, "s": 25355, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25430, "s": 25393, "text": "Logistic Regression in R Programming" } ]
How to train and predict regression and classification ML models using only SQL — using BigQuery ML | by Lak Lakshmanan | Towards Data Science
In my book (Data Science on the Google Cloud Platform), I walk through a flight-delay prediction problem and show how to address it using a variety of tools including Spark Mlib and TensorFlow. Now that BigQuery ML has been announced, I thought I’d show how to predict flight delays using BQ ML. Make no mistake — you still have to collect the data, explore it, clean it up, and enrich it. Essentially all the stuff I do in Chapter 1–9. In Chapter 10, I used TensorFlow. In this article, I will use BQML. Here’s a BigQuery query to create the model: #standardsqlCREATE OR REPLACE MODEL flights.arrdelayOPTIONS (model_type='linear_reg', input_label_cols=['arr_delay']) ASSELECT arr_delay, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL Note that: It starts with a CREATE MODEL, with the name of the model looking just like a table name. Note: ‘flights’ is the name of the dataset to store the resulting model — so, you’ll need to create an empty dataset before running the query.The options specify the algorithm — in this case, a linear regression algorithm, with arr_delay being the labelEssentially, I’m pulling in the predictor and label variables in the SELECT It starts with a CREATE MODEL, with the name of the model looking just like a table name. Note: ‘flights’ is the name of the dataset to store the resulting model — so, you’ll need to create an empty dataset before running the query. The options specify the algorithm — in this case, a linear regression algorithm, with arr_delay being the label Essentially, I’m pulling in the predictor and label variables in the SELECT About 10 minutes later, the model is trained and evaluation results have been populated for each iteration: The loss here is mean squared error, so the model converges on iteration #6 with a RMSE of about sqrt(97) = 10 minutes. The purpose of training a model is to predict with it. You can do model predictions with a SQL statement: #standardsqlSELECT * FROM ML.PREDICT(MODEL flights.arrdelay,(SELECT carrier, origin, dest, dep_delay, taxi_out, distance, arr_delay AS actual_arr_delayFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULLLIMIT 10)) This results in: As you can see, because we trained the model to predict a variable called “arr_delay”, ML.PREDICT creates a result column named predicted_arr_delay. In this case, I’m pulling 10 rows from the original table and predicting the arrival delay for those flights. In the book, I don’t actually try to predict the arrival delay as such. Instead, I predict the probability that a flight will be more than 15 minutes late. This is a classification problem, and you can do that by changing the training query slightly: #standardsqlCREATE OR REPLACE MODEL flights.ontimeOPTIONS (model_type='logistic_reg', input_label_cols=['on_time']) ASSELECT IF(arr_delay < 15, 1, 0) AS on_time, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL Here’s the evaluation results: and an example of the predictions: It is possible to evaluate the model on an independent dataset. I don’t have one handy, so I’ll just show you how to run the evaluation on the same dataset the model was trained on: #standardsqlSELECT * FROM ML.EVALUATE(MODEL flights.ontime,(SELECT IF(arr_delay < 15, 1, 0) AS on_time, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL)) The result: BQML is really easy and really powerful. Enjoy!
[ { "code": null, "e": 468, "s": 172, "text": "In my book (Data Science on the Google Cloud Platform), I walk through a flight-delay prediction problem and show how to address it using a variety of tools including Spark Mlib and TensorFlow. Now that BigQuery ML has been announced, I thought I’d show how to predict flight delays using BQ ML." }, { "code": null, "e": 677, "s": 468, "text": "Make no mistake — you still have to collect the data, explore it, clean it up, and enrich it. Essentially all the stuff I do in Chapter 1–9. In Chapter 10, I used TensorFlow. In this article, I will use BQML." }, { "code": null, "e": 722, "s": 677, "text": "Here’s a BigQuery query to create the model:" }, { "code": null, "e": 992, "s": 722, "text": "#standardsqlCREATE OR REPLACE MODEL flights.arrdelayOPTIONS (model_type='linear_reg', input_label_cols=['arr_delay']) ASSELECT arr_delay, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL" }, { "code": null, "e": 1003, "s": 992, "text": "Note that:" }, { "code": null, "e": 1422, "s": 1003, "text": "It starts with a CREATE MODEL, with the name of the model looking just like a table name. Note: ‘flights’ is the name of the dataset to store the resulting model — so, you’ll need to create an empty dataset before running the query.The options specify the algorithm — in this case, a linear regression algorithm, with arr_delay being the labelEssentially, I’m pulling in the predictor and label variables in the SELECT" }, { "code": null, "e": 1655, "s": 1422, "text": "It starts with a CREATE MODEL, with the name of the model looking just like a table name. Note: ‘flights’ is the name of the dataset to store the resulting model — so, you’ll need to create an empty dataset before running the query." }, { "code": null, "e": 1767, "s": 1655, "text": "The options specify the algorithm — in this case, a linear regression algorithm, with arr_delay being the label" }, { "code": null, "e": 1843, "s": 1767, "text": "Essentially, I’m pulling in the predictor and label variables in the SELECT" }, { "code": null, "e": 1951, "s": 1843, "text": "About 10 minutes later, the model is trained and evaluation results have been populated for each iteration:" }, { "code": null, "e": 2071, "s": 1951, "text": "The loss here is mean squared error, so the model converges on iteration #6 with a RMSE of about sqrt(97) = 10 minutes." }, { "code": null, "e": 2177, "s": 2071, "text": "The purpose of training a model is to predict with it. You can do model predictions with a SQL statement:" }, { "code": null, "e": 2417, "s": 2177, "text": "#standardsqlSELECT * FROM ML.PREDICT(MODEL flights.arrdelay,(SELECT carrier, origin, dest, dep_delay, taxi_out, distance, arr_delay AS actual_arr_delayFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULLLIMIT 10))" }, { "code": null, "e": 2434, "s": 2417, "text": "This results in:" }, { "code": null, "e": 2693, "s": 2434, "text": "As you can see, because we trained the model to predict a variable called “arr_delay”, ML.PREDICT creates a result column named predicted_arr_delay. In this case, I’m pulling 10 rows from the original table and predicting the arrival delay for those flights." }, { "code": null, "e": 2944, "s": 2693, "text": "In the book, I don’t actually try to predict the arrival delay as such. Instead, I predict the probability that a flight will be more than 15 minutes late. This is a classification problem, and you can do that by changing the training query slightly:" }, { "code": null, "e": 3238, "s": 2944, "text": "#standardsqlCREATE OR REPLACE MODEL flights.ontimeOPTIONS (model_type='logistic_reg', input_label_cols=['on_time']) ASSELECT IF(arr_delay < 15, 1, 0) AS on_time, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL" }, { "code": null, "e": 3269, "s": 3238, "text": "Here’s the evaluation results:" }, { "code": null, "e": 3304, "s": 3269, "text": "and an example of the predictions:" }, { "code": null, "e": 3486, "s": 3304, "text": "It is possible to evaluate the model on an independent dataset. I don’t have one handy, so I’ll just show you how to run the evaluation on the same dataset the model was trained on:" }, { "code": null, "e": 3723, "s": 3486, "text": "#standardsqlSELECT * FROM ML.EVALUATE(MODEL flights.ontime,(SELECT IF(arr_delay < 15, 1, 0) AS on_time, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL))" }, { "code": null, "e": 3735, "s": 3723, "text": "The result:" } ]
Update _id field in MongoDB
To update, just save new ID and remove the old one using remove(). Let us first create a collection with documents − > db.updatingDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04dae5150ee0e76c06a04b") } > db.updatingDemo.insertOne({"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04dae7150ee0e76c06a04c") } Following is the query to display all documents from a collection with the help of find() method − > db.updatingDemo.find(); This will produce the following output − { "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" } { "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" } Here is the query to update _id in MongoDB − > myDocument = db.updatingDemo.findOne({"StudentName":"Bob"}); { "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" } > myDocument._id = 1001; 1001 > db.updatingDemo.insert(myDocument); WriteResult({ "nInserted" : 1 }) > db.updatingDemo.remove({_id:ObjectId("5e04dae7150ee0e76c06a04c")}); WriteResult({ "nRemoved" : 1 }) Following is the query to display all documents from a collection with the help of find() method − > db.updatingDemo.find(); This will produce the following output − { "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" } { "_id" : 1001, "StudentName" : "Bob" }
[ { "code": null, "e": 1179, "s": 1062, "text": "To update, just save new ID and remove the old one using remove(). Let us first create a collection with documents −" }, { "code": null, "e": 1456, "s": 1179, "text": "> db.updatingDemo.insertOne({\"StudentName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04dae5150ee0e76c06a04b\")\n}\n> db.updatingDemo.insertOne({\"StudentName\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04dae7150ee0e76c06a04c\")\n}" }, { "code": null, "e": 1555, "s": 1456, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1581, "s": 1555, "text": "> db.updatingDemo.find();" }, { "code": null, "e": 1622, "s": 1581, "text": "This will produce the following output −" }, { "code": null, "e": 1769, "s": 1622, "text": "{ \"_id\" : ObjectId(\"5e04dae5150ee0e76c06a04b\"), \"StudentName\" : \"Robert\" }\n{ \"_id\" : ObjectId(\"5e04dae7150ee0e76c06a04c\"), \"StudentName\" : \"Bob\" }" }, { "code": null, "e": 1814, "s": 1769, "text": "Here is the query to update _id in MongoDB −" }, { "code": null, "e": 2152, "s": 1814, "text": "> myDocument = db.updatingDemo.findOne({\"StudentName\":\"Bob\"});\n{ \"_id\" : ObjectId(\"5e04dae7150ee0e76c06a04c\"), \"StudentName\" : \"Bob\" }\n> myDocument._id = 1001;\n1001\n> db.updatingDemo.insert(myDocument);\nWriteResult({ \"nInserted\" : 1 })\n> db.updatingDemo.remove({_id:ObjectId(\"5e04dae7150ee0e76c06a04c\")});\nWriteResult({ \"nRemoved\" : 1 })" }, { "code": null, "e": 2251, "s": 2152, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2277, "s": 2251, "text": "> db.updatingDemo.find();" }, { "code": null, "e": 2318, "s": 2277, "text": "This will produce the following output −" }, { "code": null, "e": 2433, "s": 2318, "text": "{ \"_id\" : ObjectId(\"5e04dae5150ee0e76c06a04b\"), \"StudentName\" : \"Robert\" }\n{ \"_id\" : 1001, \"StudentName\" : \"Bob\" }" } ]
CSS | flex-grow Property - GeeksforGeeks
24 Aug, 2021 The flex-grow property specifies how much the item will grow compared to others item inside that container. In other words, it is the ability of an item to grow compared to other items present inside the same container. Note: If the item in the container is not flexible item then the flex-grow property will not affect that item. Syntax: flex-grow: number| initial| inherit; Default Value: 0 Property values: number: A number that defines how the item will grow compare to other flexible items. initial: It sets the value to it’s default value. inherit: It inherit the property from it’s parent elements. Example: Here we are going to see in a single container there are 5 divs, we will apply the flex-grow: On 2nd div and that div will grow compare to other 4 divs. We can apply flex-grow on any document in the same container that div will grow compared to other div’s width, the flex-grow property will help that div to grow in comparison to other items in that container. HTML <!DOCTYPE html><html> <head> <title> CSS | flex-grow Property </title> <style> #main { width: 350px; height: 100px; border: 1px solid black; display: -webkit-flex; display: flex; color: white; text-align: center; } h1 { color: #009900; font-size: 42px; margin-left: 50px; } h3 { margin-top: -20px; margin-left: 50px; } #main div:nth-of-type(1) { flex-grow: 1; } #main div:nth-of-type(2) { flex-grow: 5; } #main div:nth-of-type(3) { flex-grow: 1; } #main div:nth-of-type(4) { flex-grow: 1; } #main div:nth-of-type(5) { flex-grow: 1; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>The flex-grow:number</h3> <!-- Making 5 divs in main --> <div id="main"> <div style="background-color:#009900;"> Sql</div> <div style="background-color:#00cc99;"> Python</div> <div style="background-color:#0066ff;"> Java</div> <div style="background-color:#66ffff;;"> C++</div> <div style="background-color:#660066;"> C#</div> </div></body> </html> Output: Supported Browser: The browser supported by CSS | flex-grow Property are listed below: Google Chrome 29.0 Internet Explorer 11.0 Mozilla Firefox 28.0 Opera 17.0 Safari 9.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 ManasChhabra2 CSS-Properties Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? CSS to put icon inside an input element in a form Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 23688, "s": 23660, "text": "\n24 Aug, 2021" }, { "code": null, "e": 23908, "s": 23688, "text": "The flex-grow property specifies how much the item will grow compared to others item inside that container. In other words, it is the ability of an item to grow compared to other items present inside the same container." }, { "code": null, "e": 24019, "s": 23908, "text": "Note: If the item in the container is not flexible item then the flex-grow property will not affect that item." }, { "code": null, "e": 24029, "s": 24019, "text": "Syntax: " }, { "code": null, "e": 24066, "s": 24029, "text": "flex-grow: number| initial| inherit;" }, { "code": null, "e": 24082, "s": 24066, "text": "Default Value: " }, { "code": null, "e": 24084, "s": 24082, "text": "0" }, { "code": null, "e": 24103, "s": 24084, "text": "Property values: " }, { "code": null, "e": 24189, "s": 24103, "text": "number: A number that defines how the item will grow compare to other flexible items." }, { "code": null, "e": 24239, "s": 24189, "text": "initial: It sets the value to it’s default value." }, { "code": null, "e": 24299, "s": 24239, "text": "inherit: It inherit the property from it’s parent elements." }, { "code": null, "e": 24670, "s": 24299, "text": "Example: Here we are going to see in a single container there are 5 divs, we will apply the flex-grow: On 2nd div and that div will grow compare to other 4 divs. We can apply flex-grow on any document in the same container that div will grow compared to other div’s width, the flex-grow property will help that div to grow in comparison to other items in that container." }, { "code": null, "e": 24675, "s": 24670, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | flex-grow Property </title> <style> #main { width: 350px; height: 100px; border: 1px solid black; display: -webkit-flex; display: flex; color: white; text-align: center; } h1 { color: #009900; font-size: 42px; margin-left: 50px; } h3 { margin-top: -20px; margin-left: 50px; } #main div:nth-of-type(1) { flex-grow: 1; } #main div:nth-of-type(2) { flex-grow: 5; } #main div:nth-of-type(3) { flex-grow: 1; } #main div:nth-of-type(4) { flex-grow: 1; } #main div:nth-of-type(5) { flex-grow: 1; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3>The flex-grow:number</h3> <!-- Making 5 divs in main --> <div id=\"main\"> <div style=\"background-color:#009900;\"> Sql</div> <div style=\"background-color:#00cc99;\"> Python</div> <div style=\"background-color:#0066ff;\"> Java</div> <div style=\"background-color:#66ffff;;\"> C++</div> <div style=\"background-color:#660066;\"> C#</div> </div></body> </html> ", "e": 26092, "s": 24675, "text": null }, { "code": null, "e": 26102, "s": 26092, "text": "Output: " }, { "code": null, "e": 26191, "s": 26102, "text": "Supported Browser: The browser supported by CSS | flex-grow Property are listed below: " }, { "code": null, "e": 26210, "s": 26191, "text": "Google Chrome 29.0" }, { "code": null, "e": 26233, "s": 26210, "text": "Internet Explorer 11.0" }, { "code": null, "e": 26254, "s": 26233, "text": "Mozilla Firefox 28.0" }, { "code": null, "e": 26265, "s": 26254, "text": "Opera 17.0" }, { "code": null, "e": 26276, "s": 26265, "text": "Safari 9.0" }, { "code": null, "e": 26415, "s": 26278, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26432, "s": 26415, "text": "arorakashish0911" }, { "code": null, "e": 26446, "s": 26432, "text": "ManasChhabra2" }, { "code": null, "e": 26461, "s": 26446, "text": "CSS-Properties" }, { "code": null, "e": 26468, "s": 26461, "text": "Picked" }, { "code": null, "e": 26492, "s": 26468, "text": "Technical Scripter 2018" }, { "code": null, "e": 26496, "s": 26492, "text": "CSS" }, { "code": null, "e": 26501, "s": 26496, "text": "HTML" }, { "code": null, "e": 26520, "s": 26501, "text": "Technical Scripter" }, { "code": null, "e": 26537, "s": 26520, "text": "Web Technologies" }, { "code": null, "e": 26542, "s": 26537, "text": "HTML" }, { "code": null, "e": 26640, "s": 26542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26702, "s": 26640, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26752, "s": 26702, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26810, "s": 26752, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26858, "s": 26810, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26908, "s": 26858, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26970, "s": 26908, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27020, "s": 26970, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27080, "s": 27020, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27128, "s": 27080, "text": "How to update Node.js and NPM to next version ?" } ]
Kotlin - Sets
Kotlin set is an unordered collection of items. A Kotlin set can be either mutable (mutableSetOf) or read-only (setOf). Kotlin mutable or immutable sets do not allow to have duplicate elements. For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for mutable sets. fun main() { val theSet = setOf("one", "two", "three", "four") println(theSet) val theMutableSet = mutableSetOf("one", "two", "three", "four") println(theMutableSet) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] [one, two, three, four] There are various ways to loop through a Kotlin Set. Lets study them one by one: fun main() { val theSet = setOf("one", "two", "three", "four") println(theSet.toString()) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four] fun main() { val theSet = setOf("one", "two", "three", "four") val itr = theSet.asIterable().iterator() while (itr.hasNext()) { println(itr.next()) } } When you run the above Kotlin program, it will generate the following output: one two three four fun main() { val theSet = setOf("one", "two", "three", "four") for (i in theSet.indices) { println(theSet.elementAt(i)) } } When you run the above Kotlin program, it will generate the following output: one two three four fun main() { val theSet = setOf("one", "two", "three", "four") theSet.forEach { println(it) } } When you run the above Kotlin program, it will generate the following output: one two three four We can use size property to get the total number of elements in a set: fun main() { val theSet = setOf("one", "two", null, "four", "five") println("Size of the Set " + theSet.size) } When you run the above Kotlin program, it will generate the following output: Size of the Set 5 The in operator can be used to check the existence of an element in a set. fun main() { val theSet = setOf("one", "two", "three", "four") if("two" in theSet){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: true The contain() method can also be used to check the existence of an element in a set. fun main() { val theSet = setOf("one", "two", "three", "four") if(theSet.contains("two")){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: true The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise. fun main() { val theSet = setOf("one", "two", "three", "four") if(theSet.isEmpty()){ println(true) }else{ println(false) } } When you run the above Kotlin program, it will generate the following output: false The indexOf() method returns the index of the first occurrence of the specified element in the set, or -1 if the specified element is not contained in the set. fun main() { val theSet = setOf("one", "two", "three", "four") println("Index of 'two' - " + theSet.indexOf("two")) } When you run the above Kotlin program, it will generate the following output: Index of 'two' - 1 The elementAt() method can be used to get the element at the specified index in the set. fun main() { val theSet = setOf("one", "two", "three", "four") println("Element at 3rd position " + theSet.elementAt(2)) } When you run the above Kotlin program, it will generate the following output: Element at 3rd position three We can use + operator to add two or more sets into a single set. This will add second set into first set, discarding the duplicate elements. fun main() { val firstSet = setOf("one", "two", "three") val secondSet = setOf("one", "four", "five", "six") val resultSet = firstSet + secondSet println(resultSet) } When you run the above Kotlin program, it will generate the following output: [one, two, three, four, five, six] We can use - operator to subtract a set from another set. This operation will remove the common elements from the first set and will return the result. fun main() { val firstSet = setOf("one", "two", "three") val secondSet = setOf("one", "five", "six") val resultSet = firstSet - secondSet println(resultSet) } When you run the above Kotlin program, it will generate the following output: [two, three] We can use filterNotNull() method to remove null element from a set. fun main() { val theSet = setOf("one", "two", null, "four", "five") val resultSet = theSet.filterNotNull() println(resultSet) } When you run the above Kotlin program, it will generate the following output: [one, two, four, five] We can use sorted() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) var resultSet = theSet.sorted() println(resultSet) resultSet = theSet.sortedDescending() println(resultSet) } When you run the above Kotlin program, it will generate the following output: [-1, 0, 10, 20, 30, 31, 40, 50] [50, 40, 31, 30, 20, 10, 0, -1] We can use filter() method to filter out the elements matching with the given predicate. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) val resultSet = theSet.filter{ it > 30} println(resultSet) } When you run the above Kotlin program, it will generate the following output: [31, 40, 50] We can use drop() method to drop first N elements from the set. fun main() { val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0) val resultSet = theSet.drop(3) println(resultSet) } When you run the above Kotlin program, it will generate the following output: [31, 40, 50, -1, 0] We can use groupBy() method to group the elements matching with the given predicate. fun main() { val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0) val resultSet = theSet.groupBy{ it % 3} println(resultSet) } When you run the above Kotlin program, it will generate the following output: {1=[10, 31, 40], 0=[12, 30, 9, -3, 0]} We can use map() method to map all elements using the provided function:. fun main() { val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0) val resultSet = theSet.map{ it / 3 } println(resultSet) } When you run the above Kotlin program, it will generate the following output: [3, 4, 10, 10, 13, 3, -1, 0] We can use chunked() method to create chunks of the given size from a set. Last chunk may not have the elements equal to the number of chunk size based on the total number of elements in the set. fun main() { val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0) val resultSet = theSet.chunked(3) println(resultSet) } When you run the above Kotlin program, it will generate the following output: [[10, 12, 30], [31, 40, 9], [-3, 0]] We can use windowed() method to a set of element ranges by moving a sliding window of a given size over a collection of elements. fun main() { val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0) val resultSet = theSet.windowed(3) println(resultSet) } When you run the above Kotlin program, it will generate the following output: [[10, 12, 30], [12, 30, 31], [30, 31, 40], [31, 40, 9], [40, 9, -3], [9, -3, 0]] By default, the sliding window moves one step further each time but we can change that by passing a custom step value: fun main() { val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0) val resultSet = theSet.windowed(3, 3) println(resultSet) } When you run the above Kotlin program, it will generate the following output: [[10, 12, 30], [31, 40, 9]] We can create mutable set using mutableSetOf(), later we can use add() to add more elements in the same set, and we can use remove() method to remove the elements from the set. fun main() { val theSet = mutableSetOf(10, 20, 30) theSet.add(40) theSet.add(50) println(theSet) theSet.remove(10) theSet.remove(30) println(theSet) } When you run the above Kotlin program, it will generate the following output: [10, 20, 30, 40, 50] [20, 40, 50] Q 1 - Can we make a mutable Kotlin set as immutable? A - Yes B - No Yes we can make a mutable set to immutable by casting them to Set Q 2 - We can add two or more sets and create a single set using + operator: A - True B - False Yes we can add or subtract two Kotlin sets and generate a third set. A plus sign works like a union() for set. Q 2 - Which method will return an item from the given index of Kotlin set? A - get() B - elementAt() C - Direct index with set variable D - None of the above elementAt() method is used to get the list element from the given index. 68 Lectures 4.5 hours Arnab Chakraborty 71 Lectures 5.5 hours Frahaan Hussain 18 Lectures 1.5 hours Mahmoud Ramadan 49 Lectures 6 hours Catalin Stefan 49 Lectures 2.5 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG Print Add Notes Bookmark this page
[ { "code": null, "e": 2619, "s": 2425, "text": "Kotlin set is an unordered collection of items. A Kotlin set can be either mutable (mutableSetOf) or read-only (setOf). Kotlin mutable or immutable sets do not allow to have duplicate elements." }, { "code": null, "e": 2736, "s": 2619, "text": "For set creation, use the standard library functions setOf() for read-only sets and mutableSetOf() for mutable sets." }, { "code": null, "e": 2926, "s": 2736, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n println(theSet)\n \n val theMutableSet = mutableSetOf(\"one\", \"two\", \"three\", \"four\")\n println(theMutableSet)\n}\n" }, { "code": null, "e": 3004, "s": 2926, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3053, "s": 3004, "text": "[one, two, three, four]\n[one, two, three, four]\n" }, { "code": null, "e": 3134, "s": 3053, "text": "There are various ways to loop through a Kotlin Set. Lets study them one by one:" }, { "code": null, "e": 3235, "s": 3134, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n println(theSet.toString())\n}\n" }, { "code": null, "e": 3313, "s": 3235, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3338, "s": 3313, "text": "[one, two, three, four]\n" }, { "code": null, "e": 3519, "s": 3338, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n val itr = theSet.asIterable().iterator()\n while (itr.hasNext()) {\n println(itr.next())\n }\n}\n" }, { "code": null, "e": 3597, "s": 3519, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3617, "s": 3597, "text": "one\ntwo\nthree\nfour\n" }, { "code": null, "e": 3762, "s": 3617, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n for (i in theSet.indices) {\n println(theSet.elementAt(i))\n }\n}\n" }, { "code": null, "e": 3840, "s": 3762, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3860, "s": 3840, "text": "one\ntwo\nthree\nfour\n" }, { "code": null, "e": 3968, "s": 3860, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n theSet.forEach { println(it) }\n}\n" }, { "code": null, "e": 4046, "s": 3968, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4066, "s": 4046, "text": "one\ntwo\nthree\nfour\n" }, { "code": null, "e": 4137, "s": 4066, "text": "We can use size property to get the total number of elements in a set:" }, { "code": null, "e": 4263, "s": 4137, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", null, \"four\", \"five\")\n \n println(\"Size of the Set \" + theSet.size)\n}\n" }, { "code": null, "e": 4341, "s": 4263, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4360, "s": 4341, "text": "Size of the Set 5\n" }, { "code": null, "e": 4435, "s": 4360, "text": "The in operator can be used to check the existence of an element in a set." }, { "code": null, "e": 4589, "s": 4435, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n if(\"two\" in theSet){\n println(true)\n }else{\n println(false)\n }\n}\n" }, { "code": null, "e": 4667, "s": 4589, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4673, "s": 4667, "text": "true\n" }, { "code": null, "e": 4758, "s": 4673, "text": "The contain() method can also be used to check the existence of an element in a set." }, { "code": null, "e": 4920, "s": 4758, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n\n if(theSet.contains(\"two\")){\n println(true)\n }else{\n println(false)\n }\n \n}\n" }, { "code": null, "e": 4998, "s": 4920, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 5004, "s": 4998, "text": "true\n" }, { "code": null, "e": 5106, "s": 5004, "text": "The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise." }, { "code": null, "e": 5261, "s": 5106, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n if(theSet.isEmpty()){\n println(true)\n }else{\n println(false)\n }\n}\n" }, { "code": null, "e": 5339, "s": 5261, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 5346, "s": 5339, "text": "false\n" }, { "code": null, "e": 5506, "s": 5346, "text": "The indexOf() method returns the index of the first occurrence of the specified element in the set, or -1 if the specified element is not contained in the set." }, { "code": null, "e": 5637, "s": 5506, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n \n println(\"Index of 'two' - \" + theSet.indexOf(\"two\"))\n}\n" }, { "code": null, "e": 5715, "s": 5637, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 5736, "s": 5715, "text": "Index of 'two' - 1\n" }, { "code": null, "e": 5825, "s": 5736, "text": "The elementAt() method can be used to get the element at the specified index in the set." }, { "code": null, "e": 5956, "s": 5825, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", \"three\", \"four\")\n\n println(\"Element at 3rd position \" + theSet.elementAt(2))\n}\n" }, { "code": null, "e": 6034, "s": 5956, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 6065, "s": 6034, "text": "Element at 3rd position three\n" }, { "code": null, "e": 6206, "s": 6065, "text": "We can use + operator to add two or more sets into a single set. This will add second set into first set, discarding the duplicate elements." }, { "code": null, "e": 6395, "s": 6206, "text": "fun main() {\n val firstSet = setOf(\"one\", \"two\", \"three\")\n val secondSet = setOf(\"one\", \"four\", \"five\", \"six\")\n val resultSet = firstSet + secondSet\n \n println(resultSet)\n}\n" }, { "code": null, "e": 6473, "s": 6395, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 6509, "s": 6473, "text": "[one, two, three, four, five, six]\n" }, { "code": null, "e": 6661, "s": 6509, "text": "We can use - operator to subtract a set from another set. This operation will remove the common elements from the first set and will return the result." }, { "code": null, "e": 6842, "s": 6661, "text": "fun main() {\n val firstSet = setOf(\"one\", \"two\", \"three\")\n val secondSet = setOf(\"one\", \"five\", \"six\")\n val resultSet = firstSet - secondSet\n \n println(resultSet)\n}\n" }, { "code": null, "e": 6920, "s": 6842, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 6934, "s": 6920, "text": "[two, three]\n" }, { "code": null, "e": 7003, "s": 6934, "text": "We can use filterNotNull() method to remove null element from a set." }, { "code": null, "e": 7149, "s": 7003, "text": "fun main() {\n val theSet = setOf(\"one\", \"two\", null, \"four\", \"five\")\n val resultSet = theSet.filterNotNull()\n \n println(resultSet)\n}\n" }, { "code": null, "e": 7227, "s": 7149, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 7251, "s": 7227, "text": "[one, two, four, five]\n" }, { "code": null, "e": 7394, "s": 7251, "text": "We can use sorted() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order." }, { "code": null, "e": 7593, "s": 7394, "text": "fun main() {\n val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)\n var resultSet = theSet.sorted()\n println(resultSet)\n \n resultSet = theSet.sortedDescending()\n println(resultSet)\n}\n" }, { "code": null, "e": 7671, "s": 7593, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 7736, "s": 7671, "text": "[-1, 0, 10, 20, 30, 31, 40, 50]\n[50, 40, 31, 30, 20, 10, 0, -1]\n" }, { "code": null, "e": 7825, "s": 7736, "text": "We can use filter() method to filter out the elements matching with the given predicate." }, { "code": null, "e": 7967, "s": 7825, "text": "fun main() {\n val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)\n val resultSet = theSet.filter{ it > 30}\n \n println(resultSet)\n}\n" }, { "code": null, "e": 8045, "s": 7967, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 8059, "s": 8045, "text": "[31, 40, 50]\n" }, { "code": null, "e": 8123, "s": 8059, "text": "We can use drop() method to drop first N elements from the set." }, { "code": null, "e": 8256, "s": 8123, "text": "fun main() {\n val theSet = setOf(10, 20, 30, 31, 40, 50, -1, 0)\n val resultSet = theSet.drop(3)\n \n println(resultSet)\n}\n" }, { "code": null, "e": 8334, "s": 8256, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 8355, "s": 8334, "text": "[31, 40, 50, -1, 0]\n" }, { "code": null, "e": 8440, "s": 8355, "text": "We can use groupBy() method to group the elements matching with the given predicate." }, { "code": null, "e": 8581, "s": 8440, "text": "fun main() {\n val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)\n val resultSet = theSet.groupBy{ it % 3}\n \n println(resultSet)\n}\n" }, { "code": null, "e": 8659, "s": 8581, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 8699, "s": 8659, "text": "{1=[10, 31, 40], 0=[12, 30, 9, -3, 0]}\n" }, { "code": null, "e": 8773, "s": 8699, "text": "We can use map() method to map all elements using the provided function:." }, { "code": null, "e": 8911, "s": 8773, "text": "fun main() {\n val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)\n val resultSet = theSet.map{ it / 3 }\n \n println(resultSet)\n}\n" }, { "code": null, "e": 8989, "s": 8911, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 9019, "s": 8989, "text": "[3, 4, 10, 10, 13, 3, -1, 0]\n" }, { "code": null, "e": 9215, "s": 9019, "text": "We can use chunked() method to create chunks of the given size from a set. Last chunk may not have the elements equal to the number of chunk size based on the total number of elements in the set." }, { "code": null, "e": 9350, "s": 9215, "text": "fun main() {\n val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)\n val resultSet = theSet.chunked(3)\n \n println(resultSet)\n}\n" }, { "code": null, "e": 9428, "s": 9350, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 9466, "s": 9428, "text": "[[10, 12, 30], [31, 40, 9], [-3, 0]]\n" }, { "code": null, "e": 9596, "s": 9466, "text": "We can use windowed() method to a set of element ranges by moving a sliding window of a given size over a collection of elements." }, { "code": null, "e": 9732, "s": 9596, "text": "fun main() {\n val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)\n val resultSet = theSet.windowed(3)\n \n println(resultSet)\n}\n" }, { "code": null, "e": 9810, "s": 9732, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 9892, "s": 9810, "text": "[[10, 12, 30], [12, 30, 31], [30, 31, 40], [31, 40, 9], [40, 9, -3], [9, -3, 0]]\n" }, { "code": null, "e": 10011, "s": 9892, "text": "By default, the sliding window moves one step further each time but we can change that by passing a custom step value:" }, { "code": null, "e": 10150, "s": 10011, "text": "fun main() {\n val theSet = setOf(10, 12, 30, 31, 40, 9, -3, 0)\n val resultSet = theSet.windowed(3, 3)\n \n println(resultSet)\n}\n" }, { "code": null, "e": 10228, "s": 10150, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 10257, "s": 10228, "text": "[[10, 12, 30], [31, 40, 9]]\n" }, { "code": null, "e": 10434, "s": 10257, "text": "We can create mutable set using mutableSetOf(), later we can use add() to add more elements in the same set, and we can use remove() method to remove the elements from the set." }, { "code": null, "e": 10629, "s": 10434, "text": "fun main() {\n val theSet = mutableSetOf(10, 20, 30)\n \n theSet.add(40)\n theSet.add(50)\n println(theSet)\n \n theSet.remove(10)\n theSet.remove(30)\n println(theSet)\n \n}\n" }, { "code": null, "e": 10707, "s": 10629, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 10742, "s": 10707, "text": "[10, 20, 30, 40, 50]\n[20, 40, 50]\n" }, { "code": null, "e": 10795, "s": 10742, "text": "Q 1 - Can we make a mutable Kotlin set as immutable?" }, { "code": null, "e": 10803, "s": 10795, "text": "A - Yes" }, { "code": null, "e": 10810, "s": 10803, "text": "B - No" }, { "code": null, "e": 10876, "s": 10810, "text": "Yes we can make a mutable set to immutable by casting them to Set" }, { "code": null, "e": 10952, "s": 10876, "text": "Q 2 - We can add two or more sets and create a single set using + operator:" }, { "code": null, "e": 10961, "s": 10952, "text": "A - True" }, { "code": null, "e": 10971, "s": 10961, "text": "B - False" }, { "code": null, "e": 11082, "s": 10971, "text": "Yes we can add or subtract two Kotlin sets and generate a third set. A plus sign works like a union() for set." }, { "code": null, "e": 11157, "s": 11082, "text": "Q 2 - Which method will return an item from the given index of Kotlin set?" }, { "code": null, "e": 11167, "s": 11157, "text": "A - get()" }, { "code": null, "e": 11183, "s": 11167, "text": "B - elementAt()" }, { "code": null, "e": 11218, "s": 11183, "text": "C - Direct index with set variable" }, { "code": null, "e": 11240, "s": 11218, "text": "D - None of the above" }, { "code": null, "e": 11313, "s": 11240, "text": "elementAt() method is used to get the list element from the given index." }, { "code": null, "e": 11348, "s": 11313, "text": "\n 68 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11367, "s": 11348, "text": " Arnab Chakraborty" }, { "code": null, "e": 11402, "s": 11367, "text": "\n 71 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11419, "s": 11402, "text": " Frahaan Hussain" }, { "code": null, "e": 11454, "s": 11419, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 11471, "s": 11454, "text": " Mahmoud Ramadan" }, { "code": null, "e": 11504, "s": 11471, "text": "\n 49 Lectures \n 6 hours \n" }, { "code": null, "e": 11520, "s": 11504, "text": " Catalin Stefan" }, { "code": null, "e": 11555, "s": 11520, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11575, "s": 11555, "text": " Skillbakerystudios" }, { "code": null, "e": 11608, "s": 11575, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 11625, "s": 11608, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 11632, "s": 11625, "text": " Print" }, { "code": null, "e": 11643, "s": 11632, "text": " Add Notes" } ]
Working With The Lambda Layer in Keras | by Ahmed Gad | Towards Data Science
In this tutorial we’ll cover how to use the Lambda layer in Keras to build, save, and load models which perform custom operations on your data. Keras is a popular and easy-to-use library for building deep learning models. It supports all known type of layers: input, dense, convolutional, transposed convolution, reshape, normalization, dropout, flatten, and activation. Each layer performs a particular operations on the data. That being said, you might want to perform an operation over the data that is not applied in any of the existing layers, and then these preexisting layer types will not be enough for your task. As a trivial example, imagine you need a layer that performs the operation of adding a fixed number at a given point of the model architecture. Because there is no existing layer that does this, you can build one yourself. In this tutorial we’ll discuss using the Lambda layer in Keras. This allows you to specify the operation to be applied as a function. We'll also see how to debug the Keras loading feature when building a model that has lambda layers. The sections covered in this tutorial are as follows: Building a Keras model using the Functional API Adding a Lambda layer Passing more than one tensor to the lambda layer Saving and loading a model with a lambda layer Solving the SystemError while loading a model with a lambda layer There are three different APIs which can be used to build a model in Keras: Sequential APIFunctional APIModel Subclassing API Sequential API Functional API Model Subclassing API You can find more information about each of these in this post, but in this tutorial we’ll focus on using the Keras Functional API for building a custom model. Since we want to focus on our architecture, we'll just use a simple problem example and build a model which recognizes images in the MNIST dataset. To build a model in Keras you stack layers on top of one another. These layers are available in the keras.layers module (imported below). The module name is prepended by tensorflow because we use TensorFlow as a backend for Keras. import tensorflow.keras.layers The first layer to create is the Input layer. This is created using the tensorflow.keras.layers.Input() class. One of the necessary arguments to be passed to the constructor of this class is the shape argument which specifies the shape of each sample in the data that will be used for training. In this tutorial we're just going to use dense layers for starters, and thus the input should be 1-D vector. The shape argument is thus assigned a tuple with one value (shown below). The value is 784 because the size of each image in the MNIST dataset is 28 x 28 = 784. An optional name argument specifies the name of that layer. input_layer = tensorflow.keras.layers.Input(shape=(784), name="input_layer") The next layer is a dense layer created using the Dense class according to the code below. It accepts an argument named units to specify the number of neurons in this layer. Note how this layer is connected to the input layer by specifying the name of that layer in parentheses. This is because a layer instance in the functional API is callable on a tensor, and also returns a tensor. dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name="dense_layer_1")(input_layer) Following the dense layer, an activation layer is created using the ReLU class according to the next line. activ_layer_1 = tensorflow.keras.layers.ReLU(name="activ_layer_1")(dense_layer_1) Another couple of dense-ReLu layers are added according to the following lines. dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name="dense_layer_2")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name="relu_layer_2")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name="dense_layer_3")(activ_layer_2)activ_layer_3 = tensorflow.keras.layers.ReLU(name="relu_layer_3")(dense_layer_3) The next line adds the last layer to the network architecture according to the number of classes in the MNIST dataset. Because the MNIST dataset includes 10 classes (one for each number), the number of units used in this layer is 10. dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name="dense_layer_4")(activ_layer_3) To return the score for each class, a softmax layer is added after the previous dense layer according to the next line. output_layer = tensorflow.keras.layers.Softmax(name="output_layer")(dense_layer_4) We’ve now connected the layers but the model is not yet created. To build a model we must now use the Model class, as shown below. The first two arguments it accepts represent the input and output layers. model = tensorflow.keras.models.Model(input_layer, output_layer, name="model") Before loading the dataset and training the model, we have to compile the model using the compile() method. model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss="categorical_crossentropy") Using model.summary() we can see an overview of the model architecture. The input layer accepts a tensor of shape (None, 784) which means that each sample must be reshaped into a vector of 784 elements. The output Softmax layer returns 10 numbers, each being the score for that class of the MNIST dataset. _________________________________________________________________Layer (type) Output Shape Param # =================================================================input_layer (InputLayer) [(None, 784)] 0 _________________________________________________________________dense_layer_1 (Dense) (None, 500) 392500 _________________________________________________________________relu_layer_1 (ReLU) (None, 500) 0 _________________________________________________________________dense_layer_2 (Dense) (None, 250) 125250 _________________________________________________________________relu_layer_2 (ReLU) (None, 250) 0 _________________________________________________________________dense_layer_3 (Dense) (None, 20) 12550 _________________________________________________________________relu_layer_3 (ReLU) (None, 20) 0 _________________________________________________________________dense_layer_4 (Dense) (None, 10) 510 _________________________________________________________________output_layer (Softmax) (None, 10) 0 =================================================================Total params: 530,810Trainable params: 530,810Non-trainable params: 0_________________________________________________________________ Now that we’ve built and compiled the model, let’s see how the dataset is prepared. First we’ll load MNIST from the keras.datasets module, got their data type changed to float64 because this makes training the network easier than leaving its values in the 0-255 range, and finally reshaped so that each sample is a vector of 784 elements. (x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.mnist.load_data()x_train = x_train.astype(numpy.float64) / 255.0x_test = x_test.astype(numpy.float64) / 255.0x_train = x_train.reshape((x_train.shape[0], numpy.prod(x_train.shape[1:])))x_test = x_test.reshape((x_test.shape[0], numpy.prod(x_test.shape[1:]))) Because the used loss function in the compile() method is categorical_crossentropy, the labels of the samples should be on hot encoded according to the next code. y_test = tensorflow.keras.utils.to_categorical(y_test)y_train = tensorflow.keras.utils.to_categorical(y_train) Finally, the model training starts using the fit() method. model.fit(x_train, y_train, epochs=20, batch_size=256, validation_data=(x_test, y_test)) At this point, we have created the model architecture using the already existing types of layers. The next section discusses using the Lambda layer for building custom operations. Let’s say that after the dense layer named dense_layer_3 we'd like to do some sort of operation on the tensor, such as adding the value 2 to each element. How can we do that? None of the existing layers does this, so we'll have to build a new layer ourselves. Fortunately, the Lambda layer exists for precisely that purpose. Let's discuss how to use it. Start by building the function that will do the operation you want. In this case, a function named custom_layer is created as follows. It just accepts the input tensor(s) and returns another tensor as output. If more than one tensor is to be passed to the function, then they will be passed as a list. In this example just a single tensor is fed as input, and 2 is added to each element in the input tensor. def custom_layer(tensor): return tensor + 2 After building the function that defines the operation, next we need to create the lambda layer using the Lambda class as defined in the next line. In this case, only one tensor is fed to the custom_layer function because the lambda layer is callable on the single tensor returned by the dense layer named dense_layer_3. lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")(dense_layer_3) Here is the code that builds the full network after using the lambda layer. input_layer = tensorflow.keras.layers.Input(shape=(784), name="input_layer")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name="dense_layer_1")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name="relu_layer_1")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name="dense_layer_2")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name="relu_layer_2")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name="dense_layer_3")(activ_layer_2)def custom_layer(tensor): return tensor + 2lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")(dense_layer_3)activ_layer_3 = tensorflow.keras.layers.ReLU(name="relu_layer_3")(lambda_layer)dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name="dense_layer_4")(activ_layer_3)output_layer = tensorflow.keras.layers.Softmax(name="output_layer")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name="model") In order to see the tensor before and after being fed to the lambda layer we’ll create two new models in addition to the previous one. We’ll call these before_lambda_model and after_lambda_model. Both models use the input layer as their inputs, but the output layer differs. The before_lambda_model model returns the output of dense_layer_3 which is the layer that exists exactly before the lambda layer. The output of the after_lambda_model model is the output from the lambda layer named lambda_layer. By doing this, we can see the input before and the output after applying the lambda layer. before_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_3, name="before_lambda_model")after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name="after_lambda_model") The complete code that builds and trains the entire network is listed below. import tensorflow.keras.layersimport tensorflow.keras.modelsimport tensorflow.keras.optimizersimport tensorflow.keras.datasetsimport tensorflow.keras.utilsimport tensorflow.keras.backendimport numpyinput_layer = tensorflow.keras.layers.Input(shape=(784), name="input_layer")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name="dense_layer_1")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name="relu_layer_1")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name="dense_layer_2")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name="relu_layer_2")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name="dense_layer_3")(activ_layer_2)before_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_3, name="before_lambda_model")def custom_layer(tensor): return tensor + 2lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")(dense_layer_3)after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name="after_lambda_model")activ_layer_3 = tensorflow.keras.layers.ReLU(name="relu_layer_3")(lambda_layer)dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name="dense_layer_4")(activ_layer_3)output_layer = tensorflow.keras.layers.Softmax(name="output_layer")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name="model")model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss="categorical_crossentropy")model.summary()(x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.mnist.load_data()x_train = x_train.astype(numpy.float64) / 255.0x_test = x_test.astype(numpy.float64) / 255.0x_train = x_train.reshape((x_train.shape[0], numpy.prod(x_train.shape[1:])))x_test = x_test.reshape((x_test.shape[0], numpy.prod(x_test.shape[1:])))y_test = tensorflow.keras.utils.to_categorical(y_test)y_train = tensorflow.keras.utils.to_categorical(y_train)model.fit(x_train, y_train, epochs=20, batch_size=256, validation_data=(x_test, y_test)) Note that you do not have to compile or train the 2 newly created models because their layers are actually reused from the main model that exists in the model variable. After that model is trained, we can use the predict() method for returning the outputs of the before_lambda_model and after_lambda_model models to see how the result of the lambda layer. p = model.predict(x_train)m1 = before_lambda_model.predict(x_train)m2 = after_lambda_model.predict(x_train) The next code just prints the outputs of the first 2 samples. As you can see, each element returned from the m2 array is actually the result of m1 after adding 2. This is exactly the operation we applied in our custom lambda layer. print(m1[0, :])print(m2[0, :])[ 14.420735 8.872794 25.369402 1.4622561 5.672293 2.5202641 -14.753801 -3.8822086 -1.0581762 -6.4336205 13.342142 -3.0627508 -5.694006 -6.557313 -1.6567478 -3.8457105 11.891999 20.581928 2.669979 -8.092522 ][ 16.420734 10.872794 27.369402 3.462256 7.672293 4.520264 -12.753801 -1.8822086 0.94182384 -4.4336205 15.342142 -1.0627508 -3.694006 -4.557313 0.34325218 -1.8457105 13.891999 22.581928 4.669979 -6.0925217 ] In this section the lambda layer was used to do an operation over a single input tensor. In the next section we see how we can pass two input tensors to this layer. Assume that we want to do an operation that depends on the two layers named dense_layer_3 and relu_layer_3. In this case we have to call the lambda layer while passing two tensors. This is simply done by creating a list with all of these tensors, as given in the next line. lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")([dense_layer_3, activ_layer_3]) This list is passed to the custom_layer() function and we can fetch the individual layers simply according to the next code. It just adds these two layers together. There is actually layer in Keras named Add that can be used for adding two layers or more, but we are just presenting how you could do it yourself in case there's another operation not supported by Keras. def custom_layer(tensor): tensor1 = tensor[0] tensor2 = tensor[1] return tensor1 + tensor2 The next code builds three models: two for capturing the outputs from the dense_layer_3 and activ_layer_3 passed to the lambda layer, and another one for capturing the output from the lambda layer itself. before_lambda_model1 = tensorflow.keras.models.Model(input_layer, dense_layer_3, name="before_lambda_model1")before_lambda_model2 = tensorflow.keras.models.Model(input_layer, activ_layer_3, name="before_lambda_model2")lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")([dense_layer_3, activ_layer_3])after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name="after_lambda_model") To see the outputs from the dense_layer_3, activ_layer_3, and lambda_layer layers, the next code predicts their outputs and prints it. m1 = before_lambda_model1.predict(x_train)m2 = before_lambda_model2.predict(x_train)m3 = after_lambda_model.predict(x_train)print(m1[0, :])print(m2[0, :])print(m3[0, :]) [ 1.773366 -3.4378722 0.22042789 11.220362 3.4020965 14.487111 4.239182 -6.8589864 -6.428128 -5.477719 -8.799093 7.264849 17.503246 -6.809489 -6.846208 16.094025 24.483786 -7.084775 17.341183 20.311539 ][ 1.773366 0. 0.22042789 11.220362 3.4020965 14.487111 4.239182 0. 0. 0. 0. 7.264849 17.503246 0. 0. 16.094025 24.483786 0. 17.341183 20.311539 ][ 3.546732 -3.4378722 0.44085577 22.440723 6.804193 28.974222 8.478364 -6.8589864 -6.428128 -5.477719 -8.799093 14.529698 35.006493 -6.809489 -6.846208 32.18805 48.96757 -7.084775 34.682365 40.623077 ] Using the lambda layer is now clear. The next section discusses how you can save and load a model that uses a lambda layer. In order to save a model (whether it uses a lambda layer or not) the save() method is used. Assuming we are just interested in saving the main model, here's the line that saves it. model.save("model.h5") We can also load the saved model using the load_model() method, as in the next line. loaded_model = tensorflow.keras.models.load_model("model.h5") Hopefully, the model could be successfully loaded. Unfortunately there are some issues in Keras that may result in the SystemError: unknown opcode while loading a model with a lambda layer. It might be due to building the model using a Python version and using it in another version. We are going to discuss the solution in the next section. To solve this issue we’re not going to save the model in the way discussed above. Instead, we’ll save the model weights using the save_weights() method. Now we’ve only saved the weights. What about the model architecture? The model architecture will be recreated using the code. Why not save the model architecture as a JSON file and then load it again? The reason is that the error persists after loading the architecture. In summary, the trained model weights will be saved, the model architecture will be reproduced using the code, and finally the weights will be loaded into that architecture. The weights of the model can be saved using the next line. model.save_weights('model_weights.h5') Here’s the code that reproduces the model architecture. The model will not be trained, but the saved weights will be assigned to it again. input_layer = tensorflow.keras.layers.Input(shape=(784), name="input_layer")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name="dense_layer_1")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name="relu_layer_1")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name="dense_layer_2")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name="relu_layer_2")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name="dense_layer_3")(activ_layer_2)activ_layer_3 = tensorflow.keras.layers.ReLU(name="relu_layer_3")(dense_layer_3)def custom_layer(tensor): tensor1 = tensor[0] tensor2 = tensor[1] epsilon = tensorflow.keras.backend.random_normal(shape=tensorflow.keras.backend.shape(tensor1), mean=0.0, stddev=1.0) random_sample = tensor1 + tensorflow.keras.backend.exp(tensor2/2) * epsilon return random_samplelambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name="lambda_layer")([dense_layer_3, activ_layer_3])dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name="dense_layer_4")(lambda_layer)after_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_4, name="after_lambda_model")output_layer = tensorflow.keras.layers.Softmax(name="output_layer")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name="model")model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss="categorical_crossentropy") Here’s how the saved weights are loaded using the load_weights() method, and assigned to the reproduced architecture. model.load_weights('model_weights.h5') This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient. This tutorial discussed using the Lambda layer to create custom layers which do operations not supported by the predefined layers in Keras. The constructor of the Lambda class accepts a function that specifies how the layer works, and the function accepts the tensor(s) that the layer is called on. Inside the function, you can perform whatever operations you want and then return the modified tensors. Although Keras has an issue with loading models that use the lambda layer, we also saw how to solve this simply by saving the trained model weights, reproducing the model architecture using code, and loading the weights into this architecture.
[ { "code": null, "e": 191, "s": 47, "text": "In this tutorial we’ll cover how to use the Lambda layer in Keras to build, save, and load models which perform custom operations on your data." }, { "code": null, "e": 475, "s": 191, "text": "Keras is a popular and easy-to-use library for building deep learning models. It supports all known type of layers: input, dense, convolutional, transposed convolution, reshape, normalization, dropout, flatten, and activation. Each layer performs a particular operations on the data." }, { "code": null, "e": 892, "s": 475, "text": "That being said, you might want to perform an operation over the data that is not applied in any of the existing layers, and then these preexisting layer types will not be enough for your task. As a trivial example, imagine you need a layer that performs the operation of adding a fixed number at a given point of the model architecture. Because there is no existing layer that does this, you can build one yourself." }, { "code": null, "e": 1126, "s": 892, "text": "In this tutorial we’ll discuss using the Lambda layer in Keras. This allows you to specify the operation to be applied as a function. We'll also see how to debug the Keras loading feature when building a model that has lambda layers." }, { "code": null, "e": 1180, "s": 1126, "text": "The sections covered in this tutorial are as follows:" }, { "code": null, "e": 1228, "s": 1180, "text": "Building a Keras model using the Functional API" }, { "code": null, "e": 1250, "s": 1228, "text": "Adding a Lambda layer" }, { "code": null, "e": 1299, "s": 1250, "text": "Passing more than one tensor to the lambda layer" }, { "code": null, "e": 1346, "s": 1299, "text": "Saving and loading a model with a lambda layer" }, { "code": null, "e": 1412, "s": 1346, "text": "Solving the SystemError while loading a model with a lambda layer" }, { "code": null, "e": 1488, "s": 1412, "text": "There are three different APIs which can be used to build a model in Keras:" }, { "code": null, "e": 1538, "s": 1488, "text": "Sequential APIFunctional APIModel Subclassing API" }, { "code": null, "e": 1553, "s": 1538, "text": "Sequential API" }, { "code": null, "e": 1568, "s": 1553, "text": "Functional API" }, { "code": null, "e": 1590, "s": 1568, "text": "Model Subclassing API" }, { "code": null, "e": 1898, "s": 1590, "text": "You can find more information about each of these in this post, but in this tutorial we’ll focus on using the Keras Functional API for building a custom model. Since we want to focus on our architecture, we'll just use a simple problem example and build a model which recognizes images in the MNIST dataset." }, { "code": null, "e": 2129, "s": 1898, "text": "To build a model in Keras you stack layers on top of one another. These layers are available in the keras.layers module (imported below). The module name is prepended by tensorflow because we use TensorFlow as a backend for Keras." }, { "code": null, "e": 2160, "s": 2129, "text": "import tensorflow.keras.layers" }, { "code": null, "e": 2785, "s": 2160, "text": "The first layer to create is the Input layer. This is created using the tensorflow.keras.layers.Input() class. One of the necessary arguments to be passed to the constructor of this class is the shape argument which specifies the shape of each sample in the data that will be used for training. In this tutorial we're just going to use dense layers for starters, and thus the input should be 1-D vector. The shape argument is thus assigned a tuple with one value (shown below). The value is 784 because the size of each image in the MNIST dataset is 28 x 28 = 784. An optional name argument specifies the name of that layer." }, { "code": null, "e": 2862, "s": 2785, "text": "input_layer = tensorflow.keras.layers.Input(shape=(784), name=\"input_layer\")" }, { "code": null, "e": 3248, "s": 2862, "text": "The next layer is a dense layer created using the Dense class according to the code below. It accepts an argument named units to specify the number of neurons in this layer. Note how this layer is connected to the input layer by specifying the name of that layer in parentheses. This is because a layer instance in the functional API is callable on a tensor, and also returns a tensor." }, { "code": null, "e": 3340, "s": 3248, "text": "dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name=\"dense_layer_1\")(input_layer)" }, { "code": null, "e": 3447, "s": 3340, "text": "Following the dense layer, an activation layer is created using the ReLU class according to the next line." }, { "code": null, "e": 3529, "s": 3447, "text": "activ_layer_1 = tensorflow.keras.layers.ReLU(name=\"activ_layer_1\")(dense_layer_1)" }, { "code": null, "e": 3609, "s": 3529, "text": "Another couple of dense-ReLu layers are added according to the following lines." }, { "code": null, "e": 3955, "s": 3609, "text": "dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name=\"dense_layer_2\")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name=\"relu_layer_2\")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name=\"dense_layer_3\")(activ_layer_2)activ_layer_3 = tensorflow.keras.layers.ReLU(name=\"relu_layer_3\")(dense_layer_3)" }, { "code": null, "e": 4189, "s": 3955, "text": "The next line adds the last layer to the network architecture according to the number of classes in the MNIST dataset. Because the MNIST dataset includes 10 classes (one for each number), the number of units used in this layer is 10." }, { "code": null, "e": 4282, "s": 4189, "text": "dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name=\"dense_layer_4\")(activ_layer_3)" }, { "code": null, "e": 4402, "s": 4282, "text": "To return the score for each class, a softmax layer is added after the previous dense layer according to the next line." }, { "code": null, "e": 4485, "s": 4402, "text": "output_layer = tensorflow.keras.layers.Softmax(name=\"output_layer\")(dense_layer_4)" }, { "code": null, "e": 4690, "s": 4485, "text": "We’ve now connected the layers but the model is not yet created. To build a model we must now use the Model class, as shown below. The first two arguments it accepts represent the input and output layers." }, { "code": null, "e": 4769, "s": 4690, "text": "model = tensorflow.keras.models.Model(input_layer, output_layer, name=\"model\")" }, { "code": null, "e": 4877, "s": 4769, "text": "Before loading the dataset and training the model, we have to compile the model using the compile() method." }, { "code": null, "e": 4979, "s": 4877, "text": "model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss=\"categorical_crossentropy\")" }, { "code": null, "e": 5285, "s": 4979, "text": "Using model.summary() we can see an overview of the model architecture. The input layer accepts a tensor of shape (None, 784) which means that each sample must be reshaped into a vector of 784 elements. The output Softmax layer returns 10 numbers, each being the score for that class of the MNIST dataset." }, { "code": null, "e": 6785, "s": 5285, "text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_layer (InputLayer) [(None, 784)] 0 _________________________________________________________________dense_layer_1 (Dense) (None, 500) 392500 _________________________________________________________________relu_layer_1 (ReLU) (None, 500) 0 _________________________________________________________________dense_layer_2 (Dense) (None, 250) 125250 _________________________________________________________________relu_layer_2 (ReLU) (None, 250) 0 _________________________________________________________________dense_layer_3 (Dense) (None, 20) 12550 _________________________________________________________________relu_layer_3 (ReLU) (None, 20) 0 _________________________________________________________________dense_layer_4 (Dense) (None, 10) 510 _________________________________________________________________output_layer (Softmax) (None, 10) 0 =================================================================Total params: 530,810Trainable params: 530,810Non-trainable params: 0_________________________________________________________________" }, { "code": null, "e": 7124, "s": 6785, "text": "Now that we’ve built and compiled the model, let’s see how the dataset is prepared. First we’ll load MNIST from the keras.datasets module, got their data type changed to float64 because this makes training the network easier than leaving its values in the 0-255 range, and finally reshaped so that each sample is a vector of 784 elements." }, { "code": null, "e": 7447, "s": 7124, "text": "(x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.mnist.load_data()x_train = x_train.astype(numpy.float64) / 255.0x_test = x_test.astype(numpy.float64) / 255.0x_train = x_train.reshape((x_train.shape[0], numpy.prod(x_train.shape[1:])))x_test = x_test.reshape((x_test.shape[0], numpy.prod(x_test.shape[1:])))" }, { "code": null, "e": 7610, "s": 7447, "text": "Because the used loss function in the compile() method is categorical_crossentropy, the labels of the samples should be on hot encoded according to the next code." }, { "code": null, "e": 7721, "s": 7610, "text": "y_test = tensorflow.keras.utils.to_categorical(y_test)y_train = tensorflow.keras.utils.to_categorical(y_train)" }, { "code": null, "e": 7780, "s": 7721, "text": "Finally, the model training starts using the fit() method." }, { "code": null, "e": 7869, "s": 7780, "text": "model.fit(x_train, y_train, epochs=20, batch_size=256, validation_data=(x_test, y_test))" }, { "code": null, "e": 8049, "s": 7869, "text": "At this point, we have created the model architecture using the already existing types of layers. The next section discusses using the Lambda layer for building custom operations." }, { "code": null, "e": 8403, "s": 8049, "text": "Let’s say that after the dense layer named dense_layer_3 we'd like to do some sort of operation on the tensor, such as adding the value 2 to each element. How can we do that? None of the existing layers does this, so we'll have to build a new layer ourselves. Fortunately, the Lambda layer exists for precisely that purpose. Let's discuss how to use it." }, { "code": null, "e": 8705, "s": 8403, "text": "Start by building the function that will do the operation you want. In this case, a function named custom_layer is created as follows. It just accepts the input tensor(s) and returns another tensor as output. If more than one tensor is to be passed to the function, then they will be passed as a list." }, { "code": null, "e": 8811, "s": 8705, "text": "In this example just a single tensor is fed as input, and 2 is added to each element in the input tensor." }, { "code": null, "e": 8858, "s": 8811, "text": "def custom_layer(tensor): return tensor + 2" }, { "code": null, "e": 9179, "s": 8858, "text": "After building the function that defines the operation, next we need to create the lambda layer using the Lambda class as defined in the next line. In this case, only one tensor is fed to the custom_layer function because the lambda layer is callable on the single tensor returned by the dense layer named dense_layer_3." }, { "code": null, "e": 9275, "s": 9179, "text": "lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")(dense_layer_3)" }, { "code": null, "e": 9351, "s": 9275, "text": "Here is the code that builds the full network after using the lambda layer." }, { "code": null, "e": 10336, "s": 9351, "text": "input_layer = tensorflow.keras.layers.Input(shape=(784), name=\"input_layer\")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name=\"dense_layer_1\")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name=\"relu_layer_1\")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name=\"dense_layer_2\")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name=\"relu_layer_2\")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name=\"dense_layer_3\")(activ_layer_2)def custom_layer(tensor): return tensor + 2lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")(dense_layer_3)activ_layer_3 = tensorflow.keras.layers.ReLU(name=\"relu_layer_3\")(lambda_layer)dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name=\"dense_layer_4\")(activ_layer_3)output_layer = tensorflow.keras.layers.Softmax(name=\"output_layer\")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name=\"model\")" }, { "code": null, "e": 10931, "s": 10336, "text": "In order to see the tensor before and after being fed to the lambda layer we’ll create two new models in addition to the previous one. We’ll call these before_lambda_model and after_lambda_model. Both models use the input layer as their inputs, but the output layer differs. The before_lambda_model model returns the output of dense_layer_3 which is the layer that exists exactly before the lambda layer. The output of the after_lambda_model model is the output from the lambda layer named lambda_layer. By doing this, we can see the input before and the output after applying the lambda layer." }, { "code": null, "e": 11143, "s": 10931, "text": "before_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_3, name=\"before_lambda_model\")after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name=\"after_lambda_model\")" }, { "code": null, "e": 11220, "s": 11143, "text": "The complete code that builds and trains the entire network is listed below." }, { "code": null, "e": 13250, "s": 11220, "text": "import tensorflow.keras.layersimport tensorflow.keras.modelsimport tensorflow.keras.optimizersimport tensorflow.keras.datasetsimport tensorflow.keras.utilsimport tensorflow.keras.backendimport numpyinput_layer = tensorflow.keras.layers.Input(shape=(784), name=\"input_layer\")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name=\"dense_layer_1\")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name=\"relu_layer_1\")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name=\"dense_layer_2\")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name=\"relu_layer_2\")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name=\"dense_layer_3\")(activ_layer_2)before_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_3, name=\"before_lambda_model\")def custom_layer(tensor): return tensor + 2lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")(dense_layer_3)after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name=\"after_lambda_model\")activ_layer_3 = tensorflow.keras.layers.ReLU(name=\"relu_layer_3\")(lambda_layer)dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name=\"dense_layer_4\")(activ_layer_3)output_layer = tensorflow.keras.layers.Softmax(name=\"output_layer\")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name=\"model\")model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss=\"categorical_crossentropy\")model.summary()(x_train, y_train), (x_test, y_test) = tensorflow.keras.datasets.mnist.load_data()x_train = x_train.astype(numpy.float64) / 255.0x_test = x_test.astype(numpy.float64) / 255.0x_train = x_train.reshape((x_train.shape[0], numpy.prod(x_train.shape[1:])))x_test = x_test.reshape((x_test.shape[0], numpy.prod(x_test.shape[1:])))y_test = tensorflow.keras.utils.to_categorical(y_test)y_train = tensorflow.keras.utils.to_categorical(y_train)model.fit(x_train, y_train, epochs=20, batch_size=256, validation_data=(x_test, y_test))" }, { "code": null, "e": 13606, "s": 13250, "text": "Note that you do not have to compile or train the 2 newly created models because their layers are actually reused from the main model that exists in the model variable. After that model is trained, we can use the predict() method for returning the outputs of the before_lambda_model and after_lambda_model models to see how the result of the lambda layer." }, { "code": null, "e": 13714, "s": 13606, "text": "p = model.predict(x_train)m1 = before_lambda_model.predict(x_train)m2 = after_lambda_model.predict(x_train)" }, { "code": null, "e": 13946, "s": 13714, "text": "The next code just prints the outputs of the first 2 samples. As you can see, each element returned from the m2 array is actually the result of m1 after adding 2. This is exactly the operation we applied in our custom lambda layer." }, { "code": null, "e": 14475, "s": 13946, "text": "print(m1[0, :])print(m2[0, :])[ 14.420735 8.872794 25.369402 1.4622561 5.672293 2.5202641 -14.753801 -3.8822086 -1.0581762 -6.4336205 13.342142 -3.0627508 -5.694006 -6.557313 -1.6567478 -3.8457105 11.891999 20.581928 2.669979 -8.092522 ][ 16.420734 10.872794 27.369402 3.462256 7.672293 4.520264 -12.753801 -1.8822086 0.94182384 -4.4336205 15.342142 -1.0627508 -3.694006 -4.557313 0.34325218 -1.8457105 13.891999 22.581928 4.669979 -6.0925217 ]" }, { "code": null, "e": 14640, "s": 14475, "text": "In this section the lambda layer was used to do an operation over a single input tensor. In the next section we see how we can pass two input tensors to this layer." }, { "code": null, "e": 14914, "s": 14640, "text": "Assume that we want to do an operation that depends on the two layers named dense_layer_3 and relu_layer_3. In this case we have to call the lambda layer while passing two tensors. This is simply done by creating a list with all of these tensors, as given in the next line." }, { "code": null, "e": 15027, "s": 14914, "text": "lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")([dense_layer_3, activ_layer_3])" }, { "code": null, "e": 15397, "s": 15027, "text": "This list is passed to the custom_layer() function and we can fetch the individual layers simply according to the next code. It just adds these two layers together. There is actually layer in Keras named Add that can be used for adding two layers or more, but we are just presenting how you could do it yourself in case there's another operation not supported by Keras." }, { "code": null, "e": 15497, "s": 15397, "text": "def custom_layer(tensor): tensor1 = tensor[0] tensor2 = tensor[1] return tensor1 + tensor2" }, { "code": null, "e": 15702, "s": 15497, "text": "The next code builds three models: two for capturing the outputs from the dense_layer_3 and activ_layer_3 passed to the lambda layer, and another one for capturing the output from the lambda layer itself." }, { "code": null, "e": 16137, "s": 15702, "text": "before_lambda_model1 = tensorflow.keras.models.Model(input_layer, dense_layer_3, name=\"before_lambda_model1\")before_lambda_model2 = tensorflow.keras.models.Model(input_layer, activ_layer_3, name=\"before_lambda_model2\")lambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")([dense_layer_3, activ_layer_3])after_lambda_model = tensorflow.keras.models.Model(input_layer, lambda_layer, name=\"after_lambda_model\")" }, { "code": null, "e": 16272, "s": 16137, "text": "To see the outputs from the dense_layer_3, activ_layer_3, and lambda_layer layers, the next code predicts their outputs and prints it." }, { "code": null, "e": 17142, "s": 16272, "text": "m1 = before_lambda_model1.predict(x_train)m2 = before_lambda_model2.predict(x_train)m3 = after_lambda_model.predict(x_train)print(m1[0, :])print(m2[0, :])print(m3[0, :]) [ 1.773366 -3.4378722 0.22042789 11.220362 3.4020965 14.487111 4.239182 -6.8589864 -6.428128 -5.477719 -8.799093 7.264849 17.503246 -6.809489 -6.846208 16.094025 24.483786 -7.084775 17.341183 20.311539 ][ 1.773366 0. 0.22042789 11.220362 3.4020965 14.487111 4.239182 0. 0. 0. 0. 7.264849 17.503246 0. 0. 16.094025 24.483786 0. 17.341183 20.311539 ][ 3.546732 -3.4378722 0.44085577 22.440723 6.804193 28.974222 8.478364 -6.8589864 -6.428128 -5.477719 -8.799093 14.529698 35.006493 -6.809489 -6.846208 32.18805 48.96757 -7.084775 34.682365 40.623077 ]" }, { "code": null, "e": 17266, "s": 17142, "text": "Using the lambda layer is now clear. The next section discusses how you can save and load a model that uses a lambda layer." }, { "code": null, "e": 17447, "s": 17266, "text": "In order to save a model (whether it uses a lambda layer or not) the save() method is used. Assuming we are just interested in saving the main model, here's the line that saves it." }, { "code": null, "e": 17470, "s": 17447, "text": "model.save(\"model.h5\")" }, { "code": null, "e": 17555, "s": 17470, "text": "We can also load the saved model using the load_model() method, as in the next line." }, { "code": null, "e": 17617, "s": 17555, "text": "loaded_model = tensorflow.keras.models.load_model(\"model.h5\")" }, { "code": null, "e": 17959, "s": 17617, "text": "Hopefully, the model could be successfully loaded. Unfortunately there are some issues in Keras that may result in the SystemError: unknown opcode while loading a model with a lambda layer. It might be due to building the model using a Python version and using it in another version. We are going to discuss the solution in the next section." }, { "code": null, "e": 18112, "s": 17959, "text": "To solve this issue we’re not going to save the model in the way discussed above. Instead, we’ll save the model weights using the save_weights() method." }, { "code": null, "e": 18383, "s": 18112, "text": "Now we’ve only saved the weights. What about the model architecture? The model architecture will be recreated using the code. Why not save the model architecture as a JSON file and then load it again? The reason is that the error persists after loading the architecture." }, { "code": null, "e": 18557, "s": 18383, "text": "In summary, the trained model weights will be saved, the model architecture will be reproduced using the code, and finally the weights will be loaded into that architecture." }, { "code": null, "e": 18616, "s": 18557, "text": "The weights of the model can be saved using the next line." }, { "code": null, "e": 18655, "s": 18616, "text": "model.save_weights('model_weights.h5')" }, { "code": null, "e": 18794, "s": 18655, "text": "Here’s the code that reproduces the model architecture. The model will not be trained, but the saved weights will be assigned to it again." }, { "code": null, "e": 20251, "s": 18794, "text": "input_layer = tensorflow.keras.layers.Input(shape=(784), name=\"input_layer\")dense_layer_1 = tensorflow.keras.layers.Dense(units=500, name=\"dense_layer_1\")(input_layer)activ_layer_1 = tensorflow.keras.layers.ReLU(name=\"relu_layer_1\")(dense_layer_1)dense_layer_2 = tensorflow.keras.layers.Dense(units=250, name=\"dense_layer_2\")(activ_layer_1)activ_layer_2 = tensorflow.keras.layers.ReLU(name=\"relu_layer_2\")(dense_layer_2)dense_layer_3 = tensorflow.keras.layers.Dense(units=20, name=\"dense_layer_3\")(activ_layer_2)activ_layer_3 = tensorflow.keras.layers.ReLU(name=\"relu_layer_3\")(dense_layer_3)def custom_layer(tensor): tensor1 = tensor[0] tensor2 = tensor[1] epsilon = tensorflow.keras.backend.random_normal(shape=tensorflow.keras.backend.shape(tensor1), mean=0.0, stddev=1.0) random_sample = tensor1 + tensorflow.keras.backend.exp(tensor2/2) * epsilon return random_samplelambda_layer = tensorflow.keras.layers.Lambda(custom_layer, name=\"lambda_layer\")([dense_layer_3, activ_layer_3])dense_layer_4 = tensorflow.keras.layers.Dense(units=10, name=\"dense_layer_4\")(lambda_layer)after_lambda_model = tensorflow.keras.models.Model(input_layer, dense_layer_4, name=\"after_lambda_model\")output_layer = tensorflow.keras.layers.Softmax(name=\"output_layer\")(dense_layer_4)model = tensorflow.keras.models.Model(input_layer, output_layer, name=\"model\")model.compile(optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005), loss=\"categorical_crossentropy\")" }, { "code": null, "e": 20369, "s": 20251, "text": "Here’s how the saved weights are loaded using the load_weights() method, and assigned to the reproduced architecture." }, { "code": null, "e": 20408, "s": 20369, "text": "model.load_weights('model_weights.h5')" }, { "code": null, "e": 20530, "s": 20408, "text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient." }, { "code": null, "e": 20933, "s": 20530, "text": "This tutorial discussed using the Lambda layer to create custom layers which do operations not supported by the predefined layers in Keras. The constructor of the Lambda class accepts a function that specifies how the layer works, and the function accepts the tensor(s) that the layer is called on. Inside the function, you can perform whatever operations you want and then return the modified tensors." } ]
Spring MVC - Page Redirection Example
The following example shows how to write a simple web based application, which makes use of redirect to transfer an http request to another page. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework − package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value = "/redirect", method = RequestMethod.GET) public String redirect() { return "redirect:finalPage"; } @RequestMapping(value = "/finalPage", method = RequestMethod.GET) public String finalPage() { return "final"; } } Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to the access-redirect service method, which will redirect this request to another service method and finally a final.jsppage will be displayed. <%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> <html> <head> <title>Spring Page Redirection</title> </head> <body> <h2>Spring Page Redirection</h2> <p>Click below button to redirect the result to new page</p> <form:form method = "GET" action = "/HelloWeb/redirect"> <table> <tr> <td> <input type = "submit" value = "Redirect Page"/> </td> </tr> </table> </form:form> </body> </html> <%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> <html> <head> <title>Spring Page Redirection</title> </head> <body> <h2>Redirected Page</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/index and you should see the following screen if everything is fine with the Spring Web Application. Now click on the "Redirect Page" button to submit the form and to get to the final redirected page. We should see the following screen, if everything is fine with our Spring Web Application − Print Add Notes Bookmark this page
[ { "code": null, "e": 3105, "s": 2791, "text": "The following example shows how to write a simple web based application, which makes use of redirect to transfer an http request to another page. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework −" }, { "code": null, "e": 3756, "s": 3105, "text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WebController {\n\n @RequestMapping(value = \"/index\", method = RequestMethod.GET)\n public String index() {\n\t return \"index\";\n }\n \n @RequestMapping(value = \"/redirect\", method = RequestMethod.GET)\n public String redirect() {\n \n return \"redirect:finalPage\";\n }\n \n @RequestMapping(value = \"/finalPage\", method = RequestMethod.GET)\n public String finalPage() {\n \n return \"final\";\n }\n}" }, { "code": null, "e": 4016, "s": 3756, "text": "Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to the access-redirect service method, which will redirect this request to another service method and finally a final.jsppage will be displayed." }, { "code": null, "e": 4563, "s": 4016, "text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring Page Redirection</title>\n </head>\n <body>\n <h2>Spring Page Redirection</h2>\n <p>Click below button to redirect the result to new page</p>\n <form:form method = \"GET\" action = \"/HelloWeb/redirect\">\n <table>\n <tr>\n <td>\n <input type = \"submit\" value = \"Redirect Page\"/>\n </td>\n </tr>\n </table> \n </form:form>\n </body>\n</html>" }, { "code": null, "e": 4782, "s": 4563, "text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n \n <head>\n <title>Spring Page Redirection</title>\n </head>\n \n <body>\n <h2>Redirected Page</h2>\n </body>\n\n</html>" }, { "code": null, "e": 4993, "s": 4782, "text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder." }, { "code": null, "e": 5264, "s": 4993, "text": "Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/index and you should see the following screen if everything is fine with the Spring Web Application." }, { "code": null, "e": 5456, "s": 5264, "text": "Now click on the \"Redirect Page\" button to submit the form and to get to the final redirected page. We should see the following screen, if everything is fine with our Spring Web Application −" }, { "code": null, "e": 5463, "s": 5456, "text": " Print" }, { "code": null, "e": 5474, "s": 5463, "text": " Add Notes" } ]
What is the difference between a method and a function?
Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming. A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again. It helps programmers in writing modular codes. The following is the syntax of a JavaScript function: <script type="text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script> Here’s an example: <script type="text/javascript"> <!-- function sayHello() { alert("Hello there"); } //--> </script>
[ { "code": null, "e": 1188, "s": 1062, "text": "Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming." }, { "code": null, "e": 1388, "s": 1188, "text": "A function is a group of reusable code which can be called anywhere in your program. This eliminates the need for writing the same code again and again. It helps programmers in writing modular codes." }, { "code": null, "e": 1442, "s": 1388, "text": "The following is the syntax of a JavaScript function:" }, { "code": null, "e": 1575, "s": 1442, "text": "<script type=\"text/javascript\">\n <!--\n function functionname(parameter-list) {\n statements\n }\n //-->\n</script>" }, { "code": null, "e": 1594, "s": 1575, "text": "Here’s an example:" }, { "code": null, "e": 1720, "s": 1594, "text": "<script type=\"text/javascript\">\n <!--\n function sayHello() {\n alert(\"Hello there\");\n }\n //-->\n</script>" } ]
How to create a production-ready Recommender System | by Tirmidzi Faizal Aflahi | Towards Data Science
You might have seen e-commerce websites every day. Or read many articles from lots of blogs, news, and Medium publications. From your perspective as a user or reader, what is the common pain point when looking at all of those things? One simple answer: There are a lot of things available to see, and you often lost when trying to discover something. Yes, with those huge numbers of things or articles on those websites, the users need a solution, to simplify their discovery journey. If you are operating an e-commerce website or a blog, maybe you want to ask. Why bother? Well, have you heard about the funnel? The less the funnel of a user when trying to do something, the bigger the conversion. That is a basic rule in user experience. So, if reducing the number of steps can increase your site page view or even revenue, why not? If you want to read more about Recommendation System or Deep Learning in general, you can download the FREE book here. In simple terms, a recommender system is a discovery system. The system learns from the data and provides recommendations to users. Without the user specifically searching for that item, that item was brought automatically by the system. It sounds like magic. And this magic has been used by Amazon and Netflix since decades ago. How awesome it is, when you open Spotify and it already gives you a list of songs to listen to (Discover Weekly, and I amazed on how it can pick songs that I have never heard before, and I like it). In general term, there are two kinds of recommender system known by us, a human. Well, not all human. The type of recommender system that can easily be digested by our brain. Without a sign of short-circuiting or exploding. For example, you are an avid novel reader. And you like “And then there were none” by Agatha Christie. You bought it from an online bookstore. It makes sense if the bookstore will show you “The ABC Murders” the next time you open the website. Why? Because both of them written by Agatha Christie. Hence, the Content-based filtering model will recommend you that title. Wow, so easy! Let’s use that! Wait... While Content-based filtering is easily digested by our brain and looks so simple, it can fail to guess the real behavior of the user. For example, I don’t like Hercule Poirot, but I like other detectives in her novels. In that case, “The ABC Murders” should not be recommended for me. This type will overcome the previous problem. Essentially, the system record all the previous interaction of the user on the website. And provide recommendations based on that. How does it work? Take a look at this scenario. There are two users, A and B. A bought item 1 A bought item 2 A bought item 3 B bought item 1 B bought item 3 The collaborative filtering will recommend B item 2 since there is another user who bought items 1 and 3 also bought item 2. You might say, wow, they could be sporadically bought together in coincidence. But, what if, there are 100 users who have the same behavior with user A? That was, the so-called, the power of crowds. So, why waiting? Let’s just start creating Collaborative filtering system in your production environment! Hold your horse, mate! While it has an extremely good performance. It has several serious issues. More importantly when you are trying to create a production-ready system. It doesn’t know about context. In contrast with Content-based filtering that recommends similar items, Collaborative filtering will not recommend based on similarity. When this is your concern, the solution is going hybrid. Combine both methods.It needs huge hardware resources since you need to store a user-item matrix. Imagine if you open your e-commerce website and it has 100K users. At the same time, you serve 10K products. In this case, you will need 10K x 100K matrix with each element hold 4 bytes integer. Yep, you need 4GB memory just for storing the matrix. Not even doing other things.Cold start. A new user will not get any benefit from the system since you have no idea about him.The unchangeable. If you are not doing anything on the website, the result of the recommender system will stay the same. The user will think that there is nothing new on the website. And they will leave. It doesn’t know about context. In contrast with Content-based filtering that recommends similar items, Collaborative filtering will not recommend based on similarity. When this is your concern, the solution is going hybrid. Combine both methods. It needs huge hardware resources since you need to store a user-item matrix. Imagine if you open your e-commerce website and it has 100K users. At the same time, you serve 10K products. In this case, you will need 10K x 100K matrix with each element hold 4 bytes integer. Yep, you need 4GB memory just for storing the matrix. Not even doing other things. Cold start. A new user will not get any benefit from the system since you have no idea about him. The unchangeable. If you are not doing anything on the website, the result of the recommender system will stay the same. The user will think that there is nothing new on the website. And they will leave. While the problem no. 1 is easily solved with going hybrid, the other ones will still be a headache. Well, solving the number 2, 3, and 4 is the reason for this post. Let’s just start. I might be in the same spot as you. I was really confused on how to make this thing possible. With the limitation of the machine, and of course common sense, I can’t deploy a huge service just for this tiny requirement. And by luck, I stumbled upon this book They told me that for a production-ready system, you might not want the best accuracy of whatever performance it has. A somewhat inaccurate yet acceptable most often work in the real world use case. The most interesting part on how you can do that is, Batch computation on the general recommendation indicator.Query on real-time, without using the user-item matrix, but take several latest interactions of the user and query it to the system. Batch computation on the general recommendation indicator. Query on real-time, without using the user-item matrix, but take several latest interactions of the user and query it to the system. Let me explain while we build the system. Why python? Well, python is one of the easiest languages to learn. It will take you just a couple of hours to understand the syntax. for item in the_bag: print(item) And you can print all the item in the bag. That easy. Go to Python website to download and install it according to your Operating System. For this tutorial, you need several packages pip install numpypip install scipypip install pandaspip install jupyterpip install requests Numpy and Scipy are python package to handle mathematical computation, you will need them for the matrix. Pandas is used for your data. Requests is for http calls. and Jupyter is a web app to run your python code interactively. type jupyter notebook and you will see something like this Write the code on the cells provided, and the code will be run interactively. Before we begin, you need several tools. Elasticsearch. it is an open-source search engine, that can enable you to search your document really fast. You will need this tool to save your computed indicator so that you can query in real-time.Postman. an API development tool. You will need this to simulate the query into elasticsearch. As elasticsearch can be accessed via http. Elasticsearch. it is an open-source search engine, that can enable you to search your document really fast. You will need this tool to save your computed indicator so that you can query in real-time. Postman. an API development tool. You will need this to simulate the query into elasticsearch. As elasticsearch can be accessed via http. Download and install both of them, and you are ready to go. For this tutorial, let’s take a look at a dataset in Kaggle. The Retailrocket recommender system dataset. Download it and extract the data in your Jupyter notebook directory. It should be like that. Among those files, you only need events.csv for this tutorial. That file consists of millions of actions by users to the items on the e-commerce website. import pandas as pdimport numpy as np Write those imports on the Jupyter notebook. And you are ready to go. df = pd.read_csv('events.csv')df.shape It will print you (2756101, 5). It means you have 2.7M rows with 5 columns. Let’s check it out. df.head() It has five columns. Timestamp, the timestamp of the event.Visitorid, the id of the userItemid, the id of the itemEvent, the eventTransactionid, an id of the transaction if the event is a transaction Timestamp, the timestamp of the event. Visitorid, the id of the user Itemid, the id of the item Event, the event Transactionid, an id of the transaction if the event is a transaction Let’s check, what kind of events are available df.event.unique() You will get three events, view, addtocart, and transaction For the sake of simplicity, you might not want to play with all of the events. And for this tutorial, you will only play with transactions. So, let’s filter the transactions only. trans = df[df['event'] == 'transaction']trans.shape It will return (22457, 5) You will have 22K transactions you can play with. I think it is good enough for a newbie like us. Let’s take a look further into the data visitors = trans['visitorid'].unique()items = trans['itemid'].unique()print(visitors.shape)print(items.shape) You will get 11,719 unique visitors and 12,025 unique items. The rule of thumb on creating a simple yet effective recommender system is to downsample the data without losing quality. It means, you can take only maybe 50 latest transactions for each user and you still get the quality you want because behavior changes over-time. trans2 = trans.groupby(['visitorid']).head(50)trans2.shape Now you only have 19,939 transactions. Means around 2K transactions are obsolete. Because of the visitor id and item id are huge numbers, you will be hard to remember each of those ids. trans2['visitors'] = trans2['visitorid'].apply(lambda x : np.argwhere(visitors == x)[0][0])trans2['items'] = trans2['itemid'].apply(lambda x : np.argwhere(items == x)[0][0])trans2 You need other columns that are a 0 based index. You will see something like this. It’s cleaner. Now you can use only the visitors and items column for all of our next steps. The nightmare is coming... You have 11,719 unique visitors and 12,025 items, so you will need around 500MB memory to store the matrix. Sparse matrix comes to the rescue. Sparse matrices are a matrix with most of their element are zero. It makes sense since not all of the users buy all the items. Lot’s of the connection will be zero. from scipy.sparse import csr_matrix Scipy has the thing. occurences = csr_matrix((visitors.shape[0], items.shape[0]), dtype='int8')def set_occurences(visitor, item): occurences[visitor, item] += 1trans2.apply(lambda row: set_occurences(row['visitors'], row['items']), axis=1)occurences Apply the set_occurences function on each row in the data you have. It will print something like this <11719x12025 sparse matrix of type '<class 'numpy.int8'>' with 18905 stored elements in Compressed Sparse Row format> From those 140 million cells in the matrix, only 18,905 are filled with non-zero. So basically you only need to store those 18,905 value to the memory. A 99.99% improved efficiency. The downside of the sparse matrix is, it is computationally higher when trying to retrieve the data in real-time. So, you should not finish at this step. Let’s construct an item-item matrix where each element means how many times both items bought together by a user. Call it the co-occurrence matrix. To create a co-occurrence matrix, you need to dot product the transpose of the occurrence matrix with itself. I have tried it without sparse matrix and my computer suddenly stops working. So, let’s not do that. cooc = occurences.transpose().dot(occurences)cooc.setdiag(0) It finished instantly with a sparse matrix. And I am happy. The setdiag function is setting the diagonal to 0, means you don’t want to compute the value of item 1 and item 1 comes together since they are the same item. The co-occurrence matrix will consist of the number of the time both items bought together. But there is a chance, that there is an item. That item is bought regardless of the behavior of the user. Might be a flash sale, or something like that. In reality, you might want to really capture the behavior of the user, clean from something like that flash sale. Because it is not a behavior you are expecting. To remove those things affected, you need to penalize the score on the co-occurrence matrix. Ted Dunnings in the previous book has an algorithm called, Log-Likelihood Ratio or LLR. def xLogX(x): return x * np.log(x) if x != 0 else 0.0def entropy(x1, x2=0, x3=0, x4=0): return xLogX(x1 + x2 + x3 + x4) - xLogX(x1) - xLogX(x2) - xLogX(x3) - xLogX(x4)def LLR(k11, k12, k21, k22): rowEntropy = entropy(k11 + k12, k21 + k22) columnEntropy = entropy(k11 + k21, k12 + k22) matrixEntropy = entropy(k11, k12, k21, k22) if rowEntropy + columnEntropy < matrixEntropy: return 0.0 return 2.0 * (rowEntropy + columnEntropy - matrixEntropy)def rootLLR(k11, k12, k21, k22): llr = LLR(k11, k12, k21, k22) sqrt = np.sqrt(llr) if k11 * 1.0 / (k11 + k12) < k21 * 1.0 / (k21 + k22): sqrt = -sqrt return sqrt The LLR function is computing the likelihood of two events, A and B appear together. The parameters are, k11, number of when both events appeared togetherk12, number of B appear without Ak21, number of A appear without Bk22, number of other things appeared without both of them k11, number of when both events appeared together k12, number of B appear without A k21, number of A appear without B k22, number of other things appeared without both of them Now calculate the LLR function and save it to the pp_score matrix. row_sum = np.sum(cooc, axis=0).A.flatten()column_sum = np.sum(cooc, axis=1).A.flatten()total = np.sum(row_sum, axis=0)pp_score = csr_matrix((cooc.shape[0], cooc.shape[1]), dtype='double')cx = cooc.tocoo()for i,j,v in zip(cx.row, cx.col, cx.data): if v != 0: k11 = v k12 = row_sum[i] - k11 k21 = column_sum[j] - k11 k22 = total - k11 - k12 - k21 pp_score[i,j] = rootLLR(k11, k12, k21, k22) Sort the result, so that the highest LLR score on each item is on the first column of each row. result = np.flip(np.sort(pp_score.A, axis=1), axis=1)result_indices = np.flip(np.argsort(pp_score.A, axis=1), axis=1) That first item on the result matrix, if high enough, can be considered as an indicator to the item. Let’s take a look at one of the result result[8456] You will get array([15.33511076, 14.60017668, 3.62091635, ..., 0. , 0. , 0. ]) And looking at the indices result_indices[8456] Will get you array([8682, 380, 8501, ..., 8010, 8009, 0], dtype=int64) You can safely answer that with a high number of LLR score, item 8682 and 380 can be an indicator for item 8456. While item 8501 since the score is not that big, might not be an indicator for item 8456. It means that, if someone bought 8682 and 380, you can recommend him 8456. Easy. But, for a rule of thumb, you might want to give some limit on the LLR score, so insignificant indicators will be removed. minLLR = 5indicators = result[:, :50]indicators[indicators < minLLR] = 0.0indicators_indices = result_indices[:, :50]max_indicator_indices = (indicators==0).argmax(axis=1)max = max_indicator_indices.max()indicators = indicators[:, :max+1]indicators_indices = indicators_indices[:, :max+1] Now you are ready to put those together to elasticsearch. So you can query the recommendation in real-time. import requestsimport json Okay, now you are ready to put the things inside elasticsearch you have prepared before. But, be careful. If you are trying to add the data one by one using /_create/<id> API, it will take you forever. Of course, you can, but you need maybe half an hour to an hour just to move our 12,025 items into elasticsearch. I did it once, so please, don’t repeat my mistake. So what’s the solution? Fortunately, elasticsearch has bulk API that can easily send multiple documents at once. So, create a new index (items2, I used items for the previous mistake) and let’s try it actions = []for i in range(indicators.shape[0]): length = indicators[i].nonzero()[0].shape[0] real_indicators = items[indicators_indices[i, :length]].astype("int").tolist() id = items[i] action = { "index" : { "_index" : "items2", "_id" : str(id) } } data = { "id": int(id), "indicators": real_indicators } actions.append(json.dumps(action)) actions.append(json.dumps(data)) if len(actions) == 200: actions_string = "\n".join(actions) + "\n" actions = [] url = "http://127.0.0.1:9200/_bulk/" headers = { "Content-Type" : "application/x-ndjson" } requests.post(url, headers=headers, data=actions_string)if len(actions) > 0: actions_string = "\n".join(actions) + "\n" actions = [] url = "http://127.0.0.1:9200/_bulk/" headers = { "Content-Type" : "application/x-ndjson" } requests.post(url, headers=headers, data=actions_string) And voila, it will finish within several seconds. Hit this API in Postman 127.0.0.1:9200/items2/_count You will have your data stored already { "count": 12025, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }} Let’s check to the data of your item with /items2/240708 { "id": 240708, "indicators": [ 305675, 346067, 312728 ]} Id is the id of the item. While indicators are the other items which become indicators to recommend this item. The best part of the thing we create is a real-time query, { "query": { "bool": { "should": [ { "terms": {"indicators" : [240708], "boost": 2}} ] } }} Post the request to 127.0.0.1:9200/items2/_search And you will get three results. 312728, 305675, and 346067. Exactly the three items that were bought together with item 240708. Great! So, the problem of needing a huge resource is a non-factor now. So, how about the other two problems? Before that, rest your eye for a while. The very common problem when building recommender systems is the cold start problem. Every new user will not have any of their behavior recorded in the system. So, what should the system recommend them? Let’s take a look at our recently built recommendation system. Do you think anything strange about the result? Yep, the result only returns 3 recommended items. Just 3. How do you plan to display it to the customer? Let’s display the other item not recommended at the end of the list. Just for the sake of good user experience. { "query": { "bool": { "should": [ { "terms": {"indicators" : [240708]}}, { "constant_score": {"filter" : {"match_all": {}}, "boost" : 0.000001}} ] } }} You can use a constant score to return all other items. But, for all the non-recommended items, you need to rank them so that the things that users probably will like even though not captured in their behavior. In many cases, popular item works really well. How do you calculate a popular item? popular = np.zeros(items.shape[0])def inc_popular(index): popular[index] += 1trans2.apply(lambda row: inc_popular(row['items']), axis=1) Simple, count the item appearance one by one. So the highest popular value is the most popular. Let’s create another index, called items3. And bulk insert actions = []for i in range(indicators.shape[0]): length = indicators[i].nonzero()[0].shape[0] real_indicators = items[indicators_indices[i, :length]].astype("int").tolist() id = items[i] action = { "index" : { "_index" : "items3", "_id" : str(id) } } # url = "http://127.0.0.1:9200/items/_create/" + str(id) data = { "id": int(id), "indicators": real_indicators, "popular": popular[i] } actions.append(json.dumps(action)) actions.append(json.dumps(data)) if len(actions) == 200: actions_string = "\n".join(actions) + "\n" actions = [] url = "http://127.0.0.1:9200/_bulk/" headers = { "Content-Type" : "application/x-ndjson" } requests.post(url, headers=headers, data=actions_string)if len(actions) > 0: actions_string = "\n".join(actions) + "\n" actions = []url = "http://127.0.0.1:9200/_bulk/" headers = { "Content-Type" : "application/x-ndjson" } requests.post(url, headers=headers, data=actions_string) In this indexing phase, you include the popular field. So, your data will look like this { "id": 240708, "indicators": [ 305675, 346067, 312728 ], "popular": 3.0} You will have three fields. Id and indicators like the previous one, and the popular field. The count of that item bought by users. Let’s add popular to our previous query. So, you have multiple sources of scores now, i.e. the indicator matches and popular, how to combine the scores? Elasticsearch has function score to do with that. { "query": { "function_score":{ "query": { "bool": { "should": [ { "terms": {"indicators" : [240708], "boost": 2}}, { "constant_score": {"filter" : {"match_all": {}}, "boost" : 0.000001}} ] } }, "functions":[ { "filter": {"range": {"popular": {"gt": 0}}}, "script_score" : { "script" : { "source": "doc['popular'].value * 0.1" } } } ], "score_mode": "sum", "min_score" : 0 } }} Rework your query and add a function score to slightly add 0.1 times the popular value to the constant score you have above. You don’t have to stick with 0.1, you can use other function, even Natural logarithm. Like this, Math.log(doc['popular'].value) Now, you will see your most popular item, 461686 placed fourth, just below the recommended items. And also other popular items below. As you can see, our result stays the same every time we run the real-time query. That might be good because our technique is reproducible, but at the same time, the user might not be happy about it. Ted Dunnings from the book said, the click-through rate of the recommendation, will fall really low after the 20th result. It means any item we recommend after that will not be known to the user. How to solve this? There is a technique called dithering. It is creating a random noise when querying to bring up the least recommended item but still make the strongly recommended item at the top. { "query": { "function_score":{ "query": { "bool": { "should": [ { "terms": {"indicators" : [240708], "boost": 2}}, { "constant_score": {"filter" : {"match_all": {}}, "boost" : 0.000001}} ] } }, "functions":[ { "filter": {"range": {"popular": {"gt": 1}}}, "script_score" : { "script" : { "source": "0.1 * Math.log(doc['popular'].value)" } } }, { "filter": {"match_all": {}}, "random_score": {} } ], "score_mode": "sum", "min_score" : 0 } }} The random score, it will give all of your item uniformly distributed random noise. The score will be minuscule so that the top recommendation will not go down. Hit that query, and see the result. You can see The positive note is. your user will not have to go scrolling to the second or third page. He or she just needs to hit that refresh button on the browser, and he or she will be provided new contents. Just like magic. Building a production-ready recommender system is not that hard. And current technology allows us to do that. Create the system with your data and get ready to deploy it to production. And of course, you can learn AI from this best course for AI
[ { "code": null, "e": 296, "s": 172, "text": "You might have seen e-commerce websites every day. Or read many articles from lots of blogs, news, and Medium publications." }, { "code": null, "e": 406, "s": 296, "text": "From your perspective as a user or reader, what is the common pain point when looking at all of those things?" }, { "code": null, "e": 425, "s": 406, "text": "One simple answer:" }, { "code": null, "e": 523, "s": 425, "text": "There are a lot of things available to see, and you often lost when trying to discover something." }, { "code": null, "e": 657, "s": 523, "text": "Yes, with those huge numbers of things or articles on those websites, the users need a solution, to simplify their discovery journey." }, { "code": null, "e": 746, "s": 657, "text": "If you are operating an e-commerce website or a blog, maybe you want to ask. Why bother?" }, { "code": null, "e": 785, "s": 746, "text": "Well, have you heard about the funnel?" }, { "code": null, "e": 1007, "s": 785, "text": "The less the funnel of a user when trying to do something, the bigger the conversion. That is a basic rule in user experience. So, if reducing the number of steps can increase your site page view or even revenue, why not?" }, { "code": null, "e": 1126, "s": 1007, "text": "If you want to read more about Recommendation System or Deep Learning in general, you can download the FREE book here." }, { "code": null, "e": 1364, "s": 1126, "text": "In simple terms, a recommender system is a discovery system. The system learns from the data and provides recommendations to users. Without the user specifically searching for that item, that item was brought automatically by the system." }, { "code": null, "e": 1386, "s": 1364, "text": "It sounds like magic." }, { "code": null, "e": 1456, "s": 1386, "text": "And this magic has been used by Amazon and Netflix since decades ago." }, { "code": null, "e": 1655, "s": 1456, "text": "How awesome it is, when you open Spotify and it already gives you a list of songs to listen to (Discover Weekly, and I amazed on how it can pick songs that I have never heard before, and I like it)." }, { "code": null, "e": 1757, "s": 1655, "text": "In general term, there are two kinds of recommender system known by us, a human. Well, not all human." }, { "code": null, "e": 1879, "s": 1757, "text": "The type of recommender system that can easily be digested by our brain. Without a sign of short-circuiting or exploding." }, { "code": null, "e": 2022, "s": 1879, "text": "For example, you are an avid novel reader. And you like “And then there were none” by Agatha Christie. You bought it from an online bookstore." }, { "code": null, "e": 2122, "s": 2022, "text": "It makes sense if the bookstore will show you “The ABC Murders” the next time you open the website." }, { "code": null, "e": 2127, "s": 2122, "text": "Why?" }, { "code": null, "e": 2176, "s": 2127, "text": "Because both of them written by Agatha Christie." }, { "code": null, "e": 2248, "s": 2176, "text": "Hence, the Content-based filtering model will recommend you that title." }, { "code": null, "e": 2278, "s": 2248, "text": "Wow, so easy! Let’s use that!" }, { "code": null, "e": 2286, "s": 2278, "text": "Wait..." }, { "code": null, "e": 2421, "s": 2286, "text": "While Content-based filtering is easily digested by our brain and looks so simple, it can fail to guess the real behavior of the user." }, { "code": null, "e": 2572, "s": 2421, "text": "For example, I don’t like Hercule Poirot, but I like other detectives in her novels. In that case, “The ABC Murders” should not be recommended for me." }, { "code": null, "e": 2749, "s": 2572, "text": "This type will overcome the previous problem. Essentially, the system record all the previous interaction of the user on the website. And provide recommendations based on that." }, { "code": null, "e": 2767, "s": 2749, "text": "How does it work?" }, { "code": null, "e": 2797, "s": 2767, "text": "Take a look at this scenario." }, { "code": null, "e": 2827, "s": 2797, "text": "There are two users, A and B." }, { "code": null, "e": 2843, "s": 2827, "text": "A bought item 1" }, { "code": null, "e": 2859, "s": 2843, "text": "A bought item 2" }, { "code": null, "e": 2875, "s": 2859, "text": "A bought item 3" }, { "code": null, "e": 2891, "s": 2875, "text": "B bought item 1" }, { "code": null, "e": 2907, "s": 2891, "text": "B bought item 3" }, { "code": null, "e": 3032, "s": 2907, "text": "The collaborative filtering will recommend B item 2 since there is another user who bought items 1 and 3 also bought item 2." }, { "code": null, "e": 3111, "s": 3032, "text": "You might say, wow, they could be sporadically bought together in coincidence." }, { "code": null, "e": 3185, "s": 3111, "text": "But, what if, there are 100 users who have the same behavior with user A?" }, { "code": null, "e": 3231, "s": 3185, "text": "That was, the so-called, the power of crowds." }, { "code": null, "e": 3337, "s": 3231, "text": "So, why waiting? Let’s just start creating Collaborative filtering system in your production environment!" }, { "code": null, "e": 3360, "s": 3337, "text": "Hold your horse, mate!" }, { "code": null, "e": 3509, "s": 3360, "text": "While it has an extremely good performance. It has several serious issues. More importantly when you are trying to create a production-ready system." }, { "code": null, "e": 4409, "s": 3509, "text": "It doesn’t know about context. In contrast with Content-based filtering that recommends similar items, Collaborative filtering will not recommend based on similarity. When this is your concern, the solution is going hybrid. Combine both methods.It needs huge hardware resources since you need to store a user-item matrix. Imagine if you open your e-commerce website and it has 100K users. At the same time, you serve 10K products. In this case, you will need 10K x 100K matrix with each element hold 4 bytes integer. Yep, you need 4GB memory just for storing the matrix. Not even doing other things.Cold start. A new user will not get any benefit from the system since you have no idea about him.The unchangeable. If you are not doing anything on the website, the result of the recommender system will stay the same. The user will think that there is nothing new on the website. And they will leave." }, { "code": null, "e": 4655, "s": 4409, "text": "It doesn’t know about context. In contrast with Content-based filtering that recommends similar items, Collaborative filtering will not recommend based on similarity. When this is your concern, the solution is going hybrid. Combine both methods." }, { "code": null, "e": 5010, "s": 4655, "text": "It needs huge hardware resources since you need to store a user-item matrix. Imagine if you open your e-commerce website and it has 100K users. At the same time, you serve 10K products. In this case, you will need 10K x 100K matrix with each element hold 4 bytes integer. Yep, you need 4GB memory just for storing the matrix. Not even doing other things." }, { "code": null, "e": 5108, "s": 5010, "text": "Cold start. A new user will not get any benefit from the system since you have no idea about him." }, { "code": null, "e": 5312, "s": 5108, "text": "The unchangeable. If you are not doing anything on the website, the result of the recommender system will stay the same. The user will think that there is nothing new on the website. And they will leave." }, { "code": null, "e": 5413, "s": 5312, "text": "While the problem no. 1 is easily solved with going hybrid, the other ones will still be a headache." }, { "code": null, "e": 5479, "s": 5413, "text": "Well, solving the number 2, 3, and 4 is the reason for this post." }, { "code": null, "e": 5497, "s": 5479, "text": "Let’s just start." }, { "code": null, "e": 5717, "s": 5497, "text": "I might be in the same spot as you. I was really confused on how to make this thing possible. With the limitation of the machine, and of course common sense, I can’t deploy a huge service just for this tiny requirement." }, { "code": null, "e": 5756, "s": 5717, "text": "And by luck, I stumbled upon this book" }, { "code": null, "e": 5874, "s": 5756, "text": "They told me that for a production-ready system, you might not want the best accuracy of whatever performance it has." }, { "code": null, "e": 5955, "s": 5874, "text": "A somewhat inaccurate yet acceptable most often work in the real world use case." }, { "code": null, "e": 6008, "s": 5955, "text": "The most interesting part on how you can do that is," }, { "code": null, "e": 6199, "s": 6008, "text": "Batch computation on the general recommendation indicator.Query on real-time, without using the user-item matrix, but take several latest interactions of the user and query it to the system." }, { "code": null, "e": 6258, "s": 6199, "text": "Batch computation on the general recommendation indicator." }, { "code": null, "e": 6391, "s": 6258, "text": "Query on real-time, without using the user-item matrix, but take several latest interactions of the user and query it to the system." }, { "code": null, "e": 6433, "s": 6391, "text": "Let me explain while we build the system." }, { "code": null, "e": 6566, "s": 6433, "text": "Why python? Well, python is one of the easiest languages to learn. It will take you just a couple of hours to understand the syntax." }, { "code": null, "e": 6602, "s": 6566, "text": "for item in the_bag: print(item)" }, { "code": null, "e": 6645, "s": 6602, "text": "And you can print all the item in the bag." }, { "code": null, "e": 6656, "s": 6645, "text": "That easy." }, { "code": null, "e": 6740, "s": 6656, "text": "Go to Python website to download and install it according to your Operating System." }, { "code": null, "e": 6785, "s": 6740, "text": "For this tutorial, you need several packages" }, { "code": null, "e": 6877, "s": 6785, "text": "pip install numpypip install scipypip install pandaspip install jupyterpip install requests" }, { "code": null, "e": 7105, "s": 6877, "text": "Numpy and Scipy are python package to handle mathematical computation, you will need them for the matrix. Pandas is used for your data. Requests is for http calls. and Jupyter is a web app to run your python code interactively." }, { "code": null, "e": 7164, "s": 7105, "text": "type jupyter notebook and you will see something like this" }, { "code": null, "e": 7242, "s": 7164, "text": "Write the code on the cells provided, and the code will be run interactively." }, { "code": null, "e": 7283, "s": 7242, "text": "Before we begin, you need several tools." }, { "code": null, "e": 7620, "s": 7283, "text": "Elasticsearch. it is an open-source search engine, that can enable you to search your document really fast. You will need this tool to save your computed indicator so that you can query in real-time.Postman. an API development tool. You will need this to simulate the query into elasticsearch. As elasticsearch can be accessed via http." }, { "code": null, "e": 7820, "s": 7620, "text": "Elasticsearch. it is an open-source search engine, that can enable you to search your document really fast. You will need this tool to save your computed indicator so that you can query in real-time." }, { "code": null, "e": 7958, "s": 7820, "text": "Postman. an API development tool. You will need this to simulate the query into elasticsearch. As elasticsearch can be accessed via http." }, { "code": null, "e": 8018, "s": 7958, "text": "Download and install both of them, and you are ready to go." }, { "code": null, "e": 8193, "s": 8018, "text": "For this tutorial, let’s take a look at a dataset in Kaggle. The Retailrocket recommender system dataset. Download it and extract the data in your Jupyter notebook directory." }, { "code": null, "e": 8217, "s": 8193, "text": "It should be like that." }, { "code": null, "e": 8280, "s": 8217, "text": "Among those files, you only need events.csv for this tutorial." }, { "code": null, "e": 8371, "s": 8280, "text": "That file consists of millions of actions by users to the items on the e-commerce website." }, { "code": null, "e": 8409, "s": 8371, "text": "import pandas as pdimport numpy as np" }, { "code": null, "e": 8479, "s": 8409, "text": "Write those imports on the Jupyter notebook. And you are ready to go." }, { "code": null, "e": 8518, "s": 8479, "text": "df = pd.read_csv('events.csv')df.shape" }, { "code": null, "e": 8594, "s": 8518, "text": "It will print you (2756101, 5). It means you have 2.7M rows with 5 columns." }, { "code": null, "e": 8614, "s": 8594, "text": "Let’s check it out." }, { "code": null, "e": 8624, "s": 8614, "text": "df.head()" }, { "code": null, "e": 8645, "s": 8624, "text": "It has five columns." }, { "code": null, "e": 8824, "s": 8645, "text": "Timestamp, the timestamp of the event.Visitorid, the id of the userItemid, the id of the itemEvent, the eventTransactionid, an id of the transaction if the event is a transaction" }, { "code": null, "e": 8863, "s": 8824, "text": "Timestamp, the timestamp of the event." }, { "code": null, "e": 8893, "s": 8863, "text": "Visitorid, the id of the user" }, { "code": null, "e": 8920, "s": 8893, "text": "Itemid, the id of the item" }, { "code": null, "e": 8937, "s": 8920, "text": "Event, the event" }, { "code": null, "e": 9007, "s": 8937, "text": "Transactionid, an id of the transaction if the event is a transaction" }, { "code": null, "e": 9054, "s": 9007, "text": "Let’s check, what kind of events are available" }, { "code": null, "e": 9072, "s": 9054, "text": "df.event.unique()" }, { "code": null, "e": 9132, "s": 9072, "text": "You will get three events, view, addtocart, and transaction" }, { "code": null, "e": 9272, "s": 9132, "text": "For the sake of simplicity, you might not want to play with all of the events. And for this tutorial, you will only play with transactions." }, { "code": null, "e": 9312, "s": 9272, "text": "So, let’s filter the transactions only." }, { "code": null, "e": 9364, "s": 9312, "text": "trans = df[df['event'] == 'transaction']trans.shape" }, { "code": null, "e": 9390, "s": 9364, "text": "It will return (22457, 5)" }, { "code": null, "e": 9488, "s": 9390, "text": "You will have 22K transactions you can play with. I think it is good enough for a newbie like us." }, { "code": null, "e": 9528, "s": 9488, "text": "Let’s take a look further into the data" }, { "code": null, "e": 9638, "s": 9528, "text": "visitors = trans['visitorid'].unique()items = trans['itemid'].unique()print(visitors.shape)print(items.shape)" }, { "code": null, "e": 9699, "s": 9638, "text": "You will get 11,719 unique visitors and 12,025 unique items." }, { "code": null, "e": 9967, "s": 9699, "text": "The rule of thumb on creating a simple yet effective recommender system is to downsample the data without losing quality. It means, you can take only maybe 50 latest transactions for each user and you still get the quality you want because behavior changes over-time." }, { "code": null, "e": 10026, "s": 9967, "text": "trans2 = trans.groupby(['visitorid']).head(50)trans2.shape" }, { "code": null, "e": 10108, "s": 10026, "text": "Now you only have 19,939 transactions. Means around 2K transactions are obsolete." }, { "code": null, "e": 10212, "s": 10108, "text": "Because of the visitor id and item id are huge numbers, you will be hard to remember each of those ids." }, { "code": null, "e": 10392, "s": 10212, "text": "trans2['visitors'] = trans2['visitorid'].apply(lambda x : np.argwhere(visitors == x)[0][0])trans2['items'] = trans2['itemid'].apply(lambda x : np.argwhere(items == x)[0][0])trans2" }, { "code": null, "e": 10475, "s": 10392, "text": "You need other columns that are a 0 based index. You will see something like this." }, { "code": null, "e": 10567, "s": 10475, "text": "It’s cleaner. Now you can use only the visitors and items column for all of our next steps." }, { "code": null, "e": 10594, "s": 10567, "text": "The nightmare is coming..." }, { "code": null, "e": 10702, "s": 10594, "text": "You have 11,719 unique visitors and 12,025 items, so you will need around 500MB memory to store the matrix." }, { "code": null, "e": 10737, "s": 10702, "text": "Sparse matrix comes to the rescue." }, { "code": null, "e": 10902, "s": 10737, "text": "Sparse matrices are a matrix with most of their element are zero. It makes sense since not all of the users buy all the items. Lot’s of the connection will be zero." }, { "code": null, "e": 10938, "s": 10902, "text": "from scipy.sparse import csr_matrix" }, { "code": null, "e": 10959, "s": 10938, "text": "Scipy has the thing." }, { "code": null, "e": 11191, "s": 10959, "text": "occurences = csr_matrix((visitors.shape[0], items.shape[0]), dtype='int8')def set_occurences(visitor, item): occurences[visitor, item] += 1trans2.apply(lambda row: set_occurences(row['visitors'], row['items']), axis=1)occurences" }, { "code": null, "e": 11259, "s": 11191, "text": "Apply the set_occurences function on each row in the data you have." }, { "code": null, "e": 11293, "s": 11259, "text": "It will print something like this" }, { "code": null, "e": 11411, "s": 11293, "text": "<11719x12025 sparse matrix of type '<class 'numpy.int8'>'\twith 18905 stored elements in Compressed Sparse Row format>" }, { "code": null, "e": 11493, "s": 11411, "text": "From those 140 million cells in the matrix, only 18,905 are filled with non-zero." }, { "code": null, "e": 11593, "s": 11493, "text": "So basically you only need to store those 18,905 value to the memory. A 99.99% improved efficiency." }, { "code": null, "e": 11747, "s": 11593, "text": "The downside of the sparse matrix is, it is computationally higher when trying to retrieve the data in real-time. So, you should not finish at this step." }, { "code": null, "e": 11895, "s": 11747, "text": "Let’s construct an item-item matrix where each element means how many times both items bought together by a user. Call it the co-occurrence matrix." }, { "code": null, "e": 12005, "s": 11895, "text": "To create a co-occurrence matrix, you need to dot product the transpose of the occurrence matrix with itself." }, { "code": null, "e": 12106, "s": 12005, "text": "I have tried it without sparse matrix and my computer suddenly stops working. So, let’s not do that." }, { "code": null, "e": 12167, "s": 12106, "text": "cooc = occurences.transpose().dot(occurences)cooc.setdiag(0)" }, { "code": null, "e": 12227, "s": 12167, "text": "It finished instantly with a sparse matrix. And I am happy." }, { "code": null, "e": 12386, "s": 12227, "text": "The setdiag function is setting the diagonal to 0, means you don’t want to compute the value of item 1 and item 1 comes together since they are the same item." }, { "code": null, "e": 12478, "s": 12386, "text": "The co-occurrence matrix will consist of the number of the time both items bought together." }, { "code": null, "e": 12631, "s": 12478, "text": "But there is a chance, that there is an item. That item is bought regardless of the behavior of the user. Might be a flash sale, or something like that." }, { "code": null, "e": 12793, "s": 12631, "text": "In reality, you might want to really capture the behavior of the user, clean from something like that flash sale. Because it is not a behavior you are expecting." }, { "code": null, "e": 12886, "s": 12793, "text": "To remove those things affected, you need to penalize the score on the co-occurrence matrix." }, { "code": null, "e": 12974, "s": 12886, "text": "Ted Dunnings in the previous book has an algorithm called, Log-Likelihood Ratio or LLR." }, { "code": null, "e": 13627, "s": 12974, "text": "def xLogX(x): return x * np.log(x) if x != 0 else 0.0def entropy(x1, x2=0, x3=0, x4=0): return xLogX(x1 + x2 + x3 + x4) - xLogX(x1) - xLogX(x2) - xLogX(x3) - xLogX(x4)def LLR(k11, k12, k21, k22): rowEntropy = entropy(k11 + k12, k21 + k22) columnEntropy = entropy(k11 + k21, k12 + k22) matrixEntropy = entropy(k11, k12, k21, k22) if rowEntropy + columnEntropy < matrixEntropy: return 0.0 return 2.0 * (rowEntropy + columnEntropy - matrixEntropy)def rootLLR(k11, k12, k21, k22): llr = LLR(k11, k12, k21, k22) sqrt = np.sqrt(llr) if k11 * 1.0 / (k11 + k12) < k21 * 1.0 / (k21 + k22): sqrt = -sqrt return sqrt" }, { "code": null, "e": 13712, "s": 13627, "text": "The LLR function is computing the likelihood of two events, A and B appear together." }, { "code": null, "e": 13732, "s": 13712, "text": "The parameters are," }, { "code": null, "e": 13905, "s": 13732, "text": "k11, number of when both events appeared togetherk12, number of B appear without Ak21, number of A appear without Bk22, number of other things appeared without both of them" }, { "code": null, "e": 13955, "s": 13905, "text": "k11, number of when both events appeared together" }, { "code": null, "e": 13989, "s": 13955, "text": "k12, number of B appear without A" }, { "code": null, "e": 14023, "s": 13989, "text": "k21, number of A appear without B" }, { "code": null, "e": 14081, "s": 14023, "text": "k22, number of other things appeared without both of them" }, { "code": null, "e": 14148, "s": 14081, "text": "Now calculate the LLR function and save it to the pp_score matrix." }, { "code": null, "e": 14575, "s": 14148, "text": "row_sum = np.sum(cooc, axis=0).A.flatten()column_sum = np.sum(cooc, axis=1).A.flatten()total = np.sum(row_sum, axis=0)pp_score = csr_matrix((cooc.shape[0], cooc.shape[1]), dtype='double')cx = cooc.tocoo()for i,j,v in zip(cx.row, cx.col, cx.data): if v != 0: k11 = v k12 = row_sum[i] - k11 k21 = column_sum[j] - k11 k22 = total - k11 - k12 - k21 pp_score[i,j] = rootLLR(k11, k12, k21, k22)" }, { "code": null, "e": 14671, "s": 14575, "text": "Sort the result, so that the highest LLR score on each item is on the first column of each row." }, { "code": null, "e": 14789, "s": 14671, "text": "result = np.flip(np.sort(pp_score.A, axis=1), axis=1)result_indices = np.flip(np.argsort(pp_score.A, axis=1), axis=1)" }, { "code": null, "e": 14890, "s": 14789, "text": "That first item on the result matrix, if high enough, can be considered as an indicator to the item." }, { "code": null, "e": 14929, "s": 14890, "text": "Let’s take a look at one of the result" }, { "code": null, "e": 14942, "s": 14929, "text": "result[8456]" }, { "code": null, "e": 14955, "s": 14942, "text": "You will get" }, { "code": null, "e": 15052, "s": 14955, "text": "array([15.33511076, 14.60017668, 3.62091635, ..., 0. , 0. , 0. ])" }, { "code": null, "e": 15079, "s": 15052, "text": "And looking at the indices" }, { "code": null, "e": 15100, "s": 15079, "text": "result_indices[8456]" }, { "code": null, "e": 15113, "s": 15100, "text": "Will get you" }, { "code": null, "e": 15175, "s": 15113, "text": "array([8682, 380, 8501, ..., 8010, 8009, 0], dtype=int64)" }, { "code": null, "e": 15378, "s": 15175, "text": "You can safely answer that with a high number of LLR score, item 8682 and 380 can be an indicator for item 8456. While item 8501 since the score is not that big, might not be an indicator for item 8456." }, { "code": null, "e": 15453, "s": 15378, "text": "It means that, if someone bought 8682 and 380, you can recommend him 8456." }, { "code": null, "e": 15459, "s": 15453, "text": "Easy." }, { "code": null, "e": 15582, "s": 15459, "text": "But, for a rule of thumb, you might want to give some limit on the LLR score, so insignificant indicators will be removed." }, { "code": null, "e": 15871, "s": 15582, "text": "minLLR = 5indicators = result[:, :50]indicators[indicators < minLLR] = 0.0indicators_indices = result_indices[:, :50]max_indicator_indices = (indicators==0).argmax(axis=1)max = max_indicator_indices.max()indicators = indicators[:, :max+1]indicators_indices = indicators_indices[:, :max+1]" }, { "code": null, "e": 15979, "s": 15871, "text": "Now you are ready to put those together to elasticsearch. So you can query the recommendation in real-time." }, { "code": null, "e": 16006, "s": 15979, "text": "import requestsimport json" }, { "code": null, "e": 16095, "s": 16006, "text": "Okay, now you are ready to put the things inside elasticsearch you have prepared before." }, { "code": null, "e": 16321, "s": 16095, "text": "But, be careful. If you are trying to add the data one by one using /_create/<id> API, it will take you forever. Of course, you can, but you need maybe half an hour to an hour just to move our 12,025 items into elasticsearch." }, { "code": null, "e": 16372, "s": 16321, "text": "I did it once, so please, don’t repeat my mistake." }, { "code": null, "e": 16396, "s": 16372, "text": "So what’s the solution?" }, { "code": null, "e": 16485, "s": 16396, "text": "Fortunately, elasticsearch has bulk API that can easily send multiple documents at once." }, { "code": null, "e": 16573, "s": 16485, "text": "So, create a new index (items2, I used items for the previous mistake) and let’s try it" }, { "code": null, "e": 17543, "s": 16573, "text": "actions = []for i in range(indicators.shape[0]): length = indicators[i].nonzero()[0].shape[0] real_indicators = items[indicators_indices[i, :length]].astype(\"int\").tolist() id = items[i] action = { \"index\" : { \"_index\" : \"items2\", \"_id\" : str(id) } } data = { \"id\": int(id), \"indicators\": real_indicators } actions.append(json.dumps(action)) actions.append(json.dumps(data)) if len(actions) == 200: actions_string = \"\\n\".join(actions) + \"\\n\" actions = [] url = \"http://127.0.0.1:9200/_bulk/\" headers = { \"Content-Type\" : \"application/x-ndjson\" } requests.post(url, headers=headers, data=actions_string)if len(actions) > 0: actions_string = \"\\n\".join(actions) + \"\\n\" actions = [] url = \"http://127.0.0.1:9200/_bulk/\" headers = { \"Content-Type\" : \"application/x-ndjson\" } requests.post(url, headers=headers, data=actions_string)" }, { "code": null, "e": 17593, "s": 17543, "text": "And voila, it will finish within several seconds." }, { "code": null, "e": 17617, "s": 17593, "text": "Hit this API in Postman" }, { "code": null, "e": 17646, "s": 17617, "text": "127.0.0.1:9200/items2/_count" }, { "code": null, "e": 17685, "s": 17646, "text": "You will have your data stored already" }, { "code": null, "e": 17811, "s": 17685, "text": "{ \"count\": 12025, \"_shards\": { \"total\": 1, \"successful\": 1, \"skipped\": 0, \"failed\": 0 }}" }, { "code": null, "e": 17868, "s": 17811, "text": "Let’s check to the data of your item with /items2/240708" }, { "code": null, "e": 17956, "s": 17868, "text": "{ \"id\": 240708, \"indicators\": [ 305675, 346067, 312728 ]}" }, { "code": null, "e": 18067, "s": 17956, "text": "Id is the id of the item. While indicators are the other items which become indicators to recommend this item." }, { "code": null, "e": 18126, "s": 18067, "text": "The best part of the thing we create is a real-time query," }, { "code": null, "e": 18239, "s": 18126, "text": "{ \"query\": { \"bool\": { \"should\": [ { \"terms\": {\"indicators\" : [240708], \"boost\": 2}} ] } }}" }, { "code": null, "e": 18289, "s": 18239, "text": "Post the request to 127.0.0.1:9200/items2/_search" }, { "code": null, "e": 18417, "s": 18289, "text": "And you will get three results. 312728, 305675, and 346067. Exactly the three items that were bought together with item 240708." }, { "code": null, "e": 18526, "s": 18417, "text": "Great! So, the problem of needing a huge resource is a non-factor now. So, how about the other two problems?" }, { "code": null, "e": 18566, "s": 18526, "text": "Before that, rest your eye for a while." }, { "code": null, "e": 18726, "s": 18566, "text": "The very common problem when building recommender systems is the cold start problem. Every new user will not have any of their behavior recorded in the system." }, { "code": null, "e": 18769, "s": 18726, "text": "So, what should the system recommend them?" }, { "code": null, "e": 18880, "s": 18769, "text": "Let’s take a look at our recently built recommendation system. Do you think anything strange about the result?" }, { "code": null, "e": 18985, "s": 18880, "text": "Yep, the result only returns 3 recommended items. Just 3. How do you plan to display it to the customer?" }, { "code": null, "e": 19097, "s": 18985, "text": "Let’s display the other item not recommended at the end of the list. Just for the sake of good user experience." }, { "code": null, "e": 19276, "s": 19097, "text": "{ \"query\": { \"bool\": { \"should\": [ { \"terms\": {\"indicators\" : [240708]}}, { \"constant_score\": {\"filter\" : {\"match_all\": {}}, \"boost\" : 0.000001}} ] } }}" }, { "code": null, "e": 19332, "s": 19276, "text": "You can use a constant score to return all other items." }, { "code": null, "e": 19487, "s": 19332, "text": "But, for all the non-recommended items, you need to rank them so that the things that users probably will like even though not captured in their behavior." }, { "code": null, "e": 19534, "s": 19487, "text": "In many cases, popular item works really well." }, { "code": null, "e": 19571, "s": 19534, "text": "How do you calculate a popular item?" }, { "code": null, "e": 19711, "s": 19571, "text": "popular = np.zeros(items.shape[0])def inc_popular(index): popular[index] += 1trans2.apply(lambda row: inc_popular(row['items']), axis=1)" }, { "code": null, "e": 19807, "s": 19711, "text": "Simple, count the item appearance one by one. So the highest popular value is the most popular." }, { "code": null, "e": 19866, "s": 19807, "text": "Let’s create another index, called items3. And bulk insert" }, { "code": null, "e": 20922, "s": 19866, "text": "actions = []for i in range(indicators.shape[0]): length = indicators[i].nonzero()[0].shape[0] real_indicators = items[indicators_indices[i, :length]].astype(\"int\").tolist() id = items[i] action = { \"index\" : { \"_index\" : \"items3\", \"_id\" : str(id) } } # url = \"http://127.0.0.1:9200/items/_create/\" + str(id) data = { \"id\": int(id), \"indicators\": real_indicators, \"popular\": popular[i] } actions.append(json.dumps(action)) actions.append(json.dumps(data)) if len(actions) == 200: actions_string = \"\\n\".join(actions) + \"\\n\" actions = [] url = \"http://127.0.0.1:9200/_bulk/\" headers = { \"Content-Type\" : \"application/x-ndjson\" } requests.post(url, headers=headers, data=actions_string)if len(actions) > 0: actions_string = \"\\n\".join(actions) + \"\\n\" actions = []url = \"http://127.0.0.1:9200/_bulk/\" headers = { \"Content-Type\" : \"application/x-ndjson\" } requests.post(url, headers=headers, data=actions_string)" }, { "code": null, "e": 21011, "s": 20922, "text": "In this indexing phase, you include the popular field. So, your data will look like this" }, { "code": null, "e": 21118, "s": 21011, "text": "{ \"id\": 240708, \"indicators\": [ 305675, 346067, 312728 ], \"popular\": 3.0}" }, { "code": null, "e": 21250, "s": 21118, "text": "You will have three fields. Id and indicators like the previous one, and the popular field. The count of that item bought by users." }, { "code": null, "e": 21291, "s": 21250, "text": "Let’s add popular to our previous query." }, { "code": null, "e": 21403, "s": 21291, "text": "So, you have multiple sources of scores now, i.e. the indicator matches and popular, how to combine the scores?" }, { "code": null, "e": 21453, "s": 21403, "text": "Elasticsearch has function score to do with that." }, { "code": null, "e": 21982, "s": 21453, "text": "{ \"query\": { \"function_score\":{ \"query\": { \"bool\": { \"should\": [ { \"terms\": {\"indicators\" : [240708], \"boost\": 2}}, { \"constant_score\": {\"filter\" : {\"match_all\": {}}, \"boost\" : 0.000001}} ] } }, \"functions\":[ { \"filter\": {\"range\": {\"popular\": {\"gt\": 0}}}, \"script_score\" : { \"script\" : { \"source\": \"doc['popular'].value * 0.1\" } } } ], \"score_mode\": \"sum\", \"min_score\" : 0 } }}" }, { "code": null, "e": 22204, "s": 21982, "text": "Rework your query and add a function score to slightly add 0.1 times the popular value to the constant score you have above. You don’t have to stick with 0.1, you can use other function, even Natural logarithm. Like this," }, { "code": null, "e": 22235, "s": 22204, "text": "Math.log(doc['popular'].value)" }, { "code": null, "e": 22333, "s": 22235, "text": "Now, you will see your most popular item, 461686 placed fourth, just below the recommended items." }, { "code": null, "e": 22369, "s": 22333, "text": "And also other popular items below." }, { "code": null, "e": 22568, "s": 22369, "text": "As you can see, our result stays the same every time we run the real-time query. That might be good because our technique is reproducible, but at the same time, the user might not be happy about it." }, { "code": null, "e": 22764, "s": 22568, "text": "Ted Dunnings from the book said, the click-through rate of the recommendation, will fall really low after the 20th result. It means any item we recommend after that will not be known to the user." }, { "code": null, "e": 22783, "s": 22764, "text": "How to solve this?" }, { "code": null, "e": 22962, "s": 22783, "text": "There is a technique called dithering. It is creating a random noise when querying to bring up the least recommended item but still make the strongly recommended item at the top." }, { "code": null, "e": 23576, "s": 22962, "text": "{ \"query\": { \"function_score\":{ \"query\": { \"bool\": { \"should\": [ { \"terms\": {\"indicators\" : [240708], \"boost\": 2}}, { \"constant_score\": {\"filter\" : {\"match_all\": {}}, \"boost\" : 0.000001}} ] } }, \"functions\":[ { \"filter\": {\"range\": {\"popular\": {\"gt\": 1}}}, \"script_score\" : { \"script\" : { \"source\": \"0.1 * Math.log(doc['popular'].value)\" } } }, { \"filter\": {\"match_all\": {}}, \"random_score\": {} } ], \"score_mode\": \"sum\", \"min_score\" : 0 } }}" }, { "code": null, "e": 23737, "s": 23576, "text": "The random score, it will give all of your item uniformly distributed random noise. The score will be minuscule so that the top recommendation will not go down." }, { "code": null, "e": 23785, "s": 23737, "text": "Hit that query, and see the result. You can see" }, { "code": null, "e": 23985, "s": 23785, "text": "The positive note is. your user will not have to go scrolling to the second or third page. He or she just needs to hit that refresh button on the browser, and he or she will be provided new contents." }, { "code": null, "e": 24002, "s": 23985, "text": "Just like magic." }, { "code": null, "e": 24112, "s": 24002, "text": "Building a production-ready recommender system is not that hard. And current technology allows us to do that." }, { "code": null, "e": 24187, "s": 24112, "text": "Create the system with your data and get ready to deploy it to production." } ]
Empty List in C#
Set a list that has zero elements − List<string> myList = new List<string>(); Now check whether the list is empty or null − Console.WriteLine(myList == null); Above, returns “False” i.e. the list is not null - the list is empty. Let us see the complete code − Live Demo using System; using System.Collections.Generic; using System.Linq; public class Demo { public static void Main() { List<string> myList = new List<string>(); // returns false i.e. an empty list (not a null list) Console.WriteLine(myList == null); } } False
[ { "code": null, "e": 1098, "s": 1062, "text": "Set a list that has zero elements −" }, { "code": null, "e": 1140, "s": 1098, "text": "List<string> myList = new List<string>();" }, { "code": null, "e": 1186, "s": 1140, "text": "Now check whether the list is empty or null −" }, { "code": null, "e": 1221, "s": 1186, "text": "Console.WriteLine(myList == null);" }, { "code": null, "e": 1291, "s": 1221, "text": "Above, returns “False” i.e. the list is not null - the list is empty." }, { "code": null, "e": 1322, "s": 1291, "text": "Let us see the complete code −" }, { "code": null, "e": 1333, "s": 1322, "text": " Live Demo" }, { "code": null, "e": 1607, "s": 1333, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n List<string> myList = new List<string>();\n // returns false i.e. an empty list (not a null list)\n Console.WriteLine(myList == null);\n }\n}" }, { "code": null, "e": 1613, "s": 1607, "text": "False" } ]
PHP Generators.
Traversing a big collection of data using looping construct such as foreach would require large memory and considerable processing time. With generators it is possible to iterate over a set of data without these overheads. A generator function is similar to a normal function. However, instead of return statement in a function, generator uses yield keyword to be executed repeatedly so that it provides values to be iterated. The yield keyword is the heart of generator mechanism. Even though its use appears to be similar to return, it doesn't stop execution of function. It provides next value for iteration and pauses execution of function. A for loop yields each value of looping variable is used inside a generator function Live Demo <?php function squaregenerator(){ for ($i=1; $i<=5; $i++){ yield $i*$i; } } $gen=squaregenerator(); foreach ($gen as $val){ echo $val . " "; } ?> As foreach statement tries to display valforfirsttime,thesquaregeneratoryieldsfirstelement,retainsi and pauses execution till foreach takes next iteration. The output is similar to a regular foreach loop 1 4 9 16 25 PHP's range() function returns a list of integers from starttostop with interval of $step between each numbers. Following program implements range() as generator Live Demo <?php function rangegenerator($start, $stop, $step){ for ($i=$start; $i<=$stop; $i+=$step){ yield $i; } } foreach (rangegenerator(2,10,2) as $val){ echo $val . " "; } ?> Output is similar to range(2,20,2) 2 4 6 8 10 An associative array can also be implemented as generator Live Demo <?php function arrgenerator($arr){ foreach ($arr as $key=>$val){ yield $key=>$val; } } $arr=array("one"=>1, "two"=>2, "three"=>3, "four"=>4); $gen=arrgenerator($arr); foreach ($gen as $key=>$val) echo $key . "=>" . $val . "\n"; ?> one=>1 two=>2 three=>3 four=>4
[ { "code": null, "e": 1489, "s": 1062, "text": "Traversing a big collection of data using looping construct such as foreach would require large memory and considerable processing time. With generators it is possible to iterate over a set of data without these overheads. A generator function is similar to a normal function. However, instead of return statement in a function, generator uses yield keyword to be executed repeatedly so that it provides values to be iterated." }, { "code": null, "e": 1707, "s": 1489, "text": "The yield keyword is the heart of generator mechanism. Even though its use appears to be similar to return, it doesn't stop execution of function. It provides next value for iteration and pauses execution of function." }, { "code": null, "e": 1792, "s": 1707, "text": "A for loop yields each value of looping variable is used inside a generator function" }, { "code": null, "e": 1803, "s": 1792, "text": " Live Demo" }, { "code": null, "e": 1964, "s": 1803, "text": "<?php\nfunction squaregenerator(){\n for ($i=1; $i<=5; $i++){\n yield $i*$i;\n }\n}\n$gen=squaregenerator();\nforeach ($gen as $val){\n echo $val . \" \";\n}\n?>" }, { "code": null, "e": 2168, "s": 1964, "text": "As foreach statement tries to display valforfirsttime,thesquaregeneratoryieldsfirstelement,retainsi and pauses execution till foreach takes next iteration. The output is similar to a regular foreach loop" }, { "code": null, "e": 2180, "s": 2168, "text": "1 4 9 16 25" }, { "code": null, "e": 2342, "s": 2180, "text": "PHP's range() function returns a list of integers from starttostop with interval of $step between each numbers. Following program implements range() as generator" }, { "code": null, "e": 2353, "s": 2342, "text": " Live Demo" }, { "code": null, "e": 2538, "s": 2353, "text": "<?php\nfunction rangegenerator($start, $stop, $step){\n for ($i=$start; $i<=$stop; $i+=$step){\n yield $i;\n }\n}\nforeach (rangegenerator(2,10,2) as $val){\n echo $val . \" \";\n}\n?>" }, { "code": null, "e": 2573, "s": 2538, "text": "Output is similar to range(2,20,2)" }, { "code": null, "e": 2584, "s": 2573, "text": "2 4 6 8 10" }, { "code": null, "e": 2642, "s": 2584, "text": "An associative array can also be implemented as generator" }, { "code": null, "e": 2653, "s": 2642, "text": " Live Demo" }, { "code": null, "e": 2896, "s": 2653, "text": "<?php\nfunction arrgenerator($arr){\n foreach ($arr as $key=>$val){\n yield $key=>$val;\n }\n}\n$arr=array(\"one\"=>1, \"two\"=>2, \"three\"=>3, \"four\"=>4);\n$gen=arrgenerator($arr);\nforeach ($gen as $key=>$val)\necho $key . \"=>\" . $val . \"\\n\";\n?>" }, { "code": null, "e": 2927, "s": 2896, "text": "one=>1\ntwo=>2\nthree=>3\nfour=>4" } ]
Lua - if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The syntax of an if...else statement in Lua programming language is − if(boolean_expression) then --[ statement(s) will execute if the boolean expression is true --] else --[ statement(s) will execute if the boolean expression is false --] end If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. Lua programming language assumes any combination of Boolean true and non-nil values as true, and if it is either Boolean false or nil, then it is assumed as false value. It is to be noted that in Lua, zero will be considered as true. --[ local variable definition --] a = 100; --[ check the boolean condition --] if( a < 20 ) then --[ if condition is true then print the following --] print("a is less than 20" ) else --[ if condition is false then print the following --] print("a is not less than 20" ) end print("value of a is :", a) When you build and run the above code, it produces the following result. a is not less than 20 value of a is : 100 An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. While using if , else if , else statements, there are a few points to keep in mind − An if can have zero or one else's and it must come after any else if's. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. The syntax of an if...else if...else statement in Lua programming language is − if(boolean_expression 1) then --[ Executes when the boolean expression 1 is true --] elseif( boolean_expression 2) --[ Executes when the boolean expression 2 is true --] elseif( boolean_expression 3) --[ Executes when the boolean expression 3 is true --] else --[ executes when the none of the above condition is true --] end --[ local variable definition --] a = 100 --[ check the boolean condition --] if( a == 10 ) then --[ if condition is true then print the following --] print("Value of a is 10" ) elseif( a == 20 ) then --[ if else if condition is true --] print("Value of a is 20" ) elseif( a == 30 ) then --[ if else if condition is true --] print("Value of a is 30" ) else --[ if none of the conditions is true --] print("None of the values is matching" ) end print("Exact value of a is: ", a ) When you build and run the above code, it produces the following result. None of the values is matching Exact value of a is: 100 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 2103, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 2289, "s": 2219, "text": "The syntax of an if...else statement in Lua programming language is −" }, { "code": null, "e": 2470, "s": 2289, "text": "if(boolean_expression)\nthen\n --[ statement(s) will execute if the boolean expression is true --]\nelse\n --[ statement(s) will execute if the boolean expression is false --]\nend\n" }, { "code": null, "e": 2606, "s": 2470, "text": "If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed." }, { "code": null, "e": 2840, "s": 2606, "text": "Lua programming language assumes any combination of Boolean true and non-nil values as true, and if it is either Boolean false or nil, then it is assumed as false value. It is to be noted that in Lua, zero will be considered as true." }, { "code": null, "e": 3158, "s": 2840, "text": "--[ local variable definition --]\na = 100;\n\n--[ check the boolean condition --]\n\nif( a < 20 )\nthen\n --[ if condition is true then print the following --]\n print(\"a is less than 20\" )\nelse\n --[ if condition is false then print the following --]\n print(\"a is not less than 20\" )\nend\n\nprint(\"value of a is :\", a)" }, { "code": null, "e": 3231, "s": 3158, "text": "When you build and run the above code, it produces the following result." }, { "code": null, "e": 3274, "s": 3231, "text": "a is not less than 20\nvalue of a is :\t100\n" }, { "code": null, "e": 3432, "s": 3274, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 3517, "s": 3432, "text": "While using if , else if , else statements, there are a few points to keep in mind −" }, { "code": null, "e": 3589, "s": 3517, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3661, "s": 3589, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 3735, "s": 3661, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3809, "s": 3735, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 3893, "s": 3809, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 3977, "s": 3893, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4057, "s": 3977, "text": "The syntax of an if...else if...else statement in Lua programming language is −" }, { "code": null, "e": 4399, "s": 4057, "text": "if(boolean_expression 1)\nthen\n --[ Executes when the boolean expression 1 is true --]\n\nelseif( boolean_expression 2)\n --[ Executes when the boolean expression 2 is true --]\n\nelseif( boolean_expression 3)\n --[ Executes when the boolean expression 3 is true --]\nelse \n --[ executes when the none of the above condition is true --]\nend\n" }, { "code": null, "e": 4908, "s": 4399, "text": "--[ local variable definition --]\na = 100\n\n--[ check the boolean condition --]\n\nif( a == 10 )\nthen\n --[ if condition is true then print the following --]\n print(\"Value of a is 10\" )\nelseif( a == 20 )\nthen \n --[ if else if condition is true --]\n print(\"Value of a is 20\" )\nelseif( a == 30 )\nthen\n --[ if else if condition is true --]\n print(\"Value of a is 30\" )\nelse\n --[ if none of the conditions is true --]\n print(\"None of the values is matching\" )\nend\nprint(\"Exact value of a is: \", a )" }, { "code": null, "e": 4981, "s": 4908, "text": "When you build and run the above code, it produces the following result." }, { "code": null, "e": 5038, "s": 4981, "text": "None of the values is matching\nExact value of a is:\t100\n" }, { "code": null, "e": 5071, "s": 5038, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 5085, "s": 5071, "text": " Manish Gupta" }, { "code": null, "e": 5118, "s": 5085, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 5134, "s": 5118, "text": " Sanjeev Mittal" }, { "code": null, "e": 5169, "s": 5134, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5185, "s": 5169, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 5192, "s": 5185, "text": " Print" }, { "code": null, "e": 5203, "s": 5192, "text": " Add Notes" } ]
MariaDB - Installation
All downloads for MariaDB are located in the Download section of the official MariaDB foundation website. Click the link to the version you would like, and a list of downloads for multiple operating systems, architectures, and installation file types is displayed. If you have intimate knowledge of Linux/Unix systems, simply download source to build your install. Our recommended way of installing is to utilize distribution packages. MariaDB offers packages for the following Linux/Unix distributions − RedHat/CentOS/Fedora Debian/Ubuntu The following distributions include a MariaDB package in their repositories − openSUSE Arch Linux Mageia Mint Slackware Follow these steps to install in an Ubuntu environment − Step 1 − Login as a root user. Step 2 − Navigate to the directory containing the MariaDB package. Step 3 − Import the GnuPG signing key with the following code − sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xcbcb082a1bb943db Step 4 − Add MariaDB to the sources.list file. Open the file, and add the following code − sudo add-apt-repository 'deb http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntuprecise main' Step 5 − Refresh the system with the following − sudo apt-get update Step 6 − Install MariaDB with the following − sudo apt-get install mariadb-server After locating and downloading an automated install file (MSI), simply double click the file to start the installation. The installation wizard will walk you through every step of installation and any necessary settings. Test the installation by starting it from the command prompt. Navigate to the location of the installation, typically in the directory, and type the following at the prompt − mysqld.exe --console If the installation is successful, you will see messages related to startup. If this does not appear, you may have permission issues. Ensure that your user account can access the application. Graphical clients are available for MariaDB administration in the Windows environment. If you find the command line uncomfortable or cumbersome, be sure to experiment with them. Perform a few simple tasks to confirm the functioning and installation of MariaDB. Use the Admin Utility to Get Server Status View the server version with the mysqladmin binary. [root@host]# mysqladmin --version It should display the version, distribution, operating system, and architecture. If you do not see the output of that type, examine your installation for issues. Execute Simple Commands with a Client Bring up the command prompt for MariaDB. This should connect you to MariaDB and allow execution of commands. Enter a simple command as follows − mysql> SHOW DATABASES; After successful installation of MariaDB, set a root password. A fresh install will have a blank password. Enter the following to set the new password − mysqladmin -u root password "[enter your password here]"; Enter the following to connect to the server with your new credentials − mysql -u root -p Enter password:******* If you already have MySQL installed on your Windows system, and want to upgrade to MariaDB; do not uninstall MySQL and install MariaDB. This will cause a conflict with the existing database. You must instead install MariaDB, and then use the upgrade wizard in the Windows installation file. The options of your MySQL my.cnf file should work with MariaDB. However, MariaDB has many features, which are not found in MySQL. Consider the following conflicts in your my.cnf file − MariaDB uses Aria storage engine by default for temporary files. If you have a lot of temporary files, modify key buffer size if you do not use MyISAM tables. MariaDB uses Aria storage engine by default for temporary files. If you have a lot of temporary files, modify key buffer size if you do not use MyISAM tables. If your applications connect/disconnect frequently, alter the thread cache size. If your applications connect/disconnect frequently, alter the thread cache size. If you use over 100 connections, use the thread pool. If you use over 100 connections, use the thread pool. MySQL and MariaDB are essentially identical. However, there are enough differences to create issues in upgradation. Review more of these key differences in the MariaDB Knowledge Base. Print Add Notes Bookmark this page
[ { "code": null, "e": 2627, "s": 2362, "text": "All downloads for MariaDB are located in the Download section of the official MariaDB foundation website. Click the link to the version you would like, and a list of downloads for multiple operating systems, architectures, and installation file types is displayed." }, { "code": null, "e": 2867, "s": 2627, "text": "If you have intimate knowledge of Linux/Unix systems, simply download source to build your install. Our recommended way of installing is to utilize distribution packages. MariaDB offers packages for the following Linux/Unix distributions −" }, { "code": null, "e": 2888, "s": 2867, "text": "RedHat/CentOS/Fedora" }, { "code": null, "e": 2902, "s": 2888, "text": "Debian/Ubuntu" }, { "code": null, "e": 2980, "s": 2902, "text": "The following distributions include a MariaDB package in their repositories −" }, { "code": null, "e": 2989, "s": 2980, "text": "openSUSE" }, { "code": null, "e": 3000, "s": 2989, "text": "Arch Linux" }, { "code": null, "e": 3007, "s": 3000, "text": "Mageia" }, { "code": null, "e": 3012, "s": 3007, "text": "Mint" }, { "code": null, "e": 3022, "s": 3012, "text": "Slackware" }, { "code": null, "e": 3079, "s": 3022, "text": "Follow these steps to install in an Ubuntu environment −" }, { "code": null, "e": 3110, "s": 3079, "text": "Step 1 − Login as a root user." }, { "code": null, "e": 3177, "s": 3110, "text": "Step 2 − Navigate to the directory containing the MariaDB package." }, { "code": null, "e": 3241, "s": 3177, "text": "Step 3 − Import the GnuPG signing key with the following code −" }, { "code": null, "e": 3323, "s": 3241, "text": "sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xcbcb082a1bb943db\n" }, { "code": null, "e": 3414, "s": 3323, "text": "Step 4 − Add MariaDB to the sources.list file. Open the file, and add the following code −" }, { "code": null, "e": 3507, "s": 3414, "text": "sudo add-apt-repository 'deb http://ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntuprecise main'\n" }, { "code": null, "e": 3556, "s": 3507, "text": "Step 5 − Refresh the system with the following −" }, { "code": null, "e": 3577, "s": 3556, "text": "sudo apt-get update\n" }, { "code": null, "e": 3623, "s": 3577, "text": "Step 6 − Install MariaDB with the following −" }, { "code": null, "e": 3660, "s": 3623, "text": "sudo apt-get install mariadb-server\n" }, { "code": null, "e": 3881, "s": 3660, "text": "After locating and downloading an automated install file (MSI), simply double click the file to start the installation. The installation wizard will walk you through every step of installation and any necessary settings." }, { "code": null, "e": 4056, "s": 3881, "text": "Test the installation by starting it from the command prompt. Navigate to the location of the installation, typically in the directory, and type the following at the prompt −" }, { "code": null, "e": 4078, "s": 4056, "text": "mysqld.exe --console\n" }, { "code": null, "e": 4448, "s": 4078, "text": "If the installation is successful, you will see messages related to startup. If this does not appear, you may have permission issues. Ensure that your user account can access the application. Graphical clients are available for MariaDB administration in the Windows environment. If you find the command line uncomfortable or cumbersome, be sure to experiment with them." }, { "code": null, "e": 4531, "s": 4448, "text": "Perform a few simple tasks to confirm the functioning and installation of MariaDB." }, { "code": null, "e": 4574, "s": 4531, "text": "Use the Admin Utility to Get Server Status" }, { "code": null, "e": 4626, "s": 4574, "text": "View the server version with the mysqladmin binary." }, { "code": null, "e": 4661, "s": 4626, "text": "[root@host]# mysqladmin --version\n" }, { "code": null, "e": 4823, "s": 4661, "text": "It should display the version, distribution, operating system, and architecture. If you do not see the output of that type, examine your installation for issues." }, { "code": null, "e": 4861, "s": 4823, "text": "Execute Simple Commands with a Client" }, { "code": null, "e": 5006, "s": 4861, "text": "Bring up the command prompt for MariaDB. This should connect you to MariaDB and allow execution of commands. Enter a simple command as follows −" }, { "code": null, "e": 5030, "s": 5006, "text": "mysql> SHOW DATABASES;\n" }, { "code": null, "e": 5183, "s": 5030, "text": "After successful installation of MariaDB, set a root password. A fresh install will have a blank password. Enter the following to set the new password −" }, { "code": null, "e": 5242, "s": 5183, "text": "mysqladmin -u root password \"[enter your password here]\";\n" }, { "code": null, "e": 5315, "s": 5242, "text": "Enter the following to connect to the server with your new credentials −" }, { "code": null, "e": 5356, "s": 5315, "text": "mysql -u root -p\nEnter password:*******\n" }, { "code": null, "e": 5647, "s": 5356, "text": "If you already have MySQL installed on your Windows system, and want to upgrade to MariaDB; do not uninstall MySQL and install MariaDB. This will cause a conflict with the existing database. You must instead install MariaDB, and then use the upgrade wizard in the Windows installation file." }, { "code": null, "e": 5777, "s": 5647, "text": "The options of your MySQL my.cnf file should work with MariaDB. However, MariaDB has many features, which are not found in MySQL." }, { "code": null, "e": 5832, "s": 5777, "text": "Consider the following conflicts in your my.cnf file −" }, { "code": null, "e": 5991, "s": 5832, "text": "MariaDB uses Aria storage engine by default for temporary files. If you have a lot of temporary files, modify key buffer size if you do not use MyISAM tables." }, { "code": null, "e": 6150, "s": 5991, "text": "MariaDB uses Aria storage engine by default for temporary files. If you have a lot of temporary files, modify key buffer size if you do not use MyISAM tables." }, { "code": null, "e": 6231, "s": 6150, "text": "If your applications connect/disconnect frequently, alter the thread cache size." }, { "code": null, "e": 6312, "s": 6231, "text": "If your applications connect/disconnect frequently, alter the thread cache size." }, { "code": null, "e": 6366, "s": 6312, "text": "If you use over 100 connections, use the thread pool." }, { "code": null, "e": 6420, "s": 6366, "text": "If you use over 100 connections, use the thread pool." }, { "code": null, "e": 6604, "s": 6420, "text": "MySQL and MariaDB are essentially identical. However, there are enough differences to create issues in upgradation. Review more of these key differences in the MariaDB Knowledge Base." }, { "code": null, "e": 6611, "s": 6604, "text": " Print" }, { "code": null, "e": 6622, "s": 6611, "text": " Add Notes" } ]
How to enter values in an edit box in Selenium with python?
We can enter values in an edit box in Selenium with the help of the methods listed below − Using the send_keys method.This method can send any text to an edit box or perform pressing keys with the help of Keys class. Using the send_keys method. This method can send any text to an edit box or perform pressing keys with the help of Keys class. Using the Javascript executor.Javascript Document Object Model can work with any of the elements on the page. Javascript works on the client side and performs actions on the web page. Selenium can execute a Javascript script with the help of execute_script() method. We can enter values on any edit box with the help of this method. Using the Javascript executor. Javascript Document Object Model can work with any of the elements on the page. Javascript works on the client side and performs actions on the web page. Selenium can execute a Javascript script with the help of execute_script() method. We can enter values on any edit box with the help of this method. Code Implementation with send_keys method. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke #actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") #to refresh the browser driver.refresh() # identifying the edit box and entering text with send_keys method driver. find_element_by_css_selector("input[class='gsc-input']"). send_keys("Selenium") #to close the browser driver.close() Code Implementation with Javascript executor. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke #actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") #to refresh the browser driver.refresh() # enter text with the Javascript executor driver.execute_script( "document.getElementsByName('search')[0].value = 'Selenium' ;") #to close the browser driver.close()
[ { "code": null, "e": 1153, "s": 1062, "text": "We can enter values in an edit box in Selenium with the help of the methods listed below −" }, { "code": null, "e": 1279, "s": 1153, "text": "Using the send_keys method.This method can send any text to an edit box or perform pressing keys with the help of Keys class." }, { "code": null, "e": 1307, "s": 1279, "text": "Using the send_keys method." }, { "code": null, "e": 1406, "s": 1307, "text": "This method can send any text to an edit box or perform pressing keys with the help of Keys class." }, { "code": null, "e": 1739, "s": 1406, "text": "Using the Javascript executor.Javascript Document Object Model can work with any of the elements on the page. Javascript works on the client side and performs actions on the web page. Selenium can execute a Javascript script with the help of execute_script() method. We can enter values on any edit box with the help of this method." }, { "code": null, "e": 1770, "s": 1739, "text": "Using the Javascript executor." }, { "code": null, "e": 2073, "s": 1770, "text": "Javascript Document Object Model can work with any of the elements on the page. Javascript works on the client side and performs actions on the web page. Selenium can execute a Javascript script with the help of execute_script() method. We can enter values on any edit box with the help of this method." }, { "code": null, "e": 2116, "s": 2073, "text": "Code Implementation with send_keys method." }, { "code": null, "e": 2723, "s": 2116, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the edit box and entering text with send_keys method\ndriver. find_element_by_css_selector(\"input[class='gsc-input']\").\nsend_keys(\"Selenium\")\n#to close the browser\ndriver.close()" }, { "code": null, "e": 2769, "s": 2723, "text": "Code Implementation with Javascript executor." }, { "code": null, "e": 3350, "s": 2769, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n# enter text with the Javascript executor\ndriver.execute_script(\n\"document.getElementsByName('search')[0].value = 'Selenium' ;\")\n#to close the browser\ndriver.close()" } ]
What does your Spotify music sound like? Data Science with Spotify (Part 1) | by Alvin Chung | Towards Data Science
Music has always been an integral part of everyone’s lives. We hear music, if not listen to music where ever we are, the melodic sounds when we are studying, the exhilarating thrills and beats when we’re at parties and the exciting and fun car pool karaokes we have with our friends when traveling. Music is everywhere around us. What if we could analyze the music we listen to using Data Science derive insights on the types of music we listen to? The motivation of this series is to enable anyone to discover patterns and insights about themselves and the music that they listen to. In doing so, gain a greater understanding of the musical behaviors they have when listening to Spotify. Note: The code to collect data and perform insights on your own music is linked below. To achieve this we will aim to show a full end to end cycle of deriving a Data Science Project quantitatively, and will be sectioned into the following. Here we will learn the basics of statistical analysis. This gives us an understanding of the data we are working with and derive insights on the features we have. Exploratory Data Analysis is often the most essential step of any Data Science project as it provides a great deal of insight towards building further analytics. What sort of music styles are often featured on Spotify? Is the music that is featured often more acoustic? What are the sorts of music we might enjoy? Do the most popular songs charting, follow some sort of pattern? In this section, we will learn to place some statistical rigor towards our observations that we made in our data visualizations. After all, we want to quantitatively verify our hypotheses. Some statistical tests, we will perform are the Chi-Squared Good fitness, and T-testing, as well as a look into correlation. Here, we will look at understanding how to perform A/B testing in answering questions about our music tastes, such as: - Does the style of music I listen to differ from those that are played in the top 100 and different from those featured on Spotify. What styles of music do we listen to that might be more pronounced that the typical music featured on Spotify Lastly, Are we generic? Meaning, do we listen to music that follows a similar pattern when compared to the most popular songs. This last part will use the insights we made from both Exploratory Data Analytics and A/B testing in developing a Machine Learning algorithm which suggests us new songs! What styles of music is often featured on Spotify? Is the music that is featured often more acoustic? What are the sorts of music we might enjoy? Do the most popular songs charting follow some sort of pattern? One of the greatest aspects of Data Science is the ability to concentrate large scales of data into a single piece of information. This enables us to answer questions we might have and gain a greater understanding of our individual behaviors, and the types of music we enjoy. An essential part of Data Science is to understand the distributions of the data we have collected. We care about the distributions as it provides us insights on the frequencies of the various styles of music, as well as the shape of the frequencies as if they were on Spotify. Let’s start by look at the distributions of songs featured on Spotify! Through observing the distribution plot, we can immediately observe the following: There is a very heavy slope downwards in the features speechiness and acousticness, which we can note a slight up-tail in the distribution near the end of the plot. This indicates to us that the music styles of songs featured on Spotify are in general less acoustic or speechy. The uptail indicates to us, that songs with high speechy or acoustic are more likely to be selected near the upper-bound. Or more quantitatively, styles of songs rated to be more than 25% acoustic or speechy are less likely to be featured on Spotify. Most songs featured on Spotify are often not very lively, and as the liveliness of the song increases, the likelihood of it being featured on Spotify decreases. Danceability appears to normally distributed with tails of the distribution featuring lower likelihoods of being featured on Spotify. The attributes, Valence and Energy appear to be approximately evenly (uniformly distributed). Indicating no preference for those attributes affecting the selection of music featured on Spotify. In sum, songs featured on Spotify tend to exhibit low acousticness, speechiness and liveness with valence and energy showing no notable impact on a song being featured on Spotify. Finally, songs approximately 65% Danceability are most commonly featured on Spotify. Knock Knock, who’s there? What sort of music style is this, It’s so good! Well let’s find out! Music tastes can be a great reflection of our emotions and feeling. They provide us an identity, a feeling of security, and more often than not, a melodic tune which ebbs and flows alongside our daily lives. When we are feeling amazing! We’ll listen to music that feels like we’re on the top of the world! And when we suffer from a heart break, we will listen to songs that reflect the loss of a loved one. This introspective view of our lives, can actually be encapsulated in the music we listen to! So let’s see what we can find from inspecting my favorite songs as of current! What we can observe from the graph above are the following: The songs I listen to are quite normally distributed in acousticness, valence, danceability and energy. We might note that the distributions for liveness and speechiness to be concentrated on the lower-bound suggesting that the music I listen to is not very lively nor speechy. We can observe that I tend to enjoy music which is more acoustic, danceable and energetic. With a low preference for music that are lively or speechy. Bob why is your music so generic! It’s because their is no significance is your taste. hue hue hue The top 50 songs charting are undoubtedly the most prolifically played throughout the world, whether you listen to it when shopping for your new bag, or listening to it in the background when having a conversation with your friends at a cafe. It is everywhere around us. But, we never seem to mind listening to these songs, they may get bland in some cases as our ears adjust to the music. But never do we say “Man I can’t stand listening to this song, It hurts my ears”, why is that? Is their a sort of pattern which the top 50 songs adopt that allows us to enjoy the song playing in the background and even sometimes, sing along to it? We’ll achieve this through plotting a box-plot for each one of the styles of music in the top 100! By observing the box-plot, we can see that most songs that are charting in the top 100 are: Highly danceable and energetic. But low in acousticness, speechiness and liveness Songs in the charting in the top 100, exhibit high preference for songs which are very much danceable, and low in speechiness. For instance, Middle by Zed, Happier by Marshmello. I hope you all very much enjoyed the insights derived through visualizing the top 100 charting songs, featured songs and my personal favorite songs on Spotify! If you would like to try this for yourselves and have a look at your own Spotify tastes and try to do this yourselves, I've attached the link to the code I've used to collect this data here If you really liked this article, please do 👏 and share it with your friends. This will let me know you guys really enjoyed this first of a series, and I’ll look to continue doing more if that is the case. Remember, you can clap up to 50 times — it really makes a big difference for me.
[ { "code": null, "e": 502, "s": 172, "text": "Music has always been an integral part of everyone’s lives. We hear music, if not listen to music where ever we are, the melodic sounds when we are studying, the exhilarating thrills and beats when we’re at parties and the exciting and fun car pool karaokes we have with our friends when traveling. Music is everywhere around us." }, { "code": null, "e": 621, "s": 502, "text": "What if we could analyze the music we listen to using Data Science derive insights on the types of music we listen to?" }, { "code": null, "e": 861, "s": 621, "text": "The motivation of this series is to enable anyone to discover patterns and insights about themselves and the music that they listen to. In doing so, gain a greater understanding of the musical behaviors they have when listening to Spotify." }, { "code": null, "e": 948, "s": 861, "text": "Note: The code to collect data and perform insights on your own music is linked below." }, { "code": null, "e": 1101, "s": 948, "text": "To achieve this we will aim to show a full end to end cycle of deriving a Data Science Project quantitatively, and will be sectioned into the following." }, { "code": null, "e": 1426, "s": 1101, "text": "Here we will learn the basics of statistical analysis. This gives us an understanding of the data we are working with and derive insights on the features we have. Exploratory Data Analysis is often the most essential step of any Data Science project as it provides a great deal of insight towards building further analytics." }, { "code": null, "e": 1534, "s": 1426, "text": "What sort of music styles are often featured on Spotify? Is the music that is featured often more acoustic?" }, { "code": null, "e": 1578, "s": 1534, "text": "What are the sorts of music we might enjoy?" }, { "code": null, "e": 1643, "s": 1578, "text": "Do the most popular songs charting, follow some sort of pattern?" }, { "code": null, "e": 1957, "s": 1643, "text": "In this section, we will learn to place some statistical rigor towards our observations that we made in our data visualizations. After all, we want to quantitatively verify our hypotheses. Some statistical tests, we will perform are the Chi-Squared Good fitness, and T-testing, as well as a look into correlation." }, { "code": null, "e": 2076, "s": 1957, "text": "Here, we will look at understanding how to perform A/B testing in answering questions about our music tastes, such as:" }, { "code": null, "e": 2209, "s": 2076, "text": "- Does the style of music I listen to differ from those that are played in the top 100 and different from those featured on Spotify." }, { "code": null, "e": 2319, "s": 2209, "text": "What styles of music do we listen to that might be more pronounced that the typical music featured on Spotify" }, { "code": null, "e": 2446, "s": 2319, "text": "Lastly, Are we generic? Meaning, do we listen to music that follows a similar pattern when compared to the most popular songs." }, { "code": null, "e": 2616, "s": 2446, "text": "This last part will use the insights we made from both Exploratory Data Analytics and A/B testing in developing a Machine Learning algorithm which suggests us new songs!" }, { "code": null, "e": 2826, "s": 2616, "text": "What styles of music is often featured on Spotify? Is the music that is featured often more acoustic? What are the sorts of music we might enjoy? Do the most popular songs charting follow some sort of pattern?" }, { "code": null, "e": 3102, "s": 2826, "text": "One of the greatest aspects of Data Science is the ability to concentrate large scales of data into a single piece of information. This enables us to answer questions we might have and gain a greater understanding of our individual behaviors, and the types of music we enjoy." }, { "code": null, "e": 3451, "s": 3102, "text": "An essential part of Data Science is to understand the distributions of the data we have collected. We care about the distributions as it provides us insights on the frequencies of the various styles of music, as well as the shape of the frequencies as if they were on Spotify. Let’s start by look at the distributions of songs featured on Spotify!" }, { "code": null, "e": 3534, "s": 3451, "text": "Through observing the distribution plot, we can immediately observe the following:" }, { "code": null, "e": 3934, "s": 3534, "text": "There is a very heavy slope downwards in the features speechiness and acousticness, which we can note a slight up-tail in the distribution near the end of the plot. This indicates to us that the music styles of songs featured on Spotify are in general less acoustic or speechy. The uptail indicates to us, that songs with high speechy or acoustic are more likely to be selected near the upper-bound." }, { "code": null, "e": 4063, "s": 3934, "text": "Or more quantitatively, styles of songs rated to be more than 25% acoustic or speechy are less likely to be featured on Spotify." }, { "code": null, "e": 4224, "s": 4063, "text": "Most songs featured on Spotify are often not very lively, and as the liveliness of the song increases, the likelihood of it being featured on Spotify decreases." }, { "code": null, "e": 4358, "s": 4224, "text": "Danceability appears to normally distributed with tails of the distribution featuring lower likelihoods of being featured on Spotify." }, { "code": null, "e": 4552, "s": 4358, "text": "The attributes, Valence and Energy appear to be approximately evenly (uniformly distributed). Indicating no preference for those attributes affecting the selection of music featured on Spotify." }, { "code": null, "e": 4817, "s": 4552, "text": "In sum, songs featured on Spotify tend to exhibit low acousticness, speechiness and liveness with valence and energy showing no notable impact on a song being featured on Spotify. Finally, songs approximately 65% Danceability are most commonly featured on Spotify." }, { "code": null, "e": 4912, "s": 4817, "text": "Knock Knock, who’s there? What sort of music style is this, It’s so good! Well let’s find out!" }, { "code": null, "e": 5120, "s": 4912, "text": "Music tastes can be a great reflection of our emotions and feeling. They provide us an identity, a feeling of security, and more often than not, a melodic tune which ebbs and flows alongside our daily lives." }, { "code": null, "e": 5413, "s": 5120, "text": "When we are feeling amazing! We’ll listen to music that feels like we’re on the top of the world! And when we suffer from a heart break, we will listen to songs that reflect the loss of a loved one. This introspective view of our lives, can actually be encapsulated in the music we listen to!" }, { "code": null, "e": 5492, "s": 5413, "text": "So let’s see what we can find from inspecting my favorite songs as of current!" }, { "code": null, "e": 5552, "s": 5492, "text": "What we can observe from the graph above are the following:" }, { "code": null, "e": 5656, "s": 5552, "text": "The songs I listen to are quite normally distributed in acousticness, valence, danceability and energy." }, { "code": null, "e": 5830, "s": 5656, "text": "We might note that the distributions for liveness and speechiness to be concentrated on the lower-bound suggesting that the music I listen to is not very lively nor speechy." }, { "code": null, "e": 5981, "s": 5830, "text": "We can observe that I tend to enjoy music which is more acoustic, danceable and energetic. With a low preference for music that are lively or speechy." }, { "code": null, "e": 6080, "s": 5981, "text": "Bob why is your music so generic! It’s because their is no significance is your taste. hue hue hue" }, { "code": null, "e": 6565, "s": 6080, "text": "The top 50 songs charting are undoubtedly the most prolifically played throughout the world, whether you listen to it when shopping for your new bag, or listening to it in the background when having a conversation with your friends at a cafe. It is everywhere around us. But, we never seem to mind listening to these songs, they may get bland in some cases as our ears adjust to the music. But never do we say “Man I can’t stand listening to this song, It hurts my ears”, why is that?" }, { "code": null, "e": 6718, "s": 6565, "text": "Is their a sort of pattern which the top 50 songs adopt that allows us to enjoy the song playing in the background and even sometimes, sing along to it?" }, { "code": null, "e": 6817, "s": 6718, "text": "We’ll achieve this through plotting a box-plot for each one of the styles of music in the top 100!" }, { "code": null, "e": 6909, "s": 6817, "text": "By observing the box-plot, we can see that most songs that are charting in the top 100 are:" }, { "code": null, "e": 6991, "s": 6909, "text": "Highly danceable and energetic. But low in acousticness, speechiness and liveness" }, { "code": null, "e": 7170, "s": 6991, "text": "Songs in the charting in the top 100, exhibit high preference for songs which are very much danceable, and low in speechiness. For instance, Middle by Zed, Happier by Marshmello." }, { "code": null, "e": 7330, "s": 7170, "text": "I hope you all very much enjoyed the insights derived through visualizing the top 100 charting songs, featured songs and my personal favorite songs on Spotify!" }, { "code": null, "e": 7520, "s": 7330, "text": "If you would like to try this for yourselves and have a look at your own Spotify tastes and try to do this yourselves, I've attached the link to the code I've used to collect this data here" } ]
Functions That Generate a Multi-index in Pandas and How to Remove the Levels | by Susan Maina | Towards Data Science
Introduction In this article, we will look at what a multiindex is, where and when to use it, functions that generate a multiindex, and how to collapse it into a single index. But first, let’s get some basic definitions out of the way. An index is a column in a DataFrame that ‘uniquely’ identifies each row. Think of it as the row labels. A multiindex is when there is more than one index. Other names are multiple index and hierarchical index. Multiindex can also refer to multiple header levels, or when you have a hierarchy of column names. Advantages of multiple indices For holding data that is higher-dimensional and contains hierarchies or levels. Provides a helpful visual display of the hierarchy levels in a table format. It allows for efficient selection and manipulation of hierarchical data using functions such as df.xs() and df.unstack(). Disadvantages of multiindex The format does not allow for direct plotting of graphs. There are no performance benefits when using the multiindex. We will use the diamonds dataset from seaborn to demonstrate the various scenarios that result in a multiindex situation, and how to collapse the multiindex back into a single index DataFrame. import pandas as pdimport seaborn as snsdiamonds = sns.load_dataset('diamonds') So, how do we end up with multiple indices? A1. Using df.set_index(col_list) The code below manually sets the index to two columns (cut and clarity). sorted_df = diamonds.sort_values([ 'cut’, ’clarity’])multiind_df = sorted_df.set_index([ 'cut','clarity'])multiind_df What to look out for: The hierarchies are displayed as expected. If not, remember to sort the DataFrame by these columns. The number of rows of the resulting DataFrame does not change, but rather the DataFrame is rearranged so that the hierarchies are visible. diamonds.shape###Results(53940, 10)multiind_df.shape###Results(53940, 8) The number of the resulting columns is now less by two because of the columns lost to the index (see results of df.shape above). The index is now a multiindex. Run df.index to display a multiindex list where each element is a tuple. multiind_df.index The previous index was dropped by default. See what happens below when we set the index to another column in the new DataFrame. multiind_df.set_index('carat') If you want to retain the previous index, first use df.reset_index() to make the index part of the existing columns, then use df.set_index(col_list). A2. Multiindex resulting from groupby of many columns df.groupby summarizes columns (features) based on a chosen column’s categories. For example, we can group the diamonds by the cut and color to see how other features are distributed among these categories. We use max() as the aggregation function. grouped_df = diamonds.groupby([’cut’, 'color’]).max()grouped_df What to look out for: The number of rows will substantially reduce. This is because only unique indices are displayed (unique cut and color combinations here). The specified aggregate function (max ) combines the other values that fall in these groups into one value. diamonds.shape###Results(53940, 10)grouped_df.shape###Results(35, 7) The number of columns also reduces to 7 because two columns now reside as the index, while clarity was dropped because the aggregate function — max — does not work with non-numeric features. Let us now demonstrate how we end up with multiple header levels. B1. Groupby more than two columns then unstack We’ll continue with the code from the previous section. We performed a groupby using cut and color. Now let’s unstack it so that the ‘cut’ categories appear as column headers. This is by flipping them from a row index to column headers. grouped_df = diamonds.groupby(['cut','color']).max()unstacked_df = grouped_df.unstack('cut')unstacked_df We now have a new header level below the original headers — carat, depth, price, etc. B2. Groupby using several aggregation functions In our previous groupbys, we used only max() as the aggregate function. However, we can include several aggregation functions and their names will be held at a new level. The code below groups the data by one column — cut — but uses 3 aggregation functions —median, max and mean. diamonds.groupby( 'cut').agg( ['median','max','mean'] ) B3. use pivot_table to convert rows into columns A pivot_table provides a convenient way of reshaping a column’s values into column headers like the unstack method we used above. Here we will pivot on our original diamonds dataset. diamonds.pivot_table( values = 'price', index = 'color', columns = ['clarity','cut'], aggfunc='median') B4. Pandas Cross-tab The pandas.crosstab function allows us to create a frequency table of data. In the code below, we want to find the distribution of clarity and cut for every color. We use normalize=’columns’ to show the percentage distributions per column. pd.crosstab( index = diamonds[’color’], columns = [diamonds[’clarity’], diamonds[’cut’]], normalize = 'columns’) C1. Use df.reset_index() df.reset_index() resets the index by converting the existing index (or indices) into a normal column. A RangeIndex is generated as the new index. grouped_df.reset_index() In a Multiindex situation, we can choose the name (or position) of the index to reset by including level=n. grouped_df.reset_index( level='cut') We can also reset the index and still maintain multiple header levels. df = diamonds.groupby( 'cut’).agg( [’median’,’max’,’mean’])df.reset_index() C2. Remove multiindex using df.droplevel(level = level_to_drop, axis=0) This is used when you want to entirely drop an index. Using the grouped_df generated earlier, let’s drop the color index. Note that we can either use level=index_name or level=position (counting from 0 as the outermost level). This method returns the modified DataFrame. grouped_df.droplevel( level = 1, axis=0) C3. Remove multiindex using df.index.droplevel(level = level_to_drop) This function drops the specified level from the index and returns the remaining index list. The next step is to assign this list to be the DataFrame’s index. grouped_df.index = grouped_df.index.droplevel('color') Print the DataFrame to display the same results like the image in the previous section. D1. Merge the levels’ names for each column Merging the header levels is a common solution because both levels might be useful and it is impossible to reset the index here. Method 1: Using the map and join functions The map function modifies every element in a list using a given function. Here, we have a list of tuples for each column name, and .map uses .join to merge the tuples into one name separated by an underscore. df.columns.map('_'.join) The code above returns an index object. We need to assign this to the column names and then print out the DataFrame. df.columns = df.columns.map('_'.join) Method 2: Using a list comprehension A list comprehension also takes in a list, modifies each element through some operation, and returns a new list. We use .join to merge each tuple into one name using a different joining symbol (|). df.columns = ['|'.join(s) for s in df.columns] Another list comprehension example uses the f-string format. This is useful to change the order of the names after a merge. In the code below, the lower-level names come first. df.columns = [f'{j}#{i}' for i,j in df.columns] D2. Remove multiindex per column Using df.droplevel(level, axis=1) If a header level is not useful at identifying the columns, you can choose to drop it. We use axis=1 (or axis= ’columns’) to signify column header levels. Let us demonstrate. First we group the dataset by cut and use four aggregation functions. Then we select only the price columns using df.xs(). df = diamonds.groupby( 'cut').agg( ['max', 'median', 'min','mean'])df.xs( key='price', axis=1, level=0, drop_level=False) Now we can drop the top level ‘price’ since we already know all the values represent the price. df_price.droplevel( level=0, axis=1) D3. df.columns.droplevel(level_to_drop) We can also drop a header level and return the desired level(s) as a list. (This is similar to df.index.droplevel earlier but with columns instead of index). We then assign this list to the column names. df.columns = df.columns.droplevel(0)display(df) Print the DataFrame to display the same results like the image in the previous section. D4. df.columns.get_level_values(level_to_return) This function returns the desired level(s) and drops the rest. The code below yields the same results as the image in the previous section. df.columns = df.columns.get_level_values(1)df In this article, we explored the various functions that generate a multiindex and how to collapse it back into a basic DataFrame with one index. There are other ways of creating multiindex DataFrames from scratch and several sophisticated ways of accessing and selecting the data. I encourage you to experiment and practice with multi-dimensional data that contains many prominent categorical features and play around with the multiindex. Find the code used in this blog post here. If you liked this content and would like to get notified of more like it, subscribe here. If you are not yet a medium member, join here. Thank you for reading. 1. Pandas MultiIndex Tutorial by Zax Rosenberg, CFA 2. Accessing Data in a MultiIndex DataFrame in Pandas by B. Chen 3. Hierarchical Indexing from the Python Data Science Handbook by Jake VanderPlas
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 348, "s": 185, "text": "In this article, we will look at what a multiindex is, where and when to use it, functions that generate a multiindex, and how to collapse it into a single index." }, { "code": null, "e": 408, "s": 348, "text": "But first, let’s get some basic definitions out of the way." }, { "code": null, "e": 512, "s": 408, "text": "An index is a column in a DataFrame that ‘uniquely’ identifies each row. Think of it as the row labels." }, { "code": null, "e": 618, "s": 512, "text": "A multiindex is when there is more than one index. Other names are multiple index and hierarchical index." }, { "code": null, "e": 717, "s": 618, "text": "Multiindex can also refer to multiple header levels, or when you have a hierarchy of column names." }, { "code": null, "e": 748, "s": 717, "text": "Advantages of multiple indices" }, { "code": null, "e": 828, "s": 748, "text": "For holding data that is higher-dimensional and contains hierarchies or levels." }, { "code": null, "e": 905, "s": 828, "text": "Provides a helpful visual display of the hierarchy levels in a table format." }, { "code": null, "e": 1027, "s": 905, "text": "It allows for efficient selection and manipulation of hierarchical data using functions such as df.xs() and df.unstack()." }, { "code": null, "e": 1055, "s": 1027, "text": "Disadvantages of multiindex" }, { "code": null, "e": 1112, "s": 1055, "text": "The format does not allow for direct plotting of graphs." }, { "code": null, "e": 1173, "s": 1112, "text": "There are no performance benefits when using the multiindex." }, { "code": null, "e": 1366, "s": 1173, "text": "We will use the diamonds dataset from seaborn to demonstrate the various scenarios that result in a multiindex situation, and how to collapse the multiindex back into a single index DataFrame." }, { "code": null, "e": 1446, "s": 1366, "text": "import pandas as pdimport seaborn as snsdiamonds = sns.load_dataset('diamonds')" }, { "code": null, "e": 1490, "s": 1446, "text": "So, how do we end up with multiple indices?" }, { "code": null, "e": 1523, "s": 1490, "text": "A1. Using df.set_index(col_list)" }, { "code": null, "e": 1596, "s": 1523, "text": "The code below manually sets the index to two columns (cut and clarity)." }, { "code": null, "e": 1714, "s": 1596, "text": "sorted_df = diamonds.sort_values([ 'cut’, ’clarity’])multiind_df = sorted_df.set_index([ 'cut','clarity'])multiind_df" }, { "code": null, "e": 1736, "s": 1714, "text": "What to look out for:" }, { "code": null, "e": 1836, "s": 1736, "text": "The hierarchies are displayed as expected. If not, remember to sort the DataFrame by these columns." }, { "code": null, "e": 1975, "s": 1836, "text": "The number of rows of the resulting DataFrame does not change, but rather the DataFrame is rearranged so that the hierarchies are visible." }, { "code": null, "e": 2048, "s": 1975, "text": "diamonds.shape###Results(53940, 10)multiind_df.shape###Results(53940, 8)" }, { "code": null, "e": 2177, "s": 2048, "text": "The number of the resulting columns is now less by two because of the columns lost to the index (see results of df.shape above)." }, { "code": null, "e": 2281, "s": 2177, "text": "The index is now a multiindex. Run df.index to display a multiindex list where each element is a tuple." }, { "code": null, "e": 2299, "s": 2281, "text": "multiind_df.index" }, { "code": null, "e": 2427, "s": 2299, "text": "The previous index was dropped by default. See what happens below when we set the index to another column in the new DataFrame." }, { "code": null, "e": 2458, "s": 2427, "text": "multiind_df.set_index('carat')" }, { "code": null, "e": 2608, "s": 2458, "text": "If you want to retain the previous index, first use df.reset_index() to make the index part of the existing columns, then use df.set_index(col_list)." }, { "code": null, "e": 2662, "s": 2608, "text": "A2. Multiindex resulting from groupby of many columns" }, { "code": null, "e": 2742, "s": 2662, "text": "df.groupby summarizes columns (features) based on a chosen column’s categories." }, { "code": null, "e": 2910, "s": 2742, "text": "For example, we can group the diamonds by the cut and color to see how other features are distributed among these categories. We use max() as the aggregation function." }, { "code": null, "e": 2974, "s": 2910, "text": "grouped_df = diamonds.groupby([’cut’, 'color’]).max()grouped_df" }, { "code": null, "e": 2996, "s": 2974, "text": "What to look out for:" }, { "code": null, "e": 3242, "s": 2996, "text": "The number of rows will substantially reduce. This is because only unique indices are displayed (unique cut and color combinations here). The specified aggregate function (max ) combines the other values that fall in these groups into one value." }, { "code": null, "e": 3311, "s": 3242, "text": "diamonds.shape###Results(53940, 10)grouped_df.shape###Results(35, 7)" }, { "code": null, "e": 3502, "s": 3311, "text": "The number of columns also reduces to 7 because two columns now reside as the index, while clarity was dropped because the aggregate function — max — does not work with non-numeric features." }, { "code": null, "e": 3568, "s": 3502, "text": "Let us now demonstrate how we end up with multiple header levels." }, { "code": null, "e": 3615, "s": 3568, "text": "B1. Groupby more than two columns then unstack" }, { "code": null, "e": 3715, "s": 3615, "text": "We’ll continue with the code from the previous section. We performed a groupby using cut and color." }, { "code": null, "e": 3852, "s": 3715, "text": "Now let’s unstack it so that the ‘cut’ categories appear as column headers. This is by flipping them from a row index to column headers." }, { "code": null, "e": 3957, "s": 3852, "text": "grouped_df = diamonds.groupby(['cut','color']).max()unstacked_df = grouped_df.unstack('cut')unstacked_df" }, { "code": null, "e": 4043, "s": 3957, "text": "We now have a new header level below the original headers — carat, depth, price, etc." }, { "code": null, "e": 4091, "s": 4043, "text": "B2. Groupby using several aggregation functions" }, { "code": null, "e": 4262, "s": 4091, "text": "In our previous groupbys, we used only max() as the aggregate function. However, we can include several aggregation functions and their names will be held at a new level." }, { "code": null, "e": 4371, "s": 4262, "text": "The code below groups the data by one column — cut — but uses 3 aggregation functions —median, max and mean." }, { "code": null, "e": 4427, "s": 4371, "text": "diamonds.groupby( 'cut').agg( ['median','max','mean'] )" }, { "code": null, "e": 4476, "s": 4427, "text": "B3. use pivot_table to convert rows into columns" }, { "code": null, "e": 4659, "s": 4476, "text": "A pivot_table provides a convenient way of reshaping a column’s values into column headers like the unstack method we used above. Here we will pivot on our original diamonds dataset." }, { "code": null, "e": 4775, "s": 4659, "text": "diamonds.pivot_table( values = 'price', index = 'color', columns = ['clarity','cut'], aggfunc='median')" }, { "code": null, "e": 4796, "s": 4775, "text": "B4. Pandas Cross-tab" }, { "code": null, "e": 5036, "s": 4796, "text": "The pandas.crosstab function allows us to create a frequency table of data. In the code below, we want to find the distribution of clarity and cut for every color. We use normalize=’columns’ to show the percentage distributions per column." }, { "code": null, "e": 5169, "s": 5036, "text": "pd.crosstab( index = diamonds[’color’], columns = [diamonds[’clarity’], diamonds[’cut’]], normalize = 'columns’)" }, { "code": null, "e": 5194, "s": 5169, "text": "C1. Use df.reset_index()" }, { "code": null, "e": 5340, "s": 5194, "text": "df.reset_index() resets the index by converting the existing index (or indices) into a normal column. A RangeIndex is generated as the new index." }, { "code": null, "e": 5365, "s": 5340, "text": "grouped_df.reset_index()" }, { "code": null, "e": 5473, "s": 5365, "text": "In a Multiindex situation, we can choose the name (or position) of the index to reset by including level=n." }, { "code": null, "e": 5513, "s": 5473, "text": "grouped_df.reset_index( level='cut')" }, { "code": null, "e": 5584, "s": 5513, "text": "We can also reset the index and still maintain multiple header levels." }, { "code": null, "e": 5666, "s": 5584, "text": "df = diamonds.groupby( 'cut’).agg( [’median’,’max’,’mean’])df.reset_index()" }, { "code": null, "e": 5738, "s": 5666, "text": "C2. Remove multiindex using df.droplevel(level = level_to_drop, axis=0)" }, { "code": null, "e": 5792, "s": 5738, "text": "This is used when you want to entirely drop an index." }, { "code": null, "e": 6009, "s": 5792, "text": "Using the grouped_df generated earlier, let’s drop the color index. Note that we can either use level=index_name or level=position (counting from 0 as the outermost level). This method returns the modified DataFrame." }, { "code": null, "e": 6056, "s": 6009, "text": "grouped_df.droplevel( level = 1, axis=0)" }, { "code": null, "e": 6126, "s": 6056, "text": "C3. Remove multiindex using df.index.droplevel(level = level_to_drop)" }, { "code": null, "e": 6285, "s": 6126, "text": "This function drops the specified level from the index and returns the remaining index list. The next step is to assign this list to be the DataFrame’s index." }, { "code": null, "e": 6340, "s": 6285, "text": "grouped_df.index = grouped_df.index.droplevel('color')" }, { "code": null, "e": 6428, "s": 6340, "text": "Print the DataFrame to display the same results like the image in the previous section." }, { "code": null, "e": 6472, "s": 6428, "text": "D1. Merge the levels’ names for each column" }, { "code": null, "e": 6601, "s": 6472, "text": "Merging the header levels is a common solution because both levels might be useful and it is impossible to reset the index here." }, { "code": null, "e": 6644, "s": 6601, "text": "Method 1: Using the map and join functions" }, { "code": null, "e": 6853, "s": 6644, "text": "The map function modifies every element in a list using a given function. Here, we have a list of tuples for each column name, and .map uses .join to merge the tuples into one name separated by an underscore." }, { "code": null, "e": 6878, "s": 6853, "text": "df.columns.map('_'.join)" }, { "code": null, "e": 6995, "s": 6878, "text": "The code above returns an index object. We need to assign this to the column names and then print out the DataFrame." }, { "code": null, "e": 7033, "s": 6995, "text": "df.columns = df.columns.map('_'.join)" }, { "code": null, "e": 7070, "s": 7033, "text": "Method 2: Using a list comprehension" }, { "code": null, "e": 7268, "s": 7070, "text": "A list comprehension also takes in a list, modifies each element through some operation, and returns a new list. We use .join to merge each tuple into one name using a different joining symbol (|)." }, { "code": null, "e": 7315, "s": 7268, "text": "df.columns = ['|'.join(s) for s in df.columns]" }, { "code": null, "e": 7492, "s": 7315, "text": "Another list comprehension example uses the f-string format. This is useful to change the order of the names after a merge. In the code below, the lower-level names come first." }, { "code": null, "e": 7540, "s": 7492, "text": "df.columns = [f'{j}#{i}' for i,j in df.columns]" }, { "code": null, "e": 7607, "s": 7540, "text": "D2. Remove multiindex per column Using df.droplevel(level, axis=1)" }, { "code": null, "e": 7762, "s": 7607, "text": "If a header level is not useful at identifying the columns, you can choose to drop it. We use axis=1 (or axis= ’columns’) to signify column header levels." }, { "code": null, "e": 7905, "s": 7762, "text": "Let us demonstrate. First we group the dataset by cut and use four aggregation functions. Then we select only the price columns using df.xs()." }, { "code": null, "e": 8048, "s": 7905, "text": "df = diamonds.groupby( 'cut').agg( ['max', 'median', 'min','mean'])df.xs( key='price', axis=1, level=0, drop_level=False)" }, { "code": null, "e": 8144, "s": 8048, "text": "Now we can drop the top level ‘price’ since we already know all the values represent the price." }, { "code": null, "e": 8188, "s": 8144, "text": "df_price.droplevel( level=0, axis=1)" }, { "code": null, "e": 8228, "s": 8188, "text": "D3. df.columns.droplevel(level_to_drop)" }, { "code": null, "e": 8432, "s": 8228, "text": "We can also drop a header level and return the desired level(s) as a list. (This is similar to df.index.droplevel earlier but with columns instead of index). We then assign this list to the column names." }, { "code": null, "e": 8480, "s": 8432, "text": "df.columns = df.columns.droplevel(0)display(df)" }, { "code": null, "e": 8568, "s": 8480, "text": "Print the DataFrame to display the same results like the image in the previous section." }, { "code": null, "e": 8617, "s": 8568, "text": "D4. df.columns.get_level_values(level_to_return)" }, { "code": null, "e": 8757, "s": 8617, "text": "This function returns the desired level(s) and drops the rest. The code below yields the same results as the image in the previous section." }, { "code": null, "e": 8803, "s": 8757, "text": "df.columns = df.columns.get_level_values(1)df" }, { "code": null, "e": 8948, "s": 8803, "text": "In this article, we explored the various functions that generate a multiindex and how to collapse it back into a basic DataFrame with one index." }, { "code": null, "e": 9242, "s": 8948, "text": "There are other ways of creating multiindex DataFrames from scratch and several sophisticated ways of accessing and selecting the data. I encourage you to experiment and practice with multi-dimensional data that contains many prominent categorical features and play around with the multiindex." }, { "code": null, "e": 9285, "s": 9242, "text": "Find the code used in this blog post here." }, { "code": null, "e": 9445, "s": 9285, "text": "If you liked this content and would like to get notified of more like it, subscribe here. If you are not yet a medium member, join here. Thank you for reading." }, { "code": null, "e": 9497, "s": 9445, "text": "1. Pandas MultiIndex Tutorial by Zax Rosenberg, CFA" }, { "code": null, "e": 9562, "s": 9497, "text": "2. Accessing Data in a MultiIndex DataFrame in Pandas by B. Chen" } ]
How to handle an exception using lambda expression in Java?
A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the "throws" clause of a functional interface must declare the same exception or one of its subtype. interface Student { void studentData(String name) throws Exception; } public class LambdaExceptionTest { public static void main(String[] args) { // lamba expression Student student = name -> { System.out.println("The Student name is: " + name); throw new Exception(); }; try { student.studentData("Adithya"); } catch(Exception e) { } } } The Student name is: Adithya
[ { "code": null, "e": 1318, "s": 1062, "text": "A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the \"throws\" clause of a functional interface must declare the same exception or one of its subtype." }, { "code": null, "e": 1731, "s": 1318, "text": "interface Student {\n void studentData(String name) throws Exception;\n}\npublic class LambdaExceptionTest {\n public static void main(String[] args) {\n // lamba expression \n Student student = name -> {\n System.out.println(\"The Student name is: \" + name);\n throw new Exception();\n };\n try {\n student.studentData(\"Adithya\");\n } catch(Exception e) {\n\n }\n }\n}" }, { "code": null, "e": 1760, "s": 1731, "text": "The Student name is: Adithya" } ]
Groovy - Meta Object Programming
Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly. So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods. Suppose if you had to invoke the following statements on this class. Def myStudent = new Student() myStudent.Name = ”Joe”; myStudent.Display() Now in meta object programming, even though the class does not have the member variable Name or the method Display(), the above code will still work. How can this work? Well, for this to work out, one has to implement the GroovyInterceptable interface to hook into the execution process of Groovy. Following are the methods available for this interface. Public interface GroovyInterceptable { Public object invokeMethod(String methodName, Object args) Public object getproperty(String propertyName) Public object setProperty(String propertyName, Object newValue) Public MetaClass getMetaClass() Public void setMetaClass(MetaClass metaClass) } So in the above interface description, suppose if you had to implement the invokeMethod(), it would be called for every method which either exists or does not exist. So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code. The class Student has no member variable called Name or ID defined. The class Student has no member variable called Name or ID defined. The class Student implements the GroovyInterceptable interface. The class Student implements the GroovyInterceptable interface. There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly. There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly. The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime. The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); } } class Student implements GroovyInterceptable { protected dynamicProps=[:] void setProperty(String pName,val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } } The output of the following code would be − Joe 1 So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code − The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not. The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def invokeMethod(String name, Object args) { return "called invokeMethod $name $args" } } The output of the following codewould be shown below. Note that there is no error of missing Method Exception even though the method Display does not exist. Joe 1 This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The following example shows how by using the metaClass function we are able to change the value of the private variables in the class. class Example { static void main(String[] args) { Student mst = new Student(); println mst.getName() mst.metaClass.setAttribute(mst, 'name', 'Mark') println mst.getName() } } class Student { private String name = "Joe"; public String getName() { return this.name; } } The output of the following code would be − Joe Mark Groovy supports the concept of methodMissing. This method differs from invokeMethod in that it is only invoked in case of a failed method dispatch, when no method can be found for the given name and/or the given arguments. The following example shows how the methodMissing can be used. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def methodMissing(String name, def args) { println "Missing method" } } The output of the following code would be − Joe 1 Missing method 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2359, "s": 2238, "text": "Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly." }, { "code": null, "e": 2560, "s": 2359, "text": "So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods. Suppose if you had to invoke the following statements on this class." }, { "code": null, "e": 2636, "s": 2560, "text": "Def myStudent = new Student() \nmyStudent.Name = ”Joe”; \nmyStudent.Display()" }, { "code": null, "e": 2786, "s": 2636, "text": "Now in meta object programming, even though the class does not have the member variable Name or the method Display(), the above code will still work." }, { "code": null, "e": 2990, "s": 2786, "text": "How can this work? Well, for this to work out, one has to implement the GroovyInterceptable interface to hook into the execution process of Groovy. Following are the methods available for this interface." }, { "code": null, "e": 3300, "s": 2990, "text": "Public interface GroovyInterceptable { \n Public object invokeMethod(String methodName, Object args) \n Public object getproperty(String propertyName) \n Public object setProperty(String propertyName, Object newValue) \n Public MetaClass getMetaClass() \n Public void setMetaClass(MetaClass metaClass) \n}" }, { "code": null, "e": 3466, "s": 3300, "text": "So in the above interface description, suppose if you had to implement the invokeMethod(), it would be called for every method which either exists or does not exist." }, { "code": null, "e": 3631, "s": 3466, "text": "So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code." }, { "code": null, "e": 3699, "s": 3631, "text": "The class Student has no member variable called Name or ID defined." }, { "code": null, "e": 3767, "s": 3699, "text": "The class Student has no member variable called Name or ID defined." }, { "code": null, "e": 3831, "s": 3767, "text": "The class Student implements the GroovyInterceptable interface." }, { "code": null, "e": 3895, "s": 3831, "text": "The class Student implements the GroovyInterceptable interface." }, { "code": null, "e": 4027, "s": 3895, "text": "There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly." }, { "code": null, "e": 4159, "s": 4027, "text": "There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly." }, { "code": null, "e": 4290, "s": 4159, "text": "The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime." }, { "code": null, "e": 4421, "s": 4290, "text": "The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime." }, { "code": null, "e": 4841, "s": 4421, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n }\n}\n\nclass Student implements GroovyInterceptable { \n protected dynamicProps=[:]\n\t\n void setProperty(String pName,val) {\n dynamicProps[pName] = val\n }\n \n def getProperty(String pName) {\n dynamicProps[pName]\n } \n} " }, { "code": null, "e": 4885, "s": 4841, "text": "The output of the following code would be −" }, { "code": null, "e": 4893, "s": 4885, "text": "Joe \n1\n" }, { "code": null, "e": 5059, "s": 4893, "text": "So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code −" }, { "code": null, "e": 5184, "s": 5059, "text": "The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not." }, { "code": null, "e": 5309, "s": 5184, "text": "The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not." }, { "code": null, "e": 5863, "s": 5309, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n mst.AddMarks();\n } \n}\n \nclass Student implements GroovyInterceptable {\n protected dynamicProps = [:] \n \n void setProperty(String pName, val) {\n dynamicProps[pName] = val\n } \n \n def getProperty(String pName) {\n dynamicProps[pName]\n }\n \n def invokeMethod(String name, Object args) {\n return \"called invokeMethod $name $args\"\n }\n}" }, { "code": null, "e": 6020, "s": 5863, "text": "The output of the following codewould be shown below. Note that there is no error of missing Method Exception even though the method Display does not exist." }, { "code": null, "e": 6029, "s": 6020, "text": "Joe \n1 \n" }, { "code": null, "e": 6323, "s": 6029, "text": "This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The following example shows how by using the metaClass function we are able to change the value of the private variables in the class." }, { "code": null, "e": 6642, "s": 6323, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n println mst.getName()\n mst.metaClass.setAttribute(mst, 'name', 'Mark')\n println mst.getName()\n } \n} \n\nclass Student {\n private String name = \"Joe\";\n\t\n public String getName() {\n return this.name;\n } \n}" }, { "code": null, "e": 6686, "s": 6642, "text": "The output of the following code would be −" }, { "code": null, "e": 6697, "s": 6686, "text": "Joe \nMark\n" }, { "code": null, "e": 6983, "s": 6697, "text": "Groovy supports the concept of methodMissing. This method differs from invokeMethod in that it is only invoked in case of a failed method dispatch, when no method can be found for the given name and/or the given arguments. The following example shows how the methodMissing can be used." }, { "code": null, "e": 7529, "s": 6983, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n mst.AddMarks();\n } \n} \n\nclass Student implements GroovyInterceptable {\n protected dynamicProps = [:] \n \n void setProperty(String pName, val) {\n dynamicProps[pName] = val\n }\n \n def getProperty(String pName) {\n dynamicProps[pName]\n }\n \n def methodMissing(String name, def args) { \n println \"Missing method\"\n } \n}" }, { "code": null, "e": 7573, "s": 7529, "text": "The output of the following code would be −" }, { "code": null, "e": 7598, "s": 7573, "text": "Joe \n1 \nMissing method \n" }, { "code": null, "e": 7631, "s": 7598, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 7649, "s": 7631, "text": " Krishna Sakinala" }, { "code": null, "e": 7684, "s": 7649, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7702, "s": 7684, "text": " Packt Publishing" }, { "code": null, "e": 7709, "s": 7702, "text": " Print" }, { "code": null, "e": 7720, "s": 7709, "text": " Add Notes" } ]
Building a Linear Regression by Hand | by moxú | Towards Data Science
W e employ linear regression to forecast the value of Y based on the value(s) of X. Because we need to know Y, it is a supervised learning approach. Linear regression is classified into two types: basic and multiple. Let’s start with the easy one. The notebook with all the codes is here. All the equations were made with LaTeX. Before we begin, it is critical to understand that linear regression is a parametric approach. Parametric method: 1. It assumes the function’s shape in advance. 2. It simplifies the issue of estimating f (X) to estimating a collection of parameters. This assumption simplifies the task since estimating the collection of parameters is easier than with a completely arbitrary function. 3. The most difficult aspect of these approaches is making the proper estimate. We can only make guesses about the correct form of the curve, resulting in erroneous forecasts. As a result, we must estimate parameters that will allow us to create a line that best approximates the values of Y, whether known or unknown. This is the function of a simple linear regression. Variations of this equation can be found in statistical literature, but they all have the same substance. It may be W0 and W1, alpha and beta, and so on. However, I’d want to bring your attention to something. Take note of the sign ≈. When we estimate values, our major goal is to get our predictions close to the true values of Y through X. That is, we aim to minimize the difference between the true and estimated values as much as feasible. As a result, when dealing with estimations of f(X) = Y, or more specifically, parameters of f(X) where f (X) = Y or Y = f (X), we do not aim to define f (X) perfectly, but rather estimate parameters that best represent f (X). However, because Y = ^f (X) + e, our estimate of f(X) will equal Y when added with e, the residual. Where Y = ^f (X) + e, then ^f (X) = ^B0 + ^B1X = ^Y. That is, in order to estimate ^Y, we must first estimate the parameters of ^f(X), ^B0 and ^B1. Y = ^Y + e since Y = ^f (X) + e and ^f (X) = ^Y. With that in mind, the formula we’ll use is: No more distractions. BO denotes the intercept, which is the Y value at X = 0, or the Y value at which the linear regression line begins. Here’s an example. We want to estimate the number of sales conversions based on the amount of investment made in a campaign. How much can I sell if I don’t put up any money? And what about the B1? The slope is represented by the value of B1. It basically determines the trend line. How does this work in practice? Consider the example of calculating height based on weight. Height is measured in centimeters, and weight is measured in kilograms. We discover a slope of 2.5. It indicates that for every kilogram gained, a person’s height increases by 2.5 millimeters. How do we estimate B0 and B1 given that we know what they are? These parameters can be estimated in a variety of methods. To begin, let’s look at the Ordinary Least Squares (OLS), which is one of the most frequent and straightforward. To estimate B0, we must first estimate B1. In statistics, ordinary least squares (OLS) is a type of linear least squares method for estimating the unknown parameters in a linear regression model. OLS chooses the parameters of a linear function of a set of explanatory variables by the principle of least squares: minimizing the sum of the squares of the differences between the observed dependent variable (values of the variable being observed) in the given dataset and those predicted by the linear function of the independent variable. — Source: Wikipedia. Let’s have a look at what this implies. What do we want to achieve with this method? Reduce something. What should be minimized? The sum of the squares of the differences between the observed and estimated data. Let’s put this equation together. Backwards, we have the difference between the observed and estimated values. The values we estimate as a result of our regression are referred to as estimated values. The observed values are the true values. Therefore, observedValue - estimatedValue Now, square the difference between the estimated and observed values. Hence: square (observedValue - estimatedValue) Finally, the sum of the squares of the differences between the observed and estimated data.: sum (square (observedValue - estimatedValue)) Okay, but what is the significance of the sum? observedValue and estimatedValue are valueS. Consider this: we have two columns, Y and Y. The first is the real value, the observed value, and second is the estimated value. As I previously mentioned, we construct a model and utilize X to estimate Y, resulting in Y. Assuming that each column has three values, Y = [5, 9, 2] and Y = [6, 7, 2]. We have the following results using our formula: (5–6)2(9–7)2(2–2)2 The total is the sum of these three operations. As a result, (5–6)2 + (9–7)2 + (2–2) 2. We have the Residual Sum of Squares (RSS) as a result of these procedures. RSS = 5 is used in this case. We aim to reduce RSS using OLS. The general formula for RSS is: How we code this using Python? OLS is ONE of numerous methods for reducing this RSS. Another approach is, I don’t know, guessing various parameters of B0 and B1, calculating the error of all, and selecting the smallest one, but the smallest mistake discovered may not be so tiny. We’ll finish with an approach like this. When we have a small number of features and columns, OLS is the quickest and easiest approach to use. We will utilize fictitious data in our article. In this case, I made two arrays to represent X and Y. I created 1000 values in order to provide a more intriguing perspective. I split X and Y into four separate halves. The training data will contain 80% of the X and Y values (X train and y train), whereas 20% of the data will be utilized for testing (X test and y test). Let’s discuss about assumptions before we estimate B0 and B1. What are the fundamental assumptions of linear regression? We utilize linear regressions to forecast new values or to make inferences. There are numerous methods for estimating parameters in a regression. And many methods, such as OLS, require specific assumptions in order for their conclusions to be as accurate and impartial as feasible. These premises do not have to be followed exactly in every linear regression! It is only logical that this requirement be satisfied when employing linear regression for prediction. In essence, linear regression will draw a straight line through the data. If the data does not have a linear connection, the model cannot handle the data’s complexity. How can we put this concept to the test? There are two forms of confirmation under most assumptions. There is graphical confirmation as well as mathematical confirmation. I’ll cover both whenever feasible. When things get too complicated, I’ll just cover visuals. So we may plot the X data against the Y data and look for trends. Let’s execute this command and see what happens. plt.figure(figsize=(10,10))plt.scatter(X_train, y_train)plt.show() To me, it appears to be quite linear! There’s even a straight line I can see! But what’s the point? I’m not sure about you, but visual confirmation does not completely satisfy me. Of course, your perspective is determined by your time, money, and education. However, we have all the time in the world here, it is free, and we are knowledgeable enough to use alternative methods. And, other than graphs, how do we assess a linear relationship? The correlation coefficient between X and Y is computed. But what exactly is the correlation? In statistics, correlation or dependence is any statistical relationship, whether causal or not, between two random variables or bivariate data. In the broadest sense correlation is any statistical association, though it commonly refers to the degree to which a pair of variables are linearly related. Familiar examples of dependent phenomena include the correlation between the height of parents and their offspring, and the correlation between the price of a good and the quantity the consumers are willing to purchase, as it is depicted in the so-called demand curve.. —Source: Wikipedia. Following this quick explanation, I shall reiterate a statistician’s mantra: correlation does not indicate causation! Before we can get a clear judgment on causality, we need to run a number of statistical tests. But it is a topic for another day! In our data, we wish to calculate the degree of correlation between X and Y. There are various approaches to this problem. Pearson’s coefficient is the most commonly used. Its general formula is as follows: That is, the division of two variables’ standard deviations divided by their covariance. Let’s break things down so you can comprehend it better. We’ll look at two sections. The covariance of X with respect to Y, as well as the variance of X and Y. I’ll leave this information, which includes some graphic explanations, for the idea of variance. It’s definitely worth a look. In summary, covariance denotes the degree to which two variables fluctuate in tandem. How do we compute the covariance of two variables in Python? Let’s use the formula: That’s all! And what is the standard deviation of the sample? The standard deviation of a random variable is a measure of its dispersion around the population mean. A low standard deviation implies that the data points are frequently near to the mean or anticipated value. A large standard deviation implies that the data points are distributed throughout a broad range of values (Wikipedia). The square root of the variance is also the standard deviation. Let’s use Python to create our standard deviation formula by utilizing the variance formula and calculating its root: Let’s take the standard deviations first. As you can see, we utilize the variance formula to find the root of the problem. We may now use our Pearson coefficient. Let’s start with the original formula and create our function from there: Given that we’ve already gone more than halfway, let’s simplify this formula even further: covarianceOfXY / StdX * StdY Let’s see how the outcome with our data turned out. The Pearson Correlation Coefficient between X and Y is [0.98478235]. And what is the significance of Pearson’s coefficient? Pearson’s coefficient is a number between -1 and 1, with 1 and -1 representing perfect linear correlations and 0 representing a non-existent relationship. A perfect positive correlation is 1 while a perfect negative correlation is -1. What should the ideal values be? It is conditional. Sometimes a correlation of 0.7 is optimum, and other times 0.9 is insufficient. It will be determined by the nature of your problem. In a multiple linear regression, you may use Pearson’s coefficient to find the most significant factors in your model or to exclude co-dependent variables. Now that we’ve identified one of the assumptions, let’s get started on estimating the parameters. B0 and B1 will be estimated using the OLS formula. The following are the equations: Looking at it that way, it’s a bit difficult, lol. But, in reality, it’s rather easy. Let’s begin with B1: As previously stated, B1 is the covariance between X and Y divided by X’s variation. B0 is simply the value of Y when X = 0, taking into account the difference between the median of Y and the product of the angular coefficient and the median of X. Let’s use Python to estimate B0 and B1? Because we divide our data in training and testing, our X and Y will be our training X and Y. It’s time to estimate! Intercept: -4.959319577525191, Slope: [2.00341869]. To put it another way, our line begins at -4.9593 and progresses at a rate of 2.003 for each increment of X. Now we’ll apply these parameters to new data and see how our predictions fare! Now is the time to build our linear regression! Because we separated our data before, we can now test and evaluate our model! y_pred = predict_function(b0_coeficient, b1_coeficient, X_test) After that? Now it’s time to design our return route! plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, y_pred, color='red', linewidth=2)plt.title("Linear Regression Demonstration", fontweight="bold", size=15)plt.show() It appears that our return went well! Naturally, linear regression lines will never reach all points. Or, at the very least, if they are correct, it will not be a good thing if the model’s intention is to generalize it to new data. This is due to the error that every linear equation has. In this moment, we will add the final component of our equation, about which we have already spoken. Error. The error is the difference between the predicted and actual value of Y. The cost of an error might be the result of a variety of factors. Sometimes it’s a single variable that you’re not considering, and other times you’ve assumed a linear relationship that doesn’t exist in reality. Another reason might be a data shortage. With so limited data, it is possible that your estimates will fail to reveal the true nature of the problem.To begin, there are several paths to take in order to reduce error. You may look for more data, choose a non-parametric or linear model, and add more variables. The strategies differ and will be determined by your assessment. How much does it cost to look for more data? Is it worthwhile to look for further information? How long will it take to test another model? When working professionally, you should ask all of these questions. Is there a limit? Yes. Call it an irreversible error. The irreversible error is aleatory and, by definition, cannot be measured or observed. We’ll bring you our new equation, which I’ll explain to you. Y = ^f(X) + e Sure, we’ve already completed the first stage and estimated the parameters of f(X). To aid comprehension, we are employing a linear regression to determine or predict the average level of heart beats throughout an hour given a certain quantity of Pfizer vaccine applied in mouses. However, the error has not yet been committed and will not be committed. Why is this so? We’re guessing you came home late last night, tired and with a heavy night’s sleep. On that same night, one of your mouses, Pitu, bridled by Marquinhos. Pitu, like the other rats in the gaiola, became extremely stressed. Fortunately, no one was injured. Pitu tried to tell you about the injustice the next day, but because you don’t talk to animals, you don’t know what happened. The stress levels of Pitu were altered by what happened and by the fact that you didn’t understand what happened. Stress levels were an important variable in your results that you ignored for N reasons, one of which was that you don’t speak “mouseguese”. Magdalena, another little mouse, is lonely and has no one to talk to or play with. When you go out, the others have a party, but Magdalena stays in her corner, mulling over her sorrows. You will most likely be unable to identify Magdalene’s sadness because you did not major in mouse psychology. This variable, which you couldn’t measure or even see, will be crucial in evaluating Magdalene’s results! Did you get my point? There are factors that are just not observable or collectable for your analysis. You should be wondering, but what error is this, and why do I believe I heard it somewhere? You saw it up there, but it had a different name: RSS. Will we compute the model’s RSS? print(f'The RSS is {get_rss(y_pred, y_test)}.')# The RSS is 191.16066429. With this number, we may look for ways to reduce it. But it isn’t the issue today! I’m mentioning the error for a reason. The second premise of Linear Regression. Why is this so? There are several disputes over why this assumption should be confirmed and what happens when it is not satisfied, even if it is necessary. As these are quite technical issues, I will not address them in this article. And how can we know if a data distribution is normal? There are two types of graphs: graphic and mathematical. I’ll be using graphics in this section. If we want to examine the behavior of all the leftovers, we can’t use RSS since RSS looks at the sum of the leftovers, but I’m not interested in the sum of the leftovers, but rather in the individual ones. Remember that registration at the start? We’ll look at the formula Y = ^Y + e. To calculate the residual, just switch Y from left to right, resulting in: Y − ^Y = e. e = observedValue— estimatedValue It’s simple, in Python: residual_lr = get_residual(y_test, y_pred) As a result, we will have an array with our leftovers. Will we examine their distribution using a histogram? plt.subplots(figsize=(12, 6))plt.title('Distribution of Residuals')sns.distplot(residual_lr)plt.show() Well, it appears to be a normal distribution, albeit slightly asymmetric! Is there another way to confirm that this is a normal distribution graphically? Yes, there is! It’s known as the QQPlot graph! lst = []for i in residual_lr: for n in i: lst.append(n)sm.qqplot(np.array(lst), line='45', fit=True)plt.show() In this code, I extracted the values from an array of arrays and placed them in a list for our QQPlot to validate! There you have it! What exactly is this stuff I’ve never seen before? You may be curious. I will not spend too much time conceptualizing the QQPlot, but rather interpreting it. In case you’re interested in learning more. What can we conclude from a QQ plot? We have a red straight line and a blue dispersion of residuals. We may visualize the distribution of our data using the QQ plot. We have a perfect normal distribution if they perfectly follow the red line. The further our data deviates from this straight line, the less of a normal distribution character remains. For a better understanding, you may find an explanation with visualizations here. Based on this visualization, we concluded that our waste had a typical distribution, despite some points being further away from the center. There are several statistical tests that may determine if a distribution is normal or not, such as the Shapiro-Wilk test. But for now, we’ll just stick with the visualization! We’re heading to our next stop. Linear regression models rely heavily on the premise of homoscedasticity (which means “constant variance”). Homoscedasticity defines a situation in which the error term (the “noise” or random disturbance in the relationship between the independent variables and the dependent variable) is the same for all independent variable values. Heteroscedasticity (the violation of homoscedasticity) occurs when the size of the error term varies across independent variable values. The impact of a breach of the homoscedasticity assumption is proportional to the degree of heteroscedasticity. What is the significance of this to us? When we use MMQ, we give all X-values the same weight. We have an issue if some X values have a greater influence than others. Consider an estimate of luxury goods purchases based on household income. We have impoverished families who do not or only buy a few luxury items. If the purchase of luxury goods grew with every increase in household income, we would have a constant variance. But assume that just a portion of the wealthy families buy luxury items, while the others buy relatively little: we have a problem with heteroscedasticity. Do you remember the B1 formula? The variance of the values of X is calculated in the divisor section. Because the OLS provides the same weight to all variables of X, very big variations can get in the way! How can we see this? Let’s put Python to use! Let’s start with a visual representation. We will plot our residuals against the anticipated values to observe the variation of the errors. plt.scatter(residual_lr, y_pred)plt.show() To be honest, I couldn’t draw any conclusions from this image! There doesn’t appear to be any pattern in the dots. So, shall we put it to the test? H0 = homocedasticityH1 != homocedasticityalpha = 0.05 Let’s use the statsmodels.stats library for this! print(sm.diagnostics.het_goldfeldquandt(residual_lr, y_pred))Test: 1.0206718127917291p-value: 0.45956295321355667 We cannot reject the null hypothesis because of alpha < p-value, hence we cannot deny the presence of homoscedasticity! Whew! Our model confirmed and passed all of the assumptions! You are most likely thinking “Can we leave now? The model is amazing! “. You can relax if you wish to utilize the model to analyze the variables. You can start examining it tomorrow to see if you can get anything out of it. We’re just halfway there if you want to utilize the model to make predictions! Now it is time to evaluate our model’s generalizability! As you can see, our model did a good job of staring at the test data. But how well? How do we assess our model? Using metrics! There are a number of measurements for this. One of these is the R-squared, often known as the Coefficient of Determination. R2 is a measure that expresses how much of the variation in the data is explained by the model. In other words, this metric computes the proportion of variance that the regression model might predict, and so shows us how “closer” the actual measures are to our model. It denotes the proportion of the variability in the response variable that may be explained by the predictor or explanatory variable. Its R-squared value varies from 0 to 1, with 0 being the poorest possible estimate and 1 representing the best possible estimate. It is typically expressed as a percentage. For example, an R2 = 73 % indicates that the model can explain 73% of the volatility in our data, while the remaining 27% is theoretically a residual variance. Is it possible to have negative R-squares? Yes, when your model is capable of being worse than kicking the mean of Y for all Y values. What exactly is the R2 formula? Let’s go over our RSS formula again. We will change it based on it. We have the sum of the squares of the residuals in RSS. However, we wish to calculate the total sum of squares of the residuals. In RSS, we take the difference between each observed and estimated value of Y, or Y, square it, and add the findings. In TSS, we compute the difference between the Y values and the Y squared mean. That is to say: TSS = sum ( ( valuesX — meanY ) 2) R2 is basically: 1 — (RSS / TSS) rss = get_rss(y_pred, y_test)rst = rst_metric(y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.') The R2 of the model is 97.17569151561773% That means, our model was able to explain nearly 97.18 % of our data! The model appears to be generalizable to fresh data! R-squared can alternatively be calculated by squaring Pearson’s Coefficient: print(0.98478235 ** 2)# 0.969796276871522 Do you want to know what R-squared would be if you just took the average? Let’s have a look together! Let’s make a list the same size as Y, but with the mean of Y instead. plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, lst, color='red', linewidth=2)plt.title("Linear Regression Demonstration", size=15)plt.show() Now, let’s calculate the R-squared: rst = tss_metric(y_test)rss = get_rss(lst, y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.') The R2 of the model is 0.0%. Remember when I said that R-squared could be less than 0? The greater the RSS is above RST, the lower the R-squared will be. However, the question persists. What’s the other method for estimating a linear regression? Okay, I’ll swiftly approach a reasonable strategy that I had in mind. The explanation behind this is as follows. Let’s pick 100 intercept and 100 slope values, then test 10,000 linear regressions, compare them, and pick the combination with the smallest RSS. Let’s get started! Here we run 10,000 regressions. Shall we calculate and get the smallest RSS? min_index = rss_list.index(np.min(rss_list))print(f'The lowest RSS is: {np.min(rss_list)} with index {min_index}.')# The lowest RSS is: 190.52186974065032 with index 4552. We get a little smaller RSS when we use this workaround than when we use OLS! Take this index and use it to plot our regression line on the test data. plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, linear_reg[min_index], color='red', linewidth=2)plt.title("Linear Regression Demonstration", size=15)plt.show() And the R-squared? rst = tss_metric(y_test)rss = get_rss(linear_reg[min_index], y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.')# The R2 of the model is 97.18512940329813%. As you can see, the difference is negligible, almost non-existent. While using the MMQ method we got 97.175%, here we get 97.185%. With that, we’ll conclude our article! I attempted to address the most important aspects of creating a linear regression by understanding what lies behind the five or six lines of code that are sufficient to do everything we’ve discussed here. The remaining questions are: Is it required to check all of this? Is there another way to achieve consistent results without going through all of this? All I want to do now is finish Kaggle’s Titanic linear regression. Is it really necessary for me to do so? This is a heated debate! Some splashes can be found here. But keep in mind that as a data scientist, you must solve the problem and demonstrate your findings to your peers. When you deal with real data, it won’t be cute like the ones here, but you need to solve the problem! References: Homoscedasticidade — CENTRO DE ESTATÍSTICA APLICADA. Disponível em: <https://estatistica.pt/homoscedasticidade/>. Acesso em: 24 set. 2021. ‌Teste para normalidade e homocedasticidade. Disponível em: <https://biostatistics-uem.github.io/Bio/aula8/teste_normalidade_homocedasticidade.html>. Acesso em: 24 set. 2021. ‌HOW WOULD YOU EXPLAIN COVARIANCE TO SOMEONE WHO UNDERSTANDS ONLY THE MEAN. How would you explain covariance to someone who understands only the mean? Disponível em: <https://stats.stackexchange.com/questions/18058/how-would-you-explain-covariance-to-someone-who-understands-only-the-mean>. Acesso em: 24 set. 2021. ‌DAMACENO, L. Entendendo Regressão Linear: as suposições por trás de tudo! Disponível em: <https://medium.com/@lauradamaceno/entendendo-regress%C3%A3o-linear-as-suposi%C3%A7%C3%B5es-por-tr%C3%A1s-de-tudo-d0e29004c7f8>. Acesso em: 24 set. 2021. ‌SHRUTIMECHLEARN. Step by Step Assumptions — Linear Regression. Disponível em: <https://www.kaggle.com/shrutimechlearn/step-by-step-assumptions-linear-regression>. Acesso em: 24 set. 2021. ‌NATHÁLIA TITO. Scikit-learn ou statsmodels? Avaliando meu modelo de regressão. Disponível em: <https://nathaliatito.medium.com/scikit-learn-ou-statsmodels-avaliando-meu-modelo-de-regress%C3%A3o-f4c04b361fa7>. Acesso em: 24 set. 2021. ‌Regressão multilinear usando Python. Disponível em: <https://ichi.pro/pt/regressao-multilinear-usando-python-75578758662189>. Acesso em: 24 set. 2021. ‌SERGIO MIRANDA FREIRE. 19 Regressão Linear | Bioestatística Básica. Disponível em: <http://www.lampada.uerj.br/arquivosdb/_book/regress%C3%A3o-linear.html#eqReta>. Acesso em: 24 set. 2021.
[ { "code": null, "e": 500, "s": 171, "text": "W e employ linear regression to forecast the value of Y based on the value(s) of X. Because we need to know Y, it is a supervised learning approach. Linear regression is classified into two types: basic and multiple. Let’s start with the easy one. The notebook with all the codes is here. All the equations were made with LaTeX." }, { "code": null, "e": 595, "s": 500, "text": "Before we begin, it is critical to understand that linear regression is a parametric approach." }, { "code": null, "e": 614, "s": 595, "text": "Parametric method:" }, { "code": null, "e": 661, "s": 614, "text": "1. It assumes the function’s shape in advance." }, { "code": null, "e": 885, "s": 661, "text": "2. It simplifies the issue of estimating f (X) to estimating a collection of parameters. This assumption simplifies the task since estimating the collection of parameters is easier than with a completely arbitrary function." }, { "code": null, "e": 1061, "s": 885, "text": "3. The most difficult aspect of these approaches is making the proper estimate. We can only make guesses about the correct form of the curve, resulting in erroneous forecasts." }, { "code": null, "e": 1204, "s": 1061, "text": "As a result, we must estimate parameters that will allow us to create a line that best approximates the values of Y, whether known or unknown." }, { "code": null, "e": 1410, "s": 1204, "text": "This is the function of a simple linear regression. Variations of this equation can be found in statistical literature, but they all have the same substance. It may be W0 and W1, alpha and beta, and so on." }, { "code": null, "e": 1700, "s": 1410, "text": "However, I’d want to bring your attention to something. Take note of the sign ≈. When we estimate values, our major goal is to get our predictions close to the true values of Y through X. That is, we aim to minimize the difference between the true and estimated values as much as feasible." }, { "code": null, "e": 2026, "s": 1700, "text": "As a result, when dealing with estimations of f(X) = Y, or more specifically, parameters of f(X) where f (X) = Y or Y = f (X), we do not aim to define f (X) perfectly, but rather estimate parameters that best represent f (X). However, because Y = ^f (X) + e, our estimate of f(X) will equal Y when added with e, the residual." }, { "code": null, "e": 2223, "s": 2026, "text": "Where Y = ^f (X) + e, then ^f (X) = ^B0 + ^B1X = ^Y. That is, in order to estimate ^Y, we must first estimate the parameters of ^f(X), ^B0 and ^B1. Y = ^Y + e since Y = ^f (X) + e and ^f (X) = ^Y." }, { "code": null, "e": 2268, "s": 2223, "text": "With that in mind, the formula we’ll use is:" }, { "code": null, "e": 2290, "s": 2268, "text": "No more distractions." }, { "code": null, "e": 2580, "s": 2290, "text": "BO denotes the intercept, which is the Y value at X = 0, or the Y value at which the linear regression line begins. Here’s an example. We want to estimate the number of sales conversions based on the amount of investment made in a campaign. How much can I sell if I don’t put up any money?" }, { "code": null, "e": 2973, "s": 2580, "text": "And what about the B1? The slope is represented by the value of B1. It basically determines the trend line. How does this work in practice? Consider the example of calculating height based on weight. Height is measured in centimeters, and weight is measured in kilograms. We discover a slope of 2.5. It indicates that for every kilogram gained, a person’s height increases by 2.5 millimeters." }, { "code": null, "e": 3251, "s": 2973, "text": "How do we estimate B0 and B1 given that we know what they are? These parameters can be estimated in a variety of methods. To begin, let’s look at the Ordinary Least Squares (OLS), which is one of the most frequent and straightforward. To estimate B0, we must first estimate B1." }, { "code": null, "e": 3768, "s": 3251, "text": "In statistics, ordinary least squares (OLS) is a type of linear least squares method for estimating the unknown parameters in a linear regression model. OLS chooses the parameters of a linear function of a set of explanatory variables by the principle of least squares: minimizing the sum of the squares of the differences between the observed dependent variable (values of the variable being observed) in the given dataset and those predicted by the linear function of the independent variable. — Source: Wikipedia." }, { "code": null, "e": 4014, "s": 3768, "text": "Let’s have a look at what this implies. What do we want to achieve with this method? Reduce something. What should be minimized? The sum of the squares of the differences between the observed and estimated data. Let’s put this equation together." }, { "code": null, "e": 4233, "s": 4014, "text": "Backwards, we have the difference between the observed and estimated values. The values we estimate as a result of our regression are referred to as estimated values. The observed values are the true values. Therefore," }, { "code": null, "e": 4264, "s": 4233, "text": "observedValue - estimatedValue" }, { "code": null, "e": 4341, "s": 4264, "text": "Now, square the difference between the estimated and observed values. Hence:" }, { "code": null, "e": 4381, "s": 4341, "text": "square (observedValue - estimatedValue)" }, { "code": null, "e": 4474, "s": 4381, "text": "Finally, the sum of the squares of the differences between the observed and estimated data.:" }, { "code": null, "e": 4520, "s": 4474, "text": "sum (square (observedValue - estimatedValue))" }, { "code": null, "e": 4960, "s": 4520, "text": "Okay, but what is the significance of the sum? observedValue and estimatedValue are valueS. Consider this: we have two columns, Y and Y. The first is the real value, the observed value, and second is the estimated value. As I previously mentioned, we construct a model and utilize X to estimate Y, resulting in Y. Assuming that each column has three values, Y = [5, 9, 2] and Y = [6, 7, 2]. We have the following results using our formula:" }, { "code": null, "e": 4979, "s": 4960, "text": "(5–6)2(9–7)2(2–2)2" }, { "code": null, "e": 5204, "s": 4979, "text": "The total is the sum of these three operations. As a result, (5–6)2 + (9–7)2 + (2–2) 2. We have the Residual Sum of Squares (RSS) as a result of these procedures. RSS = 5 is used in this case. We aim to reduce RSS using OLS." }, { "code": null, "e": 5236, "s": 5204, "text": "The general formula for RSS is:" }, { "code": null, "e": 5267, "s": 5236, "text": "How we code this using Python?" }, { "code": null, "e": 5659, "s": 5267, "text": "OLS is ONE of numerous methods for reducing this RSS. Another approach is, I don’t know, guessing various parameters of B0 and B1, calculating the error of all, and selecting the smallest one, but the smallest mistake discovered may not be so tiny. We’ll finish with an approach like this. When we have a small number of features and columns, OLS is the quickest and easiest approach to use." }, { "code": null, "e": 5707, "s": 5659, "text": "We will utilize fictitious data in our article." }, { "code": null, "e": 6031, "s": 5707, "text": "In this case, I made two arrays to represent X and Y. I created 1000 values in order to provide a more intriguing perspective. I split X and Y into four separate halves. The training data will contain 80% of the X and Y values (X train and y train), whereas 20% of the data will be utilized for testing (X test and y test)." }, { "code": null, "e": 6512, "s": 6031, "text": "Let’s discuss about assumptions before we estimate B0 and B1. What are the fundamental assumptions of linear regression? We utilize linear regressions to forecast new values or to make inferences. There are numerous methods for estimating parameters in a regression. And many methods, such as OLS, require specific assumptions in order for their conclusions to be as accurate and impartial as feasible. These premises do not have to be followed exactly in every linear regression!" }, { "code": null, "e": 6824, "s": 6512, "text": "It is only logical that this requirement be satisfied when employing linear regression for prediction. In essence, linear regression will draw a straight line through the data. If the data does not have a linear connection, the model cannot handle the data’s complexity. How can we put this concept to the test?" }, { "code": null, "e": 7047, "s": 6824, "text": "There are two forms of confirmation under most assumptions. There is graphical confirmation as well as mathematical confirmation. I’ll cover both whenever feasible. When things get too complicated, I’ll just cover visuals." }, { "code": null, "e": 7162, "s": 7047, "text": "So we may plot the X data against the Y data and look for trends. Let’s execute this command and see what happens." }, { "code": null, "e": 7229, "s": 7162, "text": "plt.figure(figsize=(10,10))plt.scatter(X_train, y_train)plt.show()" }, { "code": null, "e": 7608, "s": 7229, "text": "To me, it appears to be quite linear! There’s even a straight line I can see! But what’s the point? I’m not sure about you, but visual confirmation does not completely satisfy me. Of course, your perspective is determined by your time, money, and education. However, we have all the time in the world here, it is free, and we are knowledgeable enough to use alternative methods." }, { "code": null, "e": 7766, "s": 7608, "text": "And, other than graphs, how do we assess a linear relationship? The correlation coefficient between X and Y is computed. But what exactly is the correlation?" }, { "code": null, "e": 8358, "s": 7766, "text": "In statistics, correlation or dependence is any statistical relationship, whether causal or not, between two random variables or bivariate data. In the broadest sense correlation is any statistical association, though it commonly refers to the degree to which a pair of variables are linearly related. Familiar examples of dependent phenomena include the correlation between the height of parents and their offspring, and the correlation between the price of a good and the quantity the consumers are willing to purchase, as it is depicted in the so-called demand curve.. —Source: Wikipedia." }, { "code": null, "e": 8606, "s": 8358, "text": "Following this quick explanation, I shall reiterate a statistician’s mantra: correlation does not indicate causation! Before we can get a clear judgment on causality, we need to run a number of statistical tests. But it is a topic for another day!" }, { "code": null, "e": 8813, "s": 8606, "text": "In our data, we wish to calculate the degree of correlation between X and Y. There are various approaches to this problem. Pearson’s coefficient is the most commonly used. Its general formula is as follows:" }, { "code": null, "e": 9275, "s": 8813, "text": "That is, the division of two variables’ standard deviations divided by their covariance. Let’s break things down so you can comprehend it better. We’ll look at two sections. The covariance of X with respect to Y, as well as the variance of X and Y. I’ll leave this information, which includes some graphic explanations, for the idea of variance. It’s definitely worth a look. In summary, covariance denotes the degree to which two variables fluctuate in tandem." }, { "code": null, "e": 9359, "s": 9275, "text": "How do we compute the covariance of two variables in Python? Let’s use the formula:" }, { "code": null, "e": 9934, "s": 9359, "text": "That’s all! And what is the standard deviation of the sample? The standard deviation of a random variable is a measure of its dispersion around the population mean. A low standard deviation implies that the data points are frequently near to the mean or anticipated value. A large standard deviation implies that the data points are distributed throughout a broad range of values (Wikipedia). The square root of the variance is also the standard deviation. Let’s use Python to create our standard deviation formula by utilizing the variance formula and calculating its root:" }, { "code": null, "e": 9976, "s": 9934, "text": "Let’s take the standard deviations first." }, { "code": null, "e": 10171, "s": 9976, "text": "As you can see, we utilize the variance formula to find the root of the problem. We may now use our Pearson coefficient. Let’s start with the original formula and create our function from there:" }, { "code": null, "e": 10262, "s": 10171, "text": "Given that we’ve already gone more than halfway, let’s simplify this formula even further:" }, { "code": null, "e": 10291, "s": 10262, "text": "covarianceOfXY / StdX * StdY" }, { "code": null, "e": 10343, "s": 10291, "text": "Let’s see how the outcome with our data turned out." }, { "code": null, "e": 10412, "s": 10343, "text": "The Pearson Correlation Coefficient between X and Y is [0.98478235]." }, { "code": null, "e": 10702, "s": 10412, "text": "And what is the significance of Pearson’s coefficient? Pearson’s coefficient is a number between -1 and 1, with 1 and -1 representing perfect linear correlations and 0 representing a non-existent relationship. A perfect positive correlation is 1 while a perfect negative correlation is -1." }, { "code": null, "e": 11043, "s": 10702, "text": "What should the ideal values be? It is conditional. Sometimes a correlation of 0.7 is optimum, and other times 0.9 is insufficient. It will be determined by the nature of your problem. In a multiple linear regression, you may use Pearson’s coefficient to find the most significant factors in your model or to exclude co-dependent variables." }, { "code": null, "e": 11141, "s": 11043, "text": "Now that we’ve identified one of the assumptions, let’s get started on estimating the parameters." }, { "code": null, "e": 11225, "s": 11141, "text": "B0 and B1 will be estimated using the OLS formula. The following are the equations:" }, { "code": null, "e": 11332, "s": 11225, "text": "Looking at it that way, it’s a bit difficult, lol. But, in reality, it’s rather easy. Let’s begin with B1:" }, { "code": null, "e": 11580, "s": 11332, "text": "As previously stated, B1 is the covariance between X and Y divided by X’s variation. B0 is simply the value of Y when X = 0, taking into account the difference between the median of Y and the product of the angular coefficient and the median of X." }, { "code": null, "e": 11620, "s": 11580, "text": "Let’s use Python to estimate B0 and B1?" }, { "code": null, "e": 11737, "s": 11620, "text": "Because we divide our data in training and testing, our X and Y will be our training X and Y. It’s time to estimate!" }, { "code": null, "e": 11796, "s": 11737, "text": "Intercept: -4.959319577525191, Slope: [2.00341869]." }, { "code": null, "e": 12032, "s": 11796, "text": "To put it another way, our line begins at -4.9593 and progresses at a rate of 2.003 for each increment of X. Now we’ll apply these parameters to new data and see how our predictions fare! Now is the time to build our linear regression!" }, { "code": null, "e": 12110, "s": 12032, "text": "Because we separated our data before, we can now test and evaluate our model!" }, { "code": null, "e": 12174, "s": 12110, "text": "y_pred = predict_function(b0_coeficient, b1_coeficient, X_test)" }, { "code": null, "e": 12228, "s": 12174, "text": "After that? Now it’s time to design our return route!" }, { "code": null, "e": 12428, "s": 12228, "text": "plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, y_pred, color='red', linewidth=2)plt.title(\"Linear Regression Demonstration\", fontweight=\"bold\", size=15)plt.show()" }, { "code": null, "e": 12466, "s": 12428, "text": "It appears that our return went well!" }, { "code": null, "e": 12717, "s": 12466, "text": "Naturally, linear regression lines will never reach all points. Or, at the very least, if they are correct, it will not be a good thing if the model’s intention is to generalize it to new data. This is due to the error that every linear equation has." }, { "code": null, "e": 12825, "s": 12717, "text": "In this moment, we will add the final component of our equation, about which we have already spoken. Error." }, { "code": null, "e": 13110, "s": 12825, "text": "The error is the difference between the predicted and actual value of Y. The cost of an error might be the result of a variety of factors. Sometimes it’s a single variable that you’re not considering, and other times you’ve assumed a linear relationship that doesn’t exist in reality." }, { "code": null, "e": 13693, "s": 13110, "text": "Another reason might be a data shortage. With so limited data, it is possible that your estimates will fail to reveal the true nature of the problem.To begin, there are several paths to take in order to reduce error. You may look for more data, choose a non-parametric or linear model, and add more variables. The strategies differ and will be determined by your assessment. How much does it cost to look for more data? Is it worthwhile to look for further information? How long will it take to test another model? When working professionally, you should ask all of these questions." }, { "code": null, "e": 13895, "s": 13693, "text": "Is there a limit? Yes. Call it an irreversible error. The irreversible error is aleatory and, by definition, cannot be measured or observed. We’ll bring you our new equation, which I’ll explain to you." }, { "code": null, "e": 13909, "s": 13895, "text": "Y = ^f(X) + e" }, { "code": null, "e": 14190, "s": 13909, "text": "Sure, we’ve already completed the first stage and estimated the parameters of f(X). To aid comprehension, we are employing a linear regression to determine or predict the average level of heart beats throughout an hour given a certain quantity of Pfizer vaccine applied in mouses." }, { "code": null, "e": 14659, "s": 14190, "text": "However, the error has not yet been committed and will not be committed. Why is this so? We’re guessing you came home late last night, tired and with a heavy night’s sleep. On that same night, one of your mouses, Pitu, bridled by Marquinhos. Pitu, like the other rats in the gaiola, became extremely stressed. Fortunately, no one was injured. Pitu tried to tell you about the injustice the next day, but because you don’t talk to animals, you don’t know what happened." }, { "code": null, "e": 14914, "s": 14659, "text": "The stress levels of Pitu were altered by what happened and by the fact that you didn’t understand what happened. Stress levels were an important variable in your results that you ignored for N reasons, one of which was that you don’t speak “mouseguese”." }, { "code": null, "e": 15316, "s": 14914, "text": "Magdalena, another little mouse, is lonely and has no one to talk to or play with. When you go out, the others have a party, but Magdalena stays in her corner, mulling over her sorrows. You will most likely be unable to identify Magdalene’s sadness because you did not major in mouse psychology. This variable, which you couldn’t measure or even see, will be crucial in evaluating Magdalene’s results!" }, { "code": null, "e": 15419, "s": 15316, "text": "Did you get my point? There are factors that are just not observable or collectable for your analysis." }, { "code": null, "e": 15599, "s": 15419, "text": "You should be wondering, but what error is this, and why do I believe I heard it somewhere? You saw it up there, but it had a different name: RSS. Will we compute the model’s RSS?" }, { "code": null, "e": 15673, "s": 15599, "text": "print(f'The RSS is {get_rss(y_pred, y_test)}.')# The RSS is 191.16066429." }, { "code": null, "e": 15836, "s": 15673, "text": "With this number, we may look for ways to reduce it. But it isn’t the issue today! I’m mentioning the error for a reason. The second premise of Linear Regression." }, { "code": null, "e": 16070, "s": 15836, "text": "Why is this so? There are several disputes over why this assumption should be confirmed and what happens when it is not satisfied, even if it is necessary. As these are quite technical issues, I will not address them in this article." }, { "code": null, "e": 16427, "s": 16070, "text": "And how can we know if a data distribution is normal? There are two types of graphs: graphic and mathematical. I’ll be using graphics in this section. If we want to examine the behavior of all the leftovers, we can’t use RSS since RSS looks at the sum of the leftovers, but I’m not interested in the sum of the leftovers, but rather in the individual ones." }, { "code": null, "e": 16593, "s": 16427, "text": "Remember that registration at the start? We’ll look at the formula Y = ^Y + e. To calculate the residual, just switch Y from left to right, resulting in: Y − ^Y = e." }, { "code": null, "e": 16627, "s": 16593, "text": "e = observedValue— estimatedValue" }, { "code": null, "e": 16651, "s": 16627, "text": "It’s simple, in Python:" }, { "code": null, "e": 16694, "s": 16651, "text": "residual_lr = get_residual(y_test, y_pred)" }, { "code": null, "e": 16803, "s": 16694, "text": "As a result, we will have an array with our leftovers. Will we examine their distribution using a histogram?" }, { "code": null, "e": 16906, "s": 16803, "text": "plt.subplots(figsize=(12, 6))plt.title('Distribution of Residuals')sns.distplot(residual_lr)plt.show()" }, { "code": null, "e": 17107, "s": 16906, "text": "Well, it appears to be a normal distribution, albeit slightly asymmetric! Is there another way to confirm that this is a normal distribution graphically? Yes, there is! It’s known as the QQPlot graph!" }, { "code": null, "e": 17228, "s": 17107, "text": "lst = []for i in residual_lr: for n in i: lst.append(n)sm.qqplot(np.array(lst), line='45', fit=True)plt.show()" }, { "code": null, "e": 17362, "s": 17228, "text": "In this code, I extracted the values from an array of arrays and placed them in a list for our QQPlot to validate! There you have it!" }, { "code": null, "e": 17564, "s": 17362, "text": "What exactly is this stuff I’ve never seen before? You may be curious. I will not spend too much time conceptualizing the QQPlot, but rather interpreting it. In case you’re interested in learning more." }, { "code": null, "e": 17997, "s": 17564, "text": "What can we conclude from a QQ plot? We have a red straight line and a blue dispersion of residuals. We may visualize the distribution of our data using the QQ plot. We have a perfect normal distribution if they perfectly follow the red line. The further our data deviates from this straight line, the less of a normal distribution character remains. For a better understanding, you may find an explanation with visualizations here." }, { "code": null, "e": 18138, "s": 17997, "text": "Based on this visualization, we concluded that our waste had a typical distribution, despite some points being further away from the center." }, { "code": null, "e": 18346, "s": 18138, "text": "There are several statistical tests that may determine if a distribution is normal or not, such as the Shapiro-Wilk test. But for now, we’ll just stick with the visualization! We’re heading to our next stop." }, { "code": null, "e": 18681, "s": 18346, "text": "Linear regression models rely heavily on the premise of homoscedasticity (which means “constant variance”). Homoscedasticity defines a situation in which the error term (the “noise” or random disturbance in the relationship between the independent variables and the dependent variable) is the same for all independent variable values." }, { "code": null, "e": 18929, "s": 18681, "text": "Heteroscedasticity (the violation of homoscedasticity) occurs when the size of the error term varies across independent variable values. The impact of a breach of the homoscedasticity assumption is proportional to the degree of heteroscedasticity." }, { "code": null, "e": 19096, "s": 18929, "text": "What is the significance of this to us? When we use MMQ, we give all X-values the same weight. We have an issue if some X values have a greater influence than others." }, { "code": null, "e": 19512, "s": 19096, "text": "Consider an estimate of luxury goods purchases based on household income. We have impoverished families who do not or only buy a few luxury items. If the purchase of luxury goods grew with every increase in household income, we would have a constant variance. But assume that just a portion of the wealthy families buy luxury items, while the others buy relatively little: we have a problem with heteroscedasticity." }, { "code": null, "e": 19718, "s": 19512, "text": "Do you remember the B1 formula? The variance of the values of X is calculated in the divisor section. Because the OLS provides the same weight to all variables of X, very big variations can get in the way!" }, { "code": null, "e": 19904, "s": 19718, "text": "How can we see this? Let’s put Python to use! Let’s start with a visual representation. We will plot our residuals against the anticipated values to observe the variation of the errors." }, { "code": null, "e": 19947, "s": 19904, "text": "plt.scatter(residual_lr, y_pred)plt.show()" }, { "code": null, "e": 20095, "s": 19947, "text": "To be honest, I couldn’t draw any conclusions from this image! There doesn’t appear to be any pattern in the dots. So, shall we put it to the test?" }, { "code": null, "e": 20149, "s": 20095, "text": "H0 = homocedasticityH1 != homocedasticityalpha = 0.05" }, { "code": null, "e": 20199, "s": 20149, "text": "Let’s use the statsmodels.stats library for this!" }, { "code": null, "e": 20313, "s": 20199, "text": "print(sm.diagnostics.het_goldfeldquandt(residual_lr, y_pred))Test: 1.0206718127917291p-value: 0.45956295321355667" }, { "code": null, "e": 20433, "s": 20313, "text": "We cannot reject the null hypothesis because of alpha < p-value, hence we cannot deny the presence of homoscedasticity!" }, { "code": null, "e": 20797, "s": 20433, "text": "Whew! Our model confirmed and passed all of the assumptions! You are most likely thinking “Can we leave now? The model is amazing! “. You can relax if you wish to utilize the model to analyze the variables. You can start examining it tomorrow to see if you can get anything out of it. We’re just halfway there if you want to utilize the model to make predictions!" }, { "code": null, "e": 20981, "s": 20797, "text": "Now it is time to evaluate our model’s generalizability! As you can see, our model did a good job of staring at the test data. But how well? How do we assess our model? Using metrics!" }, { "code": null, "e": 21508, "s": 20981, "text": "There are a number of measurements for this. One of these is the R-squared, often known as the Coefficient of Determination. R2 is a measure that expresses how much of the variation in the data is explained by the model. In other words, this metric computes the proportion of variance that the regression model might predict, and so shows us how “closer” the actual measures are to our model. It denotes the proportion of the variability in the response variable that may be explained by the predictor or explanatory variable." }, { "code": null, "e": 21841, "s": 21508, "text": "Its R-squared value varies from 0 to 1, with 0 being the poorest possible estimate and 1 representing the best possible estimate. It is typically expressed as a percentage. For example, an R2 = 73 % indicates that the model can explain 73% of the volatility in our data, while the remaining 27% is theoretically a residual variance." }, { "code": null, "e": 21976, "s": 21841, "text": "Is it possible to have negative R-squares? Yes, when your model is capable of being worse than kicking the mean of Y for all Y values." }, { "code": null, "e": 22205, "s": 21976, "text": "What exactly is the R2 formula? Let’s go over our RSS formula again. We will change it based on it. We have the sum of the squares of the residuals in RSS. However, we wish to calculate the total sum of squares of the residuals." }, { "code": null, "e": 22418, "s": 22205, "text": "In RSS, we take the difference between each observed and estimated value of Y, or Y, square it, and add the findings. In TSS, we compute the difference between the Y values and the Y squared mean. That is to say:" }, { "code": null, "e": 22453, "s": 22418, "text": "TSS = sum ( ( valuesX — meanY ) 2)" }, { "code": null, "e": 22470, "s": 22453, "text": "R2 is basically:" }, { "code": null, "e": 22486, "s": 22470, "text": "1 — (RSS / TSS)" }, { "code": null, "e": 22600, "s": 22486, "text": "rss = get_rss(y_pred, y_test)rst = rst_metric(y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.')" }, { "code": null, "e": 22642, "s": 22600, "text": "The R2 of the model is 97.17569151561773%" }, { "code": null, "e": 22765, "s": 22642, "text": "That means, our model was able to explain nearly 97.18 % of our data! The model appears to be generalizable to fresh data!" }, { "code": null, "e": 22842, "s": 22765, "text": "R-squared can alternatively be calculated by squaring Pearson’s Coefficient:" }, { "code": null, "e": 22884, "s": 22842, "text": "print(0.98478235 ** 2)# 0.969796276871522" }, { "code": null, "e": 23056, "s": 22884, "text": "Do you want to know what R-squared would be if you just took the average? Let’s have a look together! Let’s make a list the same size as Y, but with the mean of Y instead." }, { "code": null, "e": 23234, "s": 23056, "text": "plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, lst, color='red', linewidth=2)plt.title(\"Linear Regression Demonstration\", size=15)plt.show()" }, { "code": null, "e": 23270, "s": 23234, "text": "Now, let’s calculate the R-squared:" }, { "code": null, "e": 23381, "s": 23270, "text": "rst = tss_metric(y_test)rss = get_rss(lst, y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.')" }, { "code": null, "e": 23410, "s": 23381, "text": "The R2 of the model is 0.0%." }, { "code": null, "e": 23535, "s": 23410, "text": "Remember when I said that R-squared could be less than 0? The greater the RSS is above RST, the lower the R-squared will be." }, { "code": null, "e": 23697, "s": 23535, "text": "However, the question persists. What’s the other method for estimating a linear regression? Okay, I’ll swiftly approach a reasonable strategy that I had in mind." }, { "code": null, "e": 23905, "s": 23697, "text": "The explanation behind this is as follows. Let’s pick 100 intercept and 100 slope values, then test 10,000 linear regressions, compare them, and pick the combination with the smallest RSS. Let’s get started!" }, { "code": null, "e": 23982, "s": 23905, "text": "Here we run 10,000 regressions. Shall we calculate and get the smallest RSS?" }, { "code": null, "e": 24154, "s": 23982, "text": "min_index = rss_list.index(np.min(rss_list))print(f'The lowest RSS is: {np.min(rss_list)} with index {min_index}.')# The lowest RSS is: 190.52186974065032 with index 4552." }, { "code": null, "e": 24305, "s": 24154, "text": "We get a little smaller RSS when we use this workaround than when we use OLS! Take this index and use it to plot our regression line on the test data." }, { "code": null, "e": 24501, "s": 24305, "text": "plt.figure(figsize=(8,6))plt.scatter(X_test, y_test, color='blue')plt.plot(X_test, linear_reg[min_index], color='red', linewidth=2)plt.title(\"Linear Regression Demonstration\", size=15)plt.show()" }, { "code": null, "e": 24520, "s": 24501, "text": "And the R-squared?" }, { "code": null, "e": 24693, "s": 24520, "text": "rst = tss_metric(y_test)rss = get_rss(linear_reg[min_index], y_test)print(f'The R2 of the model is {get_r2(rss, rst)[0]*100}%.')# The R2 of the model is 97.18512940329813%." }, { "code": null, "e": 24824, "s": 24693, "text": "As you can see, the difference is negligible, almost non-existent. While using the MMQ method we got 97.175%, here we get 97.185%." }, { "code": null, "e": 25068, "s": 24824, "text": "With that, we’ll conclude our article! I attempted to address the most important aspects of creating a linear regression by understanding what lies behind the five or six lines of code that are sufficient to do everything we’ve discussed here." }, { "code": null, "e": 25500, "s": 25068, "text": "The remaining questions are: Is it required to check all of this? Is there another way to achieve consistent results without going through all of this? All I want to do now is finish Kaggle’s Titanic linear regression. Is it really necessary for me to do so? This is a heated debate! Some splashes can be found here. But keep in mind that as a data scientist, you must solve the problem and demonstrate your findings to your peers." }, { "code": null, "e": 25602, "s": 25500, "text": "When you deal with real data, it won’t be cute like the ones here, but you need to solve the problem!" }, { "code": null, "e": 25614, "s": 25602, "text": "References:" }, { "code": null, "e": 25755, "s": 25614, "text": "Homoscedasticidade — CENTRO DE ESTATÍSTICA APLICADA. Disponível em: <https://estatistica.pt/homoscedasticidade/>. Acesso em: 24 set. 2021." }, { "code": null, "e": 25931, "s": 25755, "text": "‌Teste para normalidade e homocedasticidade. Disponível em: <https://biostatistics-uem.github.io/Bio/aula8/teste_normalidade_homocedasticidade.html>. Acesso em: 24 set. 2021." }, { "code": null, "e": 26248, "s": 25931, "text": "‌HOW WOULD YOU EXPLAIN COVARIANCE TO SOMEONE WHO UNDERSTANDS ONLY THE MEAN. How would you explain covariance to someone who understands only the mean? Disponível em: <https://stats.stackexchange.com/questions/18058/how-would-you-explain-covariance-to-someone-who-understands-only-the-mean>. Acesso em: 24 set. 2021." }, { "code": null, "e": 26497, "s": 26248, "text": "‌DAMACENO, L. Entendendo Regressão Linear: as suposições por trás de tudo! Disponível em: <https://medium.com/@lauradamaceno/entendendo-regress%C3%A3o-linear-as-suposi%C3%A7%C3%B5es-por-tr%C3%A1s-de-tudo-d0e29004c7f8>. Acesso em: 24 set. 2021." }, { "code": null, "e": 26687, "s": 26497, "text": "‌SHRUTIMECHLEARN. Step by Step Assumptions — Linear Regression. Disponível em: <https://www.kaggle.com/shrutimechlearn/step-by-step-assumptions-linear-regression>. Acesso em: 24 set. 2021." }, { "code": null, "e": 26925, "s": 26687, "text": "‌NATHÁLIA TITO. Scikit-learn ou statsmodels? Avaliando meu modelo de regressão. Disponível em: <https://nathaliatito.medium.com/scikit-learn-ou-statsmodels-avaliando-meu-modelo-de-regress%C3%A3o-f4c04b361fa7>. Acesso em: 24 set. 2021." }, { "code": null, "e": 27079, "s": 26925, "text": "‌Regressão multilinear usando Python. Disponível em: <https://ichi.pro/pt/regressao-multilinear-usando-python-75578758662189>. Acesso em: 24 set. 2021." } ]
How to send one or more files to an API using axios in ReactJS?
14 Jan, 2021 Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below: Send multiple requests while attaching a single file in each request. Send a single request while attaching multiple files in that request itself. We are going to follow the second approach, and here are a few points to justify the action: In the first approach, we will have to make extra requests to send multiple files across the server, whereas, in the second approach, we will only have to make one request.The first approach will lead to the wastage of computing power, and it might add to extra costs if you are using cloud service providers like Google Cloud Platform(GCP) or Amazon Web Services(AWS).The first approach isn’t easy to handle the back-end server’s files, whereas it is simpler in the second approach. In the first approach, we will have to make extra requests to send multiple files across the server, whereas, in the second approach, we will only have to make one request. The first approach will lead to the wastage of computing power, and it might add to extra costs if you are using cloud service providers like Google Cloud Platform(GCP) or Amazon Web Services(AWS). The first approach isn’t easy to handle the back-end server’s files, whereas it is simpler in the second approach. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app multiple_files Step 2: Move to the directory containing the project using the following: cd multiple_files Step 3: Install axios module using the following command: npm install axios Step 4: Start the server using the following command: npm start Project structure: Here is the directory structure of the project: Project Structure Code for the 2nd approach: Filename: App.js Javascript import React from "react";import axios from "axios"; class App extends React.Component { state = { files: null, }; handleFile(e) { // Getting the files from the input let files = e.target.files; this.setState({ files }); } handleUpload(e) { let files = this.state.files; let formData = new FormData(); //Adding files to the formdata formData.append("image", files); formData.append("name", "Name"); axios({ // Endpoint to send files url: "http://localhost:8080/files", method: "POST", headers: { // Add any auth token here authorization: "your token comes here", }, // Attaching the form data data: formData, }) .then((res) => { }) // Handle the response from backend here .catch((err) => { }); // Catch errors if any } render() { return ( <div> <h1>Select your files</h1> <input type="file" multiple="multiple" //To select multiple files onChange={(e) => this.handleFile(e)} /> <button onClick={(e) => this.handleUpload(e)} >Send Files</button> </div> ); }} export default App; Output: Before clicking 'Send Files' Button: Browser output with multiple files selected To chose files click on the Choose Files button and select multiple files. After choosing the required files, click the Send Files button. After clicking 'Send Files' Button: Sending a request with the files You can see in the above photo that the files you have selected have been successfully attached in the form of data while sending to the server. Note: You can use appropriate packages in the backend to handle these files and can send the response from the server accordingly. Picked JavaScript ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2021" }, { "code": null, "e": 193, "s": 28, "text": "Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below:" }, { "code": null, "e": 263, "s": 193, "text": "Send multiple requests while attaching a single file in each request." }, { "code": null, "e": 340, "s": 263, "text": "Send a single request while attaching multiple files in that request itself." }, { "code": null, "e": 433, "s": 340, "text": "We are going to follow the second approach, and here are a few points to justify the action:" }, { "code": null, "e": 917, "s": 433, "text": "In the first approach, we will have to make extra requests to send multiple files across the server, whereas, in the second approach, we will only have to make one request.The first approach will lead to the wastage of computing power, and it might add to extra costs if you are using cloud service providers like Google Cloud Platform(GCP) or Amazon Web Services(AWS).The first approach isn’t easy to handle the back-end server’s files, whereas it is simpler in the second approach." }, { "code": null, "e": 1090, "s": 917, "text": "In the first approach, we will have to make extra requests to send multiple files across the server, whereas, in the second approach, we will only have to make one request." }, { "code": null, "e": 1288, "s": 1090, "text": "The first approach will lead to the wastage of computing power, and it might add to extra costs if you are using cloud service providers like Google Cloud Platform(GCP) or Amazon Web Services(AWS)." }, { "code": null, "e": 1403, "s": 1288, "text": "The first approach isn’t easy to handle the back-end server’s files, whereas it is simpler in the second approach." }, { "code": null, "e": 1431, "s": 1403, "text": "Creating React Application:" }, { "code": null, "e": 1495, "s": 1431, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1531, "s": 1495, "text": "npx create-react-app multiple_files" }, { "code": null, "e": 1605, "s": 1531, "text": "Step 2: Move to the directory containing the project using the following:" }, { "code": null, "e": 1623, "s": 1605, "text": "cd multiple_files" }, { "code": null, "e": 1681, "s": 1623, "text": "Step 3: Install axios module using the following command:" }, { "code": null, "e": 1699, "s": 1681, "text": "npm install axios" }, { "code": null, "e": 1753, "s": 1699, "text": "Step 4: Start the server using the following command:" }, { "code": null, "e": 1763, "s": 1753, "text": "npm start" }, { "code": null, "e": 1830, "s": 1763, "text": "Project structure: Here is the directory structure of the project:" }, { "code": null, "e": 1848, "s": 1830, "text": "Project Structure" }, { "code": null, "e": 1875, "s": 1848, "text": "Code for the 2nd approach:" }, { "code": null, "e": 1892, "s": 1875, "text": "Filename: App.js" }, { "code": null, "e": 1903, "s": 1892, "text": "Javascript" }, { "code": "import React from \"react\";import axios from \"axios\"; class App extends React.Component { state = { files: null, }; handleFile(e) { // Getting the files from the input let files = e.target.files; this.setState({ files }); } handleUpload(e) { let files = this.state.files; let formData = new FormData(); //Adding files to the formdata formData.append(\"image\", files); formData.append(\"name\", \"Name\"); axios({ // Endpoint to send files url: \"http://localhost:8080/files\", method: \"POST\", headers: { // Add any auth token here authorization: \"your token comes here\", }, // Attaching the form data data: formData, }) .then((res) => { }) // Handle the response from backend here .catch((err) => { }); // Catch errors if any } render() { return ( <div> <h1>Select your files</h1> <input type=\"file\" multiple=\"multiple\" //To select multiple files onChange={(e) => this.handleFile(e)} /> <button onClick={(e) => this.handleUpload(e)} >Send Files</button> </div> ); }} export default App;", "e": 3075, "s": 1903, "text": null }, { "code": null, "e": 3084, "s": 3075, "text": "Output: " }, { "code": null, "e": 3121, "s": 3084, "text": "Before clicking 'Send Files' Button:" }, { "code": null, "e": 3165, "s": 3121, "text": "Browser output with multiple files selected" }, { "code": null, "e": 3304, "s": 3165, "text": "To chose files click on the Choose Files button and select multiple files. After choosing the required files, click the Send Files button." }, { "code": null, "e": 3340, "s": 3304, "text": "After clicking 'Send Files' Button:" }, { "code": null, "e": 3373, "s": 3340, "text": "Sending a request with the files" }, { "code": null, "e": 3519, "s": 3373, "text": "You can see in the above photo that the files you have selected have been successfully attached in the form of data while sending to the server. " }, { "code": null, "e": 3650, "s": 3519, "text": "Note: You can use appropriate packages in the backend to handle these files and can send the response from the server accordingly." }, { "code": null, "e": 3657, "s": 3650, "text": "Picked" }, { "code": null, "e": 3668, "s": 3657, "text": "JavaScript" }, { "code": null, "e": 3676, "s": 3668, "text": "ReactJS" }, { "code": null, "e": 3774, "s": 3676, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3835, "s": 3774, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3875, "s": 3835, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3916, "s": 3875, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3958, "s": 3916, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3980, "s": 3958, "text": "JavaScript | Promises" }, { "code": null, "e": 4023, "s": 3980, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4068, "s": 4023, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 4106, "s": 4068, "text": "Axios in React: A Guide for Beginners" } ]
Differences between Java 8 and Java 9?
Java 9 version has introduced new enhancements and added new features. It includes JShell, Http2Client, Java Platform Module System (JPMS), Multi-release jar files, Stack Walking API, Private methods in an interface, Process API updates, Collection API updates, Stream API improvements, and etc. Below are the few differences between Java 8 and Java 9 In Java 8 and earlier versions, the top-level component is the package. It places a set of related types (classes, interfaces, enums, and etc) into a group, and also contains a set of resources whereas Java 9 introduces a new component: module, which can be used to place a set of related packages into a group, and also another new component: the module descriptor, module-info.java file. Java 8 applications use packages as a top-level component whereas Java 9 applications use modules as a top-level component. Each Java 9 module has only one module with one module descriptor whereas Java 8 package doesn't build multiple modules into a single module. Packages - Types (classes, enums, interfaces, etc) - Code - Data - Resources - xml - images - properties Modules (Resources, Module Descriptor) - Packages - Types (classes, enums, interfaces, etc) - Code - Data - Resources - xml - images - properties
[ { "code": null, "e": 1483, "s": 1187, "text": "Java 9 version has introduced new enhancements and added new features. It includes JShell, Http2Client, Java Platform Module System (JPMS), Multi-release jar files, Stack Walking API, Private methods in an interface, Process API updates, Collection API updates, Stream API improvements, and etc." }, { "code": null, "e": 1539, "s": 1483, "text": "Below are the few differences between Java 8 and Java 9" }, { "code": null, "e": 1929, "s": 1539, "text": "In Java 8 and earlier versions, the top-level component is the package. It places a set of related types (classes, interfaces, enums, and etc) into a group, and also contains a set of resources whereas Java 9 introduces a new component: module, which can be used to place a set of related packages into a group, and also another new component: the module descriptor, module-info.java file." }, { "code": null, "e": 2053, "s": 1929, "text": "Java 8 applications use packages as a top-level component whereas Java 9 applications use modules as a top-level component." }, { "code": null, "e": 2195, "s": 2053, "text": "Each Java 9 module has only one module with one module descriptor whereas Java 8 package doesn't build multiple modules into a single module." }, { "code": null, "e": 2353, "s": 2195, "text": "Packages \n - Types (classes, enums, interfaces, etc)\n - Code\n - Data\n - Resources\n - xml\n - images \n - properties" }, { "code": null, "e": 2571, "s": 2353, "text": "Modules (Resources, Module Descriptor)\n - Packages\n - Types (classes, enums, interfaces, etc)\n - Code\n - Data\n - Resources\n - xml\n - images\n - properties" } ]
How to Build a WiFi Scanner in Python using Scapy?
24 Feb, 2021 In this article, we are going to build a WiFi Scanner in Python using Scapy. WiFi Scanning or Network scanning refers to the scanning of the whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each client using their IP and MAC address. We can use ARP ping to find out the alive systems in our network. The network scanner will send the ARP request indicating who has some specific IP address, let’s say “192.168.1.1”, the owner of that IP address ( the target ) will automatically respond saying that he is “192.168.1.1”, with that response, the MAC address will also be included in the packet, this allows us to successfully retrieve all network users’ IP and MAC addresses simultaneously when we send a broadcast packet ( sending a packet to all the devices in the network ). Some important functions for creating a Network scanner: ARP(): This function defined in scapy module which allows us to create ARP packets (request or response). By default, if we are calling it, it will create an ARP request packet for us. This method provides us with the status of the packet that we have created. It does not provide detailed information about the packet, it just gives us the basic idea like what is the type of packet, what is the destination of the packet, etc. For example, if we want to create an ARP packet using ARP() method which is present in the scapy module and wants to see the summary of the packet then we can do this by creating the object of ARP class. show() Method: This method is very similar to summary() method. It gives more detailed information about the packet. The usage of this function is also much similar to a summary() method. ls() Function: This method is present in the scapy class. By using this method, we can see what are the fields that we can set for a specific packet. we will create an ARP packet and the with the help of ls() function, we will see what are the available fields for this packet. Approach: Create an ARP packet using ARP() method. Set the network range using a variable. Create an Ethernet packet using Ether() method. Set the destination to broadcast using variable hwdst. Combine ARP request packet and Ethernet frame using ‘/’. Send this to your network and capture the response from different devices.#scapy.srp() Print the IP and MAC address from the response packets. Below is the Python implementation: Python3 import scapy.all as scapy request = scapy.ARP() request.pdst = '192.168.0.1/24'broadcast = scapy.Ether() broadcast.dst = 'ff:ff:ff:ff:ff:ff' request_broadcast = broadcast / request clients = scapy.srp(request_broadcast, timeout = 10,verbose = 1)[0] for element in clients: print(element[1].psrc + " " + element[1].hwsrc) Output: Explanation: Here x = Network range. For example x = 192.168.0.1/24, 172.16.5.1/16 etc pdst is where the ARP packet should go (target), psrc is the IP to update in the target’s arp table, hwsrc is the sender’s hardware address. hwdst is a target hardware address Picked python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2021" }, { "code": null, "e": 432, "s": 54, "text": "In this article, we are going to build a WiFi Scanner in Python using Scapy. WiFi Scanning or Network scanning refers to the scanning of the whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each client using their IP and MAC address. We can use ARP ping to find out the alive systems in our network." }, { "code": null, "e": 908, "s": 432, "text": "The network scanner will send the ARP request indicating who has some specific IP address, let’s say “192.168.1.1”, the owner of that IP address ( the target ) will automatically respond saying that he is “192.168.1.1”, with that response, the MAC address will also be included in the packet, this allows us to successfully retrieve all network users’ IP and MAC addresses simultaneously when we send a broadcast packet ( sending a packet to all the devices in the network )." }, { "code": null, "e": 965, "s": 908, "text": "Some important functions for creating a Network scanner:" }, { "code": null, "e": 1598, "s": 965, "text": "ARP(): This function defined in scapy module which allows us to create ARP packets (request or response). By default, if we are calling it, it will create an ARP request packet for us. This method provides us with the status of the packet that we have created. It does not provide detailed information about the packet, it just gives us the basic idea like what is the type of packet, what is the destination of the packet, etc. For example, if we want to create an ARP packet using ARP() method which is present in the scapy module and wants to see the summary of the packet then we can do this by creating the object of ARP class." }, { "code": null, "e": 1786, "s": 1598, "text": "show() Method: This method is very similar to summary() method. It gives more detailed information about the packet. The usage of this function is also much similar to a summary() method." }, { "code": null, "e": 1936, "s": 1786, "text": "ls() Function: This method is present in the scapy class. By using this method, we can see what are the fields that we can set for a specific packet." }, { "code": null, "e": 2064, "s": 1936, "text": "we will create an ARP packet and the with the help of ls() function, we will see what are the available fields for this packet." }, { "code": null, "e": 2074, "s": 2064, "text": "Approach:" }, { "code": null, "e": 2115, "s": 2074, "text": "Create an ARP packet using ARP() method." }, { "code": null, "e": 2155, "s": 2115, "text": "Set the network range using a variable." }, { "code": null, "e": 2203, "s": 2155, "text": "Create an Ethernet packet using Ether() method." }, { "code": null, "e": 2258, "s": 2203, "text": "Set the destination to broadcast using variable hwdst." }, { "code": null, "e": 2315, "s": 2258, "text": "Combine ARP request packet and Ethernet frame using ‘/’." }, { "code": null, "e": 2402, "s": 2315, "text": "Send this to your network and capture the response from different devices.#scapy.srp()" }, { "code": null, "e": 2458, "s": 2402, "text": "Print the IP and MAC address from the response packets." }, { "code": null, "e": 2494, "s": 2458, "text": "Below is the Python implementation:" }, { "code": null, "e": 2502, "s": 2494, "text": "Python3" }, { "code": "import scapy.all as scapy request = scapy.ARP() request.pdst = '192.168.0.1/24'broadcast = scapy.Ether() broadcast.dst = 'ff:ff:ff:ff:ff:ff' request_broadcast = broadcast / request clients = scapy.srp(request_broadcast, timeout = 10,verbose = 1)[0] for element in clients: print(element[1].psrc + \" \" + element[1].hwsrc) ", "e": 2846, "s": 2502, "text": null }, { "code": null, "e": 2854, "s": 2846, "text": "Output:" }, { "code": null, "e": 2867, "s": 2854, "text": "Explanation:" }, { "code": null, "e": 2941, "s": 2867, "text": "Here x = Network range. For example x = 192.168.0.1/24, 172.16.5.1/16 etc" }, { "code": null, "e": 2990, "s": 2941, "text": "pdst is where the ARP packet should go (target)," }, { "code": null, "e": 3042, "s": 2990, "text": "psrc is the IP to update in the target’s arp table," }, { "code": null, "e": 3082, "s": 3042, "text": "hwsrc is the sender’s hardware address." }, { "code": null, "e": 3117, "s": 3082, "text": "hwdst is a target hardware address" }, { "code": null, "e": 3124, "s": 3117, "text": "Picked" }, { "code": null, "e": 3139, "s": 3124, "text": "python-modules" }, { "code": null, "e": 3154, "s": 3139, "text": "python-utility" }, { "code": null, "e": 3161, "s": 3154, "text": "Python" }, { "code": null, "e": 3259, "s": 3161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3291, "s": 3259, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3318, "s": 3291, "text": "Python Classes and Objects" }, { "code": null, "e": 3339, "s": 3318, "text": "Python OOPs Concepts" }, { "code": null, "e": 3362, "s": 3339, "text": "Introduction To PYTHON" }, { "code": null, "e": 3393, "s": 3362, "text": "Python | os.path.join() method" }, { "code": null, "e": 3449, "s": 3393, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3491, "s": 3449, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3533, "s": 3491, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3572, "s": 3533, "text": "Python | Get unique values from a list" } ]
How to Create an End to End Object Detector using Yolov5? | by Rahul Agarwal | Towards Data Science
Ultralytics recently launched YOLOv5 amid controversy surrounding its name. For context, the first three versions of YOLO (You Only Look Once) were created by Joseph Redmon. Following this, Alexey Bochkovskiy created YOLOv4 on darknet, which boasted higher Average Precision (AP) and faster results than previous iterations. Now, Ultralytics has released YOLOv5, with comparable AP and faster inference times than YOLOv4. This has left many asking: is a new version warranted given similar accuracy to YOLOv4? Whatever the answer may be, it’s definitely a sign of how quickly the detection community is evolving. Since they first ported YOLOv3, Ultralytics has made it very simple to create and deploy models using Pytorch, so I was eager to try out YOLOv5. As it turns out, Ultralytics has further simplified the process, and the results speak for themselves. In this article, we’ll create a detection model using YOLOv5, from creating our dataset and annotating it to training and inferencing using their remarkable library. This post focuses on the implementation of YOLOv5, including: Creating a toy dataset Annotating the image data Creating the project structure Training YOLOv5 You can forgo the first step if you have your image Dataset. Since I don’t have images, I am downloading data from the Open Image Dataset(OID), which is an excellent resource for getting annotated image data that can be used for classification as well as detection. Note that we won’t be using the provided annotations from OID and create our own for the sake of learning. To download images from the Open Image dataset, we start by cloning the OIDv4_ToolKit and installing all requirements. git clone https://github.com/EscVM/OIDv4_ToolKitcd OIDv4_ToolKitpip install -r requirements.txt We can now use the main.py script within this folder to download images as well as labels for multiple classes. Below I am downloading the data for Cricketball and Football to create our Custom Dataset. That is, we will be creating a dataset with footballs and cricket balls, and the learning task is to detect these balls. python3 main.py downloader --classes Cricket_ball Football --type_csv all -y --limit 500 The below command creates a directory named “OID” with the following structure: Before we continue, we will need to copy all the images in the same folder to start our labeling exercise from Scratch. You can choose to do this manually, but this can also be quickly done programmatically using recursive glob function: import osfrom glob import globos.system("mkdir Images")images = glob(r'OID/**/*.jpg', recursive=True)for img in images: os.system(f"cp {img} Images/") We will use a tool called Hyperlabel to label our images. In the past, I have used many tools to create annotations like labelimg, labelbox, etc. but never came across a tool so straightforward and that too open source. The only downside is that you cannot get this tool for Linux and only for Mac and Windows, but I guess that is fine for most of us. The best part of this tool is the variety of output formats it provides. Since we want to get the data for Yolo, we will close Yolo Format and export it after being done with our annotations. But you can choose to use this tool if you want to get annotations in JSON format(COCO) or XML format(Pascal VOC) too. Exporting in Yolo format essentially creates a .txt file for each of our images, which contains the class_id, x_center, y_center, width, and the height of the image. It also creates a file named obj.names , which helps map the class_id to the class name. For example: Notice that the coordinates are scaled from 0 to 1 in the annotation file. Also, note that the class_id is 0 for Cricketball and 1 for football as per obj.names file, which starts from 0. There are a few other files we create using this, but we won’t be using them in this example. Once we have done this, we are mostly set up with our custom dataset and would only need to rearrange some of these files for subsequent training and validation splits later when we train our model. The dataset currently will be a single folder like below containing both the images as well as annotations: dataset - 0027773a6d54b960.jpg - 0027773a6d54b960.txt - 2bded1f9cb587843.jpg - 2bded1f9cb587843.txt -- -- To train our custom object detector, we will be using Yolov5 from Ultralytics. We start by cloning the repository and installing the dependencies: git clone https://github.com/ultralytics/yolov5 # clone repocd yolov5pip install -U -r requirements.txt We then start with creating our own folder named training in which we will keep our custom dataset. !mkdir training We start by copying our custom dataset folder in this folder and creating the train validation folders using the simple train_val_folder_split.ipynb notebook. This code below just creates some train and validation folders and populates them with images. import glob, osimport random# put your own path heredataset_path = 'dataset'# Percentage of images to be used for the validation setpercentage_test = 20!mkdir data!mkdir data/images!mkdir data/labels!mkdir data/images/train!mkdir data/images/valid!mkdir data/labels/train!mkdir data/labels/valid# Populate the foldersp = percentage_test/100for pathAndFilename in glob.iglob(os.path.join(dataset_path, "*.jpg")): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) if random.random() <=p : os.system(f"cp {dataset_path}/{title}.jpg data/images/valid") os.system(f"cp {dataset_path}/{title}.txt data/labels/valid") else: os.system(f"cp {dataset_path}/{title}.jpg data/images/train") os.system(f"cp {dataset_path}/{title}.txt data/labels/train") After running this, your data folder structure should look like below. It should have two directories images and labels. We now have to add two configuration files to training folder: 1. Dataset.yaml: We create a file “dataset.yaml” that contains the path of training and validation images and also the classes. # train and val datasets (image directory or *.txt file with image paths)train: training/data/images/train/val: training/data/images/valid/# number of classesnc: 2# class namesnames: ['Cricketball', 'Football'] 2. Model.yaml: We can use multiple models ranging from small to large while creating our network. For example, yolov5s.yaml file in the yolov5/models directory is the small Yolo model with 7M parameters, while the yolov5x.yaml is the largest Yolo model with 96M Params. For this project, I will use the yolov5l.yaml which has 50M params. We start by copying the file from yolov5/models/yolov5l.yaml to the training folder and changing nc , which is the number of classes to 2 as per our project requirements. # parametersnc: 2 # change number of classesdepth_multiple: 1.0 # model depth multiplewidth_multiple: 1.0 # layer channel multiple At this point our training folder looks like: Once we are done with the above steps, we can start training our model. This is as simple as running the below command, where we provide the locations of our config files and various other params. You can check out the different other options in train.py file, but these are the ones I found noteworthy. # Train yolov5l on custom dataset for 300 epochs$ python train.py --img 640 --batch 16 --epochs 300--data training/dataset.yaml --cfg training/yolov5l.yaml --weights '' Sometimes you might get an error with PyTorch version 1.5 in that case run on a single GPU using: # Train yolov5l on custom dataset for 300 epochs$ python train.py --img 640 --batch 16 --epochs 300--data training/dataset.yaml --cfg training/yolov5l.yaml --weights '' --device 0 Once you start the training, you can check whether the training has been set up by checking the automatically created filetrain_batch0.jpg , which contains the training labels for the first batch and test_batch0_gt.jpg which includes the ground truth for test images. This is how they look for me. To see the results for the training at localhost:6006 in your browser using tensorboard, run this command in another terminal tab tensorboard --logdir=runs Here are the various validation metrics. These metrics also get saved in a file results.png at the end of the training run. Ultralytics Yolov5 provides a lot of different ways to check the results on new data. To detect some images you can simply put them in the folder named inference/images and run the inference using the best weights as per validation AP: python detect.py --weights weights/best.pt You can also detect in a video using the detect.py file: python detect.py --weights weights/best.pt --source inference/videos/messi.mp4 --view-img --output inference/output Here I specify that I want to see the output using the — view-img flag, and we store the output at the location inference/output. This will create a .mp4 file in this location. It's impressive that the network can see the ball, the speed at which inference is made here, and also the mindblowing accuracy on never observed data. You can also use the webcam as a source by specifying the --source as 0. You can check out the various other options in detect.py file. In this post, I talked about how to create a Yolov5 object detection model using a Custom Dataset. I love the way Ultralytics has made it so easy to create an object detection model. Additionally, the various ways that they have provided to see the model results make it a complete package I have seen in a long time. If you would like to experiment with the custom dataset yourself, you can download the annotated data on Kaggle and the code at Github. If you want to know more about various Object Detection techniques, motion estimation, object tracking in video, etc., I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization. If you wish to know more about how the object detection field has evolved over the years, you can also take a look at my last post on Object detection. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz This story was first published here.
[ { "code": null, "e": 496, "s": 171, "text": "Ultralytics recently launched YOLOv5 amid controversy surrounding its name. For context, the first three versions of YOLO (You Only Look Once) were created by Joseph Redmon. Following this, Alexey Bochkovskiy created YOLOv4 on darknet, which boasted higher Average Precision (AP) and faster results than previous iterations." }, { "code": null, "e": 784, "s": 496, "text": "Now, Ultralytics has released YOLOv5, with comparable AP and faster inference times than YOLOv4. This has left many asking: is a new version warranted given similar accuracy to YOLOv4? Whatever the answer may be, it’s definitely a sign of how quickly the detection community is evolving." }, { "code": null, "e": 1032, "s": 784, "text": "Since they first ported YOLOv3, Ultralytics has made it very simple to create and deploy models using Pytorch, so I was eager to try out YOLOv5. As it turns out, Ultralytics has further simplified the process, and the results speak for themselves." }, { "code": null, "e": 1260, "s": 1032, "text": "In this article, we’ll create a detection model using YOLOv5, from creating our dataset and annotating it to training and inferencing using their remarkable library. This post focuses on the implementation of YOLOv5, including:" }, { "code": null, "e": 1283, "s": 1260, "text": "Creating a toy dataset" }, { "code": null, "e": 1309, "s": 1283, "text": "Annotating the image data" }, { "code": null, "e": 1340, "s": 1309, "text": "Creating the project structure" }, { "code": null, "e": 1356, "s": 1340, "text": "Training YOLOv5" }, { "code": null, "e": 1729, "s": 1356, "text": "You can forgo the first step if you have your image Dataset. Since I don’t have images, I am downloading data from the Open Image Dataset(OID), which is an excellent resource for getting annotated image data that can be used for classification as well as detection. Note that we won’t be using the provided annotations from OID and create our own for the sake of learning." }, { "code": null, "e": 1848, "s": 1729, "text": "To download images from the Open Image dataset, we start by cloning the OIDv4_ToolKit and installing all requirements." }, { "code": null, "e": 1944, "s": 1848, "text": "git clone https://github.com/EscVM/OIDv4_ToolKitcd OIDv4_ToolKitpip install -r requirements.txt" }, { "code": null, "e": 2056, "s": 1944, "text": "We can now use the main.py script within this folder to download images as well as labels for multiple classes." }, { "code": null, "e": 2268, "s": 2056, "text": "Below I am downloading the data for Cricketball and Football to create our Custom Dataset. That is, we will be creating a dataset with footballs and cricket balls, and the learning task is to detect these balls." }, { "code": null, "e": 2358, "s": 2268, "text": "python3 main.py downloader --classes Cricket_ball Football --type_csv all -y --limit 500" }, { "code": null, "e": 2438, "s": 2358, "text": "The below command creates a directory named “OID” with the following structure:" }, { "code": null, "e": 2676, "s": 2438, "text": "Before we continue, we will need to copy all the images in the same folder to start our labeling exercise from Scratch. You can choose to do this manually, but this can also be quickly done programmatically using recursive glob function:" }, { "code": null, "e": 2830, "s": 2676, "text": "import osfrom glob import globos.system(\"mkdir Images\")images = glob(r'OID/**/*.jpg', recursive=True)for img in images: os.system(f\"cp {img} Images/\")" }, { "code": null, "e": 3182, "s": 2830, "text": "We will use a tool called Hyperlabel to label our images. In the past, I have used many tools to create annotations like labelimg, labelbox, etc. but never came across a tool so straightforward and that too open source. The only downside is that you cannot get this tool for Linux and only for Mac and Windows, but I guess that is fine for most of us." }, { "code": null, "e": 3493, "s": 3182, "text": "The best part of this tool is the variety of output formats it provides. Since we want to get the data for Yolo, we will close Yolo Format and export it after being done with our annotations. But you can choose to use this tool if you want to get annotations in JSON format(COCO) or XML format(Pascal VOC) too." }, { "code": null, "e": 3761, "s": 3493, "text": "Exporting in Yolo format essentially creates a .txt file for each of our images, which contains the class_id, x_center, y_center, width, and the height of the image. It also creates a file named obj.names , which helps map the class_id to the class name. For example:" }, { "code": null, "e": 4043, "s": 3761, "text": "Notice that the coordinates are scaled from 0 to 1 in the annotation file. Also, note that the class_id is 0 for Cricketball and 1 for football as per obj.names file, which starts from 0. There are a few other files we create using this, but we won’t be using them in this example." }, { "code": null, "e": 4350, "s": 4043, "text": "Once we have done this, we are mostly set up with our custom dataset and would only need to rearrange some of these files for subsequent training and validation splits later when we train our model. The dataset currently will be a single folder like below containing both the images as well as annotations:" }, { "code": null, "e": 4476, "s": 4350, "text": "dataset - 0027773a6d54b960.jpg - 0027773a6d54b960.txt - 2bded1f9cb587843.jpg - 2bded1f9cb587843.txt -- --" }, { "code": null, "e": 4623, "s": 4476, "text": "To train our custom object detector, we will be using Yolov5 from Ultralytics. We start by cloning the repository and installing the dependencies:" }, { "code": null, "e": 4727, "s": 4623, "text": "git clone https://github.com/ultralytics/yolov5 # clone repocd yolov5pip install -U -r requirements.txt" }, { "code": null, "e": 4827, "s": 4727, "text": "We then start with creating our own folder named training in which we will keep our custom dataset." }, { "code": null, "e": 4843, "s": 4827, "text": "!mkdir training" }, { "code": null, "e": 5097, "s": 4843, "text": "We start by copying our custom dataset folder in this folder and creating the train validation folders using the simple train_val_folder_split.ipynb notebook. This code below just creates some train and validation folders and populates them with images." }, { "code": null, "e": 5892, "s": 5097, "text": "import glob, osimport random# put your own path heredataset_path = 'dataset'# Percentage of images to be used for the validation setpercentage_test = 20!mkdir data!mkdir data/images!mkdir data/labels!mkdir data/images/train!mkdir data/images/valid!mkdir data/labels/train!mkdir data/labels/valid# Populate the foldersp = percentage_test/100for pathAndFilename in glob.iglob(os.path.join(dataset_path, \"*.jpg\")): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) if random.random() <=p : os.system(f\"cp {dataset_path}/{title}.jpg data/images/valid\") os.system(f\"cp {dataset_path}/{title}.txt data/labels/valid\") else: os.system(f\"cp {dataset_path}/{title}.jpg data/images/train\") os.system(f\"cp {dataset_path}/{title}.txt data/labels/train\")" }, { "code": null, "e": 6013, "s": 5892, "text": "After running this, your data folder structure should look like below. It should have two directories images and labels." }, { "code": null, "e": 6076, "s": 6013, "text": "We now have to add two configuration files to training folder:" }, { "code": null, "e": 6204, "s": 6076, "text": "1. Dataset.yaml: We create a file “dataset.yaml” that contains the path of training and validation images and also the classes." }, { "code": null, "e": 6415, "s": 6204, "text": "# train and val datasets (image directory or *.txt file with image paths)train: training/data/images/train/val: training/data/images/valid/# number of classesnc: 2# class namesnames: ['Cricketball', 'Football']" }, { "code": null, "e": 6924, "s": 6415, "text": "2. Model.yaml: We can use multiple models ranging from small to large while creating our network. For example, yolov5s.yaml file in the yolov5/models directory is the small Yolo model with 7M parameters, while the yolov5x.yaml is the largest Yolo model with 96M Params. For this project, I will use the yolov5l.yaml which has 50M params. We start by copying the file from yolov5/models/yolov5l.yaml to the training folder and changing nc , which is the number of classes to 2 as per our project requirements." }, { "code": null, "e": 7058, "s": 6924, "text": "# parametersnc: 2 # change number of classesdepth_multiple: 1.0 # model depth multiplewidth_multiple: 1.0 # layer channel multiple" }, { "code": null, "e": 7104, "s": 7058, "text": "At this point our training folder looks like:" }, { "code": null, "e": 7408, "s": 7104, "text": "Once we are done with the above steps, we can start training our model. This is as simple as running the below command, where we provide the locations of our config files and various other params. You can check out the different other options in train.py file, but these are the ones I found noteworthy." }, { "code": null, "e": 7577, "s": 7408, "text": "# Train yolov5l on custom dataset for 300 epochs$ python train.py --img 640 --batch 16 --epochs 300--data training/dataset.yaml --cfg training/yolov5l.yaml --weights ''" }, { "code": null, "e": 7675, "s": 7577, "text": "Sometimes you might get an error with PyTorch version 1.5 in that case run on a single GPU using:" }, { "code": null, "e": 7855, "s": 7675, "text": "# Train yolov5l on custom dataset for 300 epochs$ python train.py --img 640 --batch 16 --epochs 300--data training/dataset.yaml --cfg training/yolov5l.yaml --weights '' --device 0" }, { "code": null, "e": 8153, "s": 7855, "text": "Once you start the training, you can check whether the training has been set up by checking the automatically created filetrain_batch0.jpg , which contains the training labels for the first batch and test_batch0_gt.jpg which includes the ground truth for test images. This is how they look for me." }, { "code": null, "e": 8283, "s": 8153, "text": "To see the results for the training at localhost:6006 in your browser using tensorboard, run this command in another terminal tab" }, { "code": null, "e": 8309, "s": 8283, "text": "tensorboard --logdir=runs" }, { "code": null, "e": 8433, "s": 8309, "text": "Here are the various validation metrics. These metrics also get saved in a file results.png at the end of the training run." }, { "code": null, "e": 8519, "s": 8433, "text": "Ultralytics Yolov5 provides a lot of different ways to check the results on new data." }, { "code": null, "e": 8669, "s": 8519, "text": "To detect some images you can simply put them in the folder named inference/images and run the inference using the best weights as per validation AP:" }, { "code": null, "e": 8712, "s": 8669, "text": "python detect.py --weights weights/best.pt" }, { "code": null, "e": 8769, "s": 8712, "text": "You can also detect in a video using the detect.py file:" }, { "code": null, "e": 8885, "s": 8769, "text": "python detect.py --weights weights/best.pt --source inference/videos/messi.mp4 --view-img --output inference/output" }, { "code": null, "e": 9214, "s": 8885, "text": "Here I specify that I want to see the output using the — view-img flag, and we store the output at the location inference/output. This will create a .mp4 file in this location. It's impressive that the network can see the ball, the speed at which inference is made here, and also the mindblowing accuracy on never observed data." }, { "code": null, "e": 9350, "s": 9214, "text": "You can also use the webcam as a source by specifying the --source as 0. You can check out the various other options in detect.py file." }, { "code": null, "e": 9533, "s": 9350, "text": "In this post, I talked about how to create a Yolov5 object detection model using a Custom Dataset. I love the way Ultralytics has made it so easy to create an object detection model." }, { "code": null, "e": 9668, "s": 9533, "text": "Additionally, the various ways that they have provided to see the model results make it a complete package I have seen in a long time." }, { "code": null, "e": 9804, "s": 9668, "text": "If you would like to experiment with the custom dataset yourself, you can download the annotated data on Kaggle and the code at Github." }, { "code": null, "e": 10208, "s": 9804, "text": "If you want to know more about various Object Detection techniques, motion estimation, object tracking in video, etc., I would like to recommend this excellent course on Deep Learning in Computer Vision in the Advanced machine learning specialization. If you wish to know more about how the object detection field has evolved over the years, you can also take a look at my last post on Object detection." }, { "code": null, "e": 10471, "s": 10208, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz" } ]
Delete records where timestamp older than 5 minutes in MySQL?
For this, use DELETE command. Let us first create a table − mysql> create table DemoTable1851 ( DueDate datetime ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1851 values('2019-12-03 21:30:35'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1851 values('2019-12-03 21:45:00'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1851 values('2019-12-03 21:34:00'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1851; This will produce the following output − +---------------------+ | DueDate | +---------------------+ | 2019-12-03 21:30:35 | | 2019-12-03 21:45:00 | | 2019-12-03 21:34:00 | +---------------------+ 3 rows in set (0.00 sec) The current date time is as follows − mysql> select now(); +---------------------+ | now() | +---------------------+ | 2019-12-03 21:38:46 | +---------------------+ 1 row in set (0.00 sec) Here is the query to delete records where timestamp is older than 5 minutes − mysql> delete from DemoTable1851 where DueDate < (NOW() - INTERVAL 5 MINUTE); Query OK, 2 rows affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1851; This will produce the following output − +---------------------+ | DueDate | +---------------------+ | 2019-12-03 21:45:00 | +---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1122, "s": 1062, "text": "For this, use DELETE command. Let us first create a table −" }, { "code": null, "e": 1230, "s": 1122, "text": "mysql> create table DemoTable1851\n (\n DueDate datetime\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1286, "s": 1230, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1586, "s": 1286, "text": "mysql> insert into DemoTable1851 values('2019-12-03 21:30:35');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1851 values('2019-12-03 21:45:00');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1851 values('2019-12-03 21:34:00');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1646, "s": 1586, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1682, "s": 1646, "text": "mysql> select * from DemoTable1851;" }, { "code": null, "e": 1723, "s": 1682, "text": "This will produce the following output −" }, { "code": null, "e": 1916, "s": 1723, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-12-03 21:30:35 |\n| 2019-12-03 21:45:00 |\n| 2019-12-03 21:34:00 |\n+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1954, "s": 1916, "text": "The current date time is as follows −" }, { "code": null, "e": 2119, "s": 1954, "text": "mysql> select now();\n+---------------------+\n| now() |\n+---------------------+\n| 2019-12-03 21:38:46 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2197, "s": 2119, "text": "Here is the query to delete records where timestamp is older than 5 minutes −" }, { "code": null, "e": 2312, "s": 2197, "text": "mysql> delete from DemoTable1851 where DueDate < (NOW() - INTERVAL 5 MINUTE);\nQuery OK, 2 rows affected (0.00 sec)" }, { "code": null, "e": 2372, "s": 2312, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2408, "s": 2372, "text": "mysql> select * from DemoTable1851;" }, { "code": null, "e": 2449, "s": 2408, "text": "This will produce the following output −" }, { "code": null, "e": 2593, "s": 2449, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-12-03 21:45:00 |\n+---------------------+\n1 row in set (0.00 sec)" } ]
Adding and Removing Elements in Perl Array
Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used the print function to print various values. Similarly, there are various other functions or sometimes called subroutines, which can be used for various other functionalities. Live Demo #!/usr/bin/perl # create a simple array @coins = ("Quarter","Dime","Nickel"); print "1. \@coins = @coins\n"; # add one element at the end of the array push(@coins, "Penny"); print "2. \@coins = @coins\n"; # add one element at the beginning of the array unshift(@coins, "Dollar"); print "3. \@coins = @coins\n"; # remove one element from the last of the array. pop(@coins); print "4. \@coins = @coins\n"; # remove one element from the beginning of the array. shift(@coins); print "5. \@coins = @coins\n"; This will produce the following result − 1. @coins = Quarter Dime Nickel 2. @coins = Quarter Dime Nickel Penny 3. @coins = Dollar Quarter Dime Nickel Penny 4. @coins = Dollar Quarter Dime Nickel 5. @coins = Quarter Dime Nickel
[ { "code": null, "e": 1385, "s": 1062, "text": "Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used the print function to print various values. Similarly, there are various other functions or sometimes called subroutines, which can be used for various other functionalities." }, { "code": null, "e": 1396, "s": 1385, "text": " Live Demo" }, { "code": null, "e": 1904, "s": 1396, "text": "#!/usr/bin/perl\n# create a simple array\n@coins = (\"Quarter\",\"Dime\",\"Nickel\");\nprint \"1. \\@coins = @coins\\n\";\n\n# add one element at the end of the array\npush(@coins, \"Penny\");\nprint \"2. \\@coins = @coins\\n\";\n\n# add one element at the beginning of the array\nunshift(@coins, \"Dollar\");\nprint \"3. \\@coins = @coins\\n\";\n\n# remove one element from the last of the array.\npop(@coins);\nprint \"4. \\@coins = @coins\\n\";\n\n# remove one element from the beginning of the array.\nshift(@coins);\nprint \"5. \\@coins = @coins\\n\";" }, { "code": null, "e": 1945, "s": 1904, "text": "This will produce the following result −" }, { "code": null, "e": 2131, "s": 1945, "text": "1. @coins = Quarter Dime Nickel\n2. @coins = Quarter Dime Nickel Penny\n3. @coins = Dollar Quarter Dime Nickel Penny\n4. @coins = Dollar Quarter Dime Nickel\n5. @coins = Quarter Dime Nickel" } ]
How to Install Tkinter in Windows? - GeeksforGeeks
09 Sep, 2021 In this article, we will look into the various methods of installing Tkinter on a Windows machine. Note: Python already comes bundled with Tkinter. But if you still face any error with Tkinter, follow along with the article for manual installation. Python PIP or conda (Depending upon your preference) Open up the command prompt and use the below command to install Tkinter: pip install tk The following message will be displayed once the installation is completed: To verify the installation use the tk._test() function. Use the below screenshots for reference: Python3 import tkintertkinter._test() Output: Conda users can open up the Anaconda Power Shell and use the below command to install Tkinter: conda install -c anaconda tk You will get the following message once the installation is completed: To verify the installation run the below code: Python3 import tkintertkinter._test() Output: Blogathon-2021 how-to-install Picked Python-tkinter Blogathon How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to parse JSON Data into React Table Component ? How to Connect Python with SQL Database? Changing CSS styling with React onClick() Event Python - Gaussian fit How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 24104, "s": 24076, "text": "\n09 Sep, 2021" }, { "code": null, "e": 24203, "s": 24104, "text": "In this article, we will look into the various methods of installing Tkinter on a Windows machine." }, { "code": null, "e": 24353, "s": 24203, "text": "Note: Python already comes bundled with Tkinter. But if you still face any error with Tkinter, follow along with the article for manual installation." }, { "code": null, "e": 24361, "s": 24353, "text": "Python " }, { "code": null, "e": 24407, "s": 24361, "text": "PIP or conda (Depending upon your preference)" }, { "code": null, "e": 24480, "s": 24407, "text": "Open up the command prompt and use the below command to install Tkinter:" }, { "code": null, "e": 24495, "s": 24480, "text": "pip install tk" }, { "code": null, "e": 24571, "s": 24495, "text": "The following message will be displayed once the installation is completed:" }, { "code": null, "e": 24668, "s": 24571, "text": "To verify the installation use the tk._test() function. Use the below screenshots for reference:" }, { "code": null, "e": 24676, "s": 24668, "text": "Python3" }, { "code": "import tkintertkinter._test()", "e": 24706, "s": 24676, "text": null }, { "code": null, "e": 24714, "s": 24706, "text": "Output:" }, { "code": null, "e": 24809, "s": 24714, "text": "Conda users can open up the Anaconda Power Shell and use the below command to install Tkinter:" }, { "code": null, "e": 24838, "s": 24809, "text": "conda install -c anaconda tk" }, { "code": null, "e": 24909, "s": 24838, "text": "You will get the following message once the installation is completed:" }, { "code": null, "e": 24956, "s": 24909, "text": "To verify the installation run the below code:" }, { "code": null, "e": 24964, "s": 24956, "text": "Python3" }, { "code": "import tkintertkinter._test()", "e": 24994, "s": 24964, "text": null }, { "code": null, "e": 25002, "s": 24994, "text": "Output:" }, { "code": null, "e": 25017, "s": 25002, "text": "Blogathon-2021" }, { "code": null, "e": 25032, "s": 25017, "text": "how-to-install" }, { "code": null, "e": 25039, "s": 25032, "text": "Picked" }, { "code": null, "e": 25054, "s": 25039, "text": "Python-tkinter" }, { "code": null, "e": 25064, "s": 25054, "text": "Blogathon" }, { "code": null, "e": 25071, "s": 25064, "text": "How To" }, { "code": null, "e": 25090, "s": 25071, "text": "Installation Guide" }, { "code": null, "e": 25097, "s": 25090, "text": "Python" }, { "code": null, "e": 25195, "s": 25097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25204, "s": 25195, "text": "Comments" }, { "code": null, "e": 25217, "s": 25204, "text": "Old Comments" }, { "code": null, "e": 25274, "s": 25217, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 25326, "s": 25274, "text": "How to parse JSON Data into React Table Component ?" }, { "code": null, "e": 25367, "s": 25326, "text": "How to Connect Python with SQL Database?" }, { "code": null, "e": 25415, "s": 25367, "text": "Changing CSS styling with React onClick() Event" }, { "code": null, "e": 25437, "s": 25415, "text": "Python - Gaussian fit" }, { "code": null, "e": 25469, "s": 25437, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25522, "s": 25469, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 25566, "s": 25522, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 25593, "s": 25566, "text": "How to Align Text in HTML?" } ]
Range Sum Queries Without Updates using C++
In this article, we will give an array of size n, which will be an integer. Then, we will compute the sum of elements from index L to index R and execute the queries multiple times, or we need to calculate the sum of the given range from [L, R]. For example − Input : arr[] = {1, 2, 3, 4, 5} L = 1, R = 3 L = 2, R = 4 Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} L = 0, R = 4 L = 1, R = 2 Output : 15 5 There are two solutions to this question. The first one is by the Brute Force approach and by the Prefix sum(Efficient) approach. In this approach, we will traverse through the given range and print the sum. #include<bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(int); // size of given array. int L1 = 1, R1 = 3; int L2 = 2, R2 = 4; int sum = 0; for(int i = L1; i <= R1; i++) // traversing through the first range. sum += arr[i]; cout << sum << "\n"; sum = 0; for(int i = L2; i <= R2; i++) // traversing through the second range. sum += arr[i]; cout << sum << "\n"; } 9 12 In this approach, we are simply traversing through the given ranges; in this case, this program is good as it has searching time complexity O(N), where N is the size of the given array. Still, this changes when we are given several queries Q then our complexity turns to O(N*Q), where Q is the number of queries and N is the size of the given array. Unfortunately, this time complexity can’t handle higher constraints, so now we will look into an efficient approach that will work for higher constraints. In this approach, we will make a new array named prefix which will be our prefix sum array, and then we answer the sum of ranges given. #include<bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(int); // size of given array. int L1 = 1, R1 = 3; int L2 = 2, R2 = 4; int sum = 0; int prefix[n]; for(int i = 0; i < n; i++){ sum += arr[i]; prefix[i] = sum; } if(L1) // to avoid segmentation fault cout << prefix[R1] - prefix[L1 - 1] << "\n"; else cout << prefix[R1] << "\n"; if(L2) // avoiding segmentation fault. cout << prefix[R2] - prefix[L2 - 1] << "\n"; else cout << prefix[R2] << "\n"; } 9 12 In this approach, we store the prefix sum values in an array called prefix. Now, this array makes our program very efficient as this gives us searching time complexity of O(1), which is the best complexity you can get, and therefore when we are given Q amount of queries, then our searching time complexity becomes O(Q) where Q is the number of queries. In this article, we solve a problem to find the Range sum queries without updates using the Prefix sum array. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.
[ { "code": null, "e": 1322, "s": 1062, "text": "In this article, we will give an array of size n, which will be an integer. Then, we will compute the sum of elements from index L to index R and execute the queries multiple times, or we need to calculate the sum of the given range from [L, R]. For example −" }, { "code": null, "e": 1485, "s": 1322, "text": "Input : arr[] = {1, 2, 3, 4, 5}\n L = 1, R = 3\n L = 2, R = 4\nOutput : 9\n 12\n\nInput : arr[] = {1, 2, 3, 4, 5}\n L = 0, R = 4\n L = 1, R = 2\nOutput : 15\n 5" }, { "code": null, "e": 1615, "s": 1485, "text": "There are two solutions to this question. The first one is by the Brute Force approach and by the Prefix sum(Efficient) approach." }, { "code": null, "e": 1693, "s": 1615, "text": "In this approach, we will traverse through the given range and print the sum." }, { "code": null, "e": 2156, "s": 1693, "text": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int arr[] = {1, 2, 3, 4, 5};\n int n = sizeof(arr)/sizeof(int); // size of given array.\n int L1 = 1, R1 = 3;\n int L2 = 2, R2 = 4;\n int sum = 0;\n for(int i = L1; i <= R1; i++) // traversing through the first range.\n sum += arr[i];\n cout << sum << \"\\n\";\n sum = 0;\n for(int i = L2; i <= R2; i++) // traversing through the second range.\n sum += arr[i];\n cout << sum << \"\\n\";\n}" }, { "code": null, "e": 2161, "s": 2156, "text": "9\n12" }, { "code": null, "e": 2666, "s": 2161, "text": "In this approach, we are simply traversing through the given ranges; in this case, this program is good as it has searching time complexity O(N), where N is the size of the given array. Still, this changes when we are given several queries Q then our complexity turns to O(N*Q), where Q is the number of queries and N is the size of the given array. Unfortunately, this time complexity can’t handle higher constraints, so now we will look into an efficient approach that will work for higher constraints." }, { "code": null, "e": 2802, "s": 2666, "text": "In this approach, we will make a new array named prefix which will be our prefix sum array, and then we answer the sum of ranges given." }, { "code": null, "e": 3386, "s": 2802, "text": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int arr[] = {1, 2, 3, 4, 5};\n int n = sizeof(arr)/sizeof(int); // size of given array.\n int L1 = 1, R1 = 3;\n int L2 = 2, R2 = 4;\n int sum = 0;\n int prefix[n];\n for(int i = 0; i < n; i++){\n sum += arr[i];\n prefix[i] = sum;\n }\n\n if(L1) // to avoid segmentation fault\n cout << prefix[R1] - prefix[L1 - 1] << \"\\n\";\n else\n cout << prefix[R1] << \"\\n\";\n\n if(L2) // avoiding segmentation fault.\n cout << prefix[R2] - prefix[L2 - 1] << \"\\n\";\n else\n cout << prefix[R2] << \"\\n\";\n}" }, { "code": null, "e": 3391, "s": 3386, "text": "9\n12" }, { "code": null, "e": 3745, "s": 3391, "text": "In this approach, we store the prefix sum values in an array called prefix. Now, this array makes our program very efficient as this gives us searching time complexity of O(1), which is the best complexity you can get, and therefore when we are given Q amount of queries, then our searching time complexity becomes O(Q) where Q is the number of queries." }, { "code": null, "e": 4119, "s": 3745, "text": "In this article, we solve a problem to find the Range sum queries without updates using the Prefix sum array. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful." } ]
How to display a list of plots with the help of grid.arrange in R?
In data analysis, we deal with many variables at a time and we want to visualize the histogram of these variables at a time. This helps us to understand the distribution of each variable in the data set, therefore we can apply the appropriate technique to deal with those variables. To create a list of plots we can use grid.arrange function in gridExtra package that can arrange plots based on our need. Consider the below data frame − > set.seed(10) > df<-data.frame(x1=rnorm(10),x2=rnorm(20,0.2),x3=rnorm(20,0.5),x4=rnorm(10,0.5)) > head(df,20) x1 x2 x3 x4 1 0.01874617 1.301779503 -1.3537405 0.09936245 2 -0.18425254 0.955781508 0.4220539 0.16544343 3 -1.37133055 -0.038233556 1.4685663 1.86795395 4 -0.59916772 1.187444703 0.6849260 2.63776710 5 0.29454513 0.941390128 -0.8799436 1.00581926 6 0.38979430 0.289347266 -0.9355144 1.28634238 7 -1.20807618 -0.754943856 0.8620872 -0.40221194 8 -0.36367602 0.004849615 -1.2590868 1.03289699 9 -1.62667268 1.125521262 0.1754560 -0.14589425 10 -0.25647839 0.682978525 -0.1515630 0.79098749 11 0.01874617 -0.396310637 1.5865514 0.09936245 12 -0.18425254 -1.985286838 -0.2625449 0.16544343 13 -1.37133055 -0.474865938 -0.3286625 1.86795395 14 -0.59916772 -1.919061192 1.3344739 2.63776710 15 0.29454513 -1.065198022 -0.4676520 1.00581926 16 0.38979430 -0.173661555 0.4711847 1.28634238 17 -1.20807618 -0.487555430 0.7325252 -0.40221194 18 -0.36367602 -0.672158827 0.1987913 1.03289699 19 -1.62667268 0.098238994 -0.1776146 -0.14589425 20 -0.25647839 -0.053780530 1.1552276 0.79098749 Loading ggplot2 package − > library(ggplot2) Loading gridExtra package − > library(gridExtra) Creating the histograms of x1, x2, x3, and x4 − > p1 <- ggplot(df, aes(x1)) + geom_histogram() > p2 <- ggplot(df, aes(x2)) + geom_histogram() > p3 <- ggplot(df, aes(x3)) + geom_histogram() > p4 <- ggplot(df, aes(x4)) + geom_histogram() > PlotsList<- list(p1,p2,p3,p4) Arranging the plots in one graph − > grid.arrange(grobs = PlotsList, ncol = 2) `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. Here R is showing “`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.” with the output but it is not an error, it is just telling us to change the binwidth and we can change it in geom_histogram() as geom_histogram(binwidth=1).
[ { "code": null, "e": 1467, "s": 1062, "text": "In data analysis, we deal with many variables at a time and we want to visualize the histogram of these variables at a time. This helps us to understand the distribution of each variable in the data set, therefore we can apply the appropriate technique to deal with those variables. To create a list of plots we can use grid.arrange function in gridExtra package that can arrange plots based on our need." }, { "code": null, "e": 1499, "s": 1467, "text": "Consider the below data frame −" }, { "code": null, "e": 2683, "s": 1499, "text": "> set.seed(10)\n> df<-data.frame(x1=rnorm(10),x2=rnorm(20,0.2),x3=rnorm(20,0.5),x4=rnorm(10,0.5))\n> head(df,20)\n x1 x2 x3 x4\n1 0.01874617 1.301779503 -1.3537405 0.09936245\n2 -0.18425254 0.955781508 0.4220539 0.16544343\n3 -1.37133055 -0.038233556 1.4685663 1.86795395\n4 -0.59916772 1.187444703 0.6849260 2.63776710\n5 0.29454513 0.941390128 -0.8799436 1.00581926\n6 0.38979430 0.289347266 -0.9355144 1.28634238\n7 -1.20807618 -0.754943856 0.8620872 -0.40221194\n8 -0.36367602 0.004849615 -1.2590868 1.03289699\n9 -1.62667268 1.125521262 0.1754560 -0.14589425\n10 -0.25647839 0.682978525 -0.1515630 0.79098749\n11 0.01874617 -0.396310637 1.5865514 0.09936245\n12 -0.18425254 -1.985286838 -0.2625449 0.16544343\n13 -1.37133055 -0.474865938 -0.3286625 1.86795395\n14 -0.59916772 -1.919061192 1.3344739 2.63776710\n15 0.29454513 -1.065198022 -0.4676520 1.00581926\n16 0.38979430 -0.173661555 0.4711847 1.28634238\n17 -1.20807618 -0.487555430 0.7325252 -0.40221194\n18 -0.36367602 -0.672158827 0.1987913 1.03289699\n19 -1.62667268 0.098238994 -0.1776146 -0.14589425\n20 -0.25647839 -0.053780530 1.1552276 0.79098749" }, { "code": null, "e": 2709, "s": 2683, "text": "Loading ggplot2 package −" }, { "code": null, "e": 2728, "s": 2709, "text": "> library(ggplot2)" }, { "code": null, "e": 2756, "s": 2728, "text": "Loading gridExtra package −" }, { "code": null, "e": 2777, "s": 2756, "text": "> library(gridExtra)" }, { "code": null, "e": 2825, "s": 2777, "text": "Creating the histograms of x1, x2, x3, and x4 −" }, { "code": null, "e": 3045, "s": 2825, "text": "> p1 <- ggplot(df, aes(x1)) + geom_histogram()\n> p2 <- ggplot(df, aes(x2)) + geom_histogram()\n> p3 <- ggplot(df, aes(x3)) + geom_histogram()\n> p4 <- ggplot(df, aes(x4)) + geom_histogram()\n> PlotsList<- list(p1,p2,p3,p4)" }, { "code": null, "e": 3080, "s": 3045, "text": "Arranging the plots in one graph −" }, { "code": null, "e": 3392, "s": 3080, "text": "> grid.arrange(grobs = PlotsList, ncol = 2)\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.\n`stat_bin()` using `bins = 30`. Pick better value with `binwidth`." }, { "code": null, "e": 3636, "s": 3392, "text": "Here R is showing “`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.” with the output but it is not an error, it is just telling us to change the binwidth and we can change it in geom_histogram() as geom_histogram(binwidth=1)." } ]
ASP.NET MVC - Selectors
Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request. It plays a very crucial role when you are writing your action methods. These selectors will decide the behavior of the method invocation based on the modified name given in front of the action method. It is usually used to alias the name of the action method. There are three types of action selector attributes − ActionName NonAction ActionVerbs This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name. Let’s take a look at a simple example from the last chapter in which we have HomeController containing two action methods. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return "This is ASP.Net MVC Filters Tutorial"; } public string GetCurrentTime(){ return DateTime.Now.ToString("T"); } } } Let’s apply the the ActionName selector for GetCurrentTime by writing [ActionName("CurrentTime")] above the GetCurrentTime() as shown in the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return "This is ASP.Net MVC Filters Tutorial"; } [ActionName("CurrentTime")] public string GetCurrentTime(){ return DateTime.Now.ToString("T"); } } } Now run this application and enter the following URL in the browser http://localhost:62833/Home/CurrentTime, you will receive the following output. You can see that we have used the CurrentTime instead of the original action name, which is GetCurrentTime in the above URL. NonAction is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when you want that a method shouldn’t be treated as an action method. Let’s take a look at a simple example by adding another method in HomeController and also apply the NonAction attribute using the following code. using MVCFiltersDemo.ActionFilters; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCFiltersDemo.Controllers { public class HomeController : Controller{ // GET: Home public string Index(){ return "This is ASP.Net MVC Filters Tutorial"; } [ActionName("CurrentTime")] public string GetCurrentTime(){ return TimeString(); } [NonAction] public string TimeString(){ return "Time is " + DateTime.Now.ToString("T"); } } } The new method TimeString is called from the GetCurrentTime() but you can’t use it as action in URL. Let’s run this application and specify the following URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the following output. Let us now check the /TimeString as action in the URL and see what happens. You can see that it gives ‘404—Not Found’ error. Another selector filter that you can apply is the ActionVerbs attributes. So this restricts the indication of a specific action to specific HttpVerbs. You can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request. MVC framework supports the following ActionVerbs. HttpGet HttpPost HttpPut HttpDelete HttpOptions HttpPatch Let’s take a look at a simple example in which we will create EmployeeController. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee public ActionResult Search(string name = “No name Entered”){ var input = Server.HtmlEncode(name); return Content(input); } } } Now let’s add another action method with the same name using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee //public ActionResult Index() //{ // return View(); //} public ActionResult Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } public ActionResult Search(){ var input = "Another Search action"; return Content(input); } } } When you run this application, it will give an error because the MVC framework is unable to figure out which action method should be picked up for the request. Let us specify the HttpGet ActionVerb with the action you want as response using the following code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCControllerDemo.Controllers { public class EmployeeController : Controller{ // GET: Employee //public ActionResult Index() //{ // return View(); //} public ActionResult Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } [HttpGet] public ActionResult Search(){ var input = "Another Search action"; return Content(input); } } } When you run this application, you will receive the following output. 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": 2520, "s": 2269, "text": "Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request." }, { "code": null, "e": 2780, "s": 2520, "text": "It plays a very crucial role when you are writing your action methods. These selectors will decide the behavior of the method invocation based on the modified name given in front of the action method. It is usually used to alias the name of the action method." }, { "code": null, "e": 2834, "s": 2780, "text": "There are three types of action selector attributes −" }, { "code": null, "e": 2845, "s": 2834, "text": "ActionName" }, { "code": null, "e": 2855, "s": 2845, "text": "NonAction" }, { "code": null, "e": 2867, "s": 2855, "text": "ActionVerbs" }, { "code": null, "e": 3021, "s": 2867, "text": "This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name." }, { "code": null, "e": 3144, "s": 3021, "text": "Let’s take a look at a simple example from the last chapter in which we have HomeController containing two action methods." }, { "code": null, "e": 3550, "s": 3144, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n } \n\t\t\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}" }, { "code": null, "e": 3707, "s": 3550, "text": "Let’s apply the the ActionName selector for GetCurrentTime by writing [ActionName(\"CurrentTime\")] above the GetCurrentTime() as shown in the following code." }, { "code": null, "e": 4146, "s": 3707, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [ActionName(\"CurrentTime\")]\n public string GetCurrentTime(){\n return DateTime.Now.ToString(\"T\");\n }\n }\n}" }, { "code": null, "e": 4294, "s": 4146, "text": "Now run this application and enter the following URL in the browser http://localhost:62833/Home/CurrentTime, you will receive the following output." }, { "code": null, "e": 4419, "s": 4294, "text": "You can see that we have used the CurrentTime instead of the original action name, which is GetCurrentTime in the above URL." }, { "code": null, "e": 4619, "s": 4419, "text": "NonAction is another built-in attribute, which indicates that a public method of a Controller is not an action method. It is used when you want that a method shouldn’t be treated as an action method." }, { "code": null, "e": 4765, "s": 4619, "text": "Let’s take a look at a simple example by adding another method in HomeController and also apply the NonAction attribute using the following code." }, { "code": null, "e": 5346, "s": 4765, "text": "using MVCFiltersDemo.ActionFilters;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCFiltersDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public string Index(){\n return \"This is ASP.Net MVC Filters Tutorial\";\n }\n\t\t\n [ActionName(\"CurrentTime\")]\n public string GetCurrentTime(){\n return TimeString();\n }\n\t\t\n [NonAction]\n public string TimeString(){\n return \"Time is \" + DateTime.Now.ToString(\"T\");\n }\n }\n}" }, { "code": null, "e": 5447, "s": 5346, "text": "The new method TimeString is called from the GetCurrentTime() but you can’t use it as action in URL." }, { "code": null, "e": 5599, "s": 5447, "text": "Let’s run this application and specify the following URL http://localhost:62833/Home/CurrentTime in the browser. You will receive the following output." }, { "code": null, "e": 5675, "s": 5599, "text": "Let us now check the /TimeString as action in the URL and see what happens." }, { "code": null, "e": 5724, "s": 5675, "text": "You can see that it gives ‘404—Not Found’ error." }, { "code": null, "e": 6052, "s": 5724, "text": "Another selector filter that you can apply is the ActionVerbs attributes. So this restricts the indication of a specific action to specific HttpVerbs. You can define two different action methods with the same name but one action method responds to an HTTP Get request and another action method responds to an HTTP Post request." }, { "code": null, "e": 6102, "s": 6052, "text": "MVC framework supports the following ActionVerbs." }, { "code": null, "e": 6110, "s": 6102, "text": "HttpGet" }, { "code": null, "e": 6119, "s": 6110, "text": "HttpPost" }, { "code": null, "e": 6127, "s": 6119, "text": "HttpPut" }, { "code": null, "e": 6138, "s": 6127, "text": "HttpDelete" }, { "code": null, "e": 6150, "s": 6138, "text": "HttpOptions" }, { "code": null, "e": 6160, "s": 6150, "text": "HttpPatch" }, { "code": null, "e": 6242, "s": 6160, "text": "Let’s take a look at a simple example in which we will create EmployeeController." }, { "code": null, "e": 6625, "s": 6242, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n public ActionResult Search(string name = “No name Entered”){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n }\n}" }, { "code": null, "e": 6706, "s": 6625, "text": "Now let’s add another action method with the same name using the following code." }, { "code": null, "e": 7280, "s": 6706, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n //public ActionResult Index()\n //{\n // return View();\n //}\n\t\t\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n\t\t\n public ActionResult Search(){\n var input = \"Another Search action\";\n return Content(input);\n }\n }\n}" }, { "code": null, "e": 7440, "s": 7280, "text": "When you run this application, it will give an error because the MVC framework is unable to figure out which action method should be picked up for the request." }, { "code": null, "e": 7541, "s": 7440, "text": "Let us specify the HttpGet ActionVerb with the action you want as response using the following code." }, { "code": null, "e": 8131, "s": 7541, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCControllerDemo.Controllers {\n public class EmployeeController : Controller{\n // GET: Employee\n //public ActionResult Index()\n //{\n // return View();\n //}\n\t\t\n public ActionResult Search(string name){\n var input = Server.HtmlEncode(name);\n return Content(input);\n }\n\t\t\n [HttpGet]\n public ActionResult Search(){\n var input = \"Another Search action\";\n return Content(input);\n }\n }\n}" }, { "code": null, "e": 8201, "s": 8131, "text": "When you run this application, you will receive the following output." }, { "code": null, "e": 8236, "s": 8201, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8250, "s": 8236, "text": " Anadi Sharma" }, { "code": null, "e": 8285, "s": 8250, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8308, "s": 8285, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8342, "s": 8308, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8362, "s": 8342, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8397, "s": 8362, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8414, "s": 8397, "text": " University Code" }, { "code": null, "e": 8449, "s": 8414, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8466, "s": 8449, "text": " University Code" }, { "code": null, "e": 8500, "s": 8466, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 8515, "s": 8500, "text": " Bhrugen Patel" }, { "code": null, "e": 8522, "s": 8515, "text": " Print" }, { "code": null, "e": 8533, "s": 8522, "text": " Add Notes" } ]
3 steps to update parameters of Faster R-CNN/SSD models in TensorFlow Object Detection API | by Vatsal Sodha | Towards Data Science
I wrote an article on configuring TensorFlow Object Detection API. Kindly, refer to that story here to configure the API. That story is a prerequisite for this article. In this story, I will discuss how to change the configuration of pre-trained model. The aim of this article is that you can configure TensorFlow/models based on your application and API will no longer be a black box! The article’s overview: Understanding of protocol buffers and proto files. Using knowledge of proto files, how can we understand the config files of the model 3 steps to follow to update the parameters of the model Miscellaneous examples: Changing the weight initializerChanging the weight optimizerEvaluating the pre-trained model. Changing the weight initializer Changing the weight optimizer Evaluating the pre-trained model. To modify the model, we need to understand it’s inner mechanisms. TensorFlow Object Detection API uses Protocol Buffers, which is language-independent, platform-independent, and extensible mechanism for serializing structured data. It’s like XML at a smaller scale, but faster and simpler. API uses the proto2 version of the protocol buffers language. I will try to explain this language which is required to update the pre-configured model. For more details on protocol buffers language, refer to this documentation and Python tutorial. Working of protocol buffers can be explained in 3 steps as below: Define a message format in .proto file. This file acts like a blueprint of all messages, which shows what all parameters are accepted by the message, what should be the data type of the parameter, whether the parameter is required or optional, what is the tag number of the parameter, what is the default value of the parameter etc. API’s protos files can be found here. For the purpose of understanding, I am using grid_anchor_generator.proto file. It is clear from the lines 30–33 that the parameters scales and aspect_ratios are mandatory for message GridAnchorGenerator, while rest of the parameters are optional if not passed, it will take default values. After defining a message format, we need to compile the protocol buffer. This compiler will generate the classes file from .proto file. During installation of API we had run the below command which will compile the protocol buffers: # From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=. After defining and compiling the protocol buffer, we need to use Python protocol buffer API to write and read messages. In our case, we can consider the config file as protocol buffer API, which can write and read messages, ignoring the inner mechanisms of TensorFlow API. In other words, we can update the parameters of the pre-trained model by appropriately changing the config file. It is clear that config files can help us to change the parameters of the model according to our needs. Next question that pops up is how can we change the parameters of the model? This section and next section answers this question where knowledge of proto files will be handy. For demonstration purpose I am using faster_rcnn_resnet50_pets.config file. Lines 7–10 implies that num_classes is one of the parameters of faster_rcnn message, which in turn is the parameter of the message model. Similarly, optimizer is the child message of parent train_config message, while batch_size is another parameter of train_config message. We can verify this by checking out the corresponding protos file. It is clear from lines 20 and 26 that num_classes is one of the optional parameter of the message faster_rcnn. I hope discussion till now helps to understand the organization of config files. Now, it is the time to correctly update one of the parameters of the model. Step 1: Decide the parameter to be updated Let’s say we need to update image_resizer parameter mentioned in line 10 of faster_rcnn_resnet50_pets.config file. Step 2: Search for the given parameter in the repository The goal is to locate the proto file of the parameter. For that we need to search in the repository. We need to search the following code: parameter_name path:research/object_detection/protos#in our case parameter_name="image_resizer" thus,image_resizer path:research/object_detection/protos Here path:research/object_detection/protos confines the search domain. More information on how to search on GitHub can be found here. The output on searching image_resizer path:research/object_detection/protos is shown below: It is clear from the output that to update the image_resizer parameter we need to analyse the image_resizer.proto file. Step 3: Analyze the proto file It is clear from lines 8–10 that we can resize the image using keep_aspect_ratio_resizer orfixed_shape_resizer. On analyzing lines 23–44, we can observe that message keep_aspect_ratio_resizer have parameters: min_dimension, max_dimension, resize_method, pad_to_max_dimension, convert_to_grayscale,and per_channel_pad_value. Moreover, fixed_shape_resizer have parameters: height, width, resize_method,and convert_to_grayscale. All the parameters have their datatypes mentioned in the proto file. So, to change the image_resizer type we can change the following lines in the config file. #beforeimage_resizer {keep_aspect_ratio_resizer {min_dimension: 600 max_dimension: 1024 }}#afterimage_resizer {fixed_shape_resizer {height: 600width: 500resize_method: AREA }} The above code will resize the image to 500 * 600 using AREA resize method. The various resize methods available in TensorFlow can be found here. Miscellaneous Examples We can update/add any parameter using steps discussed in the above section. I will demonstrate some of the examples here which are frequently used but the steps, discussed above can be helpful to update/add any parameters of the model. Decided to change the parameter initializer on line 35 of the faster_rcnn_resnet50_pets.config file. Search for the initializer path:research/object_detection/protos in the repository. From the search result, it is clear that we need to analyze the hyperparams.proto file. Line 68–74 in the hyperparams.proto file, explains initializer configuration. message Initializer { oneof initializer_oneof { TruncatedNormalInitializer truncated_normal_initializer = 1; VarianceScalingInitializer variance_scaling_initializer = 2; RandomNormalInitializer random_normal_initializer = 3; }} We can use random_normal_intializer instead of truncated_normal_initializer, for that we need to analyze line 99–102 in the hyperparams.proto file. message RandomNormalInitializer { optional float mean = 1 [default = 0.0]; optional float stddev = 2 [default = 1.0];} It is clear that random_normal_intializer have 2 parameters mean and stddev. We can change the following lines in the config file to use random_normal_intializer. #beforeinitializer { truncated_normal_initializer { stddev: 0.01 }}#afterinitializer { random_normal_intializer{ mean: 1 stddev: 0.5 }} Decided to change the parameter momentum_optimizer of parent message optimizer on line 87 of the faster_rcnn_resnet50_pets.config file. Search for the optimizer path:research/object_detection/protos in the repository. From the search result, it is clear that we need to analyze the optimizer.proto file. Lines 9–14 in optimizer.proto file, expain optimizer configuration. message Optimizer { oneof optimizer { RMSPropOptimizer rms_prop_optimizer = 1; MomentumOptimizer momentum_optimizer = 2; AdamOptimizer adam_optimizer = 3; } It is clear that instead of momentum_optimizer we can use adam_optimizer which has been proved to be good optimizer. To do that we need following changes in the faster_rcnn_resnet50_pets.config file. #beforeoptimizer { momentum_optimizer: { learning_rate: { manual_step_learning_rate { initial_learning_rate: 0.0003 schedule { step: 900000 learning_rate: .00003 } schedule { step: 1200000 learning_rate: .000003 } } } momentum_optimizer_value: 0.9 }#afteroptimizer { adam_optimizer: { learning_rate: { manual_step_learning_rate { initial_learning_rate: 0.0003 schedule { step: 900000 learning_rate: .00003 } schedule { step: 1200000 learning_rate: .000003 } } } } Eval waits for 300 seconds to check whether training model is updated or not! If your GPU is good, you can train and eval both simultaneously! Generally, resources will be exhausted. To overcome this, we can train the model first, save it in the directory, and evaluate the model later. To evaluate later, we need following changes in the config file: #Beforeeval_config: { num_examples: 2000 # Note: The below line limits the evaluation process to 10 evaluations. # Remove the below line to evaluate indefinitely. max_evals: 10}#aftereval_config: {num_examples: 10num_visualizations: 10eval_interval_secs: 0} num_visualizations should be equal to number of to be evaluated! Higher the number of visualizations, more time it will take to evaluate. If your GPU is capable enough to train and eval simultaneously, you can keep eval_interval_secs: 300. This parameter is to decide how often to run evaluation. I followed 3 steps discussed above to come to this conclusion. In a nutshell, the knowledge of protocol buffers helped us to understand that parameters to the model are passed in the form of messages and to update the parameter we can refer .proto file. 3 simple steps were discussed to find the correct .proto file for updating the parameter. Recently, I came across this article on neptune.ai which can be useful for further reference. Kindly mention any parameter you want to update/add in the config file in the comments. I hope this article helps.
[ { "code": null, "e": 341, "s": 172, "text": "I wrote an article on configuring TensorFlow Object Detection API. Kindly, refer to that story here to configure the API. That story is a prerequisite for this article." }, { "code": null, "e": 558, "s": 341, "text": "In this story, I will discuss how to change the configuration of pre-trained model. The aim of this article is that you can configure TensorFlow/models based on your application and API will no longer be a black box!" }, { "code": null, "e": 582, "s": 558, "text": "The article’s overview:" }, { "code": null, "e": 633, "s": 582, "text": "Understanding of protocol buffers and proto files." }, { "code": null, "e": 717, "s": 633, "text": "Using knowledge of proto files, how can we understand the config files of the model" }, { "code": null, "e": 773, "s": 717, "text": "3 steps to follow to update the parameters of the model" }, { "code": null, "e": 797, "s": 773, "text": "Miscellaneous examples:" }, { "code": null, "e": 891, "s": 797, "text": "Changing the weight initializerChanging the weight optimizerEvaluating the pre-trained model." }, { "code": null, "e": 923, "s": 891, "text": "Changing the weight initializer" }, { "code": null, "e": 953, "s": 923, "text": "Changing the weight optimizer" }, { "code": null, "e": 987, "s": 953, "text": "Evaluating the pre-trained model." }, { "code": null, "e": 1525, "s": 987, "text": "To modify the model, we need to understand it’s inner mechanisms. TensorFlow Object Detection API uses Protocol Buffers, which is language-independent, platform-independent, and extensible mechanism for serializing structured data. It’s like XML at a smaller scale, but faster and simpler. API uses the proto2 version of the protocol buffers language. I will try to explain this language which is required to update the pre-configured model. For more details on protocol buffers language, refer to this documentation and Python tutorial." }, { "code": null, "e": 1591, "s": 1525, "text": "Working of protocol buffers can be explained in 3 steps as below:" }, { "code": null, "e": 2041, "s": 1591, "text": "Define a message format in .proto file. This file acts like a blueprint of all messages, which shows what all parameters are accepted by the message, what should be the data type of the parameter, whether the parameter is required or optional, what is the tag number of the parameter, what is the default value of the parameter etc. API’s protos files can be found here. For the purpose of understanding, I am using grid_anchor_generator.proto file." }, { "code": null, "e": 2252, "s": 2041, "text": "It is clear from the lines 30–33 that the parameters scales and aspect_ratios are mandatory for message GridAnchorGenerator, while rest of the parameters are optional if not passed, it will take default values." }, { "code": null, "e": 2485, "s": 2252, "text": "After defining a message format, we need to compile the protocol buffer. This compiler will generate the classes file from .proto file. During installation of API we had run the below command which will compile the protocol buffers:" }, { "code": null, "e": 2573, "s": 2485, "text": "# From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 2959, "s": 2573, "text": "After defining and compiling the protocol buffer, we need to use Python protocol buffer API to write and read messages. In our case, we can consider the config file as protocol buffer API, which can write and read messages, ignoring the inner mechanisms of TensorFlow API. In other words, we can update the parameters of the pre-trained model by appropriately changing the config file." }, { "code": null, "e": 3314, "s": 2959, "text": "It is clear that config files can help us to change the parameters of the model according to our needs. Next question that pops up is how can we change the parameters of the model? This section and next section answers this question where knowledge of proto files will be handy. For demonstration purpose I am using faster_rcnn_resnet50_pets.config file." }, { "code": null, "e": 3655, "s": 3314, "text": "Lines 7–10 implies that num_classes is one of the parameters of faster_rcnn message, which in turn is the parameter of the message model. Similarly, optimizer is the child message of parent train_config message, while batch_size is another parameter of train_config message. We can verify this by checking out the corresponding protos file." }, { "code": null, "e": 3923, "s": 3655, "text": "It is clear from lines 20 and 26 that num_classes is one of the optional parameter of the message faster_rcnn. I hope discussion till now helps to understand the organization of config files. Now, it is the time to correctly update one of the parameters of the model." }, { "code": null, "e": 3966, "s": 3923, "text": "Step 1: Decide the parameter to be updated" }, { "code": null, "e": 4081, "s": 3966, "text": "Let’s say we need to update image_resizer parameter mentioned in line 10 of faster_rcnn_resnet50_pets.config file." }, { "code": null, "e": 4138, "s": 4081, "text": "Step 2: Search for the given parameter in the repository" }, { "code": null, "e": 4239, "s": 4138, "text": "The goal is to locate the proto file of the parameter. For that we need to search in the repository." }, { "code": null, "e": 4277, "s": 4239, "text": "We need to search the following code:" }, { "code": null, "e": 4430, "s": 4277, "text": "parameter_name path:research/object_detection/protos#in our case parameter_name=\"image_resizer\" thus,image_resizer path:research/object_detection/protos" }, { "code": null, "e": 4656, "s": 4430, "text": "Here path:research/object_detection/protos confines the search domain. More information on how to search on GitHub can be found here. The output on searching image_resizer path:research/object_detection/protos is shown below:" }, { "code": null, "e": 4776, "s": 4656, "text": "It is clear from the output that to update the image_resizer parameter we need to analyse the image_resizer.proto file." }, { "code": null, "e": 4807, "s": 4776, "text": "Step 3: Analyze the proto file" }, { "code": null, "e": 5393, "s": 4807, "text": "It is clear from lines 8–10 that we can resize the image using keep_aspect_ratio_resizer orfixed_shape_resizer. On analyzing lines 23–44, we can observe that message keep_aspect_ratio_resizer have parameters: min_dimension, max_dimension, resize_method, pad_to_max_dimension, convert_to_grayscale,and per_channel_pad_value. Moreover, fixed_shape_resizer have parameters: height, width, resize_method,and convert_to_grayscale. All the parameters have their datatypes mentioned in the proto file. So, to change the image_resizer type we can change the following lines in the config file." }, { "code": null, "e": 5573, "s": 5393, "text": "#beforeimage_resizer {keep_aspect_ratio_resizer {min_dimension: 600 max_dimension: 1024 }}#afterimage_resizer {fixed_shape_resizer {height: 600width: 500resize_method: AREA }}" }, { "code": null, "e": 5719, "s": 5573, "text": "The above code will resize the image to 500 * 600 using AREA resize method. The various resize methods available in TensorFlow can be found here." }, { "code": null, "e": 5742, "s": 5719, "text": "Miscellaneous Examples" }, { "code": null, "e": 5978, "s": 5742, "text": "We can update/add any parameter using steps discussed in the above section. I will demonstrate some of the examples here which are frequently used but the steps, discussed above can be helpful to update/add any parameters of the model." }, { "code": null, "e": 6079, "s": 5978, "text": "Decided to change the parameter initializer on line 35 of the faster_rcnn_resnet50_pets.config file." }, { "code": null, "e": 6251, "s": 6079, "text": "Search for the initializer path:research/object_detection/protos in the repository. From the search result, it is clear that we need to analyze the hyperparams.proto file." }, { "code": null, "e": 6329, "s": 6251, "text": "Line 68–74 in the hyperparams.proto file, explains initializer configuration." }, { "code": null, "e": 6568, "s": 6329, "text": "message Initializer { oneof initializer_oneof { TruncatedNormalInitializer truncated_normal_initializer = 1; VarianceScalingInitializer variance_scaling_initializer = 2; RandomNormalInitializer random_normal_initializer = 3; }}" }, { "code": null, "e": 6716, "s": 6568, "text": "We can use random_normal_intializer instead of truncated_normal_initializer, for that we need to analyze line 99–102 in the hyperparams.proto file." }, { "code": null, "e": 6837, "s": 6716, "text": "message RandomNormalInitializer { optional float mean = 1 [default = 0.0]; optional float stddev = 2 [default = 1.0];}" }, { "code": null, "e": 7000, "s": 6837, "text": "It is clear that random_normal_intializer have 2 parameters mean and stddev. We can change the following lines in the config file to use random_normal_intializer." }, { "code": null, "e": 7174, "s": 7000, "text": "#beforeinitializer { truncated_normal_initializer { stddev: 0.01 }}#afterinitializer { random_normal_intializer{ mean: 1 stddev: 0.5 }}" }, { "code": null, "e": 7310, "s": 7174, "text": "Decided to change the parameter momentum_optimizer of parent message optimizer on line 87 of the faster_rcnn_resnet50_pets.config file." }, { "code": null, "e": 7478, "s": 7310, "text": "Search for the optimizer path:research/object_detection/protos in the repository. From the search result, it is clear that we need to analyze the optimizer.proto file." }, { "code": null, "e": 7546, "s": 7478, "text": "Lines 9–14 in optimizer.proto file, expain optimizer configuration." }, { "code": null, "e": 7714, "s": 7546, "text": "message Optimizer { oneof optimizer { RMSPropOptimizer rms_prop_optimizer = 1; MomentumOptimizer momentum_optimizer = 2; AdamOptimizer adam_optimizer = 3; }" }, { "code": null, "e": 7914, "s": 7714, "text": "It is clear that instead of momentum_optimizer we can use adam_optimizer which has been proved to be good optimizer. To do that we need following changes in the faster_rcnn_resnet50_pets.config file." }, { "code": null, "e": 8621, "s": 7914, "text": "#beforeoptimizer { momentum_optimizer: { learning_rate: { manual_step_learning_rate { initial_learning_rate: 0.0003 schedule { step: 900000 learning_rate: .00003 } schedule { step: 1200000 learning_rate: .000003 } } } momentum_optimizer_value: 0.9 }#afteroptimizer { adam_optimizer: { learning_rate: { manual_step_learning_rate { initial_learning_rate: 0.0003 schedule { step: 900000 learning_rate: .00003 } schedule { step: 1200000 learning_rate: .000003 } } } }" }, { "code": null, "e": 8973, "s": 8621, "text": "Eval waits for 300 seconds to check whether training model is updated or not! If your GPU is good, you can train and eval both simultaneously! Generally, resources will be exhausted. To overcome this, we can train the model first, save it in the directory, and evaluate the model later. To evaluate later, we need following changes in the config file:" }, { "code": null, "e": 9235, "s": 8973, "text": "#Beforeeval_config: { num_examples: 2000 # Note: The below line limits the evaluation process to 10 evaluations. # Remove the below line to evaluate indefinitely. max_evals: 10}#aftereval_config: {num_examples: 10num_visualizations: 10eval_interval_secs: 0}" }, { "code": null, "e": 9595, "s": 9235, "text": "num_visualizations should be equal to number of to be evaluated! Higher the number of visualizations, more time it will take to evaluate. If your GPU is capable enough to train and eval simultaneously, you can keep eval_interval_secs: 300. This parameter is to decide how often to run evaluation. I followed 3 steps discussed above to come to this conclusion." }, { "code": null, "e": 9970, "s": 9595, "text": "In a nutshell, the knowledge of protocol buffers helped us to understand that parameters to the model are passed in the form of messages and to update the parameter we can refer .proto file. 3 simple steps were discussed to find the correct .proto file for updating the parameter. Recently, I came across this article on neptune.ai which can be useful for further reference." }, { "code": null, "e": 10058, "s": 9970, "text": "Kindly mention any parameter you want to update/add in the config file in the comments." } ]
Write a function that generates one of 3 numbers according to given probabilities in C++
In this problem, we have to create a function that will generate three numbers based on the given probability. For this, we will use the built-in random number generator function which is rand(a, b) which generates random numbers within the range [a, b] with equal probability. Our task is to return only three numbers A, B, C which have the probability of occurrence as P(A), P(B), P(C) respectively and according to definition of probability P(A) + P(B) + P(C) = 1. To create our function using rand(a,b). we will use its feature that the probability of occurrence of any number from a to b is the same. But we have to get A with probability P(A) and so on. So, for this, we will use percentage probabilities of the numbers i.e. if P(A) = 1/5, we will treat it as 20%. So, the maximum probability percentage will be 100%, so we will generate a random number from 0 to 100 and based on the number generated we will return numbers between A, B, C based on the following conditions. Case 1 − If the number generated is between 0 and P(A), return A. Case 2 − If the number generated is between P(A) and P(A)+P(B), return B. Case 3 − If the number generated is between P(A)+P(B) and 1{P(A)+P(B)+P(C)}, return C. Let’s see an example that will make the concept clear, A = 3 , P(A) = 35% B = 43, P(B) = 50% C = 90, P(C) = 15% The program will return, 3 if the rand function generates number between 0 and 35. 43 if the rand function generates number between 35 and 85. 90 if the rand function generates number between 85 and 100. Program to show the implementation of our logic, Live Demo #include<iostream> using namespace std; int randomABC(int A, int B, int C, int PA, int PB, int PC){ int randNumber = rand()%100+1; if (randNumber <= PA) return A; if (randNumber <= (PA+PB)) return B; else return C; } int main(){ cout<<"Random number between 3, 45, 90 with given probabilities is : "<<randomABC(3, 43, 90, 35, 40, 25); return 0; } Random number between 3, 45, 90 with given probabilities is : 3
[ { "code": null, "e": 1173, "s": 1062, "text": "In this problem, we have to create a function that will generate three numbers based on the given probability." }, { "code": null, "e": 1340, "s": 1173, "text": "For this, we will use the built-in random number generator function which is rand(a, b) which generates random numbers within the range [a, b] with equal probability." }, { "code": null, "e": 1530, "s": 1340, "text": "Our task is to return only three numbers A, B, C which have the probability of occurrence as P(A), P(B), P(C) respectively and according to definition of probability P(A) + P(B) + P(C) = 1." }, { "code": null, "e": 1833, "s": 1530, "text": "To create our function using rand(a,b). we will use its feature that the probability of occurrence of any number from a to b is the same. But we have to get A with probability P(A) and so on. So, for this, we will use percentage probabilities of the numbers i.e. if P(A) = 1/5, we will treat it as 20%." }, { "code": null, "e": 2044, "s": 1833, "text": "So, the maximum probability percentage will be 100%, so we will generate a random number from 0 to 100 and based on the number generated we will return numbers between A, B, C based on the following conditions." }, { "code": null, "e": 2110, "s": 2044, "text": "Case 1 − If the number generated is between 0 and P(A), return A." }, { "code": null, "e": 2184, "s": 2110, "text": "Case 2 − If the number generated is between P(A) and P(A)+P(B), return B." }, { "code": null, "e": 2271, "s": 2184, "text": "Case 3 − If the number generated is between P(A)+P(B) and 1{P(A)+P(B)+P(C)}, return C." }, { "code": null, "e": 2326, "s": 2271, "text": "Let’s see an example that will make the concept clear," }, { "code": null, "e": 2383, "s": 2326, "text": "A = 3 , P(A) = 35%\nB = 43, P(B) = 50%\nC = 90, P(C) = 15%" }, { "code": null, "e": 2408, "s": 2383, "text": "The program will return," }, { "code": null, "e": 2466, "s": 2408, "text": "3 if the rand function generates number between 0 and 35." }, { "code": null, "e": 2526, "s": 2466, "text": "43 if the rand function generates number between 35 and 85." }, { "code": null, "e": 2587, "s": 2526, "text": "90 if the rand function generates number between 85 and 100." }, { "code": null, "e": 2636, "s": 2587, "text": "Program to show the implementation of our logic," }, { "code": null, "e": 2647, "s": 2636, "text": " Live Demo" }, { "code": null, "e": 3021, "s": 2647, "text": "#include<iostream>\nusing namespace std;\nint randomABC(int A, int B, int C, int PA, int PB, int PC){\n int randNumber = rand()%100+1;\n if (randNumber <= PA)\n return A;\n if (randNumber <= (PA+PB))\n return B;\n else\n return C;\n}\nint main(){\n cout<<\"Random number between 3, 45, 90 with given probabilities is : \"<<randomABC(3, 43, 90, 35, 40, 25);\n return 0;\n}" }, { "code": null, "e": 3085, "s": 3021, "text": "Random number between 3, 45, 90 with given probabilities is : 3" } ]
Correcting your spelling error via 2 distance | by Edward Ma | Towards Data Science
When dealing with text, we may need to deal with incorrect text. Although we can still use character embeddings and word embeddings to compute a similar vectors. It is good for unseen data and out-of-vocabulary (OOV). However, it will be better if we can correct typo. Typo can be generated in several scenarios. If you work on optical character recognition (OCR), post-processing step for OCR output is very critical part as some error will be introduced from OCR engine and it can be caused by bad quality of image and OCR engine error. Another typo source comes from human. When you work on chatbot project, the input comes from human and it must include typos. To achieve a better result, it will be a better to correct typo as earlier as we can. After reading this post, you will understand: Spelling Corrector Implementation Take Away Norvig implemented a very simple but amazing library to correct the spelling error in 2007. Possible candidate corrections are computed by different ways and finding the most likelihood word from there. There are 2 phases to find the possible candidate words. First of all, it uses 4 different ways to generate new word while the edit distance between original word and candidate word is 1. Difference from Levenshtein Distance, it considers: Deletion: Remove one letter Transposition: Swap two adjacent letters Replacement: Change one letter to another Insertion: Add one letter Taking “edward” as an example, “edwar”, “edwadr”, “edwadd”, “edwward” are examples of “Deletion”, “Transposition”, “Replacement” and “Insertion” respectively. Obviously, tons of invalid words will be generated. Therefore, it will filter out by a given vocabulary (it call “known word” in library). To expand potential candidates, algorithm repeat this step again but the edit distance is 2. Second part is selecting candidate from possible candidates based on probability. For example, the occurrences of “Edward” in the given dictionary is 2%, the probability is 0.02. The highest probability word will be chosen from potential candidates. To facility the spell check, corpus is needed. For sake of easier for demonstration, I simply use dataset from sklearn library without pre-processing. You should use your domain specific dataset to build a better corpus for your data. Build corpus from collections import Counterfrom sklearn.datasets import fetch_20newsgroupsimport recorpus = []for line in fetch_20newsgroups().data: line = line.replace('\n', ' ').replace('\t', ' ').lower() line = re.sub('[^a-z ]', ' ', line) tokens = line.split(' ') tokens = [token for token in tokens if len(token) > 0] corpus.extend(tokens)corpus = Counter(corpus) Correction spell_corrector = SpellCorrector(dictionary=corpus)spell_corrector.correction('edwar') Output is edward To access all code, you can visit my github repo. Spell corrector does not consider the context but just the spelling purely. However, given that it is introduced in 11 years ago (2007). It is an amazing tool. From author coding, the preprocessing result should only keep English character and lower case. In other word, special character and number should be removed. Performance (in terms of speed) is very fast. I am Data Scientist in Bay Area. Focusing on state-of-the-art in Data Science, Artificial Intelligence , especially in NLP and platform related. You can reach me from Medium Blog, LinkedIn or Github.
[ { "code": null, "e": 441, "s": 172, "text": "When dealing with text, we may need to deal with incorrect text. Although we can still use character embeddings and word embeddings to compute a similar vectors. It is good for unseen data and out-of-vocabulary (OOV). However, it will be better if we can correct typo." }, { "code": null, "e": 837, "s": 441, "text": "Typo can be generated in several scenarios. If you work on optical character recognition (OCR), post-processing step for OCR output is very critical part as some error will be introduced from OCR engine and it can be caused by bad quality of image and OCR engine error. Another typo source comes from human. When you work on chatbot project, the input comes from human and it must include typos." }, { "code": null, "e": 969, "s": 837, "text": "To achieve a better result, it will be a better to correct typo as earlier as we can. After reading this post, you will understand:" }, { "code": null, "e": 988, "s": 969, "text": "Spelling Corrector" }, { "code": null, "e": 1003, "s": 988, "text": "Implementation" }, { "code": null, "e": 1013, "s": 1003, "text": "Take Away" }, { "code": null, "e": 1273, "s": 1013, "text": "Norvig implemented a very simple but amazing library to correct the spelling error in 2007. Possible candidate corrections are computed by different ways and finding the most likelihood word from there. There are 2 phases to find the possible candidate words." }, { "code": null, "e": 1456, "s": 1273, "text": "First of all, it uses 4 different ways to generate new word while the edit distance between original word and candidate word is 1. Difference from Levenshtein Distance, it considers:" }, { "code": null, "e": 1484, "s": 1456, "text": "Deletion: Remove one letter" }, { "code": null, "e": 1525, "s": 1484, "text": "Transposition: Swap two adjacent letters" }, { "code": null, "e": 1567, "s": 1525, "text": "Replacement: Change one letter to another" }, { "code": null, "e": 1593, "s": 1567, "text": "Insertion: Add one letter" }, { "code": null, "e": 1984, "s": 1593, "text": "Taking “edward” as an example, “edwar”, “edwadr”, “edwadd”, “edwward” are examples of “Deletion”, “Transposition”, “Replacement” and “Insertion” respectively. Obviously, tons of invalid words will be generated. Therefore, it will filter out by a given vocabulary (it call “known word” in library). To expand potential candidates, algorithm repeat this step again but the edit distance is 2." }, { "code": null, "e": 2234, "s": 1984, "text": "Second part is selecting candidate from possible candidates based on probability. For example, the occurrences of “Edward” in the given dictionary is 2%, the probability is 0.02. The highest probability word will be chosen from potential candidates." }, { "code": null, "e": 2469, "s": 2234, "text": "To facility the spell check, corpus is needed. For sake of easier for demonstration, I simply use dataset from sklearn library without pre-processing. You should use your domain specific dataset to build a better corpus for your data." }, { "code": null, "e": 2482, "s": 2469, "text": "Build corpus" }, { "code": null, "e": 2854, "s": 2482, "text": "from collections import Counterfrom sklearn.datasets import fetch_20newsgroupsimport recorpus = []for line in fetch_20newsgroups().data: line = line.replace('\\n', ' ').replace('\\t', ' ').lower() line = re.sub('[^a-z ]', ' ', line) tokens = line.split(' ') tokens = [token for token in tokens if len(token) > 0] corpus.extend(tokens)corpus = Counter(corpus)" }, { "code": null, "e": 2865, "s": 2854, "text": "Correction" }, { "code": null, "e": 2952, "s": 2865, "text": "spell_corrector = SpellCorrector(dictionary=corpus)spell_corrector.correction('edwar')" }, { "code": null, "e": 2962, "s": 2952, "text": "Output is" }, { "code": null, "e": 2969, "s": 2962, "text": "edward" }, { "code": null, "e": 3019, "s": 2969, "text": "To access all code, you can visit my github repo." }, { "code": null, "e": 3179, "s": 3019, "text": "Spell corrector does not consider the context but just the spelling purely. However, given that it is introduced in 11 years ago (2007). It is an amazing tool." }, { "code": null, "e": 3338, "s": 3179, "text": "From author coding, the preprocessing result should only keep English character and lower case. In other word, special character and number should be removed." }, { "code": null, "e": 3384, "s": 3338, "text": "Performance (in terms of speed) is very fast." } ]
CBSE Class 11 | Problem Solving Methodologies - GeeksforGeeks
23 Feb, 2022 The process of problem-solving is an activity which has its ingredients as the specification of the program and the served dish is a correct program. This activity comprises of four steps :1. Understanding the problem: To solve any problem it is very crucial to understand the problem first. What is the desired output of the code and how that output can be generated? The obvious and essential need to generate the output is an input. The input may be singular or it may be a set of inputs. A proper relationship between the input and output must be drawn in order to solve the problem efficiently. The input set should be complete and sufficient enough to draw the output. It means all the necessary inputs required to compute the output should be present at the time of computation. However, it should be kept in mind that the programmer should ensure that the minimum number of inputs should be there. Any irrelevant input only increases the size of and memory overhead of the program. Thus Identifying the minimum number of inputs required for output is a crucial element for understanding the problem. 2. Devising the plan: Once a problem has been understood, a proper action plan has to be devised to solve it. This is called devising the plan. This step usually involves computing the result from the given set of inputs. It uses the relationship drawn between inputs and outputs in the previous step. The complexity of this step depends upon the complexity of the problem at hand. 3. Executing the plan: Once the plan has been defined, it should follow the trajectory of action while ensuring the plan’s integrity at various checkpoints. If any inconsistency is found in between, the plan needs to be revised. 4. Evaluation: The final result so obtained must be evaluated and verified to see if the problem has been solved satisfactorily. The methodology to solve a problem is defined as the most efficient solution to the problem. Although, there can be multiple ways to crack a nut, but a methodology is one where the nut is cracked in the shortest time and with minimum effort. Clearly, a sledgehammer can never be used to crack a nut. Under problem-solving methodology, we will see a step by step solution for a problem. These steps closely resemble the software life cycle. A software life cycle involves several stages in a program’s life cycle. These steps can be used by any tyro programmer to solve a problem in the most efficient way ever. The several steps of this cycle are as follows : Step by step solution for a problem (Software Life Cycle)1. Problem Definition/Specification: A computer program is basically a machine language solution to a real-life problem. Because programs are generally made to solve the pragmatic problems of the outside world. In order to solve the problem, it is very necessary to define the problem to get its proper understanding. For example, suppose we are asked to write a code for “ Compute the average of three numbers”. In this case, a proper definition of the problem will include questions like :“What exactly does average mean?”“How to calculate the average?” Once, questions like these are raised, it helps to formulate the solution of the problem in a better way. Once a problem has been defined, the program’s specifications are then listed. Problem specifications describe what the program for the problem must do. It should definitely include : what is the input set of the program What is the desired output of the program and in what form the output is desired? 2. Problem Analysis (Breaking down the solution into simple steps): This step of solving the problem follows a modular approach to crack the nut. The problem is divided into subproblems so that designing a solution to these subproblems gets easier. The solutions to all these individual parts are then merged to get the final solution of the original problem. It is like divide and merge approach. Modular Approach for Programming : The process of breaking a large problem into subproblems and then treating these individual parts as different functions is called modular programming. Each function behaves independent of another and there is minimal inter-functional communication. There are two methods to implement modular programming : Top Down Design : In this method, the original problem is divided into subparts. These subparts are further divided. The chain continues till we get the very fundamental subpart of the problem which can’t be further divided. Then we draw a solution for each of these fundamental parts.Bottom Up Design : In this style of programming, an application is written by using the pre-existing primitives of programming language. These primitives are then amalgamated with more complicated features, till the application is written. This style is just the reverse of the top-down design style. Top Down Design : In this method, the original problem is divided into subparts. These subparts are further divided. The chain continues till we get the very fundamental subpart of the problem which can’t be further divided. Then we draw a solution for each of these fundamental parts. Bottom Up Design : In this style of programming, an application is written by using the pre-existing primitives of programming language. These primitives are then amalgamated with more complicated features, till the application is written. This style is just the reverse of the top-down design style. 3. Problem Designing: The design of a problem can be represented in either of the two forms : Algorithm : The set of instructions written down to formulate the solution of a problem is called algorithm. These instructions when followed to write the code produces the desired output. The steps involved in the algorithm are usually written in English or any colloquial language which is easier for the programmer to comprehend what the code needs.Let’s have a mundane example preparing the early morning tea and write an algorithm for the same.STEP 1 : STARTSTEP 2 : Pour water in a pan.STEP 3 : Put the pan on gas burner.STEP 4 :Light the gas burner.STEP 5 : Put sugar in the pan.STEP 6 : Put tea leaves in the pan.STEP 7 : Pour milk in the pan.STEP 8 : Filter the prepared tea in the cup.STEP 9 : Serve it to others and enjoy yourself.STEp 10 : STOPThe ways to execute any program are of three categories:Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed.Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements.Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements.Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one.Flow Chart : Flow charts are diagrammatic representation of the algorithm. It uses some symbols to illustrate the starting and ending of a program along with the flow of instructions involved in the program. Algorithm : The set of instructions written down to formulate the solution of a problem is called algorithm. These instructions when followed to write the code produces the desired output. The steps involved in the algorithm are usually written in English or any colloquial language which is easier for the programmer to comprehend what the code needs.Let’s have a mundane example preparing the early morning tea and write an algorithm for the same.STEP 1 : STARTSTEP 2 : Pour water in a pan.STEP 3 : Put the pan on gas burner.STEP 4 :Light the gas burner.STEP 5 : Put sugar in the pan.STEP 6 : Put tea leaves in the pan.STEP 7 : Pour milk in the pan.STEP 8 : Filter the prepared tea in the cup.STEP 9 : Serve it to others and enjoy yourself.STEp 10 : STOPThe ways to execute any program are of three categories:Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed.Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements.Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements.Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one. The ways to execute any program are of three categories: Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed. Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements. Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements. The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements. Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one. Flow Chart : Flow charts are diagrammatic representation of the algorithm. It uses some symbols to illustrate the starting and ending of a program along with the flow of instructions involved in the program. 4. Coding: Once an algorithm is formed, it can’t be executed on the computer. Thus in this step, this algorithm has to be translated into the syntax of a particular programming language. This process is often termed as ‘coding’. Coding is one of the most important steps of the software life cycle. It is not only challenging to find a solution to a problem but to write optimized code for a solution is far more challenging. Writing code for optimizing execution time and memory storage :A programmer writes code on his local computer. Now, suppose he writes a code which takes 5 hours to get executed. Now, this 5 hours of time is actually the idle time for the programmer. Not only it takes longer time, but it also uses the resources during that time. One of the most precious computing resources is memory. A large program is expected to utilize more memory. However, memory utilization is not a fault, but if a program is utilizing unnecessary time or memory, then it is a fault of coding. The optimized code can save both time and memory. For example, as has been discussed earlier, by using the minimum number of inputs to compute the output, one can save unnecessary memory utilization. All such techniques are very necessary to be deployed to write optimized code. The pragmatic world gives reverence not only to the solution of the problem but to the optimized solution. This art of writing the optimized code also called ‘competitive programming’. 5. Program Testing and Debugging: Program testing involves running each and every instruction of the code and check the validity of the output by a sample input. By testing a program one can also check if there’s an error in the program. If an error is detected, then program debugging is done. It is a process to locate the instruction which is causing an error in the program and then rectifying it. There are different types of error in a program :(i) Syntax ErrorEvery programming language has its own set of rules and constructs which need to be followed to form a valid program in that particular language. If at any place in the entire code, this set of rule is violated, it results in a syntax error.Take an example in C Language #include <stdio.h>void main(){ char ans[50]; printf("how are you?") gets(ans); printf("\ngood to see that you are %s", ans);} In the above program, the syntax error is in the first printf statement since the printf statement doesn’t end with a ‘;’. Now, until and unless this error is not rectified, the program will not get executed. Once the error is rectified, one gets the desired output. Suppose the input is ‘good’ then the output is :Output: how are you good to see that you are good (ii) Logical ErrorAn error caused due to the implementation of a wrong logic in the program is called logical error. They are usually detected during the runtime.Take an example in C Language: #include <stdio.h>void main(){ int n = 11, i; for (i = n; i <= 10; i++) printf("%d\n", i);} In the above code, the ‘for’ loop won’t get executed since n has been initialized with the value of 11 while ‘for’ loop can only print values smaller than or equal to 10. Such a code will result in incorrect output and thus errors like these are called logical errors.Once the error is rectified, one gets the desired output. Suppose n is initialised with the value ‘5’ then the output is :Output: 5 6 7 8 9 10 (iii) Runtime ErrorAny error which causes the unusual termination of the program is called runtime error. They are detected at the run time.Some common examples of runtime errors are :Example 1 : #include <stdio.h>void main(){ int a, b, c; printf("enter the value of a and b"); scanf("%d%d", &a, &b); c = a / b; printf("The quotient when a is divided by b is %d\n", c);} If during the runtime, the user gives the input value for B as 0 then the program terminates abruptly resulting in a runtime error. The output thus appears is :Output: NO OUTPUT Floating Point Exception Example 2 :If while executing a program, one attempts for opening an unexisting file, that is, a file which is not present in the hard disk, it also results in a runtime error. 6. Documentation : The program documentation involves : Problem DefinitionProblem DesignDocumentation of test performHistory of program developmentUser’s manualA user’s manual is used by a user to know about a program’s input, processing, and output data. Problem Definition Problem Design Documentation of test perform History of program development User’s manualA user’s manual is used by a user to know about a program’s input, processing, and output data. A user’s manual is used by a user to know about a program’s input, processing, and output data. 7. Program Maintenance: Once a program has been formed, to ensure its longevity, maintenance is a must. The maintenance of a program has its own costs associated with it, which may also exceed the development cost of the program in some cases. The maintenance of a program involves the following : Detection and Elimination of undetected errors in the existing program.Modification of current program to enhance its performance andadaptability.Enhancement of user interfaceEnriching the program with new capabilities.Updation of the documentation. Detection and Elimination of undetected errors in the existing program. Modification of current program to enhance its performance andadaptability. Enhancement of user interface Enriching the program with new capabilities. Updation of the documentation. There are codes which usually involve looping statements. Looping statements are statements in which instruction or a set of instructions is executed multiple times until a particular condition is satisfied. The while loop, for loop, do while loop, etc. form the basis of such looping structure. These statements are also called control structure because they determine or control the flow of instructions in a program. These looping structures are of two kinds : Conditional Control ( Finite Looping )In this looping, the loop gets executed a finite number of times. Once a particular condition is satisfied, the loop gets terminated.Take an example in C language :#include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf("%d\n", i);}In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output:1 2 3 4 5 6 7 8 9 10 //loop gets terminated Infinite LoopingThe infinite looping control structure is just the opposite of finite looping control structure. Here, the condition to terminate the loop never gets satisfied and hence, the loop gets executed infinitely.Take an example in C language :#include <stdio.h>void main(){ int n = 1; while (n <= 10) printf("%d\n", n);}In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output:1 1 1 1 1 1 .. .. .. //loop never terminates Conditional Control ( Finite Looping )In this looping, the loop gets executed a finite number of times. Once a particular condition is satisfied, the loop gets terminated.Take an example in C language :#include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf("%d\n", i);}In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output:1 2 3 4 5 6 7 8 9 10 //loop gets terminated #include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf("%d\n", i);} In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output: 1 2 3 4 5 6 7 8 9 10 //loop gets terminated Infinite LoopingThe infinite looping control structure is just the opposite of finite looping control structure. Here, the condition to terminate the loop never gets satisfied and hence, the loop gets executed infinitely.Take an example in C language :#include <stdio.h>void main(){ int n = 1; while (n <= 10) printf("%d\n", n);}In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output:1 1 1 1 1 1 .. .. .. //loop never terminates #include <stdio.h>void main(){ int n = 1; while (n <= 10) printf("%d\n", n);} In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output: 1 1 1 1 1 1 .. .. .. //loop never terminates Akanksha_Rai jaintarun CBSE - Class 11 Picked Programming Basics school-programming School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Destructors in C++ Python Exception Handling Difference between Abstract Class and Interface in Java Pure Virtual Functions and Abstract Classes in C++ Exception Handling in C++ 'this' pointer in C++
[ { "code": null, "e": 24206, "s": 24178, "text": "\n23 Feb, 2022" }, { "code": null, "e": 25314, "s": 24206, "text": "The process of problem-solving is an activity which has its ingredients as the specification of the program and the served dish is a correct program. This activity comprises of four steps :1. Understanding the problem: To solve any problem it is very crucial to understand the problem first. What is the desired output of the code and how that output can be generated? The obvious and essential need to generate the output is an input. The input may be singular or it may be a set of inputs. A proper relationship between the input and output must be drawn in order to solve the problem efficiently. The input set should be complete and sufficient enough to draw the output. It means all the necessary inputs required to compute the output should be present at the time of computation. However, it should be kept in mind that the programmer should ensure that the minimum number of inputs should be there. Any irrelevant input only increases the size of and memory overhead of the program. Thus Identifying the minimum number of inputs required for output is a crucial element for understanding the problem." }, { "code": null, "e": 25696, "s": 25314, "text": "2. Devising the plan: Once a problem has been understood, a proper action plan has to be devised to solve it. This is called devising the plan. This step usually involves computing the result from the given set of inputs. It uses the relationship drawn between inputs and outputs in the previous step. The complexity of this step depends upon the complexity of the problem at hand." }, { "code": null, "e": 25925, "s": 25696, "text": "3. Executing the plan: Once the plan has been defined, it should follow the trajectory of action while ensuring the plan’s integrity at various checkpoints. If any inconsistency is found in between, the plan needs to be revised." }, { "code": null, "e": 26054, "s": 25925, "text": "4. Evaluation: The final result so obtained must be evaluated and verified to see if the problem has been solved satisfactorily." }, { "code": null, "e": 26714, "s": 26054, "text": "The methodology to solve a problem is defined as the most efficient solution to the problem. Although, there can be multiple ways to crack a nut, but a methodology is one where the nut is cracked in the shortest time and with minimum effort. Clearly, a sledgehammer can never be used to crack a nut. Under problem-solving methodology, we will see a step by step solution for a problem. These steps closely resemble the software life cycle. A software life cycle involves several stages in a program’s life cycle. These steps can be used by any tyro programmer to solve a problem in the most efficient way ever. The several steps of this cycle are as follows :" }, { "code": null, "e": 27327, "s": 26714, "text": "Step by step solution for a problem (Software Life Cycle)1. Problem Definition/Specification: A computer program is basically a machine language solution to a real-life problem. Because programs are generally made to solve the pragmatic problems of the outside world. In order to solve the problem, it is very necessary to define the problem to get its proper understanding. For example, suppose we are asked to write a code for “ Compute the average of three numbers”. In this case, a proper definition of the problem will include questions like :“What exactly does average mean?”“How to calculate the average?”" }, { "code": null, "e": 27617, "s": 27327, "text": "Once, questions like these are raised, it helps to formulate the solution of the problem in a better way. Once a problem has been defined, the program’s specifications are then listed. Problem specifications describe what the program for the problem must do. It should definitely include :" }, { "code": null, "e": 27654, "s": 27617, "text": "what is the input set of the program" }, { "code": null, "e": 27736, "s": 27654, "text": "What is the desired output of the program and in what form the output is desired?" }, { "code": null, "e": 28134, "s": 27736, "text": "2. Problem Analysis (Breaking down the solution into simple steps): This step of solving the problem follows a modular approach to crack the nut. The problem is divided into subproblems so that designing a solution to these subproblems gets easier. The solutions to all these individual parts are then merged to get the final solution of the original problem. It is like divide and merge approach." }, { "code": null, "e": 28169, "s": 28134, "text": "Modular Approach for Programming :" }, { "code": null, "e": 28476, "s": 28169, "text": "The process of breaking a large problem into subproblems and then treating these individual parts as different functions is called modular programming. Each function behaves independent of another and there is minimal inter-functional communication. There are two methods to implement modular programming :" }, { "code": null, "e": 29062, "s": 28476, "text": "Top Down Design : In this method, the original problem is divided into subparts. These subparts are further divided. The chain continues till we get the very fundamental subpart of the problem which can’t be further divided. Then we draw a solution for each of these fundamental parts.Bottom Up Design : In this style of programming, an application is written by using the pre-existing primitives of programming language. These primitives are then amalgamated with more complicated features, till the application is written. This style is just the reverse of the top-down design style." }, { "code": null, "e": 29348, "s": 29062, "text": "Top Down Design : In this method, the original problem is divided into subparts. These subparts are further divided. The chain continues till we get the very fundamental subpart of the problem which can’t be further divided. Then we draw a solution for each of these fundamental parts." }, { "code": null, "e": 29649, "s": 29348, "text": "Bottom Up Design : In this style of programming, an application is written by using the pre-existing primitives of programming language. These primitives are then amalgamated with more complicated features, till the application is written. This style is just the reverse of the top-down design style." }, { "code": null, "e": 29743, "s": 29649, "text": "3. Problem Designing: The design of a problem can be represented in either of the two forms :" }, { "code": null, "e": 32334, "s": 29743, "text": "Algorithm : The set of instructions written down to formulate the solution of a problem is called algorithm. These instructions when followed to write the code produces the desired output. The steps involved in the algorithm are usually written in English or any colloquial language which is easier for the programmer to comprehend what the code needs.Let’s have a mundane example preparing the early morning tea and write an algorithm for the same.STEP 1 : STARTSTEP 2 : Pour water in a pan.STEP 3 : Put the pan on gas burner.STEP 4 :Light the gas burner.STEP 5 : Put sugar in the pan.STEP 6 : Put tea leaves in the pan.STEP 7 : Pour milk in the pan.STEP 8 : Filter the prepared tea in the cup.STEP 9 : Serve it to others and enjoy yourself.STEp 10 : STOPThe ways to execute any program are of three categories:Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed.Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements.Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements.Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one.Flow Chart : Flow charts are diagrammatic representation of the algorithm. It uses some symbols to illustrate the starting and ending of a program along with the flow of instructions involved in the program." }, { "code": null, "e": 34718, "s": 32334, "text": "Algorithm : The set of instructions written down to formulate the solution of a problem is called algorithm. These instructions when followed to write the code produces the desired output. The steps involved in the algorithm are usually written in English or any colloquial language which is easier for the programmer to comprehend what the code needs.Let’s have a mundane example preparing the early morning tea and write an algorithm for the same.STEP 1 : STARTSTEP 2 : Pour water in a pan.STEP 3 : Put the pan on gas burner.STEP 4 :Light the gas burner.STEP 5 : Put sugar in the pan.STEP 6 : Put tea leaves in the pan.STEP 7 : Pour milk in the pan.STEP 8 : Filter the prepared tea in the cup.STEP 9 : Serve it to others and enjoy yourself.STEp 10 : STOPThe ways to execute any program are of three categories:Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed.Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements.Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements.Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one." }, { "code": null, "e": 34775, "s": 34718, "text": "The ways to execute any program are of three categories:" }, { "code": null, "e": 34911, "s": 34775, "text": "Sequence StatementsHere, all the instructions are executed in a sequence, that is, one after the another, till the program is executed." }, { "code": null, "e": 35397, "s": 34911, "text": "Selection StatementsAs it is self-clear from the name, in these type of statements the whole set of instructions is not executed. A selection has to be made. A selected number of instructions are executed based on some condition. If the condition holds true then some part of the instruction set is executed, otherwise, another part of the set is executed. Since this selection out of the instruction set has to be made, thus these type of instructions are called Selection Statements." }, { "code": null, "e": 35866, "s": 35397, "text": "Iteration or Looping StatementsAs lucid by the name itself, here a particular set of instructions is being executed multiple times. This set of instructions keeps on executing in a loop until a particular condition gets terminated. These types of instructions are also called iteration statements.The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements." }, { "code": null, "e": 36038, "s": 35866, "text": "The three ways of executing a program explained above are also termed as ‘control structure’ since they determine and control the flow of execution in a set of statements." }, { "code": null, "e": 36522, "s": 36038, "text": "Identification of arithmetic and logical operations required for the solution :While writing the algorithm for a problem, the arithmetic and logical operations required for the solution are also usually identified. They help to write the code in an easier manner because the proper ordering of the arithmetic and logical symbols is necessary to determine the correct output. And when all this has been done in the algorithm writing step, it just makes the coding task a smoother one." }, { "code": null, "e": 36730, "s": 36522, "text": "Flow Chart : Flow charts are diagrammatic representation of the algorithm. It uses some symbols to illustrate the starting and ending of a program along with the flow of instructions involved in the program." }, { "code": null, "e": 37156, "s": 36730, "text": "4. Coding: Once an algorithm is formed, it can’t be executed on the computer. Thus in this step, this algorithm has to be translated into the syntax of a particular programming language. This process is often termed as ‘coding’. Coding is one of the most important steps of the software life cycle. It is not only challenging to find a solution to a problem but to write optimized code for a solution is far more challenging." }, { "code": null, "e": 38190, "s": 37156, "text": "Writing code for optimizing execution time and memory storage :A programmer writes code on his local computer. Now, suppose he writes a code which takes 5 hours to get executed. Now, this 5 hours of time is actually the idle time for the programmer. Not only it takes longer time, but it also uses the resources during that time. One of the most precious computing resources is memory. A large program is expected to utilize more memory. However, memory utilization is not a fault, but if a program is utilizing unnecessary time or memory, then it is a fault of coding. The optimized code can save both time and memory. For example, as has been discussed earlier, by using the minimum number of inputs to compute the output, one can save unnecessary memory utilization. All such techniques are very necessary to be deployed to write optimized code. The pragmatic world gives reverence not only to the solution of the problem but to the optimized solution. This art of writing the optimized code also called ‘competitive programming’." }, { "code": null, "e": 38928, "s": 38190, "text": "5. Program Testing and Debugging: Program testing involves running each and every instruction of the code and check the validity of the output by a sample input. By testing a program one can also check if there’s an error in the program. If an error is detected, then program debugging is done. It is a process to locate the instruction which is causing an error in the program and then rectifying it. There are different types of error in a program :(i) Syntax ErrorEvery programming language has its own set of rules and constructs which need to be followed to form a valid program in that particular language. If at any place in the entire code, this set of rule is violated, it results in a syntax error.Take an example in C Language" }, { "code": "#include <stdio.h>void main(){ char ans[50]; printf(\"how are you?\") gets(ans); printf(\"\\ngood to see that you are %s\", ans);}", "e": 39070, "s": 38928, "text": null }, { "code": null, "e": 39279, "s": 39070, "text": "In the above program, the syntax error is in the first printf statement since the printf statement doesn’t end with a ‘;’. Now, until and unless this error is not rectified, the program will not get executed." }, { "code": null, "e": 39393, "s": 39279, "text": "Once the error is rectified, one gets the desired output. Suppose the input is ‘good’ then the output is :Output:" }, { "code": null, "e": 39436, "s": 39393, "text": "how are you\ngood to see that you are good\n" }, { "code": null, "e": 39629, "s": 39436, "text": "(ii) Logical ErrorAn error caused due to the implementation of a wrong logic in the program is called logical error. They are usually detected during the runtime.Take an example in C Language:" }, { "code": "#include <stdio.h>void main(){ int n = 11, i; for (i = n; i <= 10; i++) printf(\"%d\\n\", i);}", "e": 39734, "s": 39629, "text": null }, { "code": null, "e": 40132, "s": 39734, "text": "In the above code, the ‘for’ loop won’t get executed since n has been initialized with the value of 11 while ‘for’ loop can only print values smaller than or equal to 10. Such a code will result in incorrect output and thus errors like these are called logical errors.Once the error is rectified, one gets the desired output. Suppose n is initialised with the value ‘5’ then the output is :Output:" }, { "code": null, "e": 40146, "s": 40132, "text": "5\n6\n7\n8\n9\n10\n" }, { "code": null, "e": 40342, "s": 40146, "text": "(iii) Runtime ErrorAny error which causes the unusual termination of the program is called runtime error. They are detected at the run time.Some common examples of runtime errors are :Example 1 :" }, { "code": "#include <stdio.h>void main(){ int a, b, c; printf(\"enter the value of a and b\"); scanf(\"%d%d\", &a, &b); c = a / b; printf(\"The quotient when a is divided by b is %d\\n\", c);}", "e": 40532, "s": 40342, "text": null }, { "code": null, "e": 40700, "s": 40532, "text": "If during the runtime, the user gives the input value for B as 0 then the program terminates abruptly resulting in a runtime error. The output thus appears is :Output:" }, { "code": null, "e": 40736, "s": 40700, "text": "NO OUTPUT\nFloating Point Exception\n" }, { "code": null, "e": 40913, "s": 40736, "text": "Example 2 :If while executing a program, one attempts for opening an unexisting file, that is, a file which is not present in the hard disk, it also results in a runtime error." }, { "code": null, "e": 40969, "s": 40913, "text": "6. Documentation : The program documentation involves :" }, { "code": null, "e": 41169, "s": 40969, "text": "Problem DefinitionProblem DesignDocumentation of test performHistory of program developmentUser’s manualA user’s manual is used by a user to know about a program’s input, processing, and output data." }, { "code": null, "e": 41188, "s": 41169, "text": "Problem Definition" }, { "code": null, "e": 41203, "s": 41188, "text": "Problem Design" }, { "code": null, "e": 41233, "s": 41203, "text": "Documentation of test perform" }, { "code": null, "e": 41264, "s": 41233, "text": "History of program development" }, { "code": null, "e": 41373, "s": 41264, "text": "User’s manualA user’s manual is used by a user to know about a program’s input, processing, and output data." }, { "code": null, "e": 41469, "s": 41373, "text": "A user’s manual is used by a user to know about a program’s input, processing, and output data." }, { "code": null, "e": 41767, "s": 41469, "text": "7. Program Maintenance: Once a program has been formed, to ensure its longevity, maintenance is a must. The maintenance of a program has its own costs associated with it, which may also exceed the development cost of the program in some cases. The maintenance of a program involves the following :" }, { "code": null, "e": 42017, "s": 41767, "text": "Detection and Elimination of undetected errors in the existing program.Modification of current program to enhance its performance andadaptability.Enhancement of user interfaceEnriching the program with new capabilities.Updation of the documentation." }, { "code": null, "e": 42089, "s": 42017, "text": "Detection and Elimination of undetected errors in the existing program." }, { "code": null, "e": 42165, "s": 42089, "text": "Modification of current program to enhance its performance andadaptability." }, { "code": null, "e": 42195, "s": 42165, "text": "Enhancement of user interface" }, { "code": null, "e": 42240, "s": 42195, "text": "Enriching the program with new capabilities." }, { "code": null, "e": 42271, "s": 42240, "text": "Updation of the documentation." }, { "code": null, "e": 42735, "s": 42271, "text": "There are codes which usually involve looping statements. Looping statements are statements in which instruction or a set of instructions is executed multiple times until a particular condition is satisfied. The while loop, for loop, do while loop, etc. form the basis of such looping structure. These statements are also called control structure because they determine or control the flow of instructions in a program. These looping structures are of two kinds :" }, { "code": null, "e": 43898, "s": 42735, "text": "Conditional Control ( Finite Looping )In this looping, the loop gets executed a finite number of times. Once a particular condition is satisfied, the loop gets terminated.Take an example in C language :#include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf(\"%d\\n\", i);}In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output:1\n2\n3\n4\n5\n6\n7\n8\n9\n10 //loop gets terminated\nInfinite LoopingThe infinite looping control structure is just the opposite of finite looping control structure. Here, the condition to terminate the loop never gets satisfied and hence, the loop gets executed infinitely.Take an example in C language :#include <stdio.h>void main(){ int n = 1; while (n <= 10) printf(\"%d\\n\", n);}In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output:1\n1\n1\n1\n1\n1\n..\n..\n.. //loop never terminates\n" }, { "code": null, "e": 44442, "s": 43898, "text": "Conditional Control ( Finite Looping )In this looping, the loop gets executed a finite number of times. Once a particular condition is satisfied, the loop gets terminated.Take an example in C language :#include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf(\"%d\\n\", i);}In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output:1\n2\n3\n4\n5\n6\n7\n8\n9\n10 //loop gets terminated\n" }, { "code": "#include <stdio.h>void main(){ int n = 1, i; for (i = n; i <= 10; i++) printf(\"%d\\n\", i);}", "e": 44546, "s": 44442, "text": null }, { "code": null, "e": 44740, "s": 44546, "text": "In the above program, the ‘for’ loop gets executed only until the value of i is less than or equal to 10. As soon as the value of i becomes greater than 10, the while loop is terminated.Output:" }, { "code": null, "e": 44786, "s": 44740, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10 //loop gets terminated\n" }, { "code": null, "e": 45406, "s": 44786, "text": "Infinite LoopingThe infinite looping control structure is just the opposite of finite looping control structure. Here, the condition to terminate the loop never gets satisfied and hence, the loop gets executed infinitely.Take an example in C language :#include <stdio.h>void main(){ int n = 1; while (n <= 10) printf(\"%d\\n\", n);}In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output:1\n1\n1\n1\n1\n1\n..\n..\n.. //loop never terminates\n" }, { "code": "#include <stdio.h>void main(){ int n = 1; while (n <= 10) printf(\"%d\\n\", n);}", "e": 45497, "s": 45406, "text": null }, { "code": null, "e": 45730, "s": 45497, "text": "In the above code, one can easily see that the value of n is not getting incremented. In such a case, the value of n will always remain 1 and hence the while loop will never get executed. Such loop is called an infinite loop.Output:" }, { "code": null, "e": 45776, "s": 45730, "text": "1\n1\n1\n1\n1\n1\n..\n..\n.. //loop never terminates\n" }, { "code": null, "e": 45789, "s": 45776, "text": "Akanksha_Rai" }, { "code": null, "e": 45799, "s": 45789, "text": "jaintarun" }, { "code": null, "e": 45815, "s": 45799, "text": "CBSE - Class 11" }, { "code": null, "e": 45822, "s": 45815, "text": "Picked" }, { "code": null, "e": 45841, "s": 45822, "text": "Programming Basics" }, { "code": null, "e": 45860, "s": 45841, "text": "school-programming" }, { "code": null, "e": 45879, "s": 45860, "text": "School Programming" }, { "code": null, "e": 45977, "s": 45879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45986, "s": 45977, "text": "Comments" }, { "code": null, "e": 45999, "s": 45986, "text": "Old Comments" }, { "code": null, "e": 46020, "s": 45999, "text": "Constructors in Java" }, { "code": null, "e": 46039, "s": 46020, "text": "Exceptions in Java" }, { "code": null, "e": 46066, "s": 46039, "text": "Ternary Operator in Python" }, { "code": null, "e": 46090, "s": 46066, "text": "Inline Functions in C++" }, { "code": null, "e": 46109, "s": 46090, "text": "Destructors in C++" }, { "code": null, "e": 46135, "s": 46109, "text": "Python Exception Handling" }, { "code": null, "e": 46191, "s": 46135, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 46242, "s": 46191, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 46268, "s": 46242, "text": "Exception Handling in C++" } ]
Program to print numbers from N to 1 in reverse order - GeeksforGeeks
26 Mar, 2021 Given a number N, the task is to print the numbers from N to 1.Examples: Input: N = 10 Output: 10 9 8 7 6 5 4 3 2 1Input: N = 7 Output: 7 6 5 4 3 2 1 Approach 1: Run a loop from N to 1 and print the value of N for each iteration. Decrement the value of N by 1 after each iteration.Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to print all numbers between 1// to N in reverse order #include <bits/stdc++.h>using namespace std; // Recursive function to print from N to 1void PrintReverseOrder(int N){ for (int i = N; i > 0; i--) cout << i << " "; } // Driven Codeint main(){ int N = 5; PrintReverseOrder(N); return 0;} // Java program to print all numbers between 1// to N in reverse orderimport java.util.*; class GFG { // Recursive function to print from N to 1static void PrintReverseOrder(int N){ for (int i = N; i > 0; i--) System.out.print( +i + " ");} // Driver codepublic static void main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by shivanisinghss2110 # Python3 program to print all numbers# between 1 to N in reverse order # Recursive function to print# from N to 1def PrintReverseOrder(N): for i in range(N, 0, -1): print(i, end = " "); # Driver codeif __name__ == '__main__': N = 5; PrintReverseOrder(N); # This code is contributed by 29AjayKumar // C# program to print all numbers// between 1 to N in reverse orderusing System; class GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ for(int i = N; i > 0; i--) Console.Write(i + " ");} // Driver codepublic static void Main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by Rajput-Ji <script> // Javascript program to print all numbers between 1 // to N in reverse order // Recursive function to print from N to 1 function PrintReverseOrder(N) { for (let i = N; i > 0; i--) document.write(i + " "); } let N = 5; PrintReverseOrder(N); </script> 5 4 3 2 1 Time Complexity: O(N) Auxiliary Space: O(1) Approach 2: We will use recursion to solve this problem. Check for the base case. Here it is N<=0.If base condition satisfied, return to the main function.If base condition not satisfied, print N and call the function recursively with value (N – 1) until base condition satisfies. Check for the base case. Here it is N<=0. If base condition satisfied, return to the main function. If base condition not satisfied, print N and call the function recursively with value (N – 1) until base condition satisfies. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program to print all numbers between 1// to N in reverse order #include <bits/stdc++.h>using namespace std; // Recursive function to print from N to 1void PrintReverseOrder(int N){ // if N is less than 1 // then return void function if (N <= 0) { return; } else { cout << N << " "; // recursive call of the function PrintReverseOrder(N - 1); }} // Driven Codeint main(){ int N = 5; PrintReverseOrder(N); return 0;} // Java program to print all numbers// between 1 to N in reverse orderclass GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ // If N is less than 1 then // return static void function if (N <= 0) { return; } else { System.out.print(N + " "); // Recursive call of the function PrintReverseOrder(N - 1); }} // Driver codepublic static void main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by 29AjayKumar # Python3 program to print all numbers between 1# to N in reverse order # Recursive function to print from N to 1def PrintReverseOrder(N): # if N is less than 1 # then return void function if (N <= 0): return; else: print(N, end = " "); # recursive call of the function PrintReverseOrder(N - 1); # Driver CodeN = 5;PrintReverseOrder(N); # This code is contributed by Nidhi_biet // C# program to print all numbers// between 1 to N in reverse orderusing System;class GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ // If N is less than 1 then // return static void function if (N <= 0) { return; } else { Console.Write(N + " "); // Recursive call of the function PrintReverseOrder(N - 1); }} // Driver codepublic static void Main(){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by Code_Mech <script> // Javascript program to print all numbers between 1 // to N in reverse order // Recursive function to print from N to 1 function PrintReverseOrder(N) { // if N is less than 1 // then return void function if (N <= 0) { return; } else { document.write(N + " "); // recursive call of the function PrintReverseOrder(N - 1); } } // Driver code let N = 5; PrintReverseOrder(N); // This code is contributed by suresh07. </script> 5 4 3 2 1 Time Complexity: O(N) Auxiliary Space: O(1) shivanisinghss2110 Rajput-Ji 29AjayKumar Code_Mech nidhi_biet subhammahato348 divyeshrabadiya07 suresh07 Natural Numbers Reverse Arrays Mathematical Recursion School Programming Arrays Mathematical Recursion Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25570, "s": 25542, "text": "\n26 Mar, 2021" }, { "code": null, "e": 25644, "s": 25570, "text": "Given a number N, the task is to print the numbers from N to 1.Examples: " }, { "code": null, "e": 25724, "s": 25644, "text": "Input: N = 10 Output: 10 9 8 7 6 5 4 3 2 1Input: N = 7 Output: 7 6 5 4 3 2 1 " }, { "code": null, "e": 25907, "s": 25724, "text": "Approach 1: Run a loop from N to 1 and print the value of N for each iteration. Decrement the value of N by 1 after each iteration.Below is the implementation of the above approach. " }, { "code": null, "e": 25911, "s": 25907, "text": "C++" }, { "code": null, "e": 25916, "s": 25911, "text": "Java" }, { "code": null, "e": 25924, "s": 25916, "text": "Python3" }, { "code": null, "e": 25927, "s": 25924, "text": "C#" }, { "code": null, "e": 25938, "s": 25927, "text": "Javascript" }, { "code": "// C++ program to print all numbers between 1// to N in reverse order #include <bits/stdc++.h>using namespace std; // Recursive function to print from N to 1void PrintReverseOrder(int N){ for (int i = N; i > 0; i--) cout << i << \" \"; } // Driven Codeint main(){ int N = 5; PrintReverseOrder(N); return 0;}", "e": 26266, "s": 25938, "text": null }, { "code": "// Java program to print all numbers between 1// to N in reverse orderimport java.util.*; class GFG { // Recursive function to print from N to 1static void PrintReverseOrder(int N){ for (int i = N; i > 0; i--) System.out.print( +i + \" \");} // Driver codepublic static void main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by shivanisinghss2110", "e": 26663, "s": 26266, "text": null }, { "code": "# Python3 program to print all numbers# between 1 to N in reverse order # Recursive function to print# from N to 1def PrintReverseOrder(N): for i in range(N, 0, -1): print(i, end = \" \"); # Driver codeif __name__ == '__main__': N = 5; PrintReverseOrder(N); # This code is contributed by 29AjayKumar", "e": 26987, "s": 26663, "text": null }, { "code": "// C# program to print all numbers// between 1 to N in reverse orderusing System; class GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ for(int i = N; i > 0; i--) Console.Write(i + \" \");} // Driver codepublic static void Main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by Rajput-Ji", "e": 27360, "s": 26987, "text": null }, { "code": "<script> // Javascript program to print all numbers between 1 // to N in reverse order // Recursive function to print from N to 1 function PrintReverseOrder(N) { for (let i = N; i > 0; i--) document.write(i + \" \"); } let N = 5; PrintReverseOrder(N); </script>", "e": 27678, "s": 27360, "text": null }, { "code": null, "e": 27688, "s": 27678, "text": "5 4 3 2 1" }, { "code": null, "e": 27712, "s": 27690, "text": "Time Complexity: O(N)" }, { "code": null, "e": 27734, "s": 27712, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27792, "s": 27734, "text": "Approach 2: We will use recursion to solve this problem. " }, { "code": null, "e": 28016, "s": 27792, "text": "Check for the base case. Here it is N<=0.If base condition satisfied, return to the main function.If base condition not satisfied, print N and call the function recursively with value (N – 1) until base condition satisfies." }, { "code": null, "e": 28058, "s": 28016, "text": "Check for the base case. Here it is N<=0." }, { "code": null, "e": 28116, "s": 28058, "text": "If base condition satisfied, return to the main function." }, { "code": null, "e": 28242, "s": 28116, "text": "If base condition not satisfied, print N and call the function recursively with value (N – 1) until base condition satisfies." }, { "code": null, "e": 28295, "s": 28242, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 28299, "s": 28295, "text": "C++" }, { "code": null, "e": 28304, "s": 28299, "text": "Java" }, { "code": null, "e": 28312, "s": 28304, "text": "Python3" }, { "code": null, "e": 28315, "s": 28312, "text": "C#" }, { "code": null, "e": 28326, "s": 28315, "text": "Javascript" }, { "code": "// C++ program to print all numbers between 1// to N in reverse order #include <bits/stdc++.h>using namespace std; // Recursive function to print from N to 1void PrintReverseOrder(int N){ // if N is less than 1 // then return void function if (N <= 0) { return; } else { cout << N << \" \"; // recursive call of the function PrintReverseOrder(N - 1); }} // Driven Codeint main(){ int N = 5; PrintReverseOrder(N); return 0;}", "e": 28806, "s": 28326, "text": null }, { "code": "// Java program to print all numbers// between 1 to N in reverse orderclass GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ // If N is less than 1 then // return static void function if (N <= 0) { return; } else { System.out.print(N + \" \"); // Recursive call of the function PrintReverseOrder(N - 1); }} // Driver codepublic static void main(String[] args){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by 29AjayKumar", "e": 29346, "s": 28806, "text": null }, { "code": "# Python3 program to print all numbers between 1# to N in reverse order # Recursive function to print from N to 1def PrintReverseOrder(N): # if N is less than 1 # then return void function if (N <= 0): return; else: print(N, end = \" \"); # recursive call of the function PrintReverseOrder(N - 1); # Driver CodeN = 5;PrintReverseOrder(N); # This code is contributed by Nidhi_biet", "e": 29774, "s": 29346, "text": null }, { "code": "// C# program to print all numbers// between 1 to N in reverse orderusing System;class GFG{ // Recursive function to print// from N to 1static void PrintReverseOrder(int N){ // If N is less than 1 then // return static void function if (N <= 0) { return; } else { Console.Write(N + \" \"); // Recursive call of the function PrintReverseOrder(N - 1); }} // Driver codepublic static void Main(){ int N = 5; PrintReverseOrder(N);}} // This code is contributed by Code_Mech", "e": 30307, "s": 29774, "text": null }, { "code": "<script> // Javascript program to print all numbers between 1 // to N in reverse order // Recursive function to print from N to 1 function PrintReverseOrder(N) { // if N is less than 1 // then return void function if (N <= 0) { return; } else { document.write(N + \" \"); // recursive call of the function PrintReverseOrder(N - 1); } } // Driver code let N = 5; PrintReverseOrder(N); // This code is contributed by suresh07. </script>", "e": 30891, "s": 30307, "text": null }, { "code": null, "e": 30901, "s": 30891, "text": "5 4 3 2 1" }, { "code": null, "e": 30925, "s": 30903, "text": "Time Complexity: O(N)" }, { "code": null, "e": 30947, "s": 30925, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30966, "s": 30947, "text": "shivanisinghss2110" }, { "code": null, "e": 30976, "s": 30966, "text": "Rajput-Ji" }, { "code": null, "e": 30988, "s": 30976, "text": "29AjayKumar" }, { "code": null, "e": 30998, "s": 30988, "text": "Code_Mech" }, { "code": null, "e": 31009, "s": 30998, "text": "nidhi_biet" }, { "code": null, "e": 31025, "s": 31009, "text": "subhammahato348" }, { "code": null, "e": 31043, "s": 31025, "text": "divyeshrabadiya07" }, { "code": null, "e": 31052, "s": 31043, "text": "suresh07" }, { "code": null, "e": 31068, "s": 31052, "text": "Natural Numbers" }, { "code": null, "e": 31076, "s": 31068, "text": "Reverse" }, { "code": null, "e": 31083, "s": 31076, "text": "Arrays" }, { "code": null, "e": 31096, "s": 31083, "text": "Mathematical" }, { "code": null, "e": 31106, "s": 31096, "text": "Recursion" }, { "code": null, "e": 31125, "s": 31106, "text": "School Programming" }, { "code": null, "e": 31132, "s": 31125, "text": "Arrays" }, { "code": null, "e": 31145, "s": 31132, "text": "Mathematical" }, { "code": null, "e": 31155, "s": 31145, "text": "Recursion" }, { "code": null, "e": 31163, "s": 31155, "text": "Reverse" }, { "code": null, "e": 31261, "s": 31163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31270, "s": 31261, "text": "Comments" }, { "code": null, "e": 31283, "s": 31270, "text": "Old Comments" }, { "code": null, "e": 31331, "s": 31283, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31375, "s": 31331, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31398, "s": 31375, "text": "Introduction to Arrays" }, { "code": null, "e": 31430, "s": 31398, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31444, "s": 31430, "text": "Linear Search" }, { "code": null, "e": 31474, "s": 31444, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31489, "s": 31474, "text": "C++ Data Types" }, { "code": null, "e": 31549, "s": 31489, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31592, "s": 31549, "text": "Set in C++ Standard Template Library (STL)" } ]
C/C++ Program for Finding the vertex, focus and directrix of a parabola - GeeksforGeeks
05 Dec, 2018 A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve. The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix. Example – Input : 5 3 2 Output : Vertex:(-0.3, 1.55) Focus: (-0.3, 1.6) Directrix: y=-198 Consult the formula below for explanation. #include <bits/stdc++.h>using namespace std; // Function to calculate Vertex, Focus and Directrixvoid parabola(float a, float b, float c){ cout << "Vertex: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b)) / (4 * a)) << ")" << endl; cout << "Focus: (" << (-b / (2 * a)) << ", " << (((4 * a * c) - (b * b) + 1) / (4 * a)) << ")" << endl; cout << "Directrix: y=" << c - ((b * b) + 1) * 4 * a << endl;} // Driver Functionint main(){ float a = 5, b = 3, c = 2; parabola(a, b, c); return 0;} Vertex: (-0.3, 1.55) Focus: (-0.3, 1.6) Directrix: y=-198 Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details! C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Regular expressions in C Handling multiple clients on server with multithreading using Socket Programming in C/C++ Exit codes in C/C++ with Examples Hamming code Implementation in C/C++ Conditional wait and signal in multi-threading C Hello World Program
[ { "code": null, "e": 24930, "s": 24902, "text": "\n05 Dec, 2018" }, { "code": null, "e": 25198, "s": 24930, "text": "A set of points on a plain surface that forms a curve such that any point on that curve is equidistant from the focus is a parabola.Vertex of a parabola is the coordinate from which it takes the sharpest turn whereas a is the straight line used to generate the curve." }, { "code": null, "e": 25364, "s": 25198, "text": "The standard form of a parabola equation is . Given the values of a, b and c; our task is to find the coordinates of vertex, focus and the equation of the directrix." }, { "code": null, "e": 25374, "s": 25364, "text": "Example –" }, { "code": null, "e": 25516, "s": 25374, "text": "Input : 5 3 2\nOutput : Vertex:(-0.3, 1.55)\n Focus: (-0.3, 1.6)\n Directrix: y=-198\nConsult the formula below for explanation.\n" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to calculate Vertex, Focus and Directrixvoid parabola(float a, float b, float c){ cout << \"Vertex: (\" << (-b / (2 * a)) << \", \" << (((4 * a * c) - (b * b)) / (4 * a)) << \")\" << endl; cout << \"Focus: (\" << (-b / (2 * a)) << \", \" << (((4 * a * c) - (b * b) + 1) / (4 * a)) << \")\" << endl; cout << \"Directrix: y=\" << c - ((b * b) + 1) * 4 * a << endl;} // Driver Functionint main(){ float a = 5, b = 3, c = 2; parabola(a, b, c); return 0;}", "e": 26070, "s": 25516, "text": null }, { "code": null, "e": 26129, "s": 26070, "text": "Vertex: (-0.3, 1.55)\nFocus: (-0.3, 1.6)\nDirectrix: y=-198\n" }, { "code": null, "e": 26234, "s": 26129, "text": "Please refer complete article on Finding the vertex, focus and directrix of a parabola for more details!" }, { "code": null, "e": 26245, "s": 26234, "text": "C Programs" }, { "code": null, "e": 26343, "s": 26245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26352, "s": 26343, "text": "Comments" }, { "code": null, "e": 26365, "s": 26352, "text": "Old Comments" }, { "code": null, "e": 26406, "s": 26365, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26437, "s": 26406, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26478, "s": 26437, "text": "C program to find the length of a string" }, { "code": null, "e": 26549, "s": 26478, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 26574, "s": 26549, "text": "Regular expressions in C" }, { "code": null, "e": 26664, "s": 26574, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 26698, "s": 26664, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 26735, "s": 26698, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 26782, "s": 26735, "text": "Conditional wait and signal in multi-threading" } ]
Absolute difference of Number arrays in JavaScript
Suppose, we have two arrays like these − const arr1 = [1,2,3,4,5,6]; const arr2 = [9,8,7,5,8,3]; We are required to write a JavaScript function that takes in such two arrays and returns an array of absolute difference between the corresponding elements of the array. So, for these arrays, the output should look like − const output = [8,6,4,1,3,3]; We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array. Therefore, let’s write the code for this function − The code for this will be − const arr1 = [1,2,3,4,5,6]; const arr2 = [9,8,7,5,8,3]; const absDifference = (arr1, arr2) => { const res = []; for(let i = 0; i < arr1.length; i++){ const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0)); res[i] = el; }; return res; }; console.log(absDifference(arr1, arr2)); The output in the console will be − [ 8, 6, 4, 1, 3, 3 ]
[ { "code": null, "e": 1103, "s": 1062, "text": "Suppose, we have two arrays like these −" }, { "code": null, "e": 1159, "s": 1103, "text": "const arr1 = [1,2,3,4,5,6];\nconst arr2 = [9,8,7,5,8,3];" }, { "code": null, "e": 1329, "s": 1159, "text": "We are required to write a JavaScript function that takes in such two arrays and returns an array of absolute difference between the corresponding elements of the array." }, { "code": null, "e": 1381, "s": 1329, "text": "So, for these arrays, the output should look like −" }, { "code": null, "e": 1411, "s": 1381, "text": "const output = [8,6,4,1,3,3];" }, { "code": null, "e": 1534, "s": 1411, "text": "We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array." }, { "code": null, "e": 1586, "s": 1534, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1614, "s": 1586, "text": "The code for this will be −" }, { "code": null, "e": 1913, "s": 1614, "text": "const arr1 = [1,2,3,4,5,6];\nconst arr2 = [9,8,7,5,8,3];\nconst absDifference = (arr1, arr2) => {\n const res = [];\n for(let i = 0; i < arr1.length; i++){\n const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0));\n res[i] = el;\n };\n return res;\n};\nconsole.log(absDifference(arr1, arr2));" }, { "code": null, "e": 1949, "s": 1913, "text": "The output in the console will be −" }, { "code": null, "e": 1970, "s": 1949, "text": "[ 8, 6, 4, 1, 3, 3 ]" } ]
Flutter - BorderSide Widget - GeeksforGeeks
21 Feb, 2022 BorderSide widget in flutter is a built-in widget whose function is to control the look and feel of individual sides of the border around a widget. Border widget in flutter also takes BorderSide as the object, which is the representative of individual sides. const BorderSide( {Color color: const Color(0xFF000000), double width: 1.0, BorderStyle style: BorderStyle.solid} ) color: The color property holds Color class (final) as the object, to assign a color to a border side. hashCode: This property takes an int value (override) as the object. This is responsible for the state representation of an object. style: The style property takes BorderStyle enum as the object. With the help of this property, we can control the style of the border-line drawn. width: This property takes a double value as the object. And it controls the width assigned to the individual side of the border. Example: Here we will see add border to an image. Dart import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment', onPressed: () {}, ), //IconButton ], //<Widget>[] ), //AppBar body: Center( child: Container( padding: EdgeInsets.all(8.0), decoration: BoxDecoration( border: Border( top: BorderSide( width: 16.0, color: Colors.lightGreen.shade300, style: BorderStyle.solid), //BorderSide ), //Border ), //BoxDecoration //Image.network child: Image.network( 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/logo.png'), ), //Container ), //Center ), //Scaffold debugShowCheckedModeBanner: false, ), //MaterialApp );} Output: Explanation: In this app, the BorderSide widget is put as the object to top, which is a property of Border widget to describe the border side on top of the element (or in this case geeksforgeeks logo). A width of 16.0 px has been given to the border, the color is set to lightGreen.shade300 and at last the style property is set to solid (which makes it visible). // style property set to none ... style: BorderStyle.none //BorderSide ... If style property is set as above. The output will be. BorderStyle.none To add a bottom border we have to do these changes. ... border: Border( top: BorderSide( width: 16.0, color: Colors.lightGreen.shade300), bottom: BorderSide( width: 16.0, color: Colors.lightGreen.shade900), ), ... Output: Bottom border This is how we can add a left border to the image. ... border: Border( top: BorderSide( width: 16.0, color: Colors.lightGreen.shade300), left: BorderSide( width: 16.0, color: Colors.lightGreen.shade300), bottom: BorderSide( width: 16.0, color: Colors.lightGreen.shade900), ), ... Output: Left border And, this is how we all border in all four sides using the BorderSide widget. ... border: Border( top: BorderSide( width: 16.0, color: Colors.lightGreen.shade300, style: BorderStyle.solid), left: BorderSide( width: 16.0, color: Colors.lightGreen.shade300), bottom: BorderSide( width: 16.0, color: Colors.lightGreen.shade900), right: BorderSide( width: 16.0, color: Colors.lightGreen.shade900), ), ... Output: Border in all four sides simranarora5sos android Flutter Flutter-widgets Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 24338, "s": 24310, "text": "\n21 Feb, 2022" }, { "code": null, "e": 24597, "s": 24338, "text": "BorderSide widget in flutter is a built-in widget whose function is to control the look and feel of individual sides of the border around a widget. Border widget in flutter also takes BorderSide as the object, which is the representative of individual sides." }, { "code": null, "e": 24713, "s": 24597, "text": "const BorderSide(\n{Color color: const Color(0xFF000000),\ndouble width: 1.0,\nBorderStyle style: BorderStyle.solid}\n)" }, { "code": null, "e": 24816, "s": 24713, "text": "color: The color property holds Color class (final) as the object, to assign a color to a border side." }, { "code": null, "e": 24948, "s": 24816, "text": "hashCode: This property takes an int value (override) as the object. This is responsible for the state representation of an object." }, { "code": null, "e": 25095, "s": 24948, "text": "style: The style property takes BorderStyle enum as the object. With the help of this property, we can control the style of the border-line drawn." }, { "code": null, "e": 25226, "s": 25095, "text": "width: This property takes a double value as the object. And it controls the width assigned to the individual side of the border." }, { "code": null, "e": 25276, "s": 25226, "text": "Example: Here we will see add border to an image." }, { "code": null, "e": 25281, "s": 25276, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Menu', onPressed: () {}, ), //IconButton actions: <Widget>[ IconButton( icon: Icon(Icons.comment), tooltip: 'Comment', onPressed: () {}, ), //IconButton ], //<Widget>[] ), //AppBar body: Center( child: Container( padding: EdgeInsets.all(8.0), decoration: BoxDecoration( border: Border( top: BorderSide( width: 16.0, color: Colors.lightGreen.shade300, style: BorderStyle.solid), //BorderSide ), //Border ), //BoxDecoration //Image.network child: Image.network( 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/logo.png'), ), //Container ), //Center ), //Scaffold debugShowCheckedModeBanner: false, ), //MaterialApp );}", "e": 26563, "s": 25281, "text": null }, { "code": null, "e": 26571, "s": 26563, "text": "Output:" }, { "code": null, "e": 26936, "s": 26571, "text": "Explanation: In this app, the BorderSide widget is put as the object to top, which is a property of Border widget to describe the border side on top of the element (or in this case geeksforgeeks logo). A width of 16.0 px has been given to the border, the color is set to lightGreen.shade300 and at last the style property is set to solid (which makes it visible)." }, { "code": null, "e": 27025, "s": 26936, "text": " // style property set to none\n ... \n style: BorderStyle.none //BorderSide\n ..." }, { "code": null, "e": 27080, "s": 27025, "text": "If style property is set as above. The output will be." }, { "code": null, "e": 27097, "s": 27080, "text": "BorderStyle.none" }, { "code": null, "e": 27149, "s": 27097, "text": "To add a bottom border we have to do these changes." }, { "code": null, "e": 27442, "s": 27149, "text": "...\n border: Border(\n top: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade300),\n bottom: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade900),\n ),\n... " }, { "code": null, "e": 27451, "s": 27442, "text": "Output: " }, { "code": null, "e": 27466, "s": 27451, "text": "Bottom border " }, { "code": null, "e": 27517, "s": 27466, "text": "This is how we can add a left border to the image." }, { "code": null, "e": 27899, "s": 27517, "text": "...\n border: Border(\n top: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade300),\n left: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade300),\n bottom: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade900),\n ),\n... " }, { "code": null, "e": 27907, "s": 27899, "text": "Output:" }, { "code": null, "e": 27919, "s": 27907, "text": "Left border" }, { "code": null, "e": 27997, "s": 27919, "text": "And, this is how we all border in all four sides using the BorderSide widget." }, { "code": null, "e": 28541, "s": 27997, "text": "...\n border: Border(\n top: BorderSide(\n width: 16.0,\n color: Colors.lightGreen.shade300,\n style: BorderStyle.solid),\n left: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade300),\n bottom: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade900),\n right: BorderSide(\n width: 16.0, color: Colors.lightGreen.shade900),\n ),\n..." }, { "code": null, "e": 28549, "s": 28541, "text": "Output:" }, { "code": null, "e": 28574, "s": 28549, "text": "Border in all four sides" }, { "code": null, "e": 28590, "s": 28574, "text": "simranarora5sos" }, { "code": null, "e": 28598, "s": 28590, "text": "android" }, { "code": null, "e": 28606, "s": 28598, "text": "Flutter" }, { "code": null, "e": 28622, "s": 28606, "text": "Flutter-widgets" }, { "code": null, "e": 28630, "s": 28622, "text": "Android" }, { "code": null, "e": 28635, "s": 28630, "text": "Dart" }, { "code": null, "e": 28643, "s": 28635, "text": "Flutter" }, { "code": null, "e": 28651, "s": 28643, "text": "Android" }, { "code": null, "e": 28749, "s": 28651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28758, "s": 28749, "text": "Comments" }, { "code": null, "e": 28771, "s": 28758, "text": "Old Comments" }, { "code": null, "e": 28814, "s": 28771, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28872, "s": 28814, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 28905, "s": 28872, "text": "Services in Android with Example" }, { "code": null, "e": 28947, "s": 28905, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28978, "s": 28947, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29006, "s": 28978, "text": "Listview.builder in Flutter" }, { "code": null, "e": 29038, "s": 29006, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 29060, "s": 29038, "text": "Flutter - Asset Image" }, { "code": null, "e": 29085, "s": 29060, "text": "Splash Screen in Flutter" } ]
XPath - Comparison Operators
XPath defines following comparison operators to be used with the XPath expressions. = is equals to != is not equals to < is less than > is greater than <= is less than or equals to >= is greater than or equals to This example creates a table of <student> element with its attribute roll no and its child <firstname>,<lastname><nickname> and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details. <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "class/student"> <xsl:if test = "marks > 90"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:if> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> 90 Lectures 20 hours Arun Motoori 23 Lectures 8 hours Sanjay Kumar 13 Lectures 1.5 hours Sanjay Kumar 24 Lectures 1.5 hours Sanjay Kumar 47 Lectures 3 hours Krishna Sakinala Print Add Notes Bookmark this page
[ { "code": null, "e": 1813, "s": 1729, "text": "XPath defines following comparison operators to be used with the XPath expressions." }, { "code": null, "e": 1815, "s": 1813, "text": "=" }, { "code": null, "e": 1828, "s": 1815, "text": "is equals to" }, { "code": null, "e": 1831, "s": 1828, "text": "!=" }, { "code": null, "e": 1848, "s": 1831, "text": "is not equals to" }, { "code": null, "e": 1850, "s": 1848, "text": "<" }, { "code": null, "e": 1863, "s": 1850, "text": "is less than" }, { "code": null, "e": 1865, "s": 1863, "text": ">" }, { "code": null, "e": 1881, "s": 1865, "text": "is greater than" }, { "code": null, "e": 1884, "s": 1881, "text": "<=" }, { "code": null, "e": 1910, "s": 1884, "text": "is less than or equals to" }, { "code": null, "e": 1913, "s": 1910, "text": ">=" }, { "code": null, "e": 1942, "s": 1913, "text": "is greater than or equals to" }, { "code": null, "e": 2188, "s": 1942, "text": "This example creates a table of <student> element with its attribute roll no and its child <firstname>,<lastname><nickname> and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details." }, { "code": null, "e": 2790, "s": 2188, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 3944, "s": 2790, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n\n <xsl:template match = \"/\">\n <html>\n <body>\n <h2>Students</h2>\n\t\t\t\t\t\n <table border = \"1\">\n <tr bgcolor = \"#9acd32\">\n <th>Roll No</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Nick Name</th>\n <th>Marks</th>\n </tr>\n\t\t\t\t\t\t\n <xsl:for-each select = \"class/student\">\n <xsl:if test = \"marks > 90\">\n <tr>\n <td><xsl:value-of select = \"@rollno\"/></td>\n <td><xsl:value-of select = \"firstname\"/></td>\n <td><xsl:value-of select = \"lastname\"/></td>\n <td><xsl:value-of select = \"nickname\"/></td>\n <td><xsl:value-of select = \"marks\"/></td>\n </tr>\n </xsl:if>\n </xsl:for-each>\n </table>\n </body>\n </html>\n </xsl:template>\n</xsl:stylesheet>" }, { "code": null, "e": 3978, "s": 3944, "text": "\n 90 Lectures \n 20 hours \n" }, { "code": null, "e": 3992, "s": 3978, "text": " Arun Motoori" }, { "code": null, "e": 4025, "s": 3992, "text": "\n 23 Lectures \n 8 hours \n" }, { "code": null, "e": 4039, "s": 4025, "text": " Sanjay Kumar" }, { "code": null, "e": 4074, "s": 4039, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4088, "s": 4074, "text": " Sanjay Kumar" }, { "code": null, "e": 4123, "s": 4088, "text": "\n 24 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4137, "s": 4123, "text": " Sanjay Kumar" }, { "code": null, "e": 4170, "s": 4137, "text": "\n 47 Lectures \n 3 hours \n" }, { "code": null, "e": 4188, "s": 4170, "text": " Krishna Sakinala" }, { "code": null, "e": 4195, "s": 4188, "text": " Print" }, { "code": null, "e": 4206, "s": 4195, "text": " Add Notes" } ]
GATE | GATE-CS-2014-(Set-1) | Question 34 - GeeksforGeeks
28 Jun, 2021 Which of the following are used to generate a message digest by the network security protocols? (P) RSA (Q) SHA-1 (R) DES (S) MD5 (A) P and R only(B) Q and R only(C) Q and S only(D) R and S onlyAnswer: (C)Explanation: RSA – It is an algorithm used to encrypt and decrypt messages. SHA 1 – Secure Hash Algorithm 1, or SHA 1 is a cryptographic hash function. It produces a 160 bit (20 byte) hash value (message digest). DES – Data Encryption Standard, or DES is a symmetric key algorithm for encryption of electronic data. MD5 – Message Digest 5, or MD5 is a widely used cryptographic hash function that produces a 128 bit hash value (message digest). Q and S i.e SHA 1 and MD5 are used to generate a message digest by the network security protocols. So, C is the correct choice.Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2012 | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24171, "s": 24075, "text": "Which of the following are used to generate a message digest by the network security protocols?" }, { "code": null, "e": 24208, "s": 24171, "text": "(P) RSA \n(Q) SHA-1 \n(R) DES \n(S) MD5" }, { "code": null, "e": 24296, "s": 24208, "text": "(A) P and R only(B) Q and R only(C) Q and S only(D) R and S onlyAnswer: (C)Explanation:" }, { "code": null, "e": 24359, "s": 24296, "text": "RSA – It is an algorithm used to encrypt and decrypt messages." }, { "code": null, "e": 24496, "s": 24359, "text": "SHA 1 – Secure Hash Algorithm 1, or SHA 1 is a cryptographic hash function. It produces a 160 bit (20 byte) hash value (message digest)." }, { "code": null, "e": 24599, "s": 24496, "text": "DES – Data Encryption Standard, or DES is a symmetric key algorithm for encryption of electronic data." }, { "code": null, "e": 24728, "s": 24599, "text": "MD5 – Message Digest 5, or MD5 is a widely used cryptographic hash function that produces a 128 bit hash value (message digest)." }, { "code": null, "e": 24827, "s": 24728, "text": "Q and S i.e SHA 1 and MD5 are used to generate a message digest by the network security protocols." }, { "code": null, "e": 24877, "s": 24827, "text": "So, C is the correct choice.Quiz of this Question" }, { "code": null, "e": 24898, "s": 24877, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 24924, "s": 24898, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 24929, "s": 24924, "text": "GATE" }, { "code": null, "e": 25027, "s": 24929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25036, "s": 25027, "text": "Comments" }, { "code": null, "e": 25049, "s": 25036, "text": "Old Comments" }, { "code": null, "e": 25091, "s": 25049, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25133, "s": 25091, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25167, "s": 25133, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25209, "s": 25167, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25263, "s": 25209, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25296, "s": 25263, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25338, "s": 25296, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25380, "s": 25338, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25414, "s": 25380, "text": "GATE | GATE CS 2011 | Question 65" } ]
BFS vs DFS for Binary Tree in C++?
BFS (Breadth First Search) − It is a tree traversal algorithm that is also known as Level Order Tree Traversal. In this traversal we will traverse the tree row by row i.e. 1st row, then 2nd row, and so on. DFS (Depth First Search ) − It is a tree traversal algorithm that traverses the structure to its deepest node. There are three most used methods that are used to traverse the tree using DFS. it goes into depth of each node as the root node and then goes to the next one. Let’s find the traversal of a tree using both these methods − BFS traversal : A B K M S T DFS traversal : Preorder : A M N K S T PostOrder: M B S T K A InOrder: M B A S K T Now, as we know the usage of both algorithms have Some similarities and some differences in their applications. And both have found applications in dynamic programming, so let’s see who these things work. The time complexity of both BFS and DFS is O(n). The time complexity of both BFS and DFS is O(n). Space required for traversal in BFS is of the order of width O(w) whereas the space required for traversal in DFS is of the order of height O(h) of the tree. Space required for traversal in BFS is of the order of width O(w) whereas the space required for traversal in DFS is of the order of height O(h) of the tree. Implementation of BFS tree traversal algorithm, Live Demo #include <iostream> #include using namespace std; struct Node { int data; struct Node *left, *right; }; Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } int main() { Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Level Order traversal of binary tree is \n"; queue<Node *> q; q.push(root); while (q.empty() == false) { Node *node = q.front(); cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } return 0; } Level Order traversal of binary tree is 1 2 3 4 5 Implementation of DFS tree traversal algorithm, Live Demo #include <iostream> using namespace std; struct Node { int data; struct Node* left, *right; Node(int data) { this->data = data; left = right = NULL; } }; void printPostorder(struct Node* node) { if (node == NULL) return; printPostorder(node->left); printPostorder(node->right); cout << node->data << " "; } void printInorder(struct Node* node) { if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right); } void printPreorder(struct Node* node) { if (node == NULL) return; cout << node->data << " "; printPreorder(node->left); printPreorder(node->right); } int main() { struct Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); cout << "\nPreorder traversal of binary tree is \n"; printPreorder(root); cout << "\nInorder traversal of binary tree is \n"; printInorder(root); cout << "\nPostorder traversal of binary tree is \n"; printPostorder(root); return 0; } Preorder traversal of binary tree is 1 2 4 5 3 Inorder traversal of binary tree is 4 2 5 1 3 Postorder traversal of binary tree is 4 5 2 3 1
[ { "code": null, "e": 1268, "s": 1062, "text": "BFS (Breadth First Search) − It is a tree traversal algorithm that is also known as Level Order Tree Traversal. In this traversal we will traverse the tree row by row i.e. 1st row, then 2nd row, and so on." }, { "code": null, "e": 1539, "s": 1268, "text": "DFS (Depth First Search ) − It is a tree traversal algorithm that traverses the structure to its deepest node. There are three most used methods that are used to traverse the tree using DFS. it goes into depth of each node as the root node and then goes to the next one." }, { "code": null, "e": 1601, "s": 1539, "text": "Let’s find the traversal of a tree using both these methods −" }, { "code": null, "e": 1712, "s": 1601, "text": "BFS traversal : A B K M S T\nDFS traversal :\nPreorder : A M N K S T\nPostOrder: M B S T K A\nInOrder: M B A S K T" }, { "code": null, "e": 1917, "s": 1712, "text": "Now, as we know the usage of both algorithms have Some similarities and some differences in their applications. And both have found applications in dynamic programming, so let’s see who these things work." }, { "code": null, "e": 1966, "s": 1917, "text": "The time complexity of both BFS and DFS is O(n)." }, { "code": null, "e": 2015, "s": 1966, "text": "The time complexity of both BFS and DFS is O(n)." }, { "code": null, "e": 2173, "s": 2015, "text": "Space required for traversal in BFS is of the order of width O(w) whereas the space required for traversal in DFS is of the order of height O(h) of the tree." }, { "code": null, "e": 2331, "s": 2173, "text": "Space required for traversal in BFS is of the order of width O(w) whereas the space required for traversal in DFS is of the order of height O(h) of the tree." }, { "code": null, "e": 2379, "s": 2331, "text": "Implementation of BFS tree traversal algorithm," }, { "code": null, "e": 2390, "s": 2379, "text": " Live Demo" }, { "code": null, "e": 3140, "s": 2390, "text": "#include <iostream>\n#include \nusing namespace std;\nstruct Node {\n int data;\n struct Node *left, *right;\n};\nNode* newNode(int data) {\n Node *temp = new Node;\n temp->data = data;\n temp->left = temp->right = NULL;\n return temp;\n}\nint main() {\n Node *root = newNode(1);\n root->left = newNode(2);\n root->right = newNode(3);\n root->left->left = newNode(4);\n root->left->right = newNode(5);\n cout << \"Level Order traversal of binary tree is \\n\";\n queue<Node *> q;\n q.push(root);\n while (q.empty() == false) {\n Node *node = q.front();\n cout << node->data << \" \";\n q.pop();\n if (node->left != NULL)\n q.push(node->left);\n if (node->right != NULL)\n q.push(node->right);\n }\n return 0;\n}" }, { "code": null, "e": 3190, "s": 3140, "text": "Level Order traversal of binary tree is\n1 2 3 4 5" }, { "code": null, "e": 3238, "s": 3190, "text": "Implementation of DFS tree traversal algorithm," }, { "code": null, "e": 3249, "s": 3238, "text": " Live Demo" }, { "code": null, "e": 4365, "s": 3249, "text": "#include <iostream>\nusing namespace std;\nstruct Node {\n int data;\n struct Node* left, *right;\n Node(int data) {\n this->data = data;\n left = right = NULL;\n }\n};\nvoid printPostorder(struct Node* node) {\n if (node == NULL)\n return;\n printPostorder(node->left);\n printPostorder(node->right);\n cout << node->data << \" \";\n}\nvoid printInorder(struct Node* node) {\n if (node == NULL)\n return;\n printInorder(node->left);\n cout << node->data << \" \";\n printInorder(node->right);\n}\nvoid printPreorder(struct Node* node) {\n if (node == NULL)\n return;\n cout << node->data << \" \";\n printPreorder(node->left);\n printPreorder(node->right);\n}\nint main() {\n struct Node *root = new Node(1);\n root->left = new Node(2);\n root->right = new Node(3);\n root->left->left = new Node(4);\n root->left->right = new Node(5);\n cout << \"\\nPreorder traversal of binary tree is \\n\";\n printPreorder(root);\n cout << \"\\nInorder traversal of binary tree is \\n\";\n printInorder(root);\n cout << \"\\nPostorder traversal of binary tree is \\n\";\n printPostorder(root);\n return 0;\n}" }, { "code": null, "e": 4506, "s": 4365, "text": "Preorder traversal of binary tree is\n1 2 4 5 3\nInorder traversal of binary tree is\n4 2 5 1 3\nPostorder traversal of binary tree is\n4 5 2 3 1" } ]
Updating a record in MySQL using NodeJS
In this article, we will see how we can update a record in MySQL using NodeJS. We will dynamically update MySQL table values from Node.js server. You can use the select statement after updating to check if the MySql record is updated. Before proceeding, please check the following steps are already executed − mkdir mysql-test mkdir mysql-test cd mysql-test cd mysql-test npm init -y npm init -y npm install mysql npm install mysql The above steps are for installing the Node - mysql dependecy in the project folder. For updating an existing record into the MySQL table, firstly create an app.js file For updating an existing record into the MySQL table, firstly create an app.js file Now copy-paste the below snippet in the file Now copy-paste the below snippet in the file Run the code using the following command Run the code using the following command >> node app.js // Checking the MySQL dependency in NPM var mysql = require('mysql'); // Creating a mysql connection var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';" con.query(sql, function (err, result) { if (err) throw err; console.log(result.affectedRows + " Record(s) updated."); console.log(result); }); }); 1 Record(s) updated. OkPacket { fieldCount: 0, affectedRows: 1, // This will return the number of rows updated. insertId: 0, serverStatus: 34, warningCount: 0, message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the number of rows matched. protocol41: true, changedRows: 1 } // Checking the MySQL dependency in NPM var mysql = require('mysql'); // Creating a mysql connection var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) throw err; // Updating the fields with address while checking the address var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';" con.query(sql, function (err, result) { if (err) throw err; console.log(result.affectedRows + " Record(s) updated."); console.log(result); }); }); 3 Record(s) updated. OkPacket { fieldCount: 0, affectedRows: 3, // This will return the number of rows updated. insertId: 0, serverStatus: 34, warningCount: 0, message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched. protocol41: true, changedRows: 3 }
[ { "code": null, "e": 1297, "s": 1062, "text": "In this article, we will see how we can update a record in MySQL using NodeJS. We will dynamically update MySQL table values from Node.js server. You can use the select statement after updating to check if the MySql record is updated." }, { "code": null, "e": 1372, "s": 1297, "text": "Before proceeding, please check the following steps are already executed −" }, { "code": null, "e": 1389, "s": 1372, "text": "mkdir mysql-test" }, { "code": null, "e": 1406, "s": 1389, "text": "mkdir mysql-test" }, { "code": null, "e": 1420, "s": 1406, "text": "cd mysql-test" }, { "code": null, "e": 1434, "s": 1420, "text": "cd mysql-test" }, { "code": null, "e": 1446, "s": 1434, "text": "npm init -y" }, { "code": null, "e": 1458, "s": 1446, "text": "npm init -y" }, { "code": null, "e": 1476, "s": 1458, "text": "npm install mysql" }, { "code": null, "e": 1494, "s": 1476, "text": "npm install mysql" }, { "code": null, "e": 1579, "s": 1494, "text": "The above steps are for installing the Node - mysql dependecy in the project folder." }, { "code": null, "e": 1663, "s": 1579, "text": "For updating an existing record into the MySQL table, firstly create an app.js file" }, { "code": null, "e": 1747, "s": 1663, "text": "For updating an existing record into the MySQL table, firstly create an app.js file" }, { "code": null, "e": 1792, "s": 1747, "text": "Now copy-paste the below snippet in the file" }, { "code": null, "e": 1837, "s": 1792, "text": "Now copy-paste the below snippet in the file" }, { "code": null, "e": 1878, "s": 1837, "text": "Run the code using the following command" }, { "code": null, "e": 1919, "s": 1878, "text": "Run the code using the following command" }, { "code": null, "e": 1934, "s": 1919, "text": ">> node app.js" }, { "code": null, "e": 2471, "s": 1934, "text": "// Checking the MySQL dependency in NPM\nvar mysql = require('mysql');\n\n// Creating a mysql connection\nvar con = mysql.createConnection({\n host: \"localhost\",\n user: \"yourusername\",\n password: \"yourpassword\",\n database: \"mydb\"\n});\n\ncon.connect(function(err) {\n if (err) throw err;\n var sql = \"UPDATE student SET address = 'Bangalore' WHERE name = 'John';\"\n con.query(sql, function (err, result) {\n if (err) throw err;\n console.log(result.affectedRows + \" Record(s) updated.\");\n console.log(result);\n });\n});" }, { "code": null, "e": 2793, "s": 2471, "text": "1 Record(s) updated.\nOkPacket {\n fieldCount: 0,\n affectedRows: 1, // This will return the number of rows updated.\n insertId: 0,\n serverStatus: 34,\n warningCount: 0,\n message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the\n number of rows matched.\n protocol41: true,\n changedRows: 1 }" }, { "code": null, "e": 3400, "s": 2793, "text": "// Checking the MySQL dependency in NPM\nvar mysql = require('mysql');\n\n// Creating a mysql connection\nvar con = mysql.createConnection({\n host: \"localhost\",\n user: \"yourusername\",\n password: \"yourpassword\",\n database: \"mydb\"\n});\n\ncon.connect(function(err) {\n if (err) throw err;\n // Updating the fields with address while checking the address\n var sql = \"UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';\"\n con.query(sql, function (err, result) {\n if (err) throw err;\n console.log(result.affectedRows + \" Record(s) updated.\");\n console.log(result);\n });\n});" }, { "code": null, "e": 3719, "s": 3400, "text": "3 Record(s) updated.\nOkPacket {\n fieldCount: 0,\n affectedRows: 3, // This will return the number of rows updated.\n insertId: 0,\n serverStatus: 34,\n warningCount: 0,\n message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched.\n protocol41: true,\n changedRows: 3 }" } ]
Amazon RDS - Oracle DBA Tasks
As an industry leading database technology, oracle has many in-built features which makes it easy to manage the DBA activities, even in the cloud. The Amazon RDS oracle DB provides access to many stored procedures and functions which can be accessed using the SQL developer client tool. This procedure can be executed using the user ID and password created during the Amazon RDS instance creation. Below are the examples of some of the most frequently used DBA activities. Sometimes a long running query or any other DB activity needs to be killed by killing the session. We use the Amazon RDS procedure rdsadmin.rdsadmin_util.kill to kill a session. The following code does that. # First get the session identifier and the session serial number, select SID, SERIAL#, STATUS from V$SESSION where USERNAME = 'AWSUSER'; # Next use the procedure begin rdsadmin.rdsadmin_util.kill( sid => sid, serial => serial_number); end; / The Amazon RDS procedure rdsadmin.rdsadmin_util.alter_default_tablespace can be used to set to the default tablespace for a DB using the following command. exec rdsadmin.rdsadmin_util.alter_default_tablespace(tablespace_name => 'AWSuser'); We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.alter_db_time_zone to changes the time zone for the DB. # Change the time zone of the DB to UTC + 5.30 exec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => '+5:30'); # Change the time zone to a specific region exec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => 'Asia/Kolkata'); We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.add_logfile to add additional redo logs. The following command adds a log file of size 128MB. exec rdsadmin.rdsadmin_util.add_logfile(p_size => '128M'); Print Add Notes Bookmark this page
[ { "code": null, "e": 3058, "s": 2585, "text": "As an industry leading database technology, oracle has many in-built features which makes it easy to manage the DBA activities, even in the cloud. The Amazon RDS oracle DB provides access to many stored procedures and functions which can be accessed using the SQL developer client tool. This procedure can be executed using the user ID and password created during the Amazon RDS instance creation. Below are the examples of some of the most frequently used DBA activities." }, { "code": null, "e": 3266, "s": 3058, "text": "Sometimes a long running query or any other DB activity needs to be killed by killing the session. We use the Amazon RDS procedure rdsadmin.rdsadmin_util.kill to kill a session. The following code does that." }, { "code": null, "e": 3535, "s": 3266, "text": "# First get the session identifier and the session serial number,\nselect SID, SERIAL#, STATUS from V$SESSION where USERNAME = 'AWSUSER';\n\n# Next use the procedure \nbegin\n rdsadmin.rdsadmin_util.kill(\n sid => sid, \n serial => serial_number);\nend;\n/\n" }, { "code": null, "e": 3691, "s": 3535, "text": "The Amazon RDS procedure rdsadmin.rdsadmin_util.alter_default_tablespace can be used to set to the default tablespace for a DB using the following command." }, { "code": null, "e": 3776, "s": 3691, "text": "exec rdsadmin.rdsadmin_util.alter_default_tablespace(tablespace_name => 'AWSuser');\n" }, { "code": null, "e": 3891, "s": 3776, "text": "We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.alter_db_time_zone to changes the time zone for the DB." }, { "code": null, "e": 4128, "s": 3891, "text": "# Change the time zone of the DB to UTC + 5.30 \nexec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => '+5:30');\n# Change the time zone to a specific region\nexec rdsadmin.rdsadmin_util.alter_db_time_zone(p_new_tz => 'Asia/Kolkata');" }, { "code": null, "e": 4281, "s": 4128, "text": "We can use the Amazon RDS procedure rdsadmin.rdsadmin_util.add_logfile to add additional redo logs. The following command adds a log file of size 128MB." }, { "code": null, "e": 4340, "s": 4281, "text": "exec rdsadmin.rdsadmin_util.add_logfile(p_size => '128M');" }, { "code": null, "e": 4347, "s": 4340, "text": " Print" }, { "code": null, "e": 4358, "s": 4347, "text": " Add Notes" } ]
How to find the Number of CPU Cores in C#?
There are several different pieces of information relating to processors that we can get Number of physical processors Number of cores Number of logical processors These can all be different; in the case of a machine with 2 dual-core hyper-threadingenabled processors, there are 2 physical processors, 4 cores, and 8 logical processors. The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems) − Add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package. class Program{ public static void Main(){ foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()){ Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]); } Console.ReadLine(); } } Number Of Physical Processors: 1 class Program{ public static void Main(){ int coreCount = 0; foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()){ coreCount += int.Parse(item["NumberOfCores"].ToString()); } Console.WriteLine("Number Of Cores: {0}", coreCount); Console.ReadLine(); } } Number Of Cores: 2 class Program{ public static void Main(){ Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount); Console.ReadLine(); } } Number Of Logical Processors: 4
[ { "code": null, "e": 1151, "s": 1062, "text": "There are several different pieces of information relating to processors that we can get" }, { "code": null, "e": 1181, "s": 1151, "text": "Number of physical processors" }, { "code": null, "e": 1197, "s": 1181, "text": "Number of cores" }, { "code": null, "e": 1226, "s": 1197, "text": "Number of logical processors" }, { "code": null, "e": 1399, "s": 1226, "text": "These can all be different; in the case of a machine with 2 dual-core hyper-threadingenabled\nprocessors, there are 2 physical processors, 4 cores, and 8 logical processors." }, { "code": null, "e": 1621, "s": 1399, "text": "The number of logical processors is available through the Environment class, but the\nother information is only available through WMI (and you may have to install some\nhotfixes or service packs to get it on some systems) −" }, { "code": null, "e": 1749, "s": 1621, "text": "Add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package." }, { "code": null, "e": 2071, "s": 1749, "text": "class Program{\n public static void Main(){\n foreach (var item in new\n System.Management.ManagementObjectSearcher(\"Select * from\n Win32_ComputerSystem\").Get()){\n Console.WriteLine(\"Number Of Physical Processors: {0} \",\n item[\"NumberOfProcessors\"]);\n }\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2104, "s": 2071, "text": "Number Of Physical Processors: 1" }, { "code": null, "e": 2469, "s": 2104, "text": "class Program{\n public static void Main(){\n int coreCount = 0;\n foreach (var item in new\n System.Management.ManagementObjectSearcher(\"Select * from\n Win32_Processor\").Get()){\n coreCount += int.Parse(item[\"NumberOfCores\"].ToString());\n }\n Console.WriteLine(\"Number Of Cores: {0}\", coreCount);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2488, "s": 2469, "text": "Number Of Cores: 2" }, { "code": null, "e": 2662, "s": 2488, "text": "class Program{\n public static void Main(){\n Console.WriteLine(\"Number Of Logical Processors: {0}\",\n Environment.ProcessorCount);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2694, "s": 2662, "text": "Number Of Logical Processors: 4" } ]
How Machine Learning Recommends Movies for You | by Tommy | Towards Data Science
In this article, let’s discuss a project that articulates on how Machine Learning algorithm recommend what is the next movie that you might want to watch by using the Recommender System. This approach not only can be implemented for movie contents, but also for other digital objects chosen distinctively for each user, for instance, books, web pages, music, messages, products, dating preference, and of course, movies that have been widely executed by several companies to improve their customer experience within their digital platforms. There are three types of recommender systems that will be implemented in this project, which are: Demographic Filtering offers users with similar demographic background the similar movies that are popular and well-rated regardless of the genre or any other factors. Therefore, since it does not consider the individual taste of each person, it provides a simple result but easy to be implemented. Content Based Filtering consider the object’s contents, in movie case, it would be the actors, directors, description, genre, etc. therefore, it will give users the movie recommendation more closely to the individual’s preference. Collaborative Filtering focuses on user’s preference data and recommend movies based on it through matching with other users’ historical movies that have a similar preference as well and does not require movies’ metadata. After understanding the mechanism of Recommender System, let’s jump start our first Recommender System project by using TMDB’s movie dataset that can be downloaded through Kaggle here. This dataset contains 2 sets of files, which are Credits file and Movies file. The Credits file has the size of 38MB with 4 features, which are, movies’ ID, titles, the cast members’ name (on-screen members), and the crew members’ name (backstage members). On the other hand, with the size of 5.4MB, Movies file contains more features, namely, the movies’ budget, genre, homepage, ID, keywords, original language, original title, production companies, production countries, release date, revenue, runtime (in minutes), status (released or rumored), tagline, title, average vote, and vote’s count. As usual, firstly, we need to import several starting libraries as follow: import numpy as npimport pandas as pd If you are using Google Colab, don’t forget to upload the Movies and Credits files to Colab as follow: from google.colab import filesuploaded = files.upload() And then assign those files to variables by using Pandas’ read function and read their sizes: credits = pd.read_csv('tmdb_5000_credits.csv')movies = pd.read_csv('tmdb_5000_movies.csv')print(credits.shape)print(movies.shape) As we can see below, both files have 4803 data with 4 features for Credits file and 20 features for Movies file. Since there are two files, we should merge those files based on their movies ID. But before merging, let’s change the Credits’ file “movies ID” column into “ID”, therefore, they would have identical “ID” feature when merged and then check the new merged file’s size. credits.columns = ['id','tittle','cast','crew']movies= movies.merge(credits,on='id')print(movies.shape) Now our new merged file contains 23 features as shown below: As we understood, demographic filtering is one of the simplest Recommender System that only offers the users the best rated and most popular movies. However, although it might be simple, we still need the appropriate formula to calculate the best rated movies because some movies have 9.0 rating but only have 5 votes, so it is not fair for the rest of the movies that are rated slightly lower but with much more votes. The best formula to calculate movie rating is provided by IMDB, which is articulated clearly here. It basically taking number of votes, minimum number of votes required to be considered, mean of votes, and average rating into account and ended up with a formula as follow: Where: W = Weighted Rating v = number of votes for the movie m = minimum number of votes necessary to be considered R = average number of the movie’s rating C = the mean vote from overall data Therefore, we need to determine each of those elements in order to obtain W. Number of votes (v) and average number of votes (R) have already been provided in the dataset, therefore, we do not need to calculate further for those variables. Next, we need to find out C, which is the mean of the overall votes that can be determined through the following function: C= movies['vote_average'].mean() If we try to print out the value of C, we will get 6.092.. as follows: Next, we need to determine m, which is the number of votes required for a movie to be considered as a recommendation. We can set it as any number, however, let’s say in our algorithm, we will set it as 85th percentile as our cutoff, which means to be considered, the movie needs to have more votes than 85% of the overall movies. Let’s find out: m= movies['vote_count'].quantile(0.85) As we can see the result below, in order for a movie to be considered in the recommendation, it has to have at least 1301 votes in its rating. By using the value of m, we can eliminate movies with the number of ratings below 1301 as follow: demograph_movies = movies.copy().loc[movies['vote_count'] >= m] Now we can see only 721 out of 4803 movies that have more than 1301 votes. After we have found out all the elements, let’s create the IMDB weighted rating formula by defining its function as shown below: def weighted_rating(a, m=m, C=C): v = a['vote_count'] R = a['vote_average'] return (v/(v+m) * R) + (m/(m+v) * C) Then we can insert the IMDB formula’s results into the demographic recommendation file by creating a new feature called “score” demograph_movies['score'] = demograph_movies.apply(weighted_rating, axis=1) Afterwards, we need to sort the movies based on the weighted rating score in descending order. demograph_movies = demograph_movies.sort_values('score', ascending=False) Now let’s see what are the top 10 movies based on our demographic recommendation algorithm by using IMDB formula that we have just built: demograph_movies[['title', 'vote_count', 'vote_average', 'score']].head(10) Turns out The Shawshank Redemption topped the chart followed by Fight Club, and Pulp Fiction. They indeed are great movies, however, this recommendation system applies for everyone regardless of the users’ genre or other factors preferences, therefore, it is considered far from perfect. Unlike demographic filtering, content based filtering considers every elements in the movies before recommend them to the users, such as the movies’ descriptions, genres, casts, crews, etc. This way, the users will more likely to receive recommendations that are more aligned with their favorite movies. Recommendation Based on Movie’s Description Let’s start off by offering movie recommendations that have similar descriptions, where in Movies dataset, the data stored in the “overview” feature which we can be found through here: movies['overview'].head(10) Since we are dealing with sentences here, it is wiser to adopt one of NLP (Natural Language Processing) techniques called TF-IDF, which is a short of Term Frequency-Inverse Document Frequency. What TF-IDF does is, it analyses the importance of each word by finding TF and IDF by using the following formulas: And then TF-IDF can be found by simply multiplying the result of TF and IDF, therefore: TF-IDF = TF*IDF TF-IDF calculation has been provided by Scikit-Learn library, which can be imported by the following code: from sklearn.feature_extraction.text import TfidfVectorizer Before we execute TF-IDF, we need to do the necessary NLP pre-processing tasks, such as removing stop words (words that do not have meaning, for instance, “a”, “the”, “but”, “what”, “or”, “how”, and “and”) by assigning a new variable. tfidf = TfidfVectorizer(stop_words='english') And we also need to replace NaN with an empty string: movies['overview'] = movies['overview'].fillna('') Then we can apply TF-IDF vectorisation to the movies’ overview and check its size: tfidf_overview = tfidf.fit_transform(movies['overview'])tfidf_overview.shape As we can see above, there are more than 20,000 words that are used to describe 4803 movies in the “overview” feature. Because we have calculated the TF-IDF vectorisation for the overview’s sentences, we can now find out similarities between two movies, which actually have several methods, such as Euclidian, Pearson Correlation, and Cosine Similarities. However, by considering simplicity, we will use Cosine Similarities, which can be obtained by using linear_kernel() function from sklearn library. First, we need to import linear kernel from sklearn below: from sklearn.metrics.pairwise import linear_kernel Then we can find out the cosine similarity through it. cos_sim = linear_kernel(tfidf_overview, tfidf_overview) This way, we have discovered the similarities between the movies’ description across the dataset. However, before we create a function that returns movie recommendations based on the description’s similarities, we need to set index in each title as follows: indices = pd.Series(movies.index, index=movies['title']).drop_duplicates() Then, we can start building a function for movie recommendation based on their descriptions as follows: def des_recommendations(title, cos_sim=cos_sim): idx = indices[title] sim_scores = list(enumerate(cos_sim[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:16] movie_indices = [i[0] for i in sim_scores] return movies['title'].iloc[movie_indices] In the description based recommendation algorithm above, firstly, we obtain the movie’s index based on its title, and then gather movies with similar cosine similarity results, then sort the movies in descend order, then set the number of results to be 15, then get the recommended movies’ indices, and finally, show us top 15 movies based on the stated methods. Let’s try the movie recommendation for Minions: des_recommendations('Minions') We get the following cartoon/kids movies as recommendations: If we try The Dark Knight: des_recommendations('The Dark Knight') We get mostly another Batman movies as recommendations: I would say this type of Recommender System will be able to provide recommendations that are much more relevant compared to demographic filtering system. Different to Content Based Filtering which recommend movies for us only based on the other movies’ elements, Collaborative Filtering will allow more personal experience for the users because it involves the user’s ratings into account. Before moving further, first we need to understand two types of Collaborative Filtering, which are user based filtering and item based filtering. As we can see from their name, user based filtering assesses similarity of ratings based on the users, on the other hand, item based filtering assesses similarity between their ratings based on the items. Moreover, the similarity between both users and items can be calculated from Pearson Correlation and Cosine Similarity formulas. Therefore, CF can predict how much user will like a certain movie even though the user hasn’t rated it yet. Moving on, to get started in CF project, we need to download another dataset from Kaggle here, specifically the “ratings_small.csv” dataset because the previous dataset does not contain a User ID feature, which is essential in CF project. ratings = pd.read_csv('ratings_small.csv') We will also need to import scikit-surprise library to utilise its SVD and other functions. If you have not install surprise, you can run the following code: pip install surprise Then, we can import surprise libraries: from surprise import Reader, Dataset, SVDfrom surprise.model_selection import cross_validate Because we are dealing with large number of user and product based data, we need to mitigate the possibility of scalability and sparsity issues by implementing Singular Value Decomposition (SVD), which we will be able to check the dataset performance by assessing the RMSE (Root Mean Square Error) and MAE (Mean Absolute Error). Note: the lower the values of RMSE and MAE, indicate the better performance it is for the dataset. reader = Reader()data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)svd = SVD()cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5) As we can see, the result of MAE and RMSE after implementing SVD are less than 1, which is in an acceptable range: Since it has shown a good performance, let’s train our data: train = data.build_full_trainset()svd.fit(train) Let’s check the data with user ID of 1: ratings[ratings['userId'] == 1] And let’s make a prediction for user ID 1 with movie ID 302: svd.predict(1, 302, 3) We get an estimation rating prediction of 2.87 Demographic, Content Based, and Collaborative are very distinct Recommender Systems that operate by considering different element, however, Demographic is considered to be the simplest among the others, but Content Based and Collaborative give more personalised movie recommendations. Thank you for reading and I hope you enjoy it.
[ { "code": null, "e": 713, "s": 172, "text": "In this article, let’s discuss a project that articulates on how Machine Learning algorithm recommend what is the next movie that you might want to watch by using the Recommender System. This approach not only can be implemented for movie contents, but also for other digital objects chosen distinctively for each user, for instance, books, web pages, music, messages, products, dating preference, and of course, movies that have been widely executed by several companies to improve their customer experience within their digital platforms." }, { "code": null, "e": 811, "s": 713, "text": "There are three types of recommender systems that will be implemented in this project, which are:" }, { "code": null, "e": 1110, "s": 811, "text": "Demographic Filtering offers users with similar demographic background the similar movies that are popular and well-rated regardless of the genre or any other factors. Therefore, since it does not consider the individual taste of each person, it provides a simple result but easy to be implemented." }, { "code": null, "e": 1341, "s": 1110, "text": "Content Based Filtering consider the object’s contents, in movie case, it would be the actors, directors, description, genre, etc. therefore, it will give users the movie recommendation more closely to the individual’s preference." }, { "code": null, "e": 1563, "s": 1341, "text": "Collaborative Filtering focuses on user’s preference data and recommend movies based on it through matching with other users’ historical movies that have a similar preference as well and does not require movies’ metadata." }, { "code": null, "e": 2345, "s": 1563, "text": "After understanding the mechanism of Recommender System, let’s jump start our first Recommender System project by using TMDB’s movie dataset that can be downloaded through Kaggle here. This dataset contains 2 sets of files, which are Credits file and Movies file. The Credits file has the size of 38MB with 4 features, which are, movies’ ID, titles, the cast members’ name (on-screen members), and the crew members’ name (backstage members). On the other hand, with the size of 5.4MB, Movies file contains more features, namely, the movies’ budget, genre, homepage, ID, keywords, original language, original title, production companies, production countries, release date, revenue, runtime (in minutes), status (released or rumored), tagline, title, average vote, and vote’s count." }, { "code": null, "e": 2420, "s": 2345, "text": "As usual, firstly, we need to import several starting libraries as follow:" }, { "code": null, "e": 2458, "s": 2420, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 2561, "s": 2458, "text": "If you are using Google Colab, don’t forget to upload the Movies and Credits files to Colab as follow:" }, { "code": null, "e": 2617, "s": 2561, "text": "from google.colab import filesuploaded = files.upload()" }, { "code": null, "e": 2711, "s": 2617, "text": "And then assign those files to variables by using Pandas’ read function and read their sizes:" }, { "code": null, "e": 2841, "s": 2711, "text": "credits = pd.read_csv('tmdb_5000_credits.csv')movies = pd.read_csv('tmdb_5000_movies.csv')print(credits.shape)print(movies.shape)" }, { "code": null, "e": 2954, "s": 2841, "text": "As we can see below, both files have 4803 data with 4 features for Credits file and 20 features for Movies file." }, { "code": null, "e": 3221, "s": 2954, "text": "Since there are two files, we should merge those files based on their movies ID. But before merging, let’s change the Credits’ file “movies ID” column into “ID”, therefore, they would have identical “ID” feature when merged and then check the new merged file’s size." }, { "code": null, "e": 3325, "s": 3221, "text": "credits.columns = ['id','tittle','cast','crew']movies= movies.merge(credits,on='id')print(movies.shape)" }, { "code": null, "e": 3386, "s": 3325, "text": "Now our new merged file contains 23 features as shown below:" }, { "code": null, "e": 3806, "s": 3386, "text": "As we understood, demographic filtering is one of the simplest Recommender System that only offers the users the best rated and most popular movies. However, although it might be simple, we still need the appropriate formula to calculate the best rated movies because some movies have 9.0 rating but only have 5 votes, so it is not fair for the rest of the movies that are rated slightly lower but with much more votes." }, { "code": null, "e": 4079, "s": 3806, "text": "The best formula to calculate movie rating is provided by IMDB, which is articulated clearly here. It basically taking number of votes, minimum number of votes required to be considered, mean of votes, and average rating into account and ended up with a formula as follow:" }, { "code": null, "e": 4086, "s": 4079, "text": "Where:" }, { "code": null, "e": 4106, "s": 4086, "text": "W = Weighted Rating" }, { "code": null, "e": 4140, "s": 4106, "text": "v = number of votes for the movie" }, { "code": null, "e": 4195, "s": 4140, "text": "m = minimum number of votes necessary to be considered" }, { "code": null, "e": 4236, "s": 4195, "text": "R = average number of the movie’s rating" }, { "code": null, "e": 4272, "s": 4236, "text": "C = the mean vote from overall data" }, { "code": null, "e": 4635, "s": 4272, "text": "Therefore, we need to determine each of those elements in order to obtain W. Number of votes (v) and average number of votes (R) have already been provided in the dataset, therefore, we do not need to calculate further for those variables. Next, we need to find out C, which is the mean of the overall votes that can be determined through the following function:" }, { "code": null, "e": 4668, "s": 4635, "text": "C= movies['vote_average'].mean()" }, { "code": null, "e": 4739, "s": 4668, "text": "If we try to print out the value of C, we will get 6.092.. as follows:" }, { "code": null, "e": 5085, "s": 4739, "text": "Next, we need to determine m, which is the number of votes required for a movie to be considered as a recommendation. We can set it as any number, however, let’s say in our algorithm, we will set it as 85th percentile as our cutoff, which means to be considered, the movie needs to have more votes than 85% of the overall movies. Let’s find out:" }, { "code": null, "e": 5124, "s": 5085, "text": "m= movies['vote_count'].quantile(0.85)" }, { "code": null, "e": 5267, "s": 5124, "text": "As we can see the result below, in order for a movie to be considered in the recommendation, it has to have at least 1301 votes in its rating." }, { "code": null, "e": 5365, "s": 5267, "text": "By using the value of m, we can eliminate movies with the number of ratings below 1301 as follow:" }, { "code": null, "e": 5429, "s": 5365, "text": "demograph_movies = movies.copy().loc[movies['vote_count'] >= m]" }, { "code": null, "e": 5504, "s": 5429, "text": "Now we can see only 721 out of 4803 movies that have more than 1301 votes." }, { "code": null, "e": 5633, "s": 5504, "text": "After we have found out all the elements, let’s create the IMDB weighted rating formula by defining its function as shown below:" }, { "code": null, "e": 5749, "s": 5633, "text": "def weighted_rating(a, m=m, C=C): v = a['vote_count'] R = a['vote_average'] return (v/(v+m) * R) + (m/(m+v) * C)" }, { "code": null, "e": 5877, "s": 5749, "text": "Then we can insert the IMDB formula’s results into the demographic recommendation file by creating a new feature called “score”" }, { "code": null, "e": 5953, "s": 5877, "text": "demograph_movies['score'] = demograph_movies.apply(weighted_rating, axis=1)" }, { "code": null, "e": 6048, "s": 5953, "text": "Afterwards, we need to sort the movies based on the weighted rating score in descending order." }, { "code": null, "e": 6122, "s": 6048, "text": "demograph_movies = demograph_movies.sort_values('score', ascending=False)" }, { "code": null, "e": 6260, "s": 6122, "text": "Now let’s see what are the top 10 movies based on our demographic recommendation algorithm by using IMDB formula that we have just built:" }, { "code": null, "e": 6336, "s": 6260, "text": "demograph_movies[['title', 'vote_count', 'vote_average', 'score']].head(10)" }, { "code": null, "e": 6624, "s": 6336, "text": "Turns out The Shawshank Redemption topped the chart followed by Fight Club, and Pulp Fiction. They indeed are great movies, however, this recommendation system applies for everyone regardless of the users’ genre or other factors preferences, therefore, it is considered far from perfect." }, { "code": null, "e": 6928, "s": 6624, "text": "Unlike demographic filtering, content based filtering considers every elements in the movies before recommend them to the users, such as the movies’ descriptions, genres, casts, crews, etc. This way, the users will more likely to receive recommendations that are more aligned with their favorite movies." }, { "code": null, "e": 6972, "s": 6928, "text": "Recommendation Based on Movie’s Description" }, { "code": null, "e": 7157, "s": 6972, "text": "Let’s start off by offering movie recommendations that have similar descriptions, where in Movies dataset, the data stored in the “overview” feature which we can be found through here:" }, { "code": null, "e": 7185, "s": 7157, "text": "movies['overview'].head(10)" }, { "code": null, "e": 7494, "s": 7185, "text": "Since we are dealing with sentences here, it is wiser to adopt one of NLP (Natural Language Processing) techniques called TF-IDF, which is a short of Term Frequency-Inverse Document Frequency. What TF-IDF does is, it analyses the importance of each word by finding TF and IDF by using the following formulas:" }, { "code": null, "e": 7582, "s": 7494, "text": "And then TF-IDF can be found by simply multiplying the result of TF and IDF, therefore:" }, { "code": null, "e": 7598, "s": 7582, "text": "TF-IDF = TF*IDF" }, { "code": null, "e": 7705, "s": 7598, "text": "TF-IDF calculation has been provided by Scikit-Learn library, which can be imported by the following code:" }, { "code": null, "e": 7765, "s": 7705, "text": "from sklearn.feature_extraction.text import TfidfVectorizer" }, { "code": null, "e": 8000, "s": 7765, "text": "Before we execute TF-IDF, we need to do the necessary NLP pre-processing tasks, such as removing stop words (words that do not have meaning, for instance, “a”, “the”, “but”, “what”, “or”, “how”, and “and”) by assigning a new variable." }, { "code": null, "e": 8046, "s": 8000, "text": "tfidf = TfidfVectorizer(stop_words='english')" }, { "code": null, "e": 8100, "s": 8046, "text": "And we also need to replace NaN with an empty string:" }, { "code": null, "e": 8151, "s": 8100, "text": "movies['overview'] = movies['overview'].fillna('')" }, { "code": null, "e": 8234, "s": 8151, "text": "Then we can apply TF-IDF vectorisation to the movies’ overview and check its size:" }, { "code": null, "e": 8311, "s": 8234, "text": "tfidf_overview = tfidf.fit_transform(movies['overview'])tfidf_overview.shape" }, { "code": null, "e": 8430, "s": 8311, "text": "As we can see above, there are more than 20,000 words that are used to describe 4803 movies in the “overview” feature." }, { "code": null, "e": 8814, "s": 8430, "text": "Because we have calculated the TF-IDF vectorisation for the overview’s sentences, we can now find out similarities between two movies, which actually have several methods, such as Euclidian, Pearson Correlation, and Cosine Similarities. However, by considering simplicity, we will use Cosine Similarities, which can be obtained by using linear_kernel() function from sklearn library." }, { "code": null, "e": 8873, "s": 8814, "text": "First, we need to import linear kernel from sklearn below:" }, { "code": null, "e": 8924, "s": 8873, "text": "from sklearn.metrics.pairwise import linear_kernel" }, { "code": null, "e": 8979, "s": 8924, "text": "Then we can find out the cosine similarity through it." }, { "code": null, "e": 9035, "s": 8979, "text": "cos_sim = linear_kernel(tfidf_overview, tfidf_overview)" }, { "code": null, "e": 9293, "s": 9035, "text": "This way, we have discovered the similarities between the movies’ description across the dataset. However, before we create a function that returns movie recommendations based on the description’s similarities, we need to set index in each title as follows:" }, { "code": null, "e": 9368, "s": 9293, "text": "indices = pd.Series(movies.index, index=movies['title']).drop_duplicates()" }, { "code": null, "e": 9472, "s": 9368, "text": "Then, we can start building a function for movie recommendation based on their descriptions as follows:" }, { "code": null, "e": 9785, "s": 9472, "text": "def des_recommendations(title, cos_sim=cos_sim): idx = indices[title] sim_scores = list(enumerate(cos_sim[idx])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:16] movie_indices = [i[0] for i in sim_scores] return movies['title'].iloc[movie_indices]" }, { "code": null, "e": 10148, "s": 9785, "text": "In the description based recommendation algorithm above, firstly, we obtain the movie’s index based on its title, and then gather movies with similar cosine similarity results, then sort the movies in descend order, then set the number of results to be 15, then get the recommended movies’ indices, and finally, show us top 15 movies based on the stated methods." }, { "code": null, "e": 10196, "s": 10148, "text": "Let’s try the movie recommendation for Minions:" }, { "code": null, "e": 10227, "s": 10196, "text": "des_recommendations('Minions')" }, { "code": null, "e": 10288, "s": 10227, "text": "We get the following cartoon/kids movies as recommendations:" }, { "code": null, "e": 10315, "s": 10288, "text": "If we try The Dark Knight:" }, { "code": null, "e": 10354, "s": 10315, "text": "des_recommendations('The Dark Knight')" }, { "code": null, "e": 10410, "s": 10354, "text": "We get mostly another Batman movies as recommendations:" }, { "code": null, "e": 10564, "s": 10410, "text": "I would say this type of Recommender System will be able to provide recommendations that are much more relevant compared to demographic filtering system." }, { "code": null, "e": 11280, "s": 10564, "text": "Different to Content Based Filtering which recommend movies for us only based on the other movies’ elements, Collaborative Filtering will allow more personal experience for the users because it involves the user’s ratings into account. Before moving further, first we need to understand two types of Collaborative Filtering, which are user based filtering and item based filtering. As we can see from their name, user based filtering assesses similarity of ratings based on the users, on the other hand, item based filtering assesses similarity between their ratings based on the items. Moreover, the similarity between both users and items can be calculated from Pearson Correlation and Cosine Similarity formulas." }, { "code": null, "e": 11627, "s": 11280, "text": "Therefore, CF can predict how much user will like a certain movie even though the user hasn’t rated it yet. Moving on, to get started in CF project, we need to download another dataset from Kaggle here, specifically the “ratings_small.csv” dataset because the previous dataset does not contain a User ID feature, which is essential in CF project." }, { "code": null, "e": 11670, "s": 11627, "text": "ratings = pd.read_csv('ratings_small.csv')" }, { "code": null, "e": 11828, "s": 11670, "text": "We will also need to import scikit-surprise library to utilise its SVD and other functions. If you have not install surprise, you can run the following code:" }, { "code": null, "e": 11849, "s": 11828, "text": "pip install surprise" }, { "code": null, "e": 11889, "s": 11849, "text": "Then, we can import surprise libraries:" }, { "code": null, "e": 11982, "s": 11889, "text": "from surprise import Reader, Dataset, SVDfrom surprise.model_selection import cross_validate" }, { "code": null, "e": 12410, "s": 11982, "text": "Because we are dealing with large number of user and product based data, we need to mitigate the possibility of scalability and sparsity issues by implementing Singular Value Decomposition (SVD), which we will be able to check the dataset performance by assessing the RMSE (Root Mean Square Error) and MAE (Mean Absolute Error). Note: the lower the values of RMSE and MAE, indicate the better performance it is for the dataset." }, { "code": null, "e": 12573, "s": 12410, "text": "reader = Reader()data = Dataset.load_from_df(ratings[['userId', 'movieId', 'rating']], reader)svd = SVD()cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5)" }, { "code": null, "e": 12688, "s": 12573, "text": "As we can see, the result of MAE and RMSE after implementing SVD are less than 1, which is in an acceptable range:" }, { "code": null, "e": 12749, "s": 12688, "text": "Since it has shown a good performance, let’s train our data:" }, { "code": null, "e": 12798, "s": 12749, "text": "train = data.build_full_trainset()svd.fit(train)" }, { "code": null, "e": 12838, "s": 12798, "text": "Let’s check the data with user ID of 1:" }, { "code": null, "e": 12870, "s": 12838, "text": "ratings[ratings['userId'] == 1]" }, { "code": null, "e": 12931, "s": 12870, "text": "And let’s make a prediction for user ID 1 with movie ID 302:" }, { "code": null, "e": 12954, "s": 12931, "text": "svd.predict(1, 302, 3)" }, { "code": null, "e": 13001, "s": 12954, "text": "We get an estimation rating prediction of 2.87" }, { "code": null, "e": 13286, "s": 13001, "text": "Demographic, Content Based, and Collaborative are very distinct Recommender Systems that operate by considering different element, however, Demographic is considered to be the simplest among the others, but Content Based and Collaborative give more personalised movie recommendations." } ]
Explain about initial, incremental and terminal cash flows in finance management.
Initial cash flows Initial cash flow is the cash required to start a project or business. This cash is estimated mainly at planning stages of a business or a project. Fixed capital, working capital, salvage value, tax rate, and book value are considered, while calculating the initial cash flows. Sometimes, the decision for estimation of initial cash flow depends on profitability of a project or strategic purpose. Generally, initial cash flows are negative number because at a start of project or a business, there will be no returns. Initial cash flows = FC+WC-S + (S-B) * T Here, FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate. Incremental cash flow is the additional cash flow for an organization. A positive cash flow indicates that there will be an increase in organization cash flows and chances for approving the project are high. Sunk cost, opportunity cost, cannibalization and allocated cost makes calculation of incremental cash flow difficult. Market conditions, policies and legal constraints will also sometimes affect incremental cash flows. These cash flows act as deciding tool to accept or invest on a project. Initial investment, operating cash flow and terminal cash flows are components of an incremental cash flow. Incremental cash flow = CI – ICO - E Here CI = Cash Inflow, E = Expenses and ICO = initial cash outflow Terminal cash flows Terminal cash flows are cash flows at the end of the project, after all taxes are deducted. In other words, terminal cash flows are the net amount made by company after disposing the asset and necessary amounts are paid. These are calculated after disposal of asset and all other amounts are paid (expenses, taxes etc.). With the help of these cash flows, company can get more information on financials of a project. Based on the financials, they can accept or reject. Sometimes forecasting errors may lead to making wrong decisions, estimation of equipment may differ. Terminal cash flow = Ta + ΔWC Terminal cash flow = Sp – T + ΔWC Terminal cash flow = (Sp – B) * (1-T) + ΔWC Here, Ta = disposal (after tax), Sp = sales (pre tax) , T = Tax rate, ΔWC= change in working capital , B = Book value of asset.
[ { "code": null, "e": 1081, "s": 1062, "text": "Initial cash flows" }, { "code": null, "e": 1600, "s": 1081, "text": "Initial cash flow is the cash required to start a project or business. This cash is estimated mainly at planning stages of a business or a project. Fixed capital, working capital, salvage value, tax rate, and book value are considered, while calculating the initial cash flows.\nSometimes, the decision for estimation of initial cash flow depends on profitability of a project or strategic purpose. Generally, initial cash flows are negative number because at a start of project or a business, there will be no returns." }, { "code": null, "e": 1738, "s": 1600, "text": "Initial cash flows = FC+WC-S + (S-B) * T\nHere, FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate." }, { "code": null, "e": 1946, "s": 1738, "text": "Incremental cash flow is the additional cash flow for an organization. A positive cash flow indicates that there will be an increase in organization cash flows and chances for approving the project are high." }, { "code": null, "e": 2345, "s": 1946, "text": "Sunk cost, opportunity cost, cannibalization and allocated cost makes calculation of incremental cash flow difficult. Market conditions, policies and legal constraints will also sometimes affect\nincremental cash flows. These cash flows act as deciding tool to accept or invest on a project. Initial investment, operating cash flow and terminal cash flows are components of an incremental cash flow." }, { "code": null, "e": 2449, "s": 2345, "text": "Incremental cash flow = CI – ICO - E\nHere CI = Cash Inflow, E = Expenses and ICO = initial cash outflow" }, { "code": null, "e": 2469, "s": 2449, "text": "Terminal cash flows" }, { "code": null, "e": 2690, "s": 2469, "text": "Terminal cash flows are cash flows at the end of the project, after all taxes are deducted. In other words, terminal cash flows are the net amount made by company after disposing the asset and necessary amounts are paid." }, { "code": null, "e": 2938, "s": 2690, "text": "These are calculated after disposal of asset and all other amounts are paid (expenses, taxes etc.). With the help of these cash flows, company can get more information on financials of a project. Based on the financials, they can accept or reject." }, { "code": null, "e": 3039, "s": 2938, "text": "Sometimes forecasting errors may lead to making wrong decisions, estimation of equipment may differ." }, { "code": null, "e": 3147, "s": 3039, "text": "Terminal cash flow = Ta + ΔWC\nTerminal cash flow = Sp – T + ΔWC\nTerminal cash flow = (Sp – B) * (1-T) + ΔWC" }, { "code": null, "e": 3275, "s": 3147, "text": "Here, Ta = disposal (after tax), Sp = sales (pre tax) , T = Tax rate, ΔWC= change in working capital , B = Book value of asset." } ]
DAX Text - TRIM function
Removes all the spaces from the text except for single spaces between words. TRIM (<text>) text The text from which you want spaces removed, or a column that contains text. A text string. You can use DAX TRIM function on the text that you have received from another application that may have irregular spacing. When you use DAX TRIM function on a column of text with trailing spaces, the results of the TRIM function may not be apparent in the calculated column. However, you can compare the length of the input text and the resulting text to find the difference. = TRIM ("Product used for Fabric Care") returns Product used for Fabric Care. If you use TRIM function on a column of text values, the results might not be visible. You can use LEN function on both, the parameter column and the resulting column, to compare the lengths of the strings. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2078, "s": 2001, "text": "Removes all the spaces from the text except for single spaces between words." }, { "code": null, "e": 2094, "s": 2078, "text": "TRIM (<text>) \n" }, { "code": null, "e": 2099, "s": 2094, "text": "text" }, { "code": null, "e": 2176, "s": 2099, "text": "The text from which you want spaces removed, or a column that contains text." }, { "code": null, "e": 2191, "s": 2176, "text": "A text string." }, { "code": null, "e": 2314, "s": 2191, "text": "You can use DAX TRIM function on the text that you have received from another application that may have irregular spacing." }, { "code": null, "e": 2567, "s": 2314, "text": "When you use DAX TRIM function on a column of text with trailing spaces, the results of the TRIM function may not be apparent in the calculated column. However, you can compare the length of the input text and the resulting text to find the difference." }, { "code": null, "e": 2609, "s": 2567, "text": "= TRIM (\"Product used for Fabric Care\") " }, { "code": null, "e": 2854, "s": 2609, "text": "returns Product used for Fabric Care. If you use TRIM function on a column of text values, the results might not be visible. You can use LEN function on both, the parameter column and the resulting column, to compare the lengths of the strings." }, { "code": null, "e": 2889, "s": 2854, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2903, "s": 2889, "text": " Abhay Gadiya" }, { "code": null, "e": 2936, "s": 2903, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2950, "s": 2936, "text": " Randy Minder" }, { "code": null, "e": 2985, "s": 2950, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2999, "s": 2985, "text": " Randy Minder" }, { "code": null, "e": 3006, "s": 2999, "text": " Print" }, { "code": null, "e": 3017, "s": 3006, "text": " Add Notes" } ]
htmlentities() vs htmlspecialchars() Function in PHP - GeeksforGeeks
03 Mar, 2022 In this article, we will see what htmlentities() & htmlspecialchars() Function is used for & also understand their implementation through the examples. htmlentities() Function: The htmlentities() function is an inbuilt function in PHP that is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entities. Syntax: string htmlentities( $string, $flags, $encoding, $double_encode ) Parameters value: This function accepts four parameters as mentioned above and described below: $string: This parameter is used to hold the input string. $flags: This parameter is used to hold the flags. It is a combination of one or two flags, which tells how to handle quotes. $encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the PHP default version. $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything. Return Values: This function returns the string which has been encoded. Example: This example uses the htmlentities() function to transform all characters which are applicable to HTML entities. PHP <?php // String convertible to htmlentities $str = '<a href="https://www.geeksforgeeks.org">GeeksforGeeks</a>'; // It will convert htmlentities and print them echo htmlentities( $str );?> Output: <a href="https://www.geeksforgeeks.org">GeeksforGeeks</a> htmlspecialchars() Function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. Syntax: string htmlspecialchars( $string, $flags, $encoding, $double_encode ) Parameter value: $string: This parameter is used to hold the input string. $flags: This parameter is used to hold the flags. It is a combination of one or two flags, which tells how to handle quotes. $encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the PHP default version. $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything. Return Values: This function returns the converted string. If there is an invalid input string then an empty string will be returned. Example: This example uses the htmlspecialchars() function to convert all predefined characters to HTML entities. PHP <?php // String to be converted $str = '"geeksforgeeks.org" Go to GeeksforGeeks'; // Converts double and single quotes echo htmlspecialchars($str, ENT_QUOTES);?> Output: "geeksforgeeks.org" Go to GeeksforGeeks Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities. bhaskargeeksforgeeks rkbhola5 PHP-function Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Comparing two dates in PHP PHP | Converting string to Date and DateTime Download file from URL using PHP Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24517, "s": 24489, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24669, "s": 24517, "text": "In this article, we will see what htmlentities() & htmlspecialchars() Function is used for & also understand their implementation through the examples." }, { "code": null, "e": 24909, "s": 24669, "text": "htmlentities() Function: The htmlentities() function is an inbuilt function in PHP that is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entities. " }, { "code": null, "e": 24917, "s": 24909, "text": "Syntax:" }, { "code": null, "e": 24983, "s": 24917, "text": "string htmlentities( $string, $flags, $encoding, $double_encode )" }, { "code": null, "e": 25080, "s": 24983, "text": "Parameters value: This function accepts four parameters as mentioned above and described below: " }, { "code": null, "e": 25138, "s": 25080, "text": "$string: This parameter is used to hold the input string." }, { "code": null, "e": 25263, "s": 25138, "text": "$flags: This parameter is used to hold the flags. It is a combination of one or two flags, which tells how to handle quotes." }, { "code": null, "e": 25458, "s": 25263, "text": "$encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the PHP default version." }, { "code": null, "e": 25592, "s": 25458, "text": "$double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything." }, { "code": null, "e": 25665, "s": 25592, "text": "Return Values: This function returns the string which has been encoded. " }, { "code": null, "e": 25787, "s": 25665, "text": "Example: This example uses the htmlentities() function to transform all characters which are applicable to HTML entities." }, { "code": null, "e": 25791, "s": 25787, "text": "PHP" }, { "code": "<?php // String convertible to htmlentities $str = '<a href=\"https://www.geeksforgeeks.org\">GeeksforGeeks</a>'; // It will convert htmlentities and print them echo htmlentities( $str );?>", "e": 25985, "s": 25791, "text": null }, { "code": null, "e": 25993, "s": 25985, "text": "Output:" }, { "code": null, "e": 26051, "s": 25993, "text": "<a href=\"https://www.geeksforgeeks.org\">GeeksforGeeks</a>" }, { "code": null, "e": 26212, "s": 26051, "text": "htmlspecialchars() Function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. " }, { "code": null, "e": 26220, "s": 26212, "text": "Syntax:" }, { "code": null, "e": 26290, "s": 26220, "text": "string htmlspecialchars( $string, $flags, $encoding, $double_encode )" }, { "code": null, "e": 26307, "s": 26290, "text": "Parameter value:" }, { "code": null, "e": 26365, "s": 26307, "text": "$string: This parameter is used to hold the input string." }, { "code": null, "e": 26490, "s": 26365, "text": "$flags: This parameter is used to hold the flags. It is a combination of one or two flags, which tells how to handle quotes." }, { "code": null, "e": 26685, "s": 26490, "text": "$encoding: It is an optional argument that specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to the PHP default version." }, { "code": null, "e": 26819, "s": 26685, "text": "$double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything." }, { "code": null, "e": 26954, "s": 26819, "text": "Return Values: This function returns the converted string. If there is an invalid input string then an empty string will be returned. " }, { "code": null, "e": 27069, "s": 26954, "text": "Example: This example uses the htmlspecialchars() function to convert all predefined characters to HTML entities. " }, { "code": null, "e": 27073, "s": 27069, "text": "PHP" }, { "code": "<?php // String to be converted $str = '\"geeksforgeeks.org\" Go to GeeksforGeeks'; // Converts double and single quotes echo htmlspecialchars($str, ENT_QUOTES);?>", "e": 27241, "s": 27073, "text": null }, { "code": null, "e": 27249, "s": 27241, "text": "Output:" }, { "code": null, "e": 27289, "s": 27249, "text": "\"geeksforgeeks.org\" Go to GeeksforGeeks" }, { "code": null, "e": 27567, "s": 27289, "text": "Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities." }, { "code": null, "e": 27588, "s": 27567, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27597, "s": 27588, "text": "rkbhola5" }, { "code": null, "e": 27610, "s": 27597, "text": "PHP-function" }, { "code": null, "e": 27617, "s": 27610, "text": "Picked" }, { "code": null, "e": 27621, "s": 27617, "text": "PHP" }, { "code": null, "e": 27638, "s": 27621, "text": "Web Technologies" }, { "code": null, "e": 27642, "s": 27638, "text": "PHP" }, { "code": null, "e": 27740, "s": 27642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27749, "s": 27740, "text": "Comments" }, { "code": null, "e": 27762, "s": 27749, "text": "Old Comments" }, { "code": null, "e": 27812, "s": 27762, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27852, "s": 27812, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27879, "s": 27852, "text": "Comparing two dates in PHP" }, { "code": null, "e": 27924, "s": 27879, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27957, "s": 27924, "text": "Download file from URL using PHP" }, { "code": null, "e": 27994, "s": 27957, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28027, "s": 27994, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28072, "s": 28027, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28132, "s": 28072, "text": "How to set the default value for an HTML <select> element ?" } ]
C - strncmp function
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structured Datatypes C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <stdio.h> int strncmp(char *string1, char *string2, int n); The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship. if Return value if < 0 then it indicates string1 is less than string2 if Return value if < 0 then it indicates string1 is less than string2 if Return value if > 0 then it indicates string2 is less than string1 if Return value if > 0 then it indicates string2 is less than string1 if Return value if = 0 then it indicates string1 is equal to string2 if Return value if = 0 then it indicates string1 is equal to string2 #include <stdio.h> int main() { char string1[20]; char string2[20]; strcpy(string1, "Hello"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 4)); strcpy(string1, "Helloooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 10)); strcpy(string1, "Hellooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 20)); return 0; } It will proiduce following result: Return Value is : 0 Return Value is : 111 Return Value is : 0 Advertisements 6 Lectures 1.5 hours Mr. Pradeep Kshetrapal 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 1475, "s": 1454, "text": "C - Programming HOME" }, { "code": null, "e": 1498, "s": 1475, "text": "C - Basic Introduction" }, { "code": null, "e": 1520, "s": 1498, "text": "C - Program Structure" }, { "code": null, "e": 1542, "s": 1520, "text": "C - Reserved Keywords" }, { "code": null, "e": 1562, "s": 1542, "text": "C - Basic Datatypes" }, { "code": null, "e": 1581, "s": 1562, "text": "C - Variable Types" }, { "code": null, "e": 1601, "s": 1581, "text": "C - Storage Classes" }, { "code": null, "e": 1621, "s": 1601, "text": "C - Using Constants" }, { "code": null, "e": 1640, "s": 1621, "text": "C - Operator Types" }, { "code": null, "e": 1663, "s": 1640, "text": "C - Control Statements" }, { "code": null, "e": 1684, "s": 1663, "text": "C - Input and Output" }, { "code": null, "e": 1705, "s": 1684, "text": "C - Pointing to Data" }, { "code": null, "e": 1725, "s": 1705, "text": "C - Using Functions" }, { "code": null, "e": 1747, "s": 1725, "text": "C - Play with Strings" }, { "code": null, "e": 1772, "s": 1747, "text": "C - Structured Datatypes" }, { "code": null, "e": 1795, "s": 1772, "text": "C - Working with Files" }, { "code": null, "e": 1817, "s": 1795, "text": "C - Bits Manipulation" }, { "code": null, "e": 1836, "s": 1817, "text": "C - Pre-Processors" }, { "code": null, "e": 1856, "s": 1836, "text": "C - Useful Concepts" }, { "code": null, "e": 1879, "s": 1856, "text": "C - Built-in Functions" }, { "code": null, "e": 1900, "s": 1879, "text": "C - Useful Resources" }, { "code": null, "e": 1918, "s": 1900, "text": "Computer Glossary" }, { "code": null, "e": 1929, "s": 1918, "text": "Who is Who" }, { "code": null, "e": 1964, "s": 1929, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2036, "s": 1964, "text": "#include <stdio.h>\n\nint strncmp(char *string1, char *string2, int n); \n" }, { "code": null, "e": 2159, "s": 2036, "text": "The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship." }, { "code": null, "e": 2230, "s": 2159, "text": " if Return value if < 0 then it indicates string1 is less than string2" }, { "code": null, "e": 2301, "s": 2230, "text": " if Return value if < 0 then it indicates string1 is less than string2" }, { "code": null, "e": 2372, "s": 2301, "text": " if Return value if > 0 then it indicates string2 is less than string1" }, { "code": null, "e": 2443, "s": 2372, "text": " if Return value if > 0 then it indicates string2 is less than string1" }, { "code": null, "e": 2513, "s": 2443, "text": " if Return value if = 0 then it indicates string1 is equal to string2" }, { "code": null, "e": 2583, "s": 2513, "text": " if Return value if = 0 then it indicates string1 is equal to string2" }, { "code": null, "e": 3057, "s": 2583, "text": "#include <stdio.h>\n\nint main() {\n char string1[20];\n char string2[20];\n\n strcpy(string1, \"Hello\");\n strcpy(string2, \"Hellooo\");\n printf(\"Return Value is : %d\\n\", strncmp( string1, string2, 4));\n\n strcpy(string1, \"Helloooo\");\n strcpy(string2, \"Hellooo\");\n printf(\"Return Value is : %d\\n\", strncmp( string1, string2, 10));\n\n strcpy(string1, \"Hellooo\");\n strcpy(string2, \"Hellooo\");\n printf(\"Return Value is : %d\\n\", strncmp( string1, string2, 20));\n\n return 0;\n}\n" }, { "code": null, "e": 3092, "s": 3057, "text": "It will proiduce following result:" }, { "code": null, "e": 3155, "s": 3092, "text": "Return Value is : 0\nReturn Value is : 111\nReturn Value is : 0\n" }, { "code": null, "e": 3172, "s": 3155, "text": "\nAdvertisements\n" }, { "code": null, "e": 3206, "s": 3172, "text": "\n 6 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3230, "s": 3206, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 3263, "s": 3230, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 3275, "s": 3263, "text": " AR Shankar" }, { "code": null, "e": 3307, "s": 3275, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 3323, "s": 3307, "text": " Musab Zayadneh" }, { "code": null, "e": 3359, "s": 3323, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 3371, "s": 3359, "text": " Narendra P" }, { "code": null, "e": 3404, "s": 3371, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 3417, "s": 3404, "text": " Sagar Mehta" }, { "code": null, "e": 3450, "s": 3417, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 3463, "s": 3450, "text": " Vikas Yadav" }, { "code": null, "e": 3470, "s": 3463, "text": " Print" }, { "code": null, "e": 3481, "s": 3470, "text": " Add Notes" } ]
C library function - perror()
The C library function void perror(const char *str) prints a descriptive error message to stderr. First the string str is printed, followed by a colon then a space. Following is the declaration for perror() function. void perror(const char *str) str − This is the C string containing a custom message to be printed before the error message itself. str − This is the C string containing a custom message to be printed before the error message itself. This function does not return any value. The following example shows the usage of perror() function. #include <stdio.h> int main () { FILE *fp; /* first rename if there is any file */ rename("file.txt", "newfile.txt"); /* now let's try to open same file */ fp = fopen("file.txt", "r"); if( fp == NULL ) { perror("Error: "); return(-1); } fclose(fp); return(0); } Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist − Error: : No such file or directory 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2172, "s": 2007, "text": "The C library function void perror(const char *str) prints a descriptive error message to stderr. First the string str is printed, followed by a colon then a space." }, { "code": null, "e": 2224, "s": 2172, "text": "Following is the declaration for perror() function." }, { "code": null, "e": 2253, "s": 2224, "text": "void perror(const char *str)" }, { "code": null, "e": 2355, "s": 2253, "text": "str − This is the C string containing a custom message to be printed before the error message itself." }, { "code": null, "e": 2457, "s": 2355, "text": "str − This is the C string containing a custom message to be printed before the error message itself." }, { "code": null, "e": 2498, "s": 2457, "text": "This function does not return any value." }, { "code": null, "e": 2558, "s": 2498, "text": "The following example shows the usage of perror() function." }, { "code": null, "e": 2869, "s": 2558, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n\n /* first rename if there is any file */\n rename(\"file.txt\", \"newfile.txt\");\n\n /* now let's try to open same file */\n fp = fopen(\"file.txt\", \"r\");\n if( fp == NULL ) {\n perror(\"Error: \");\n return(-1);\n }\n fclose(fp);\n \n return(0);\n}" }, { "code": null, "e": 3009, "s": 2869, "text": "Let us compile and run the above program that will produce the following result because we are trying to open a file which does not exist −" }, { "code": null, "e": 3045, "s": 3009, "text": "Error: : No such file or directory\n" }, { "code": null, "e": 3078, "s": 3045, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3093, "s": 3078, "text": " Nishant Malik" }, { "code": null, "e": 3128, "s": 3093, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3143, "s": 3128, "text": " Nishant Malik" }, { "code": null, "e": 3178, "s": 3143, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3192, "s": 3178, "text": " Asif Hussain" }, { "code": null, "e": 3225, "s": 3192, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3243, "s": 3225, "text": " Richa Maheshwari" }, { "code": null, "e": 3278, "s": 3243, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3297, "s": 3278, "text": " Vandana Annavaram" }, { "code": null, "e": 3330, "s": 3297, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3342, "s": 3330, "text": " Amit Diwan" }, { "code": null, "e": 3349, "s": 3342, "text": " Print" }, { "code": null, "e": 3360, "s": 3349, "text": " Add Notes" } ]
Convert BGR and RGB with Python - OpenCV - GeeksforGeeks
24 Feb, 2021 Prerequisites: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will convert a BGR image to RGB with python and OpenCV. OpenCV uses BGR image format. So, when we read an image using cv2.imread() it interprets in BGR format by default. We can use cvtColor() method to convert a BGR image to RGB and vice-versa. Syntax: cv2.cvtColor(code) Parameter: cv2.COLOR_BGR2RGB – BGR image is converted to RGB. cv2.COLOR_RGB2BGR – RGB image is converted to BGR. Converting a BGR image to RGB and vice versa can have several reasons, one of them being that several image processing libraries have different pixel orderings. Import module Read image Convert it using cvtColor() Add wait key Add destroy window mechanism Image used: Apple First, we will display the image as it is imported which means in BGR format. Example: Python3 import cv2 image = cv2.imread("/content/gfg.jpeg")cv2.imshow('image',image)cv2.waitKey(0)cv2.destroyAllWindows() Output: Now to convert BGR to RGB implementation is given below. Example: Python3 import cv2 image = cv2.imread("/content/gfg.jpeg") # converting BGR to RGBimage_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imshow('image', image_rgb)cv2.waitKey(0)cv2.destroyAllWindows() Output: Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24238, "s": 24210, "text": "\n24 Feb, 2021" }, { "code": null, "e": 24260, "s": 24238, "text": "Prerequisites: OpenCV" }, { "code": null, "e": 24616, "s": 24260, "text": "OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will convert a BGR image to RGB with python and OpenCV." }, { "code": null, "e": 24731, "s": 24616, "text": "OpenCV uses BGR image format. So, when we read an image using cv2.imread() it interprets in BGR format by default." }, { "code": null, "e": 24806, "s": 24731, "text": "We can use cvtColor() method to convert a BGR image to RGB and vice-versa." }, { "code": null, "e": 24834, "s": 24806, "text": "Syntax: cv2.cvtColor(code) " }, { "code": null, "e": 24845, "s": 24834, "text": "Parameter:" }, { "code": null, "e": 24898, "s": 24845, "text": " cv2.COLOR_BGR2RGB – BGR image is converted to RGB." }, { "code": null, "e": 24950, "s": 24898, "text": "cv2.COLOR_RGB2BGR – RGB image is converted to BGR." }, { "code": null, "e": 25112, "s": 24950, "text": "Converting a BGR image to RGB and vice versa can have several reasons, one of them being that several image processing libraries have different pixel orderings. " }, { "code": null, "e": 25126, "s": 25112, "text": "Import module" }, { "code": null, "e": 25137, "s": 25126, "text": "Read image" }, { "code": null, "e": 25165, "s": 25137, "text": "Convert it using cvtColor()" }, { "code": null, "e": 25178, "s": 25165, "text": "Add wait key" }, { "code": null, "e": 25207, "s": 25178, "text": "Add destroy window mechanism" }, { "code": null, "e": 25225, "s": 25207, "text": "Image used: Apple" }, { "code": null, "e": 25303, "s": 25225, "text": "First, we will display the image as it is imported which means in BGR format." }, { "code": null, "e": 25312, "s": 25303, "text": "Example:" }, { "code": null, "e": 25320, "s": 25312, "text": "Python3" }, { "code": "import cv2 image = cv2.imread(\"/content/gfg.jpeg\")cv2.imshow('image',image)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 25434, "s": 25320, "text": null }, { "code": null, "e": 25442, "s": 25434, "text": "Output:" }, { "code": null, "e": 25499, "s": 25442, "text": "Now to convert BGR to RGB implementation is given below." }, { "code": null, "e": 25508, "s": 25499, "text": "Example:" }, { "code": null, "e": 25516, "s": 25508, "text": "Python3" }, { "code": "import cv2 image = cv2.imread(\"/content/gfg.jpeg\") # converting BGR to RGBimage_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imshow('image', image_rgb)cv2.waitKey(0)cv2.destroyAllWindows()", "e": 25712, "s": 25516, "text": null }, { "code": null, "e": 25720, "s": 25712, "text": "Output:" }, { "code": null, "e": 25727, "s": 25720, "text": "Picked" }, { "code": null, "e": 25741, "s": 25727, "text": "Python-OpenCV" }, { "code": null, "e": 25748, "s": 25741, "text": "Python" }, { "code": null, "e": 25846, "s": 25748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25855, "s": 25846, "text": "Comments" }, { "code": null, "e": 25868, "s": 25855, "text": "Old Comments" }, { "code": null, "e": 25889, "s": 25868, "text": "Python OOPs Concepts" }, { "code": null, "e": 25921, "s": 25889, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25944, "s": 25921, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25966, "s": 25944, "text": "Defaultdict in Python" }, { "code": null, "e": 25993, "s": 25966, "text": "Python Classes and Objects" }, { "code": null, "e": 26009, "s": 25993, "text": "Deque in Python" }, { "code": null, "e": 26051, "s": 26009, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26107, "s": 26051, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26152, "s": 26107, "text": "Python - Ways to remove duplicates from list" } ]
Introduction to Kivy; A Cross-platform Python Framework
In this article, we will learn about Kivy framework and its installation. Kivy is a GUI based application interface, open-source that helps in cross-platform applications for Windows, Linux and Mac. Firstly we need to install python on pc. After that we need to install the dependencies − Windows − >>> python -m pip install docutils pygments pypiwin32kivy.deps.sdl2 kivy.deps.glew >>> python -m pip install kivy.deps.gstreamer >>> python -m pip install kivy.deps.angle Linux − $ sudo add-apt-repository ppa:kivy-team/kivy Windows − >>> python -m pip install kivy Linux − >>> sudo apt-get install python3-kivy Now let’s see how we can make a graphical user interface using Kivy − import kivy kivy.require('1.10.0') from kivy.app import App # gui interface creator from kivy.uix.button import Label # button label import statement class Sample(App): # display content on screen def build(self): # Return a label widget with Sample return Label(text ="Tutorialpoint") sample = Sample() sample.run() A new window popup will be displayed with the title of Sample containing text “Tutorialspoint” in it . A window popup will be observed on the screen In this manner we can use Kivy to create a GUI badsed application in Python In this article, we learnt about the use of kivy framework for the creation of GUI based application.
[ { "code": null, "e": 1261, "s": 1062, "text": "In this article, we will learn about Kivy framework and its installation. Kivy is a GUI based application interface, open-source that helps in cross-platform applications for Windows, Linux and Mac." }, { "code": null, "e": 1302, "s": 1261, "text": "Firstly we need to install python on pc." }, { "code": null, "e": 1351, "s": 1302, "text": "After that we need to install the dependencies −" }, { "code": null, "e": 1361, "s": 1351, "text": "Windows −" }, { "code": null, "e": 1532, "s": 1361, "text": ">>> python -m pip install docutils pygments pypiwin32kivy.deps.sdl2 kivy.deps.glew\n>>> python -m pip install kivy.deps.gstreamer\n>>> python -m pip install kivy.deps.angle" }, { "code": null, "e": 1540, "s": 1532, "text": "Linux −" }, { "code": null, "e": 1585, "s": 1540, "text": "$ sudo add-apt-repository ppa:kivy-team/kivy" }, { "code": null, "e": 1595, "s": 1585, "text": "Windows −" }, { "code": null, "e": 1626, "s": 1595, "text": ">>> python -m pip install kivy" }, { "code": null, "e": 1634, "s": 1626, "text": "Linux −" }, { "code": null, "e": 1672, "s": 1634, "text": ">>> sudo apt-get install python3-kivy" }, { "code": null, "e": 1742, "s": 1672, "text": "Now let’s see how we can make a graphical user interface using Kivy −" }, { "code": null, "e": 2071, "s": 1742, "text": "import kivy\nkivy.require('1.10.0')\nfrom kivy.app import App # gui interface creator\nfrom kivy.uix.button import Label # button label import statement\nclass Sample(App):\n # display content on screen\n def build(self):\n # Return a label widget with Sample\n return Label(text =\"Tutorialpoint\")\nsample = Sample()\nsample.run()" }, { "code": null, "e": 2174, "s": 2071, "text": "A new window popup will be displayed with the title of Sample containing text “Tutorialspoint” in it ." }, { "code": null, "e": 2220, "s": 2174, "text": "A window popup will be observed on the screen" }, { "code": null, "e": 2296, "s": 2220, "text": "In this manner we can use Kivy to create a GUI badsed application in Python" }, { "code": null, "e": 2398, "s": 2296, "text": "In this article, we learnt about the use of kivy framework for the creation of GUI based application." } ]
Tryit Editor v3.7
Tryit: Let an image float to the right in a paragraph
[]
C++ Program to Represent Graph Using Linked List
The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph. In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e. The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory. The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory. Input: Output: Input − The u and v of an edge {u,v}, and the adjacency list Output − Adjacency List of the graph G Begin Append v into the list at index u Append u into the list at index v End Live Demo #include<iostream> #include<list> #include<iterator> using namespace std; void displayAdjList(list<int> adj_list[], int v) { for(int i = 0; i<v; i++) { cout << i << "--->"; list<int> :: iterator it; for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) { cout << *it << " "; } cout << endl; } } void add_edge(list<int> adj_list[], int u, int v) { //add v into the list u, and u into list v adj_list[u].push_back(v); adj_list[v].push_back(u); } main(int argc, char* argv[]) { int v = 6; //there are 6 vertices in the graph //create an array of lists whose size is 6 list<int> adj_list[v]; add_edge(adj_list, 0, 4); add_edge(adj_list, 0, 3); add_edge(adj_list, 1, 2); add_edge(adj_list, 1, 4); add_edge(adj_list, 1, 5); add_edge(adj_list, 2, 3); add_edge(adj_list, 2, 5); add_edge(adj_list, 5, 3); add_edge(adj_list, 5, 4); displayAdjList(adj_list, v); } 0--->4 3 1--->2 4 5 2--->1 3 5 3--->0 2 5 4--->0 1 5 5--->1 2 3 4
[ { "code": null, "e": 1314, "s": 1062, "text": "The incidence matrix of a graph is another representation of a graph to store into the memory. This matrix is not a square matrix. The order of the incidence matrix is V x E. Where V is the number of vertices and E is the number of edges in the graph." }, { "code": null, "e": 1514, "s": 1314, "text": "In each row of this matrix we are placing the vertices, and in each column the edges are placed. In this representation for an edge e {u, v}, it will be marked by 1 for the place u and v of column e." }, { "code": null, "e": 1710, "s": 1514, "text": "The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory." }, { "code": null, "e": 1906, "s": 1710, "text": "The incidence matrix representation takes O(V x E) amount of space while it is computed. For complete graph the number of edges will be V(V-1)/2. So incidence matrix takes larger space in memory." }, { "code": null, "e": 1913, "s": 1906, "text": "Input:" }, { "code": null, "e": 1921, "s": 1913, "text": "Output:" }, { "code": null, "e": 1982, "s": 1921, "text": "Input − The u and v of an edge {u,v}, and the adjacency list" }, { "code": null, "e": 2021, "s": 1982, "text": "Output − Adjacency List of the graph G" }, { "code": null, "e": 2105, "s": 2021, "text": "Begin\n Append v into the list at index u\n Append u into the list at index v\nEnd" }, { "code": null, "e": 2116, "s": 2105, "text": " Live Demo" }, { "code": null, "e": 3069, "s": 2116, "text": "#include<iostream>\n#include<list>\n#include<iterator>\nusing namespace std;\nvoid displayAdjList(list<int> adj_list[], int v) {\n for(int i = 0; i<v; i++) {\n cout << i << \"--->\";\n list<int> :: iterator it;\n for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {\n cout << *it << \" \";\n }\n cout << endl;\n }\n}\nvoid add_edge(list<int> adj_list[], int u, int v) { //add v into the list u, and u into list v\n adj_list[u].push_back(v);\n adj_list[v].push_back(u);\n}\nmain(int argc, char* argv[]) {\n int v = 6; //there are 6 vertices in the graph\n //create an array of lists whose size is 6\n list<int> adj_list[v];\n add_edge(adj_list, 0, 4);\n add_edge(adj_list, 0, 3);\n add_edge(adj_list, 1, 2);\n add_edge(adj_list, 1, 4);\n add_edge(adj_list, 1, 5);\n add_edge(adj_list, 2, 3);\n add_edge(adj_list, 2, 5);\n add_edge(adj_list, 5, 3);\n add_edge(adj_list, 5, 4);\n displayAdjList(adj_list, v);\n}" }, { "code": null, "e": 3135, "s": 3069, "text": "0--->4 3\n1--->2 4 5\n2--->1 3 5\n3--->0 2 5\n4--->0 1 5\n5--->1 2 3 4" } ]
Group month and year in MySQL?
You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used. The syntax is as follows − SELECT DATE_FORMAT(yourColumnName, '%m-%Y') from yourTableName GROUP BY MONTH(yourColumnName), YEAR(yourColumnName)DESC; To understand the above concept, let us create a table. The following is the query to create a table − mysql> create table GroupMonthAndYearDemo −> ( −> DueDate datetime −> ); Query OK, 0 rows affected (1.49 sec) Insert records in the table using the following query − mysql> insert into GroupMonthAndYearDemo values(now()); Query OK, 1 row affected (0.11 sec) mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 2 year)); Query OK, 1 row affected (0.12 sec) mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -2 year)); Query OK, 1 row affected (0.10 sec) mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 1 year)); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -1 year)); Query OK, 1 row affected (0.14 sec) Display all records from the table with the help of select statement. The query is as follows − mysql> select *from GroupMonthAndYearDemo; The following is the output − +---------------------+ | DueDate | +---------------------+ | 2018-12-06 13:12:34 | | 2020-12-06 13:12:59 | | 2016-12-06 13:13:08 | | 2019-12-06 13:13:14 | | 2017-12-06 13:13:19 | +---------------------+ 5 rows in set (0.00 sec) The query to group by month and year is as follows − mysql> select DATE_FORMAT(DueDate, '%m-%Y') from GroupMonthAndYearDemo −> GROUP BY MONTH(DueDate) , YEAR(DueDate)DESC; The following is the output displaying month and year grouped by using GROUP BY − +-------------------------------+ | DATE_FORMAT(DueDate, '%m-%Y') | +-------------------------------+ | 12-2020 | | 12-2019 | | 12-2018 | | 12-2017 | | 12-2016 | +-------------------------------+ 5 rows in set, 2 warnings (0.00 sec)
[ { "code": null, "e": 1175, "s": 1062, "text": "You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used." }, { "code": null, "e": 1202, "s": 1175, "text": "The syntax is as follows −" }, { "code": null, "e": 1323, "s": 1202, "text": "SELECT DATE_FORMAT(yourColumnName, '%m-%Y') from yourTableName\nGROUP BY MONTH(yourColumnName), YEAR(yourColumnName)DESC;" }, { "code": null, "e": 1426, "s": 1323, "text": "To understand the above concept, let us create a table. The following is the query to create a table −" }, { "code": null, "e": 1545, "s": 1426, "text": "mysql> create table GroupMonthAndYearDemo\n −> (\n −> DueDate datetime\n −> );\nQuery OK, 0 rows affected (1.49 sec)" }, { "code": null, "e": 1601, "s": 1545, "text": "Insert records in the table using the following query −" }, { "code": null, "e": 2171, "s": 1601, "text": "mysql> insert into GroupMonthAndYearDemo values(now());\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 2 year));\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -2 year));\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval 1 year));\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into GroupMonthAndYearDemo values(date_add(now(),interval -1 year));\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2267, "s": 2171, "text": "Display all records from the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 2310, "s": 2267, "text": "mysql> select *from GroupMonthAndYearDemo;" }, { "code": null, "e": 2340, "s": 2310, "text": "The following is the output −" }, { "code": null, "e": 2581, "s": 2340, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2018-12-06 13:12:34 |\n| 2020-12-06 13:12:59 |\n| 2016-12-06 13:13:08 |\n| 2019-12-06 13:13:14 |\n| 2017-12-06 13:13:19 |\n+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2634, "s": 2581, "text": "The query to group by month and year is as follows −" }, { "code": null, "e": 2757, "s": 2634, "text": "mysql> select DATE_FORMAT(DueDate, '%m-%Y') from GroupMonthAndYearDemo \n −> GROUP BY MONTH(DueDate) , YEAR(DueDate)DESC;" }, { "code": null, "e": 2839, "s": 2757, "text": "The following is the output displaying month and year grouped by using GROUP BY −" }, { "code": null, "e": 3182, "s": 2839, "text": "+-------------------------------+\n| DATE_FORMAT(DueDate, '%m-%Y') |\n+-------------------------------+\n| 12-2020 |\n| 12-2019 |\n| 12-2018 |\n| 12-2017 |\n| 12-2016 |\n+-------------------------------+\n5 rows in set, 2 warnings (0.00 sec)" } ]
Reverse words in a given String in Python - GeeksforGeeks
23 Nov, 2020 We are given a string and we need to reverse words of a given string? Examples: Input : str = geeks quiz practice code Output : str = code practice quiz geeks This problem has existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem. Separate each word in given string using split() method of string data type in python. Reverse the word separated list. Print words of list, in string form after joining each word with space using ” “.join() method in python. # Function to reverse words of string def rev_sentence(sentence): # first split the string into words words = sentence.split(' ') # then reverse the split string list and join using space reverse_sentence = ' '.join(reversed(words)) # finally return the joined string return reverse_sentence if __name__ == "__main__": input = 'geeks quiz practice code' print (rev_sentence(input)) Output: code practice quiz geeks This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. TanmayThaakur Python string-programs Python Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24581, "s": 24553, "text": "\n23 Nov, 2020" }, { "code": null, "e": 24651, "s": 24581, "text": "We are given a string and we need to reverse words of a given string?" }, { "code": null, "e": 24661, "s": 24651, "text": "Examples:" }, { "code": null, "e": 24741, "s": 24661, "text": "Input : str = geeks quiz practice code\nOutput : str = code practice quiz geeks\n" }, { "code": null, "e": 24929, "s": 24741, "text": "This problem has existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem." }, { "code": null, "e": 25016, "s": 24929, "text": "Separate each word in given string using split() method of string data type in python." }, { "code": null, "e": 25049, "s": 25016, "text": "Reverse the word separated list." }, { "code": null, "e": 25155, "s": 25049, "text": "Print words of list, in string form after joining each word with space using ” “.join() method in python." }, { "code": "# Function to reverse words of string def rev_sentence(sentence): # first split the string into words words = sentence.split(' ') # then reverse the split string list and join using space reverse_sentence = ' '.join(reversed(words)) # finally return the joined string return reverse_sentence if __name__ == \"__main__\": input = 'geeks quiz practice code' print (rev_sentence(input))", "e": 25578, "s": 25155, "text": null }, { "code": null, "e": 25586, "s": 25578, "text": "Output:" }, { "code": null, "e": 25612, "s": 25586, "text": "code practice quiz geeks\n" }, { "code": null, "e": 25923, "s": 25612, "text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26048, "s": 25923, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26062, "s": 26048, "text": "TanmayThaakur" }, { "code": null, "e": 26085, "s": 26062, "text": "Python string-programs" }, { "code": null, "e": 26092, "s": 26085, "text": "Python" }, { "code": null, "e": 26100, "s": 26092, "text": "Strings" }, { "code": null, "e": 26108, "s": 26100, "text": "Strings" }, { "code": null, "e": 26206, "s": 26108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26215, "s": 26206, "text": "Comments" }, { "code": null, "e": 26228, "s": 26215, "text": "Old Comments" }, { "code": null, "e": 26246, "s": 26228, "text": "Python Dictionary" }, { "code": null, "e": 26281, "s": 26246, "text": "Read a file line by line in Python" }, { "code": null, "e": 26303, "s": 26281, "text": "Enumerate() in Python" }, { "code": null, "e": 26335, "s": 26303, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26365, "s": 26335, "text": "Iterate over a list in Python" }, { "code": null, "e": 26390, "s": 26365, "text": "Reverse a string in Java" }, { "code": null, "e": 26436, "s": 26390, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 26470, "s": 26436, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 26530, "s": 26470, "text": "Write a program to print all permutations of a given string" } ]
Count of subsequences having maximum distinct elements - GeeksforGeeks
20 May, 2021 Given an arr of size n. The problem is to count all the subsequences having maximum number of distinct elements.Examples: Input : arr[] = {4, 7, 6, 7} Output : 2 The indexes for the subsequences are: {0, 1, 2} - Subsequence is {4, 7, 6} and {0, 2, 3} - Subsequence is {4, 6, 7} Input : arr[] = {9, 6, 4, 4, 5, 9, 6, 1, 2} Output : 8 Naive Approach: Consider all the subsequences having distinct elements and count the one’s having maximum distinct elements.Efficient Approach: Create a hash table to store the frequency of each element of the array. Take product of all the frequencies. The solution is based on the fact that there is always 1 subsequence possible when all elements are distinct. If elements repeat, every occurrence of repeating element makes a mew subsequence of distinct elements. C++ Java Python3 C# Javascript // C++ implementation to count subsequences having// maximum distinct elements#include <bits/stdc++.h>using namespace std; typedef unsigned long long int ull; // function to count subsequences having// maximum distinct elementsull countSubseq(int arr[], int n){ // unordered_map 'um' implemented as // hash table unordered_map<int, int> um; ull count = 1; // count frequency of each element for (int i = 0; i < n; i++) um[arr[i]]++; // traverse 'um' for (auto itr = um.begin(); itr != um.end(); itr++) // multiply frequency of each element // and accumulate it in 'count' count *= (itr->second); // required number of subsequences return count;} // Driver program to test aboveint main(){ int arr[] = { 4, 7, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Count = " << countSubseq(arr, n); return 0;} // Java implementation to count subsequences having// maximum distinct elementsimport java.util.HashMap; class geeks{ // function to count subsequences having // maximum distinct elements public static long countSubseq(int[] arr, int n) { // unordered_map 'um' implemented as // hash table HashMap<Integer, Integer> um = new HashMap<>(); long count = 1; // count frequency of each element for (int i = 0; i < n; i++) { if (um.get(arr[i]) != null) { int a = um.get(arr[i]); um.put(arr[i], ++a); } else um.put(arr[i], 1); } // traverse 'um' for (HashMap.Entry<Integer, Integer> entry : um.entrySet()) { // multiply frequency of each element // and accumulate it in 'count' count *= entry.getValue(); } // required number of subsequences return count; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 7, 6, 7 }; int n = arr.length; System.out.println("Count = " + countSubseq(arr, n)); }} // This code is contributed by// sanjeev2552 # Python 3 implementation to count subsequences# having maximum distinct elements # function to count subsequences having# maximum distinct elementsdef countSubseq(arr, n): # unordered_map 'um' implemented # as hash table # take range equal to maximum # value of arr um = {i:0 for i in range(8)} count = 1 # count frequency of each element for i in range(n): um[arr[i]] += 1 # traverse 'um' for key, values in um.items(): # multiply frequency of each element # and accumulate it in 'count' if(values > 0): count *= values # required number of subsequences return count # Driver Codeif __name__ == '__main__': arr = [4, 7, 6, 7] n = len(arr) print("Count =", countSubseq(arr, n)) # This code is contributed by# Surendra_Gangwar // C# implementation to count subsequences// having maximum distinct elementsusing System;using System.Collections.Generic; class GFG{ // function to count subsequences having // maximum distinct elements public static long countSubseq(int[] arr, int n) { // unordered_map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); long count = 1; // count frequency of each element for (int i = 0; i < n; i++) { if (um.ContainsKey(arr[i])) { int a = um[arr[i]]; um.Remove(arr[i]); um.Add(arr[i], ++a); } else um.Add(arr[i], 1); } // traverse 'um' foreach(KeyValuePair<int, int> entry in um) { // multiply frequency of each element // and accumulate it in 'count' count *= entry.Value; } // required number of subsequences return count; } // Driver Code public static void Main(String[] args) { int[] arr = { 4, 7, 6, 7 }; int n = arr.Length; Console.WriteLine("Count = " + countSubseq(arr, n)); }} // This code is contributed by Princi Singh <script> // Javascript implementation to count subsequences having// maximum distinct elements // function to count subsequences having// maximum distinct elementsfunction countSubseq(arr, n){ // unordered_map 'um' implemented as // hash table var um = new Map(); var count = 1; // count frequency of each element for (var i = 0; i < n; i++) { if(um.has(arr[i])) um.set(arr[i], um.get(arr[i])+1) else um.set(arr[i], 1); } // traverse 'um' um.forEach((value, key) => { // multiply frequency of each element // and accumulate it in 'count' count *= value; }); // required number of subsequences return count;} // Driver program to test abovevar arr = [4, 7, 6, 7];var n = arr.length;document.write( "Count = " + countSubseq(arr, n)); // This code is contributed by noob2000.</script> Output: Count = 2 Time Complexity: O(n). Auxiliary Space: O(n). SURENDRA_GANGWAR sanjeev2552 princi singh noob2000 subsequence Arrays Combinatorial Arrays Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Program to calculate value of nCr
[ { "code": null, "e": 24731, "s": 24703, "text": "\n20 May, 2021" }, { "code": null, "e": 24855, "s": 24731, "text": "Given an arr of size n. The problem is to count all the subsequences having maximum number of distinct elements.Examples: " }, { "code": null, "e": 25067, "s": 24855, "text": "Input : arr[] = {4, 7, 6, 7}\nOutput : 2\nThe indexes for the subsequences are:\n{0, 1, 2} - Subsequence is {4, 7, 6} and\n{0, 2, 3} - Subsequence is {4, 6, 7}\n\nInput : arr[] = {9, 6, 4, 4, 5, 9, 6, 1, 2}\nOutput : 8" }, { "code": null, "e": 25538, "s": 25069, "text": "Naive Approach: Consider all the subsequences having distinct elements and count the one’s having maximum distinct elements.Efficient Approach: Create a hash table to store the frequency of each element of the array. Take product of all the frequencies. The solution is based on the fact that there is always 1 subsequence possible when all elements are distinct. If elements repeat, every occurrence of repeating element makes a mew subsequence of distinct elements. " }, { "code": null, "e": 25542, "s": 25538, "text": "C++" }, { "code": null, "e": 25547, "s": 25542, "text": "Java" }, { "code": null, "e": 25555, "s": 25547, "text": "Python3" }, { "code": null, "e": 25558, "s": 25555, "text": "C#" }, { "code": null, "e": 25569, "s": 25558, "text": "Javascript" }, { "code": "// C++ implementation to count subsequences having// maximum distinct elements#include <bits/stdc++.h>using namespace std; typedef unsigned long long int ull; // function to count subsequences having// maximum distinct elementsull countSubseq(int arr[], int n){ // unordered_map 'um' implemented as // hash table unordered_map<int, int> um; ull count = 1; // count frequency of each element for (int i = 0; i < n; i++) um[arr[i]]++; // traverse 'um' for (auto itr = um.begin(); itr != um.end(); itr++) // multiply frequency of each element // and accumulate it in 'count' count *= (itr->second); // required number of subsequences return count;} // Driver program to test aboveint main(){ int arr[] = { 4, 7, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Count = \" << countSubseq(arr, n); return 0;}", "e": 26461, "s": 25569, "text": null }, { "code": "// Java implementation to count subsequences having// maximum distinct elementsimport java.util.HashMap; class geeks{ // function to count subsequences having // maximum distinct elements public static long countSubseq(int[] arr, int n) { // unordered_map 'um' implemented as // hash table HashMap<Integer, Integer> um = new HashMap<>(); long count = 1; // count frequency of each element for (int i = 0; i < n; i++) { if (um.get(arr[i]) != null) { int a = um.get(arr[i]); um.put(arr[i], ++a); } else um.put(arr[i], 1); } // traverse 'um' for (HashMap.Entry<Integer, Integer> entry : um.entrySet()) { // multiply frequency of each element // and accumulate it in 'count' count *= entry.getValue(); } // required number of subsequences return count; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 7, 6, 7 }; int n = arr.length; System.out.println(\"Count = \" + countSubseq(arr, n)); }} // This code is contributed by// sanjeev2552", "e": 27726, "s": 26461, "text": null }, { "code": "# Python 3 implementation to count subsequences# having maximum distinct elements # function to count subsequences having# maximum distinct elementsdef countSubseq(arr, n): # unordered_map 'um' implemented # as hash table # take range equal to maximum # value of arr um = {i:0 for i in range(8)} count = 1 # count frequency of each element for i in range(n): um[arr[i]] += 1 # traverse 'um' for key, values in um.items(): # multiply frequency of each element # and accumulate it in 'count' if(values > 0): count *= values # required number of subsequences return count # Driver Codeif __name__ == '__main__': arr = [4, 7, 6, 7] n = len(arr) print(\"Count =\", countSubseq(arr, n)) # This code is contributed by# Surendra_Gangwar", "e": 28555, "s": 27726, "text": null }, { "code": "// C# implementation to count subsequences// having maximum distinct elementsusing System;using System.Collections.Generic; class GFG{ // function to count subsequences having // maximum distinct elements public static long countSubseq(int[] arr, int n) { // unordered_map 'um' implemented as // hash table Dictionary<int, int> um = new Dictionary<int, int>(); long count = 1; // count frequency of each element for (int i = 0; i < n; i++) { if (um.ContainsKey(arr[i])) { int a = um[arr[i]]; um.Remove(arr[i]); um.Add(arr[i], ++a); } else um.Add(arr[i], 1); } // traverse 'um' foreach(KeyValuePair<int, int> entry in um) { // multiply frequency of each element // and accumulate it in 'count' count *= entry.Value; } // required number of subsequences return count; } // Driver Code public static void Main(String[] args) { int[] arr = { 4, 7, 6, 7 }; int n = arr.Length; Console.WriteLine(\"Count = \" + countSubseq(arr, n)); }} // This code is contributed by Princi Singh", "e": 29975, "s": 28555, "text": null }, { "code": "<script> // Javascript implementation to count subsequences having// maximum distinct elements // function to count subsequences having// maximum distinct elementsfunction countSubseq(arr, n){ // unordered_map 'um' implemented as // hash table var um = new Map(); var count = 1; // count frequency of each element for (var i = 0; i < n; i++) { if(um.has(arr[i])) um.set(arr[i], um.get(arr[i])+1) else um.set(arr[i], 1); } // traverse 'um' um.forEach((value, key) => { // multiply frequency of each element // and accumulate it in 'count' count *= value; }); // required number of subsequences return count;} // Driver program to test abovevar arr = [4, 7, 6, 7];var n = arr.length;document.write( \"Count = \" + countSubseq(arr, n)); // This code is contributed by noob2000.</script>", "e": 30876, "s": 29975, "text": null }, { "code": null, "e": 30886, "s": 30876, "text": "Output: " }, { "code": null, "e": 30896, "s": 30886, "text": "Count = 2" }, { "code": null, "e": 30943, "s": 30896, "text": "Time Complexity: O(n). Auxiliary Space: O(n). " }, { "code": null, "e": 30960, "s": 30943, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30972, "s": 30960, "text": "sanjeev2552" }, { "code": null, "e": 30985, "s": 30972, "text": "princi singh" }, { "code": null, "e": 30994, "s": 30985, "text": "noob2000" }, { "code": null, "e": 31006, "s": 30994, "text": "subsequence" }, { "code": null, "e": 31013, "s": 31006, "text": "Arrays" }, { "code": null, "e": 31027, "s": 31013, "text": "Combinatorial" }, { "code": null, "e": 31034, "s": 31027, "text": "Arrays" }, { "code": null, "e": 31048, "s": 31034, "text": "Combinatorial" }, { "code": null, "e": 31146, "s": 31048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31155, "s": 31146, "text": "Comments" }, { "code": null, "e": 31168, "s": 31155, "text": "Old Comments" }, { "code": null, "e": 31191, "s": 31168, "text": "Introduction to Arrays" }, { "code": null, "e": 31223, "s": 31191, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31237, "s": 31223, "text": "Linear Search" }, { "code": null, "e": 31322, "s": 31237, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 31343, "s": 31322, "text": "Linked List vs Array" }, { "code": null, "e": 31403, "s": 31343, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31441, "s": 31403, "text": "Permutation and Combination in Python" }, { "code": null, "e": 31518, "s": 31441, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 31546, "s": 31518, "text": "Factorial of a large number" } ]
Building and Evaluating Your Bayesian Statistical Model | by Juan Nathaniel | Towards Data Science
Even for a nondata-scientist, the term Bayesian statistics has been popular. You might have learned during your university days as one of the compulsory classes to take, not realizing how important Bayesian statistics is. In fact, Bayesian statistics is not just a particular method or even a class of methods; it is an entirely different paradigm for doing statistical analysis. Bayesian statistics provides you with the tools to update your beliefs in the evidence of new data, which is a notion that is common in many real-world scenarios, such as for tracking pandemics, forecasting economic trends, or predicting climate change. They are also the backbone of many of the more well-known statistical models, such as the Gaussian Process. towardsdatascience.com More importantly, learning the principles of Bayesian statistics can be a valuable asset for you as a data scientist because it gives you a fresh perspective to solving novel problems with dynamic sources of real-world data. Note: This is the second post out of a planned 5-part series covering the topic of Bayesian Statistical Programming. The first post covered the basic theories of Bayesian statistics and how to implement a simple one in Python. The first post covered the basic theories of Bayesian statistics and how to implement a simple one in Python. towardsdatascience.com 2. This will introduce you to Bayesian inference and how to perform basic model evaluations. 3. The third part will cover a special type of Bayesian algorithm called Monte Carlo Markov Chain (MCMC). towardsdatascience.com 4. The fourth part will build upon previous posts to build a more complex Bayesian model. 5. The fifth part will introduce you to the advanced concepts of the Bayesian model’s checking and evaluation. RecapInference and PredictionModel EvaluationSensitivity Analysis Recap Inference and Prediction Model Evaluation Sensitivity Analysis Without further ado, let’s begin the introduction to the Bayesian Statistical Programming post. In the first post here, I have discussed the basic principle of Bayesian statistics, the key terms, and how to implement a simple model using PyMC3. We use the Radon concentration (toxic gas) example to illustrate how Bayesian programming works in the real-world scenario. We will get you up to speed from where we left off. So, if you like to follow these steps in greater detail, please refer to my first post before proceeding further. Install dependencies (recommended to use conda) Install dependencies (recommended to use conda) conda install -c conda-forge pymc3 2. Download our data !wget "https://raw.githubusercontent.com/fonnesbeck/mcmc_pydata_london_2019/master/data/radon.csv" 3. Get the column of interest (log_radon) import pandas as pdradon = pd.read_csv('./radon.csv', index_col=0)anoka_radon = radon.query('county=="ANOKA"').log_radon 4. Build a simple Bayesian model from pymc3 import Model, Normal, Uniformwith Model() as radon_model: μ = Normal(’μ’, mu=0, sd=10) σ = Uniform(’σ’, 0, 10) 5. Compile and train the model with radon_model: dist = Normal('dist', mu=μ, sd=σ, observed=anoka_radon) 6. Draw some random samples from the trained Bayes model from pymc3 import samplewith radon_model: samples = sample(1000, tune=1000, cores=2, random_seed=12) Now that you have caught up with these steps, let’s move on to the main topics of this post: Bayesian inference and evaluation Given our trained Bayesian model, we can attempt to make a prediction or an inference. Suppose we are interested to find out the probability of any household in the US being exposed to log-radon concentration above 1.1 (ie. P(log-radon > 1.1)). We can perform a posterior probability prediction. Remember this guy from our previous post? But instead of estimating a parameter, θ (read: theta), from our observable data, y, we infer the log-radon concentration (z) as follows. And similar to the Bayesian formula, we can find the probability of z given all observations, y, by the following formula. The posterior prediction formula will sum up the probability of z given θ parameters multiplied by the probability of all θ given all observations y, for all values of possible θ Using PyMC3, we first sample the posterior distribution 1000 times to get 1000 values of z (log-radon). from pymc3 import sample_posterior_predictivewith radon_model: pp_samples = sample_posterior_predictive(samples, 1000) Then, we can find the mean value to retrieve the probability. radon_thres = 1.1(pp_samples['dist'] > radon_thres).mean()>>> 0.39105769230769233 The probability of a US household in ANOKA having a log-concentration of Radon above 1.1 is approximately 39.11%. But how do we know if our Bayesian model is any good? One of the basic evaluation methods would be to compare our prediction against the observable data. You can choose from a plethora of statistical tests, such as the t-test or F-test, to compare the similarity between the two “populations”. For our present use case, let’s use a graphic visualization to compare how our prediction fares with the empirical value. First, let’s find a collection of samples that exceeds our log-radon concentration threshold of 1.1: import seaborn as snsimport matplotlib.pyplot as pltp_thresh = [(sample>1.1).mean() for sample in pp_samples['dist']] Then we plot the distribution of these samples with the empirical value. ax = sns.distplot(p_thresh)plt.vlines((anoka_radon>1.1).mean(), *ax.set_ylim(), color='g') The green vertical line illustrates the mean empirical probability that a household in ANOKA has log-radon exposure concentration that is above 1.1, while the histogram represents our sampling distribution from the trained Bayesian model. The plot suggests that our initial assumption is not bad but there are rooms for improvements to make the distribution converge to the true empirical value. Further fine-tuning can be done by: Changing our assumptions about the distributions of your parameters,Experimenting with different initial values for our Bayes model Changing our assumptions about the distributions of your parameters, Experimenting with different initial values for our Bayes model It is also important to check for the sensitivity of our priors chosen earlier when building the model. This can be done by building the same model but varying the prior distributions as follow. from pymc3 import Flat, HalfCauchy, plot_posteriorwith Model() as sensitivity_check: μ = Flat('μ') σ = HalfCauchy('σ', 5) dist = Normal('dist', mu=μ, sd=σ, observed=anoka_radon) sensitivity_samples = sample(1000, cores=2) And then plotting the distribution. # Sensitivity evaluation distributionplot_posterior(sensitivity_samples, var_names=['μ'], ref_val=1.1) And comparing it with the original. # Original distributionplot_posterior(samples, var_names=['μ'], ref_val=1.1) Comparing both plots, our priors seem to be insensitive to variation (ie. pretty robust), highlighting that we are one step to achieving our goal! The only thing left is to make further adjustments to our model by constantly experimenting with different priors or initial values. We have discussed how to perform inference and evaluate our Bayesian models. In the next post, I will cover the underlying processes that govern Bayesian statistical programming, such as the Monte Carlo Markov Chain (MCMC) algorithm that helps us perform sampling. Stay tuned! Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization.
[ { "code": null, "e": 552, "s": 172, "text": "Even for a nondata-scientist, the term Bayesian statistics has been popular. You might have learned during your university days as one of the compulsory classes to take, not realizing how important Bayesian statistics is. In fact, Bayesian statistics is not just a particular method or even a class of methods; it is an entirely different paradigm for doing statistical analysis." }, { "code": null, "e": 914, "s": 552, "text": "Bayesian statistics provides you with the tools to update your beliefs in the evidence of new data, which is a notion that is common in many real-world scenarios, such as for tracking pandemics, forecasting economic trends, or predicting climate change. They are also the backbone of many of the more well-known statistical models, such as the Gaussian Process." }, { "code": null, "e": 937, "s": 914, "text": "towardsdatascience.com" }, { "code": null, "e": 1162, "s": 937, "text": "More importantly, learning the principles of Bayesian statistics can be a valuable asset for you as a data scientist because it gives you a fresh perspective to solving novel problems with dynamic sources of real-world data." }, { "code": null, "e": 1279, "s": 1162, "text": "Note: This is the second post out of a planned 5-part series covering the topic of Bayesian Statistical Programming." }, { "code": null, "e": 1389, "s": 1279, "text": "The first post covered the basic theories of Bayesian statistics and how to implement a simple one in Python." }, { "code": null, "e": 1499, "s": 1389, "text": "The first post covered the basic theories of Bayesian statistics and how to implement a simple one in Python." }, { "code": null, "e": 1522, "s": 1499, "text": "towardsdatascience.com" }, { "code": null, "e": 1615, "s": 1522, "text": "2. This will introduce you to Bayesian inference and how to perform basic model evaluations." }, { "code": null, "e": 1721, "s": 1615, "text": "3. The third part will cover a special type of Bayesian algorithm called Monte Carlo Markov Chain (MCMC)." }, { "code": null, "e": 1744, "s": 1721, "text": "towardsdatascience.com" }, { "code": null, "e": 1834, "s": 1744, "text": "4. The fourth part will build upon previous posts to build a more complex Bayesian model." }, { "code": null, "e": 1945, "s": 1834, "text": "5. The fifth part will introduce you to the advanced concepts of the Bayesian model’s checking and evaluation." }, { "code": null, "e": 2011, "s": 1945, "text": "RecapInference and PredictionModel EvaluationSensitivity Analysis" }, { "code": null, "e": 2017, "s": 2011, "text": "Recap" }, { "code": null, "e": 2042, "s": 2017, "text": "Inference and Prediction" }, { "code": null, "e": 2059, "s": 2042, "text": "Model Evaluation" }, { "code": null, "e": 2080, "s": 2059, "text": "Sensitivity Analysis" }, { "code": null, "e": 2176, "s": 2080, "text": "Without further ado, let’s begin the introduction to the Bayesian Statistical Programming post." }, { "code": null, "e": 2449, "s": 2176, "text": "In the first post here, I have discussed the basic principle of Bayesian statistics, the key terms, and how to implement a simple model using PyMC3. We use the Radon concentration (toxic gas) example to illustrate how Bayesian programming works in the real-world scenario." }, { "code": null, "e": 2615, "s": 2449, "text": "We will get you up to speed from where we left off. So, if you like to follow these steps in greater detail, please refer to my first post before proceeding further." }, { "code": null, "e": 2663, "s": 2615, "text": "Install dependencies (recommended to use conda)" }, { "code": null, "e": 2711, "s": 2663, "text": "Install dependencies (recommended to use conda)" }, { "code": null, "e": 2746, "s": 2711, "text": "conda install -c conda-forge pymc3" }, { "code": null, "e": 2767, "s": 2746, "text": "2. Download our data" }, { "code": null, "e": 2866, "s": 2767, "text": "!wget \"https://raw.githubusercontent.com/fonnesbeck/mcmc_pydata_london_2019/master/data/radon.csv\"" }, { "code": null, "e": 2908, "s": 2866, "text": "3. Get the column of interest (log_radon)" }, { "code": null, "e": 3029, "s": 2908, "text": "import pandas as pdradon = pd.read_csv('./radon.csv', index_col=0)anoka_radon = radon.query('county==\"ANOKA\"').log_radon" }, { "code": null, "e": 3062, "s": 3029, "text": "4. Build a simple Bayesian model" }, { "code": null, "e": 3190, "s": 3062, "text": "from pymc3 import Model, Normal, Uniformwith Model() as radon_model: μ = Normal(’μ’, mu=0, sd=10) σ = Uniform(’σ’, 0, 10)" }, { "code": null, "e": 3221, "s": 3190, "text": "5. Compile and train the model" }, { "code": null, "e": 3298, "s": 3221, "text": "with radon_model: dist = Normal('dist', mu=μ, sd=σ, observed=anoka_radon)" }, { "code": null, "e": 3355, "s": 3298, "text": "6. Draw some random samples from the trained Bayes model" }, { "code": null, "e": 3459, "s": 3355, "text": "from pymc3 import samplewith radon_model: samples = sample(1000, tune=1000, cores=2, random_seed=12)" }, { "code": null, "e": 3586, "s": 3459, "text": "Now that you have caught up with these steps, let’s move on to the main topics of this post: Bayesian inference and evaluation" }, { "code": null, "e": 3831, "s": 3586, "text": "Given our trained Bayesian model, we can attempt to make a prediction or an inference. Suppose we are interested to find out the probability of any household in the US being exposed to log-radon concentration above 1.1 (ie. P(log-radon > 1.1))." }, { "code": null, "e": 3924, "s": 3831, "text": "We can perform a posterior probability prediction. Remember this guy from our previous post?" }, { "code": null, "e": 4062, "s": 3924, "text": "But instead of estimating a parameter, θ (read: theta), from our observable data, y, we infer the log-radon concentration (z) as follows." }, { "code": null, "e": 4185, "s": 4062, "text": "And similar to the Bayesian formula, we can find the probability of z given all observations, y, by the following formula." }, { "code": null, "e": 4364, "s": 4185, "text": "The posterior prediction formula will sum up the probability of z given θ parameters multiplied by the probability of all θ given all observations y, for all values of possible θ" }, { "code": null, "e": 4468, "s": 4364, "text": "Using PyMC3, we first sample the posterior distribution 1000 times to get 1000 values of z (log-radon)." }, { "code": null, "e": 4590, "s": 4468, "text": "from pymc3 import sample_posterior_predictivewith radon_model: pp_samples = sample_posterior_predictive(samples, 1000)" }, { "code": null, "e": 4652, "s": 4590, "text": "Then, we can find the mean value to retrieve the probability." }, { "code": null, "e": 4734, "s": 4652, "text": "radon_thres = 1.1(pp_samples['dist'] > radon_thres).mean()>>> 0.39105769230769233" }, { "code": null, "e": 4848, "s": 4734, "text": "The probability of a US household in ANOKA having a log-concentration of Radon above 1.1 is approximately 39.11%." }, { "code": null, "e": 4902, "s": 4848, "text": "But how do we know if our Bayesian model is any good?" }, { "code": null, "e": 5142, "s": 4902, "text": "One of the basic evaluation methods would be to compare our prediction against the observable data. You can choose from a plethora of statistical tests, such as the t-test or F-test, to compare the similarity between the two “populations”." }, { "code": null, "e": 5264, "s": 5142, "text": "For our present use case, let’s use a graphic visualization to compare how our prediction fares with the empirical value." }, { "code": null, "e": 5365, "s": 5264, "text": "First, let’s find a collection of samples that exceeds our log-radon concentration threshold of 1.1:" }, { "code": null, "e": 5483, "s": 5365, "text": "import seaborn as snsimport matplotlib.pyplot as pltp_thresh = [(sample>1.1).mean() for sample in pp_samples['dist']]" }, { "code": null, "e": 5556, "s": 5483, "text": "Then we plot the distribution of these samples with the empirical value." }, { "code": null, "e": 5647, "s": 5556, "text": "ax = sns.distplot(p_thresh)plt.vlines((anoka_radon>1.1).mean(), *ax.set_ylim(), color='g')" }, { "code": null, "e": 5886, "s": 5647, "text": "The green vertical line illustrates the mean empirical probability that a household in ANOKA has log-radon exposure concentration that is above 1.1, while the histogram represents our sampling distribution from the trained Bayesian model." }, { "code": null, "e": 6079, "s": 5886, "text": "The plot suggests that our initial assumption is not bad but there are rooms for improvements to make the distribution converge to the true empirical value. Further fine-tuning can be done by:" }, { "code": null, "e": 6211, "s": 6079, "text": "Changing our assumptions about the distributions of your parameters,Experimenting with different initial values for our Bayes model" }, { "code": null, "e": 6280, "s": 6211, "text": "Changing our assumptions about the distributions of your parameters," }, { "code": null, "e": 6344, "s": 6280, "text": "Experimenting with different initial values for our Bayes model" }, { "code": null, "e": 6448, "s": 6344, "text": "It is also important to check for the sensitivity of our priors chosen earlier when building the model." }, { "code": null, "e": 6539, "s": 6448, "text": "This can be done by building the same model but varying the prior distributions as follow." }, { "code": null, "e": 6785, "s": 6539, "text": "from pymc3 import Flat, HalfCauchy, plot_posteriorwith Model() as sensitivity_check: μ = Flat('μ') σ = HalfCauchy('σ', 5) dist = Normal('dist', mu=μ, sd=σ, observed=anoka_radon) sensitivity_samples = sample(1000, cores=2)" }, { "code": null, "e": 6821, "s": 6785, "text": "And then plotting the distribution." }, { "code": null, "e": 6924, "s": 6821, "text": "# Sensitivity evaluation distributionplot_posterior(sensitivity_samples, var_names=['μ'], ref_val=1.1)" }, { "code": null, "e": 6960, "s": 6924, "text": "And comparing it with the original." }, { "code": null, "e": 7037, "s": 6960, "text": "# Original distributionplot_posterior(samples, var_names=['μ'], ref_val=1.1)" }, { "code": null, "e": 7317, "s": 7037, "text": "Comparing both plots, our priors seem to be insensitive to variation (ie. pretty robust), highlighting that we are one step to achieving our goal! The only thing left is to make further adjustments to our model by constantly experimenting with different priors or initial values." }, { "code": null, "e": 7594, "s": 7317, "text": "We have discussed how to perform inference and evaluate our Bayesian models. In the next post, I will cover the underlying processes that govern Bayesian statistical programming, such as the Monte Carlo Markov Chain (MCMC) algorithm that helps us perform sampling. Stay tuned!" } ]
SQL vs NoSQL in 8 Examples. Practical guide to compare basic... | by Soner Yıldırım | Towards Data Science
Relational databases store data in tabular form with labelled rows and columns. Although relational databases usually provide a decent solution for storing data, speed and scalability might be an issue in some cases. SQL (Structured Query Language) is used by most relational database managements systems to manage databases that store data in tabular form. NoSQL refers to non-SQL or non-relational database design. It still provides an organized way of storing data but not in tabular form. Put aside the concern for speed and scalability, both SQL and NoSQL databases provide versatile and efficient ways to query data. It is a must for a database because the accessibility is of crucial importance as well. In this article, we will cover 8 examples that demonstrate how to query a SQL and NoSQL database. The examples will cover how to: Select data based on condition Insert new items Update existing items Apply aggregation functions I will complete the same tasks in both databases so that we can see the differences and similarities. I will be using MySQL for SQL and MongoDB for NoSQL. Before starting with the examples, let’s briefly explain how data is stored in SQL and NoSQL. SQL stores data in tabular form with labelled rows and columns. The common structures adapted by NoSQL databases to store data are key-value pairs, wide column, graph, or document. MongoDB stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called “collection”. As an analogy, we can think of documents as rows in a table and collections as tables. I have created a simple table in MySQL and collection in MongoDB with same data that contains features of some cars and their prices. Here is a document that identifies one item in the car collection: { "_id" : ObjectId("600c626932e0e6419cee81a7"), "year" : "2017", "make" : "hyundai", "color" : "white", "km" : 22000, "price" : 32000} In SQL, a data point (one car in our case) is identified by a row. +------+---------+-------+-------+-------+| year | make | color | km | price |+------+---------+-------+-------+-------+| 2017 | hyundai | white | 22000 | 32000 |+------+---------+-------+-------+-------+ Find the cars made by Ford. NoSQL (MongoDB): We pass the condition to the find function. The “db” refers to the current database and “car” is the collection we are querying. > db.car.find( {make: "ford"} ).limit(1).pretty(){ "_id" : ObjectId("600c63cf32e0e6419cee81ab"), "year" : "2017", "make" : "ford", "color" : "black", "km" : 34000, "price" : 28000} There are more than one car made by Ford but I use the limit function to display only one. The pretty function makes the output more readable and appealing. Here is how it looks without the pretty function. > db.car.find( {make: "ford"} ).limit(1){ "_id" : ObjectId("600c63cf32e0e6419cee81ab"), "year" : "2017", "make" : "ford", "color" : "black", "km" : 34000, "price" : 28000 } SQL (MySQL): We select all columns (*) and specify the condition in the where clause. mysql> select * from car -> where make = "ford" -> limit 1;+------+------+-------+-------+-------+| year | make | color | km | price |+------+------+-------+-------+-------+| 2017 | ford | black | 34000 | 28000 |+------+------+-------+-------+-------+ Find the cars made by Ford in 2019. NoSQL (MongoDB): We can pass multiple conditions separated by comma to indicate the “and” logic on the conditions. > db.car.find( {make: "ford", year: "2019"} ).pretty(){ "_id" : ObjectId("600c63cf32e0e6419cee81af"), "year" : "2019", "make" : "ford", "color" : "white", "km" : 8000, "price" : 42000} SQL (MySQL): It is similar to the previous example. We can combine multiple conditions in the where clause using the and operator. mysql> select * from car -> where make = "ford" and year = "2019";+------+------+-------+------+-------+| year | make | color | km | price |+------+------+-------+------+-------+| 2019 | ford | white | 8000 | 42000 |+------+------+-------+------+-------+ Find the cars made by Ford or Hyundai in year 2017. NoSQL (MongoDB): We first combine the condition on the brand with the “or” logic and then combine with year using the “and” logic. The “$in” operator can be used for the “or” logic. > db.car.find( {make: {$in: ["ford","hyundai"] } , year: "2017"} ).pretty(){ "_id" : ObjectId("600c626932e0e6419cee81a7"), "year" : "2017", "make" : "hyundai", "color" : "white", "km" : 22000, "price" : 32000}{ "_id" : ObjectId("600c63cf32e0e6419cee81ab"), "year" : "2017", "make" : "ford", "color" : "black", "km" : 34000, "price" : 28000} SQL (MySQL): The where clause accepts the “in” operator so we can specify the conditions similar to NoSQL. mysql> select * from car -> where make in ("ford","hyundai") and year = "2017";+------+---------+-------+-------+-------+| year | make | color | km | price |+------+---------+-------+-------+-------+| 2017 | hyundai | white | 22000 | 32000 || 2017 | ford | black | 34000 | 28000 |+------+---------+-------+-------+-------+ Insert a new item. NoSQL (MongoDB): The “insertOne” function is used to insert a single document to a collection. We need to write the field-value pairs of the new document. > db.car.insertOne(... {year: "2017", make: "bmw", color: "silver", ... km: 28000, price: 39000}... ){ "acknowledged" : true, "insertedId" : ObjectId("600c6bc79445b834692e3b91")} SQL (MySQL): The “insert into” function is used to add a new row into a table. Unlike NoSQL, we do not need to write the column names. However, the order of values must match the order of columns in the table. mysql> insert into car values -> ("2017", "bmw", "silver", 28000, 39000);Query OK, 1 row affected (0.03 sec) Update the brand “bmw” as “BMW”. NoSQL (MongoDB): The update function is used. We first pass the condition that indicates the documents to be updated and then pass the updated values along with the set keyword. > db.car.update(... { make: "bmw" },... { $set: { make: "BMW" }},... { multi: true }... )WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 }) We need to use the multi parameter to update all the documents that meet the given condition. Otherwise, only one document gets updated. SQL (MySQL): We use the update statement as below: mysql> update car -> set make = "BMW" -> where make = "bmw";Query OK, 5 rows affected (0.05 sec)Rows matched: 5 Changed: 5 Warnings: 0 Both SQL and NoSQL are highly versatile in terms of data aggregation while querying a database. For instance, we can easily calculate the average price for each brand. NoSQL (MongoDB): We use the aggregate function. > db.car.aggregate([... { $group: { _id: "$make", avg_price: { $avg: "$price" }}}... ]){ "_id" : "hyundai", "avg_price" : 36333.333333333336 }{ "_id" : "BMW", "avg_price" : 47400 }{ "_id" : "ford", "avg_price" : 35333.333333333336 } We first group the documents based on brands by selecting “$make” as id. The next part specifies both the aggregation function which is “$avg” in our case and the field to be aggregated. If you are familiar with Pandas, the syntax is quite similar to the groupby function. SQL (MySQL): The group by clause is used to group the rows based on categories in the given column. The aggregate function is applied when selecting the column. mysql> select make, avg(price) -> from car -> group by make;+---------+------------+| make | avg(price) |+---------+------------+| BMW | 47400.0000 || ford | 35333.3333 || hyundai | 36333.3333 |+---------+------------+ We can implement conditions in the aggregate function. For each brand, let’s calculate the average price of cars made in 2019. NoSQL (MongoDB): We just need to add the match keyword to specify the condition. > db.car.aggregate([... { $match: { year: "2019" }},... { $group: { _id: "$make", avg_price: { $avg: "$price" }}}... ]){ "_id" : "BMW", "avg_price" : 53000 }{ "_id" : "ford", "avg_price" : 42000 }{ "_id" : "hyundai", "avg_price" : 41000 } SQL (MySQL): We use both where and group by clauses as below: mysql> select make, avg(price) -> from car -> where year = "2019" -> group by make;+---------+------------+| make | avg(price) |+---------+------------+| BMW | 53000.0000 || ford | 42000.0000 || hyundai | 41000.0000 |+---------+------------+ We have covered 8 examples that demonstrate basic operations to deal with SQL and NoSQL databases. Both of them provide many more functions and methods to create more advanced queries. As a result, they can also be used as data analysis and manipulation tools. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 389, "s": 172, "text": "Relational databases store data in tabular form with labelled rows and columns. Although relational databases usually provide a decent solution for storing data, speed and scalability might be an issue in some cases." }, { "code": null, "e": 665, "s": 389, "text": "SQL (Structured Query Language) is used by most relational database managements systems to manage databases that store data in tabular form. NoSQL refers to non-SQL or non-relational database design. It still provides an organized way of storing data but not in tabular form." }, { "code": null, "e": 883, "s": 665, "text": "Put aside the concern for speed and scalability, both SQL and NoSQL databases provide versatile and efficient ways to query data. It is a must for a database because the accessibility is of crucial importance as well." }, { "code": null, "e": 1013, "s": 883, "text": "In this article, we will cover 8 examples that demonstrate how to query a SQL and NoSQL database. The examples will cover how to:" }, { "code": null, "e": 1044, "s": 1013, "text": "Select data based on condition" }, { "code": null, "e": 1061, "s": 1044, "text": "Insert new items" }, { "code": null, "e": 1083, "s": 1061, "text": "Update existing items" }, { "code": null, "e": 1111, "s": 1083, "text": "Apply aggregation functions" }, { "code": null, "e": 1213, "s": 1111, "text": "I will complete the same tasks in both databases so that we can see the differences and similarities." }, { "code": null, "e": 1360, "s": 1213, "text": "I will be using MySQL for SQL and MongoDB for NoSQL. Before starting with the examples, let’s briefly explain how data is stored in SQL and NoSQL." }, { "code": null, "e": 1775, "s": 1360, "text": "SQL stores data in tabular form with labelled rows and columns. The common structures adapted by NoSQL databases to store data are key-value pairs, wide column, graph, or document. MongoDB stores data as documents. A document in MongoDB consists of field-value pairs. Documents are organized in a structure called “collection”. As an analogy, we can think of documents as rows in a table and collections as tables." }, { "code": null, "e": 1909, "s": 1775, "text": "I have created a simple table in MySQL and collection in MongoDB with same data that contains features of some cars and their prices." }, { "code": null, "e": 1976, "s": 1909, "text": "Here is a document that identifies one item in the car collection:" }, { "code": null, "e": 2111, "s": 1976, "text": "{ \"_id\" : ObjectId(\"600c626932e0e6419cee81a7\"), \"year\" : \"2017\", \"make\" : \"hyundai\", \"color\" : \"white\", \"km\" : 22000, \"price\" : 32000}" }, { "code": null, "e": 2178, "s": 2111, "text": "In SQL, a data point (one car in our case) is identified by a row." }, { "code": null, "e": 2389, "s": 2178, "text": "+------+---------+-------+-------+-------+| year | make | color | km | price |+------+---------+-------+-------+-------+| 2017 | hyundai | white | 22000 | 32000 |+------+---------+-------+-------+-------+" }, { "code": null, "e": 2417, "s": 2389, "text": "Find the cars made by Ford." }, { "code": null, "e": 2434, "s": 2417, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 2563, "s": 2434, "text": "We pass the condition to the find function. The “db” refers to the current database and “car” is the collection we are querying." }, { "code": null, "e": 2744, "s": 2563, "text": "> db.car.find( {make: \"ford\"} ).limit(1).pretty(){ \"_id\" : ObjectId(\"600c63cf32e0e6419cee81ab\"), \"year\" : \"2017\", \"make\" : \"ford\", \"color\" : \"black\", \"km\" : 34000, \"price\" : 28000}" }, { "code": null, "e": 2835, "s": 2744, "text": "There are more than one car made by Ford but I use the limit function to display only one." }, { "code": null, "e": 2951, "s": 2835, "text": "The pretty function makes the output more readable and appealing. Here is how it looks without the pretty function." }, { "code": null, "e": 3124, "s": 2951, "text": "> db.car.find( {make: \"ford\"} ).limit(1){ \"_id\" : ObjectId(\"600c63cf32e0e6419cee81ab\"), \"year\" : \"2017\", \"make\" : \"ford\", \"color\" : \"black\", \"km\" : 34000, \"price\" : 28000 }" }, { "code": null, "e": 3137, "s": 3124, "text": "SQL (MySQL):" }, { "code": null, "e": 3210, "s": 3137, "text": "We select all columns (*) and specify the condition in the where clause." }, { "code": null, "e": 3471, "s": 3210, "text": "mysql> select * from car -> where make = \"ford\" -> limit 1;+------+------+-------+-------+-------+| year | make | color | km | price |+------+------+-------+-------+-------+| 2017 | ford | black | 34000 | 28000 |+------+------+-------+-------+-------+" }, { "code": null, "e": 3507, "s": 3471, "text": "Find the cars made by Ford in 2019." }, { "code": null, "e": 3524, "s": 3507, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 3622, "s": 3524, "text": "We can pass multiple conditions separated by comma to indicate the “and” logic on the conditions." }, { "code": null, "e": 3807, "s": 3622, "text": "> db.car.find( {make: \"ford\", year: \"2019\"} ).pretty(){ \"_id\" : ObjectId(\"600c63cf32e0e6419cee81af\"), \"year\" : \"2019\", \"make\" : \"ford\", \"color\" : \"white\", \"km\" : 8000, \"price\" : 42000}" }, { "code": null, "e": 3820, "s": 3807, "text": "SQL (MySQL):" }, { "code": null, "e": 3938, "s": 3820, "text": "It is similar to the previous example. We can combine multiple conditions in the where clause using the and operator." }, { "code": null, "e": 4198, "s": 3938, "text": "mysql> select * from car -> where make = \"ford\" and year = \"2019\";+------+------+-------+------+-------+| year | make | color | km | price |+------+------+-------+------+-------+| 2019 | ford | white | 8000 | 42000 |+------+------+-------+------+-------+" }, { "code": null, "e": 4250, "s": 4198, "text": "Find the cars made by Ford or Hyundai in year 2017." }, { "code": null, "e": 4267, "s": 4250, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 4432, "s": 4267, "text": "We first combine the condition on the brand with the “or” logic and then combine with year using the “and” logic. The “$in” operator can be used for the “or” logic." }, { "code": null, "e": 4773, "s": 4432, "text": "> db.car.find( {make: {$in: [\"ford\",\"hyundai\"] } , year: \"2017\"} ).pretty(){ \"_id\" : ObjectId(\"600c626932e0e6419cee81a7\"), \"year\" : \"2017\", \"make\" : \"hyundai\", \"color\" : \"white\", \"km\" : 22000, \"price\" : 32000}{ \"_id\" : ObjectId(\"600c63cf32e0e6419cee81ab\"), \"year\" : \"2017\", \"make\" : \"ford\", \"color\" : \"black\", \"km\" : 34000, \"price\" : 28000}" }, { "code": null, "e": 4786, "s": 4773, "text": "SQL (MySQL):" }, { "code": null, "e": 4880, "s": 4786, "text": "The where clause accepts the “in” operator so we can specify the conditions similar to NoSQL." }, { "code": null, "e": 5215, "s": 4880, "text": "mysql> select * from car -> where make in (\"ford\",\"hyundai\") and year = \"2017\";+------+---------+-------+-------+-------+| year | make | color | km | price |+------+---------+-------+-------+-------+| 2017 | hyundai | white | 22000 | 32000 || 2017 | ford | black | 34000 | 28000 |+------+---------+-------+-------+-------+" }, { "code": null, "e": 5234, "s": 5215, "text": "Insert a new item." }, { "code": null, "e": 5251, "s": 5234, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 5389, "s": 5251, "text": "The “insertOne” function is used to insert a single document to a collection. We need to write the field-value pairs of the new document." }, { "code": null, "e": 5569, "s": 5389, "text": "> db.car.insertOne(... {year: \"2017\", make: \"bmw\", color: \"silver\", ... km: 28000, price: 39000}... ){ \"acknowledged\" : true, \"insertedId\" : ObjectId(\"600c6bc79445b834692e3b91\")}" }, { "code": null, "e": 5582, "s": 5569, "text": "SQL (MySQL):" }, { "code": null, "e": 5779, "s": 5582, "text": "The “insert into” function is used to add a new row into a table. Unlike NoSQL, we do not need to write the column names. However, the order of values must match the order of columns in the table." }, { "code": null, "e": 5892, "s": 5779, "text": "mysql> insert into car values -> (\"2017\", \"bmw\", \"silver\", 28000, 39000);Query OK, 1 row affected (0.03 sec)" }, { "code": null, "e": 5925, "s": 5892, "text": "Update the brand “bmw” as “BMW”." }, { "code": null, "e": 5942, "s": 5925, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 6103, "s": 5942, "text": "The update function is used. We first pass the condition that indicates the documents to be updated and then pass the updated values along with the set keyword." }, { "code": null, "e": 6258, "s": 6103, "text": "> db.car.update(... { make: \"bmw\" },... { $set: { make: \"BMW\" }},... { multi: true }... )WriteResult({ \"nMatched\" : 5, \"nUpserted\" : 0, \"nModified\" : 5 })" }, { "code": null, "e": 6395, "s": 6258, "text": "We need to use the multi parameter to update all the documents that meet the given condition. Otherwise, only one document gets updated." }, { "code": null, "e": 6408, "s": 6395, "text": "SQL (MySQL):" }, { "code": null, "e": 6446, "s": 6408, "text": "We use the update statement as below:" }, { "code": null, "e": 6589, "s": 6446, "text": "mysql> update car -> set make = \"BMW\" -> where make = \"bmw\";Query OK, 5 rows affected (0.05 sec)Rows matched: 5 Changed: 5 Warnings: 0" }, { "code": null, "e": 6757, "s": 6589, "text": "Both SQL and NoSQL are highly versatile in terms of data aggregation while querying a database. For instance, we can easily calculate the average price for each brand." }, { "code": null, "e": 6774, "s": 6757, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 6805, "s": 6774, "text": "We use the aggregate function." }, { "code": null, "e": 7038, "s": 6805, "text": "> db.car.aggregate([... { $group: { _id: \"$make\", avg_price: { $avg: \"$price\" }}}... ]){ \"_id\" : \"hyundai\", \"avg_price\" : 36333.333333333336 }{ \"_id\" : \"BMW\", \"avg_price\" : 47400 }{ \"_id\" : \"ford\", \"avg_price\" : 35333.333333333336 }" }, { "code": null, "e": 7225, "s": 7038, "text": "We first group the documents based on brands by selecting “$make” as id. The next part specifies both the aggregation function which is “$avg” in our case and the field to be aggregated." }, { "code": null, "e": 7311, "s": 7225, "text": "If you are familiar with Pandas, the syntax is quite similar to the groupby function." }, { "code": null, "e": 7324, "s": 7311, "text": "SQL (MySQL):" }, { "code": null, "e": 7472, "s": 7324, "text": "The group by clause is used to group the rows based on categories in the given column. The aggregate function is applied when selecting the column." }, { "code": null, "e": 7707, "s": 7472, "text": "mysql> select make, avg(price) -> from car -> group by make;+---------+------------+| make | avg(price) |+---------+------------+| BMW | 47400.0000 || ford | 35333.3333 || hyundai | 36333.3333 |+---------+------------+" }, { "code": null, "e": 7834, "s": 7707, "text": "We can implement conditions in the aggregate function. For each brand, let’s calculate the average price of cars made in 2019." }, { "code": null, "e": 7851, "s": 7834, "text": "NoSQL (MongoDB):" }, { "code": null, "e": 7915, "s": 7851, "text": "We just need to add the match keyword to specify the condition." }, { "code": null, "e": 8154, "s": 7915, "text": "> db.car.aggregate([... { $match: { year: \"2019\" }},... { $group: { _id: \"$make\", avg_price: { $avg: \"$price\" }}}... ]){ \"_id\" : \"BMW\", \"avg_price\" : 53000 }{ \"_id\" : \"ford\", \"avg_price\" : 42000 }{ \"_id\" : \"hyundai\", \"avg_price\" : 41000 }" }, { "code": null, "e": 8167, "s": 8154, "text": "SQL (MySQL):" }, { "code": null, "e": 8216, "s": 8167, "text": "We use both where and group by clauses as below:" }, { "code": null, "e": 8477, "s": 8216, "text": "mysql> select make, avg(price) -> from car -> where year = \"2019\" -> group by make;+---------+------------+| make | avg(price) |+---------+------------+| BMW | 53000.0000 || ford | 42000.0000 || hyundai | 41000.0000 |+---------+------------+" }, { "code": null, "e": 8576, "s": 8477, "text": "We have covered 8 examples that demonstrate basic operations to deal with SQL and NoSQL databases." }, { "code": null, "e": 8738, "s": 8576, "text": "Both of them provide many more functions and methods to create more advanced queries. As a result, they can also be used as data analysis and manipulation tools." } ]
Using Object Detection for Complex Image Classification Scenarios Part 2: | by Aaron (Ari) Bornstein | Towards Data Science
TLDR; This series is based on the work detecting complex policies in the following real life code story. Code for the series can be found here. In the last post of the series, we outlined the challenge of a complex image classification task in this post we will introduce and evaluate the Azure Custom Vision Service as a technique for solving our challenge. Custom Vision Service is a tool for building custom image classifiers. It makes it easy and fast to build, deploy, and improve an image classifier. We provide a REST API and a web interface to upload your images and train. The Custom Vision Service is a tool for building custom image classifiers, and for making them better over time. For example, if you want a tool that could identify images of “Daisies”, “Daffodils”, and “Dahlias”, you could train a classifier to do that. You do so by providing Custom Vision Service with images for each tag you want to recognize. Custom Vision Service works best when the item you are trying to classify is prominent in your image. Custom Vision Service does “image classification” but not yet “object detection.” This means that Custom Vision Service identifies whether an image is of a particular object, but not where that object is within the image. Very few images are required to create a classifier — 30 images per class is enough to start your prototype. The methods Custom Vision Service uses are robust to differences, which allows you to start prototyping with so little data. However, this means Custom Vision Service is not well suited to scenarios where you want to detect very subtle differences (for example, minor cracks or dents in quality assurance scenarios.) Custom Vision Service is designed to make it easy to start building your classifier, and to help you improve the quality of your classifier over time. Developers can also export their models to be run on the edge devices such as iOS, Android or the RaspberryPi The Steps below will walk you through training a model for our challenge pro-grammatically with python with the custom vision service. The following steps are based on the documentation quick start. Obtain your training and prediction key by logging into the Custom Vision Service and navigating to account settings as shown below. Next we need to programatically make a new custom vision service project using the keys your sourced above. from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClientfrom azure.cognitiveservices.vision.customvision.training.models import ImageUrlCreateEntryENDPOINT = "https://southcentralus.api.cognitive.microsoft.com"# Replace with a valid keytraining_key = '' #<your training key>prediction_key = '' #<your prediction key>trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT)# Create a new projectprint("Creating Beverage Policy Classifier...")project = trainer.create_project("Beverage Policy Classifier") Creating Beverage Policy Classifier... Run the following code to create tags for our Valid and Invalid Examples # Make two tags in the new projectvalid_tag = trainer.create_tag(project.id, "Valid")invalid_tag = trainer.create_tag(project.id, "Invalid") To add the images we have to the project, insert the following code after the tag creation. This will upload the image with the corresponding tag. print ("Adding images...")import osfrom multiprocessing.dummy import Pool as ThreadPooldef upload(filepath): with open(filepath, mode="rb") as img_data: if "Invalid" in filepath: trainer.create_images_from_data(project.id, img_data.read(), [ invalid_tag.id ]) else: trainer.create_images_from_data(project.id, img_data.read(), [ valid_tag.id ]) print('.', end='') def upload_parallel(filepaths, threads=5): pool = ThreadPool(threads) results = pool.map(upload, filepaths) pool.close() pool.join()valid_dir = "dataset/Beverages/Train/Valid/"invalid_dir = "dataset/Beverages/Train/Invalid/"valid_paths = [valid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(valid_dir))]invalid_paths = [invalid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(invalid_dir))]img_paths = valid_paths + invalid_pathsupload_parallel(img_paths)print("Added {} images, {} valid, {} invalid.".format(len(img_paths), len(valid_paths), len(invalid_paths))) Adding images.......................................................................................................................................................................................Added 180 images, 90 valid, 90 invalid. Now that we’ve added tags and images to the project, we can train it. This creates the first iteration in the project. We can then mark this iteration as the default iteration. import timeprint ("Training...")iteration = trainer.train_project(project.id)while (iteration.status == "Training"): iteration = trainer.get_iteration(project.id, iteration.id) print ("Training status: " + iteration.status) time.sleep(1) Training...Training status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: Completed Now lets evaluate the model on the local test dataset that the service has never seen. from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient # Now there is a trained endpoint, it can be used to make a predictionpredictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT)project_id = project.iddef predict(filepath): with open(filepath, mode="rb") as test_data: results = predictor.predict_image(project_id, test_data.read(), iteration.id) pred = max(results.predictions, key=lambda x:x.probability).tag_name true ='Invalid' if "Invalid" in filepath else 'Valid' print('.', pred , end='') return (true, pred) def predict_parallel(filepaths, threads=2): pool = ThreadPool(threads) results = pool.map(predict, filepaths) pool.close() pool.join() return zip(*results)test_valid_dir = "dataset/Beverages/Test/Valid/"test_invalid_dir = "dataset/Beverages/Test//Invalid/"test_valid_paths = [test_valid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(test_valid_dir))]test_invalid_paths = [test_invalid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(test_invalid_dir))]test_img_paths = test_valid_paths + test_invalid_pathsy_true, y_pred = predict_parallel(test_img_paths) . Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Invalid. Valid. Invalid. Valid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid from utils import classification_reportclassification_report(y_true, y_pred) precision recall f1-score support Invalid 1.00 1.00 1.00 30 Valid 1.00 1.00 1.00 30 micro avg 1.00 1.00 1.00 60 macro avg 1.00 1.00 1.00 60weighted avg 1.00 1.00 1.00 60Confusion matrix, without normalization[[30 0] [ 0 30]]Normalized confusion matrix[[1. 0.] [0. 1.]] As you can see the custom vision service is a great tool for generating strong models with relatively small amount of data and little work. In the majority of use cases its a go too tool and a great place to get started.Custom Vision Service works best when the item you are trying to classify is prominent in your image. The service is a go to starting point for any classification task. However there are a couple of items to consider when deploying for production. What are the cases that the service fails on (It could be that the 2% error case appears 30% in production or are the most important cases to consider for your use case.How many classes/policies are you classifying (The models work better with 2–10 policies )What domain is your task? What are the cases that the service fails on (It could be that the 2% error case appears 30% in production or are the most important cases to consider for your use case. How many classes/policies are you classifying (The models work better with 2–10 policies ) What domain is your task? medium.com github.com azure.microsoft.com The next post in this series will review how to approach this task with the Policy Recognition with Keras CNNs, MobileNet and Transfer Learning subsequent posts will address the following: Policy Detection with Keras RetinaNet Training and Computer Vision Models on the Cloud using Azure ML Service Train a Computer Vision Model on a Remote Cluster with Azure Machine Learning If you have any questions, comments, or topics you would like me to discuss feel free to follow me on Twitter if there is a milestone you feel I missed please let me know. Aaron (Ari) Bornstein is an avid AI enthusiast with a passion for history, engaging with new technologies and computational medicine. As an Open Source Engineer at Microsoft’s Cloud Developer Advocacy team, he collaborates with Israeli Hi-Tech Community, to solve real world problems with game changing technologies that are then documented, open sourced, and shared with the rest of the world.
[ { "code": null, "e": 316, "s": 172, "text": "TLDR; This series is based on the work detecting complex policies in the following real life code story. Code for the series can be found here." }, { "code": null, "e": 531, "s": 316, "text": "In the last post of the series, we outlined the challenge of a complex image classification task in this post we will introduce and evaluate the Azure Custom Vision Service as a technique for solving our challenge." }, { "code": null, "e": 754, "s": 531, "text": "Custom Vision Service is a tool for building custom image classifiers. It makes it easy and fast to build, deploy, and improve an image classifier. We provide a REST API and a web interface to upload your images and train." }, { "code": null, "e": 1102, "s": 754, "text": "The Custom Vision Service is a tool for building custom image classifiers, and for making them better over time. For example, if you want a tool that could identify images of “Daisies”, “Daffodils”, and “Dahlias”, you could train a classifier to do that. You do so by providing Custom Vision Service with images for each tag you want to recognize." }, { "code": null, "e": 1426, "s": 1102, "text": "Custom Vision Service works best when the item you are trying to classify is prominent in your image. Custom Vision Service does “image classification” but not yet “object detection.” This means that Custom Vision Service identifies whether an image is of a particular object, but not where that object is within the image." }, { "code": null, "e": 1852, "s": 1426, "text": "Very few images are required to create a classifier — 30 images per class is enough to start your prototype. The methods Custom Vision Service uses are robust to differences, which allows you to start prototyping with so little data. However, this means Custom Vision Service is not well suited to scenarios where you want to detect very subtle differences (for example, minor cracks or dents in quality assurance scenarios.)" }, { "code": null, "e": 2003, "s": 1852, "text": "Custom Vision Service is designed to make it easy to start building your classifier, and to help you improve the quality of your classifier over time." }, { "code": null, "e": 2113, "s": 2003, "text": "Developers can also export their models to be run on the edge devices such as iOS, Android or the RaspberryPi" }, { "code": null, "e": 2248, "s": 2113, "text": "The Steps below will walk you through training a model for our challenge pro-grammatically with python with the custom vision service." }, { "code": null, "e": 2312, "s": 2248, "text": "The following steps are based on the documentation quick start." }, { "code": null, "e": 2445, "s": 2312, "text": "Obtain your training and prediction key by logging into the Custom Vision Service and navigating to account settings as shown below." }, { "code": null, "e": 2553, "s": 2445, "text": "Next we need to programatically make a new custom vision service project using the keys your sourced above." }, { "code": null, "e": 3105, "s": 2553, "text": "from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClientfrom azure.cognitiveservices.vision.customvision.training.models import ImageUrlCreateEntryENDPOINT = \"https://southcentralus.api.cognitive.microsoft.com\"# Replace with a valid keytraining_key = '' #<your training key>prediction_key = '' #<your prediction key>trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT)# Create a new projectprint(\"Creating Beverage Policy Classifier...\")project = trainer.create_project(\"Beverage Policy Classifier\")" }, { "code": null, "e": 3144, "s": 3105, "text": "Creating Beverage Policy Classifier..." }, { "code": null, "e": 3217, "s": 3144, "text": "Run the following code to create tags for our Valid and Invalid Examples" }, { "code": null, "e": 3358, "s": 3217, "text": "# Make two tags in the new projectvalid_tag = trainer.create_tag(project.id, \"Valid\")invalid_tag = trainer.create_tag(project.id, \"Invalid\")" }, { "code": null, "e": 3505, "s": 3358, "text": "To add the images we have to the project, insert the following code after the tag creation. This will upload the image with the corresponding tag." }, { "code": null, "e": 4518, "s": 3505, "text": "print (\"Adding images...\")import osfrom multiprocessing.dummy import Pool as ThreadPooldef upload(filepath): with open(filepath, mode=\"rb\") as img_data: if \"Invalid\" in filepath: trainer.create_images_from_data(project.id, img_data.read(), [ invalid_tag.id ]) else: trainer.create_images_from_data(project.id, img_data.read(), [ valid_tag.id ]) print('.', end='') def upload_parallel(filepaths, threads=5): pool = ThreadPool(threads) results = pool.map(upload, filepaths) pool.close() pool.join()valid_dir = \"dataset/Beverages/Train/Valid/\"invalid_dir = \"dataset/Beverages/Train/Invalid/\"valid_paths = [valid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(valid_dir))]invalid_paths = [invalid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(invalid_dir))]img_paths = valid_paths + invalid_pathsupload_parallel(img_paths)print(\"Added {} images, {} valid, {} invalid.\".format(len(img_paths), len(valid_paths), len(invalid_paths)))" }, { "code": null, "e": 4754, "s": 4518, "text": "Adding images.......................................................................................................................................................................................Added 180 images, 90 valid, 90 invalid." }, { "code": null, "e": 4931, "s": 4754, "text": "Now that we’ve added tags and images to the project, we can train it. This creates the first iteration in the project. We can then mark this iteration as the default iteration." }, { "code": null, "e": 5178, "s": 4931, "text": "import timeprint (\"Training...\")iteration = trainer.train_project(project.id)while (iteration.status == \"Training\"): iteration = trainer.get_iteration(project.id, iteration.id) print (\"Training status: \" + iteration.status) time.sleep(1)" }, { "code": null, "e": 5441, "s": 5178, "text": "Training...Training status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: TrainingTraining status: Completed" }, { "code": null, "e": 5528, "s": 5441, "text": "Now lets evaluate the model on the local test dataset that the service has never seen." }, { "code": null, "e": 5624, "s": 5528, "text": "from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient" }, { "code": null, "e": 6736, "s": 5624, "text": "# Now there is a trained endpoint, it can be used to make a predictionpredictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT)project_id = project.iddef predict(filepath): with open(filepath, mode=\"rb\") as test_data: results = predictor.predict_image(project_id, test_data.read(), iteration.id) pred = max(results.predictions, key=lambda x:x.probability).tag_name true ='Invalid' if \"Invalid\" in filepath else 'Valid' print('.', pred , end='') return (true, pred) def predict_parallel(filepaths, threads=2): pool = ThreadPool(threads) results = pool.map(predict, filepaths) pool.close() pool.join() return zip(*results)test_valid_dir = \"dataset/Beverages/Test/Valid/\"test_invalid_dir = \"dataset/Beverages/Test//Invalid/\"test_valid_paths = [test_valid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(test_valid_dir))]test_invalid_paths = [test_invalid_dir + os.fsdecode(image) for image in os.listdir(os.fsencode(test_invalid_dir))]test_img_paths = test_valid_paths + test_invalid_pathsy_true, y_pred = predict_parallel(test_img_paths)" }, { "code": null, "e": 7217, "s": 6736, "text": ". Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Valid. Invalid. Valid. Invalid. Valid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid. Invalid" }, { "code": null, "e": 7294, "s": 7217, "text": "from utils import classification_reportclassification_report(y_true, y_pred)" }, { "code": null, "e": 7699, "s": 7294, "text": "precision recall f1-score support Invalid 1.00 1.00 1.00 30 Valid 1.00 1.00 1.00 30 micro avg 1.00 1.00 1.00 60 macro avg 1.00 1.00 1.00 60weighted avg 1.00 1.00 1.00 60Confusion matrix, without normalization[[30 0] [ 0 30]]Normalized confusion matrix[[1. 0.] [0. 1.]]" }, { "code": null, "e": 8021, "s": 7699, "text": "As you can see the custom vision service is a great tool for generating strong models with relatively small amount of data and little work. In the majority of use cases its a go too tool and a great place to get started.Custom Vision Service works best when the item you are trying to classify is prominent in your image." }, { "code": null, "e": 8167, "s": 8021, "text": "The service is a go to starting point for any classification task. However there are a couple of items to consider when deploying for production." }, { "code": null, "e": 8452, "s": 8167, "text": "What are the cases that the service fails on (It could be that the 2% error case appears 30% in production or are the most important cases to consider for your use case.How many classes/policies are you classifying (The models work better with 2–10 policies )What domain is your task?" }, { "code": null, "e": 8622, "s": 8452, "text": "What are the cases that the service fails on (It could be that the 2% error case appears 30% in production or are the most important cases to consider for your use case." }, { "code": null, "e": 8713, "s": 8622, "text": "How many classes/policies are you classifying (The models work better with 2–10 policies )" }, { "code": null, "e": 8739, "s": 8713, "text": "What domain is your task?" }, { "code": null, "e": 8750, "s": 8739, "text": "medium.com" }, { "code": null, "e": 8761, "s": 8750, "text": "github.com" }, { "code": null, "e": 8781, "s": 8761, "text": "azure.microsoft.com" }, { "code": null, "e": 8970, "s": 8781, "text": "The next post in this series will review how to approach this task with the Policy Recognition with Keras CNNs, MobileNet and Transfer Learning subsequent posts will address the following:" }, { "code": null, "e": 9008, "s": 8970, "text": "Policy Detection with Keras RetinaNet" }, { "code": null, "e": 9080, "s": 9008, "text": "Training and Computer Vision Models on the Cloud using Azure ML Service" }, { "code": null, "e": 9158, "s": 9080, "text": "Train a Computer Vision Model on a Remote Cluster with Azure Machine Learning" }, { "code": null, "e": 9330, "s": 9158, "text": "If you have any questions, comments, or topics you would like me to discuss feel free to follow me on Twitter if there is a milestone you feel I missed please let me know." } ]
How to pass both form data and credentials on submit in ajax ?
09 Dec, 2020 The purpose of this article is to send the form data and credentials to PHP backend using AJAX in an HTML document. Approach: Create a form in an HTML document with a submit button and assign an id to that button. In the JavaScript file add an event listener to the form’s submit button i.e click. Then the request is made to PHP file using jQuery Ajax. HTML code: HTML <!-- HTML Code --><!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- jQuery Ajax CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- JavaScript File --> <script src="script.js"></script> <!-- Internal CSS --> <style> .container { margin: 35px 0px; } input, textarea, button { display: block; margin: 30px auto; outline: none; border: 2px solid black; border-radius: 5px; padding: 5px; } button { cursor: pointer; font-size: large; font-weight: bolder; } h1 { text-align: center; } </style></head> <body> <div class="container"> <h1>Demo Form</h1> <!-- Form --> <form> <input type="text" name="name" id="name" placeholder= "Enter your Name"> <input type="text" name="age" id="age" placeholder= "Enter your Age"> <textarea name="aaddress" id="address" cols="30" rows="10" placeholder= "Enter your address"> </textarea> <!-- Form Submit Button --> <button type="submit" id="submitBtn"> Submit </button> </form> </div></body> </html> JavaScript Code: The following is the code for the “script.js” file. Javascript // Form Submit Button DOMlet submitBtn = document.getElementById('submitBtn'); // Adding event listener to form submit button submitBtn.addEventListener('click', (event) => { // Preventing form to submit event.preventDefault(); // Fetching Form data let name = document.getElementById('name').value; let age = document.getElementById('age').value; let address = document.getElementById('address').value; // jQuery Ajax Post Request $.post('action.php', { // Sending Form data name : name, age : age, address : address }, (response) => { // Response from PHP back-end console.log(response); });}); PHP Code: The following is the code for the “action.php” file. PHP <?php // Checking if post value is set// by user or notif(isset($_POST['name'])) { // Getting the data of form in // different variables $name = $_POST['name']; $age = $_POST['age']; $address = $_POST['address']; // Sending Response echo "Success";}?> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked Technical Scripter 2020 HTML JavaScript PHP PHP Programs Technical Scripter Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Dec, 2020" }, { "code": null, "e": 144, "s": 28, "text": "The purpose of this article is to send the form data and credentials to PHP backend using AJAX in an HTML document." }, { "code": null, "e": 382, "s": 144, "text": "Approach: Create a form in an HTML document with a submit button and assign an id to that button. In the JavaScript file add an event listener to the form’s submit button i.e click. Then the request is made to PHP file using jQuery Ajax." }, { "code": null, "e": 393, "s": 382, "text": "HTML code:" }, { "code": null, "e": 398, "s": 393, "text": "HTML" }, { "code": "<!-- HTML Code --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- jQuery Ajax CDN --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- JavaScript File --> <script src=\"script.js\"></script> <!-- Internal CSS --> <style> .container { margin: 35px 0px; } input, textarea, button { display: block; margin: 30px auto; outline: none; border: 2px solid black; border-radius: 5px; padding: 5px; } button { cursor: pointer; font-size: large; font-weight: bolder; } h1 { text-align: center; } </style></head> <body> <div class=\"container\"> <h1>Demo Form</h1> <!-- Form --> <form> <input type=\"text\" name=\"name\" id=\"name\" placeholder= \"Enter your Name\"> <input type=\"text\" name=\"age\" id=\"age\" placeholder= \"Enter your Age\"> <textarea name=\"aaddress\" id=\"address\" cols=\"30\" rows=\"10\" placeholder= \"Enter your address\"> </textarea> <!-- Form Submit Button --> <button type=\"submit\" id=\"submitBtn\"> Submit </button> </form> </div></body> </html>", "e": 1967, "s": 398, "text": null }, { "code": null, "e": 2036, "s": 1967, "text": "JavaScript Code: The following is the code for the “script.js” file." }, { "code": null, "e": 2047, "s": 2036, "text": "Javascript" }, { "code": "// Form Submit Button DOMlet submitBtn = document.getElementById('submitBtn'); // Adding event listener to form submit button submitBtn.addEventListener('click', (event) => { // Preventing form to submit event.preventDefault(); // Fetching Form data let name = document.getElementById('name').value; let age = document.getElementById('age').value; let address = document.getElementById('address').value; // jQuery Ajax Post Request $.post('action.php', { // Sending Form data name : name, age : age, address : address }, (response) => { // Response from PHP back-end console.log(response); });});", "e": 2731, "s": 2047, "text": null }, { "code": null, "e": 2794, "s": 2731, "text": "PHP Code: The following is the code for the “action.php” file." }, { "code": null, "e": 2798, "s": 2794, "text": "PHP" }, { "code": "<?php // Checking if post value is set// by user or notif(isset($_POST['name'])) { // Getting the data of form in // different variables $name = $_POST['name']; $age = $_POST['age']; $address = $_POST['address']; // Sending Response echo \"Success\";}?>", "e": 3076, "s": 2798, "text": null }, { "code": null, "e": 3084, "s": 3076, "text": "Output:" }, { "code": null, "e": 3093, "s": 3084, "text": "CSS-Misc" }, { "code": null, "e": 3103, "s": 3093, "text": "HTML-Misc" }, { "code": null, "e": 3119, "s": 3103, "text": "JavaScript-Misc" }, { "code": null, "e": 3126, "s": 3119, "text": "Picked" }, { "code": null, "e": 3150, "s": 3126, "text": "Technical Scripter 2020" }, { "code": null, "e": 3155, "s": 3150, "text": "HTML" }, { "code": null, "e": 3166, "s": 3155, "text": "JavaScript" }, { "code": null, "e": 3170, "s": 3166, "text": "PHP" }, { "code": null, "e": 3183, "s": 3170, "text": "PHP Programs" }, { "code": null, "e": 3202, "s": 3183, "text": "Technical Scripter" }, { "code": null, "e": 3219, "s": 3202, "text": "Web Technologies" }, { "code": null, "e": 3246, "s": 3219, "text": "Web technologies Questions" }, { "code": null, "e": 3251, "s": 3246, "text": "HTML" }, { "code": null, "e": 3255, "s": 3251, "text": "PHP" } ]
How to Perform Hierarchical Cluster Analysis using R Programming?
21 Jun, 2022 Cluster analysis or clustering is a technique to find subgroups of data points within a data set. The data points belonging to the same subgroup have similar features or properties. Clustering is an unsupervised machine learning approach and has a wide variety of applications such as market research, pattern recognition, recommendation systems, and so on. The most common algorithms used for clustering are K-means clustering and Hierarchical cluster analysis. In this article, we will learn about hierarchical cluster analysis and its implementation in R programming. Hierarchical cluster analysis (also known as hierarchical clustering) is a clustering technique where clusters have a hierarchy or a predetermined order. Hierarchical clustering can be represented by a tree-like structure called a Dendrogram. There are two types of hierarchical clustering: Agglomerative hierarchical clustering: This is a bottom-up approach where each data point starts in its own cluster and as one moves up the hierarchy, similar pairs of clusters are merged. Divisive hierarchical clustering: This is a top-down approach where all data points start in one cluster and as one moves down the hierarchy, clusters are split recursively. To measure the similarity or dissimilarity between a pair of data points, we use distance measures (Euclidean distance, Manhattan distance, etc.). However, to find the dissimilarity between two clusters of observations, we use agglomeration methods. The most common agglomeration methods are: Complete linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the longest (maximum) distance between two points as the distance between two clusters. Single linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the shortest (minimum) distance as the distance between two clusters. Average linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the average distance as the distance between two clusters. For computing hierarchical clustering in R, the commonly used functions are as follows: hclust in the stats package and agnes in the cluster package for agglomerative hierarchical clustering. diana in the cluster package for divisive hierarchical clustering. We will use the Iris flower data set from the datasets package in our implementation. We will use sepal width, sepal length, petal width, and petal length column as our data points. First, we load and normalize the data. Then the dissimilarity values are computed with dist function and these values are fed to clustering functions for performing hierarchical clustering. R # Load required packageslibrary(datasets) # contains iris datasetlibrary(cluster) # clustering algorithmslibrary(factoextra) # visualizationlibrary(purrr) # to use map_dbl() function # Load and preprocess the datasetdf <- iris[, 1:4]df <- na.omit(df)df <- scale(df) # Dissimilarity matrixd <- dist(df, method = "euclidean") The dissimilarity matrix obtained is fed to hclust. The method parameter of hclust specifies the agglomeration method to be used (i.e. complete, average, single). We can then plot the dendrogram. R # Hierarchical clustering using Complete Linkagehc1 <- hclust(d, method = "complete" ) # Plot the obtained dendrogramplot(hc1, cex = 0.6, hang = -1) Output: Observe that in the above dendrogram, a leaf corresponds to one observation and as we move up the tree, similar observations are fused at a higher height. The height of the dendrogram determines the clusters. In order to identify the clusters, we can cut the dendrogram with cutree. Then visualize the result in a scatter plot using fviz_cluster function from the factoextra package. R # Cut tree into 3 groupssub_grps <- cutree(hc1, k = 3) # Visualize the result in a scatter plotfviz_cluster(list(data = df, cluster = sub_grps)) Output: We can also provide a border to the dendrogram around the 3 clusters as shown below. R # Plot the obtained dendrogram with# rectangle borders for k clustersplot(hc1, cex = 0.6, hang = -1)rect.hclust(hc1, k = 3, border = 2:4) Output: Alternatively, we can use the agnes function to perform the hierarchical clustering. Unlike hclust, the agnes function gives the agglomerative coefficient, which measures the amount of clustering structure found (values closer to 1 suggest strong clustering structure). R # agglomeration methods to assessm <- c("average", "single", "complete")names(m) <- c("average", "single", "complete") # function to compute hierarchical# clustering coefficientac <- function(x) { agnes(df, method = x)$ac} map_dbl(m, ac) Output: average single complete 0.9035705 0.8023794 0.9438858 Complete linkage gives a stronger clustering structure. So, we use this agglomeration method to perform hierarchical clustering with agnes function as shown below. R # Hierarchical clusteringhc2 <- agnes(df, method = "complete") # Plot the obtained dendrogrampltree(hc2, cex = 0.6, hang = -1, main = "Dendrogram of agnes") Output: The function diana which works similar to agnes allows us to perform divisive hierarchical clustering. However, there is no method to provide. R # Compute divisive hierarchical clusteringhc3 <- diana(df) # Divise coefficienthc3$dc # Plot obtained dendrogrampltree(hc3, cex = 0.6, hang = -1, main = "Dendrogram of diana") Output: [1] 0.9397208 rkbhola5 Picked R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 599, "s": 28, "text": "Cluster analysis or clustering is a technique to find subgroups of data points within a data set. The data points belonging to the same subgroup have similar features or properties. Clustering is an unsupervised machine learning approach and has a wide variety of applications such as market research, pattern recognition, recommendation systems, and so on. The most common algorithms used for clustering are K-means clustering and Hierarchical cluster analysis. In this article, we will learn about hierarchical cluster analysis and its implementation in R programming." }, { "code": null, "e": 890, "s": 599, "text": "Hierarchical cluster analysis (also known as hierarchical clustering) is a clustering technique where clusters have a hierarchy or a predetermined order. Hierarchical clustering can be represented by a tree-like structure called a Dendrogram. There are two types of hierarchical clustering:" }, { "code": null, "e": 1079, "s": 890, "text": "Agglomerative hierarchical clustering: This is a bottom-up approach where each data point starts in its own cluster and as one moves up the hierarchy, similar pairs of clusters are merged." }, { "code": null, "e": 1253, "s": 1079, "text": "Divisive hierarchical clustering: This is a top-down approach where all data points start in one cluster and as one moves down the hierarchy, clusters are split recursively." }, { "code": null, "e": 1546, "s": 1253, "text": "To measure the similarity or dissimilarity between a pair of data points, we use distance measures (Euclidean distance, Manhattan distance, etc.). However, to find the dissimilarity between two clusters of observations, we use agglomeration methods. The most common agglomeration methods are:" }, { "code": null, "e": 1760, "s": 1546, "text": "Complete linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the longest (maximum) distance between two points as the distance between two clusters." }, { "code": null, "e": 1954, "s": 1760, "text": "Single linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the shortest (minimum) distance as the distance between two clusters." }, { "code": null, "e": 2138, "s": 1954, "text": "Average linkage clustering: It computes all pairwise dissimilarities between the observations in two clusters, and considers the average distance as the distance between two clusters." }, { "code": null, "e": 2226, "s": 2138, "text": "For computing hierarchical clustering in R, the commonly used functions are as follows:" }, { "code": null, "e": 2330, "s": 2226, "text": "hclust in the stats package and agnes in the cluster package for agglomerative hierarchical clustering." }, { "code": null, "e": 2397, "s": 2330, "text": "diana in the cluster package for divisive hierarchical clustering." }, { "code": null, "e": 2770, "s": 2397, "text": "We will use the Iris flower data set from the datasets package in our implementation. We will use sepal width, sepal length, petal width, and petal length column as our data points. First, we load and normalize the data. Then the dissimilarity values are computed with dist function and these values are fed to clustering functions for performing hierarchical clustering. " }, { "code": null, "e": 2772, "s": 2770, "text": "R" }, { "code": "# Load required packageslibrary(datasets) # contains iris datasetlibrary(cluster) # clustering algorithmslibrary(factoextra) # visualizationlibrary(purrr) # to use map_dbl() function # Load and preprocess the datasetdf <- iris[, 1:4]df <- na.omit(df)df <- scale(df) # Dissimilarity matrixd <- dist(df, method = \"euclidean\")", "e": 3097, "s": 2772, "text": null }, { "code": null, "e": 3293, "s": 3097, "text": "The dissimilarity matrix obtained is fed to hclust. The method parameter of hclust specifies the agglomeration method to be used (i.e. complete, average, single). We can then plot the dendrogram." }, { "code": null, "e": 3295, "s": 3293, "text": "R" }, { "code": "# Hierarchical clustering using Complete Linkagehc1 <- hclust(d, method = \"complete\" ) # Plot the obtained dendrogramplot(hc1, cex = 0.6, hang = -1)", "e": 3444, "s": 3295, "text": null }, { "code": null, "e": 3452, "s": 3444, "text": "Output:" }, { "code": null, "e": 3836, "s": 3452, "text": "Observe that in the above dendrogram, a leaf corresponds to one observation and as we move up the tree, similar observations are fused at a higher height. The height of the dendrogram determines the clusters. In order to identify the clusters, we can cut the dendrogram with cutree. Then visualize the result in a scatter plot using fviz_cluster function from the factoextra package." }, { "code": null, "e": 3838, "s": 3836, "text": "R" }, { "code": "# Cut tree into 3 groupssub_grps <- cutree(hc1, k = 3) # Visualize the result in a scatter plotfviz_cluster(list(data = df, cluster = sub_grps))", "e": 3983, "s": 3838, "text": null }, { "code": null, "e": 3991, "s": 3983, "text": "Output:" }, { "code": null, "e": 4076, "s": 3991, "text": "We can also provide a border to the dendrogram around the 3 clusters as shown below." }, { "code": null, "e": 4078, "s": 4076, "text": "R" }, { "code": "# Plot the obtained dendrogram with# rectangle borders for k clustersplot(hc1, cex = 0.6, hang = -1)rect.hclust(hc1, k = 3, border = 2:4)", "e": 4216, "s": 4078, "text": null }, { "code": null, "e": 4224, "s": 4216, "text": "Output:" }, { "code": null, "e": 4494, "s": 4224, "text": "Alternatively, we can use the agnes function to perform the hierarchical clustering. Unlike hclust, the agnes function gives the agglomerative coefficient, which measures the amount of clustering structure found (values closer to 1 suggest strong clustering structure)." }, { "code": null, "e": 4496, "s": 4494, "text": "R" }, { "code": "# agglomeration methods to assessm <- c(\"average\", \"single\", \"complete\")names(m) <- c(\"average\", \"single\", \"complete\") # function to compute hierarchical# clustering coefficientac <- function(x) { agnes(df, method = x)$ac} map_dbl(m, ac)", "e": 4735, "s": 4496, "text": null }, { "code": null, "e": 4743, "s": 4735, "text": "Output:" }, { "code": null, "e": 4804, "s": 4743, "text": " average single complete \n0.9035705 0.8023794 0.9438858 " }, { "code": null, "e": 4968, "s": 4804, "text": "Complete linkage gives a stronger clustering structure. So, we use this agglomeration method to perform hierarchical clustering with agnes function as shown below." }, { "code": null, "e": 4970, "s": 4968, "text": "R" }, { "code": "# Hierarchical clusteringhc2 <- agnes(df, method = \"complete\") # Plot the obtained dendrogrampltree(hc2, cex = 0.6, hang = -1, main = \"Dendrogram of agnes\")", "e": 5133, "s": 4970, "text": null }, { "code": null, "e": 5141, "s": 5133, "text": "Output:" }, { "code": null, "e": 5284, "s": 5141, "text": "The function diana which works similar to agnes allows us to perform divisive hierarchical clustering. However, there is no method to provide." }, { "code": null, "e": 5286, "s": 5284, "text": "R" }, { "code": "# Compute divisive hierarchical clusteringhc3 <- diana(df) # Divise coefficienthc3$dc # Plot obtained dendrogrampltree(hc3, cex = 0.6, hang = -1, main = \"Dendrogram of diana\")", "e": 5468, "s": 5286, "text": null }, { "code": null, "e": 5476, "s": 5468, "text": "Output:" }, { "code": null, "e": 5490, "s": 5476, "text": "[1] 0.9397208" }, { "code": null, "e": 5499, "s": 5490, "text": "rkbhola5" }, { "code": null, "e": 5506, "s": 5499, "text": "Picked" }, { "code": null, "e": 5521, "s": 5506, "text": "R Data-science" }, { "code": null, "e": 5540, "s": 5521, "text": "R Machine-Learning" }, { "code": null, "e": 5551, "s": 5540, "text": "R Language" } ]
How to remove the frame from a Matplotlib figure in Python?
11 Dec, 2020 A frame in the Matplotlib figure is an object inside which given data is represented using independent Axes. These axes represent left, bottom, right and top which can be visualized by Spines(lines) and ticks. To remove the frame (box around the figure) in Matplotlib we follow the steps. Here firstly we will plot a 2D figure in Matplotlib by importing the Matplotlib library. Syntax: plt.tick_params(axis=’x’, which=’both’, bottom=False, top=False, labelbottom=False) Approach: Select the axis to be applied. And select the tick by which the parameter are applied generally it can be ‘major’ , ‘minor’ or ‘both’. Get the current Axex and select the spines’ visibility as False. Python3 # Importing the Library import matplotlib.pyplot as plt# Defining X-axis and Y-axis data Pointsx = [0, 1, 2, 3, 4, 5, 6, 8]y = [1, 5, 2, 8, 3, 5, 2, 7] # Defining the Width and height of the Figureplt.figure(figsize=(8, 7))plt.plot(x, y)plt.show() Output: The given output contains the frame with the spines and ticks. By means of removing the frame we are actually removing the box around the figure containing axes( left, bottom, right, Top).To remove the spines denoted by Black Lines we can follow the steps, Python3 plt.figure(figsize=(4, 3)) plt.plot(x, y) # Selecting the axis-X making the bottom and top axes False.plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) # Selecting the axis-Y making the right and left axes Falseplt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False) # Iterating over all the axes in the figure# and make the Spines Visibility as Falsefor pos in ['right', 'top', 'bottom', 'left']: plt.gca().spines[pos].set_visible(False)plt.show() Output: Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 238, "s": 28, "text": "A frame in the Matplotlib figure is an object inside which given data is represented using independent Axes. These axes represent left, bottom, right and top which can be visualized by Spines(lines) and ticks." }, { "code": null, "e": 407, "s": 238, "text": "To remove the frame (box around the figure) in Matplotlib we follow the steps. Here firstly we will plot a 2D figure in Matplotlib by importing the Matplotlib library. " }, { "code": null, "e": 499, "s": 407, "text": "Syntax: plt.tick_params(axis=’x’, which=’both’, bottom=False, top=False, labelbottom=False)" }, { "code": null, "e": 509, "s": 499, "text": "Approach:" }, { "code": null, "e": 644, "s": 509, "text": "Select the axis to be applied. And select the tick by which the parameter are applied generally it can be ‘major’ , ‘minor’ or ‘both’." }, { "code": null, "e": 709, "s": 644, "text": "Get the current Axex and select the spines’ visibility as False." }, { "code": null, "e": 717, "s": 709, "text": "Python3" }, { "code": "# Importing the Library import matplotlib.pyplot as plt# Defining X-axis and Y-axis data Pointsx = [0, 1, 2, 3, 4, 5, 6, 8]y = [1, 5, 2, 8, 3, 5, 2, 7] # Defining the Width and height of the Figureplt.figure(figsize=(8, 7))plt.plot(x, y)plt.show()", "e": 967, "s": 717, "text": null }, { "code": null, "e": 977, "s": 967, "text": "Output: " }, { "code": null, "e": 1234, "s": 977, "text": "The given output contains the frame with the spines and ticks. By means of removing the frame we are actually removing the box around the figure containing axes( left, bottom, right, Top).To remove the spines denoted by Black Lines we can follow the steps," }, { "code": null, "e": 1242, "s": 1234, "text": "Python3" }, { "code": "plt.figure(figsize=(4, 3)) plt.plot(x, y) # Selecting the axis-X making the bottom and top axes False.plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) # Selecting the axis-Y making the right and left axes Falseplt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False) # Iterating over all the axes in the figure# and make the Spines Visibility as Falsefor pos in ['right', 'top', 'bottom', 'left']: plt.gca().spines[pos].set_visible(False)plt.show()", "e": 1788, "s": 1242, "text": null }, { "code": null, "e": 1796, "s": 1788, "text": "Output:" }, { "code": null, "e": 1814, "s": 1796, "text": "Python-matplotlib" }, { "code": null, "e": 1838, "s": 1814, "text": "Technical Scripter 2020" }, { "code": null, "e": 1845, "s": 1838, "text": "Python" }, { "code": null, "e": 1864, "s": 1845, "text": "Technical Scripter" }, { "code": null, "e": 1962, "s": 1864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1994, "s": 1962, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2021, "s": 1994, "text": "Python Classes and Objects" }, { "code": null, "e": 2042, "s": 2021, "text": "Python OOPs Concepts" }, { "code": null, "e": 2065, "s": 2042, "text": "Introduction To PYTHON" }, { "code": null, "e": 2096, "s": 2065, "text": "Python | os.path.join() method" }, { "code": null, "e": 2152, "s": 2096, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2194, "s": 2152, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2236, "s": 2194, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2275, "s": 2236, "text": "Python | Get unique values from a list" } ]
Using return value of cin to take unknown number of inputs in C++
23 Jun, 2022 Consider a problem where we need to take an unknown number of integer inputs. A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are not allowed to use if-else, switch-case, and conditional statements? The idea is to use the fact that ‘cin >> input’ is false if the non-numeric value is given. Note that the above approach holds true only when the input value’s data type is int (integer). Important Point: cin is an object of std::istream. In C++11 and later, std::istream has a conversion function explicit bool() const;, meaning that there is a valid conversion from std::istream to bool, but only where explicitly requested. An if or while counts as explicitly requesting conversion to bool. [Source StackOVerflow] Before C++ 11, std::istream had a conversion to operator void*() const; C++ // C++ program to take unknown number// of integers from user.#include <iostream>using namespace std;int main(){ int input; int count = 0; cout << "To stop enter anything except integer"; cout << "\nEnter Your Input::"; // cin returns false when anything // is entered except integer while (cin >> input) count++; cout << "\nTotal number of inputs entered: " << count; return 0;} //This code is updated by Susobhan Akhuli Output: To stop enter any character Enter Your Input 1 2 3 s Total number of inputs entered: 3 Time Complexity: O(count)Auxiliary Space: O(1) This article is contributed by Aditya Rakhecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. workwitharpitjain susobhanakhuli cpp-input-output cpp-puzzle C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 131, "s": 52, "text": "Consider a problem where we need to take an unknown number of integer inputs. " }, { "code": null, "e": 307, "s": 131, "text": "A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are not allowed to use if-else, switch-case, and conditional statements?" }, { "code": null, "e": 496, "s": 307, "text": "The idea is to use the fact that ‘cin >> input’ is false if the non-numeric value is given. Note that the above approach holds true only when the input value’s data type is int (integer). " }, { "code": null, "e": 826, "s": 496, "text": "Important Point: cin is an object of std::istream. In C++11 and later, std::istream has a conversion function explicit bool() const;, meaning that there is a valid conversion from std::istream to bool, but only where explicitly requested. An if or while counts as explicitly requesting conversion to bool. [Source StackOVerflow] " }, { "code": null, "e": 898, "s": 826, "text": "Before C++ 11, std::istream had a conversion to operator void*() const;" }, { "code": null, "e": 902, "s": 898, "text": "C++" }, { "code": "// C++ program to take unknown number// of integers from user.#include <iostream>using namespace std;int main(){ int input; int count = 0; cout << \"To stop enter anything except integer\"; cout << \"\\nEnter Your Input::\"; // cin returns false when anything // is entered except integer while (cin >> input) count++; cout << \"\\nTotal number of inputs entered: \" << count; return 0;} //This code is updated by Susobhan Akhuli", "e": 1372, "s": 902, "text": null }, { "code": null, "e": 1381, "s": 1372, "text": "Output: " }, { "code": null, "e": 1468, "s": 1381, "text": "To stop enter any character\nEnter Your Input 1 2 3 s\nTotal number of inputs entered: 3" }, { "code": null, "e": 1515, "s": 1468, "text": "Time Complexity: O(count)Auxiliary Space: O(1)" }, { "code": null, "e": 1939, "s": 1515, "text": "This article is contributed by Aditya Rakhecha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 1957, "s": 1939, "text": "workwitharpitjain" }, { "code": null, "e": 1972, "s": 1957, "text": "susobhanakhuli" }, { "code": null, "e": 1989, "s": 1972, "text": "cpp-input-output" }, { "code": null, "e": 2000, "s": 1989, "text": "cpp-puzzle" }, { "code": null, "e": 2004, "s": 2000, "text": "C++" }, { "code": null, "e": 2008, "s": 2004, "text": "CPP" } ]
NLP | Custom corpus
20 Feb, 2019 What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files. How it is done ?NLTK already defines a list of data paths or directories in nltk.data.path. Our custom corpora must be present within any of these given paths so it can be found by NLTK.We can also create a custom nltk_data directory in our home directory and verify that it is in the list of known paths specified by nltk.data.path. Code #1 : Creating a custom directory and verify. # importing librariesimport os, os.path # using the given pathpath = os.path.expanduser('~/nltk_data') # checkingif not os.path.exists(path): os.mkdir(path) print ("Does path exists : ", os.path.exists(path)) import nltk.dataprint ("\nDoes path exists in nltk : ", path in nltk.data.path) Output : Does path exists : True Does path exists in nltk : True Code #2 : Creating a wordlist file. # loading librariesimport nltk.data nltk.data.load('corpora/cookbook/word_file.txt', format ='raw') Output : b'nltk\n' How all this works ? nltk.data.load() recognizes the formats – ‘raw’, ‘pickle’ and ‘yaml’. It guess the format based on the file’s extension, if format is not given. As in the code above, ‘raw’ format is needed to be specified. As in the code above, ‘raw’ format is needed to be specified. If file ends in ‘.yaml’, then no need to specify the format. Code #3 : How to load a YAML file import nltk.data # loading file using the pathnltk.data.load('corpora/cookbook/synonyms.yaml') Output : {'bday': 'birthday'} Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Feb, 2019" }, { "code": null, "e": 222, "s": 28, "text": "What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files." }, { "code": null, "e": 556, "s": 222, "text": "How it is done ?NLTK already defines a list of data paths or directories in nltk.data.path. Our custom corpora must be present within any of these given paths so it can be found by NLTK.We can also create a custom nltk_data directory in our home directory and verify that it is in the list of known paths specified by nltk.data.path." }, { "code": null, "e": 606, "s": 556, "text": "Code #1 : Creating a custom directory and verify." }, { "code": "# importing librariesimport os, os.path # using the given pathpath = os.path.expanduser('~/nltk_data') # checkingif not os.path.exists(path): os.mkdir(path) print (\"Does path exists : \", os.path.exists(path)) import nltk.dataprint (\"\\nDoes path exists in nltk : \", path in nltk.data.path)", "e": 915, "s": 606, "text": null }, { "code": null, "e": 924, "s": 915, "text": "Output :" }, { "code": null, "e": 980, "s": 924, "text": "Does path exists : True\nDoes path exists in nltk : True" }, { "code": null, "e": 1016, "s": 980, "text": "Code #2 : Creating a wordlist file." }, { "code": "# loading librariesimport nltk.data nltk.data.load('corpora/cookbook/word_file.txt', format ='raw')", "e": 1117, "s": 1016, "text": null }, { "code": null, "e": 1126, "s": 1117, "text": "Output :" }, { "code": null, "e": 1136, "s": 1126, "text": "b'nltk\\n'" }, { "code": null, "e": 1157, "s": 1136, "text": "How all this works ?" }, { "code": null, "e": 1227, "s": 1157, "text": "nltk.data.load() recognizes the formats – ‘raw’, ‘pickle’ and ‘yaml’." }, { "code": null, "e": 1302, "s": 1227, "text": "It guess the format based on the file’s extension, if format is not given." }, { "code": null, "e": 1364, "s": 1302, "text": "As in the code above, ‘raw’ format is needed to be specified." }, { "code": null, "e": 1426, "s": 1364, "text": "As in the code above, ‘raw’ format is needed to be specified." }, { "code": null, "e": 1487, "s": 1426, "text": "If file ends in ‘.yaml’, then no need to specify the format." }, { "code": null, "e": 1521, "s": 1487, "text": "Code #3 : How to load a YAML file" }, { "code": "import nltk.data # loading file using the pathnltk.data.load('corpora/cookbook/synonyms.yaml')", "e": 1617, "s": 1521, "text": null }, { "code": null, "e": 1626, "s": 1617, "text": "Output :" }, { "code": null, "e": 1647, "s": 1626, "text": "{'bday': 'birthday'}" }, { "code": null, "e": 1675, "s": 1647, "text": "Natural-language-processing" }, { "code": null, "e": 1687, "s": 1675, "text": "Python-nltk" }, { "code": null, "e": 1704, "s": 1687, "text": "Machine Learning" }, { "code": null, "e": 1711, "s": 1704, "text": "Python" }, { "code": null, "e": 1728, "s": 1711, "text": "Machine Learning" } ]
Tensorflow.js tf.GraphModel class .predict() Method
01 Aug, 2021 Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. The .predict() function is used to implement the implication in favor of input tensors. Syntax: predict(inputs, config?) Parameters: inputs: It is the stated inputs. It is of type (tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor}). config: It is the stated prediction configuration in order to define the batch size as well as output node designations. Moreover, at present the batch size selection is overlooked for the graph model. It is optional and is of type object.batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32.verbose: It is the stated verbosity mode whose by default value is false and is optional. batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32. verbose: It is the stated verbosity mode whose by default value is false and is optional. Return Value: It returns tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor}. Example 1: In this example, we are loading MobileNetV2 from a URL and holding a prediction with a zeros input. Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining tensor input elementsconst model_Url ='https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json'; // Calling the loadGraphModel() methodconst mymodel = await tf.loadGraphModel(model_Url); // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]); // Calling predict() method and // Printing outputmymodel.predict(inputs).print(); Output: Tensor [[-0.1800361, -0.4059965, 0.8190175, ..., -0.8953396, -1.0841646, 1.2912753],] Example 2: In this example, we are loading MobileNetV2 from a TF Hub URL and holding a prediction with a zeros input. Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Defining tensor input elementsconst model_Url ='https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2'; // Calling the loadGraphModel() methodconst model = await tf.loadGraphModel( model_Url, {fromTFHub: true}); // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]); // Defining batchsizeconst batchsize = 1; // Defining verboseconst verbose = true; // Calling predict() method and// Printing outputmodel.predict(inputs, batchsize, verbose).print(); Output: Tensor [[-1.1690605, 0.0195426, 1.1962479, ..., -0.4825858, -0.0055641, 1.1937635],] Reference: https://js.tensorflow.org/api/latest/#tf.GraphModel.predict Picked Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2021" }, { "code": null, "e": 209, "s": 28, "text": "Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment." }, { "code": null, "e": 297, "s": 209, "text": "The .predict() function is used to implement the implication in favor of input tensors." }, { "code": null, "e": 305, "s": 297, "text": "Syntax:" }, { "code": null, "e": 330, "s": 305, "text": "predict(inputs, config?)" }, { "code": null, "e": 344, "s": 330, "text": "Parameters: " }, { "code": null, "e": 444, "s": 344, "text": "inputs: It is the stated inputs. It is of type (tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor})." }, { "code": null, "e": 919, "s": 444, "text": "config: It is the stated prediction configuration in order to define the batch size as well as output node designations. Moreover, at present the batch size selection is overlooked for the graph model. It is optional and is of type object.batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32.verbose: It is the stated verbosity mode whose by default value is false and is optional." }, { "code": null, "e": 1066, "s": 919, "text": "batchSize: It is the stated batch dimension which is optional and is of type integer. In case its undefined, then the by default value will be 32." }, { "code": null, "e": 1156, "s": 1066, "text": "verbose: It is the stated verbosity mode whose by default value is false and is optional." }, { "code": null, "e": 1232, "s": 1156, "text": "Return Value: It returns tf.Tensor|tf.Tensor[]|{[name: string]: tf.Tensor}." }, { "code": null, "e": 1343, "s": 1232, "text": "Example 1: In this example, we are loading MobileNetV2 from a URL and holding a prediction with a zeros input." }, { "code": null, "e": 1354, "s": 1343, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Defining tensor input elementsconst model_Url ='https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json'; // Calling the loadGraphModel() methodconst mymodel = await tf.loadGraphModel(model_Url); // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]); // Calling predict() method and // Printing outputmymodel.predict(inputs).print();", "e": 1808, "s": 1354, "text": null }, { "code": null, "e": 1816, "s": 1808, "text": "Output:" }, { "code": null, "e": 1919, "s": 1816, "text": "Tensor\n [[-0.1800361, -0.4059965, 0.8190175, \n ..., \n -0.8953396, -1.0841646, 1.2912753],]" }, { "code": null, "e": 2037, "s": 1919, "text": "Example 2: In this example, we are loading MobileNetV2 from a TF Hub URL and holding a prediction with a zeros input." }, { "code": null, "e": 2048, "s": 2037, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Defining tensor input elementsconst model_Url ='https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2'; // Calling the loadGraphModel() methodconst model = await tf.loadGraphModel( model_Url, {fromTFHub: true}); // Defining inputsconst inputs = tf.zeros([1, 224, 224, 3]); // Defining batchsizeconst batchsize = 1; // Defining verboseconst verbose = true; // Calling predict() method and// Printing outputmodel.predict(inputs, batchsize, verbose).print();", "e": 2615, "s": 2048, "text": null }, { "code": null, "e": 2623, "s": 2615, "text": "Output:" }, { "code": null, "e": 2725, "s": 2623, "text": "Tensor\n [[-1.1690605, 0.0195426, 1.1962479, \n ..., \n -0.4825858, -0.0055641, 1.1937635],]" }, { "code": null, "e": 2796, "s": 2725, "text": "Reference: https://js.tensorflow.org/api/latest/#tf.GraphModel.predict" }, { "code": null, "e": 2803, "s": 2796, "text": "Picked" }, { "code": null, "e": 2817, "s": 2803, "text": "Tensorflow.js" }, { "code": null, "e": 2828, "s": 2817, "text": "JavaScript" }, { "code": null, "e": 2845, "s": 2828, "text": "Web Technologies" } ]
GATE | GATE CS 2013 | Question 65
10 Sep, 2021 Consider the following two sets of LR(1) items of an LR(1) grammar. X -> c.X, c/d X -> .cX, c/d X -> .d, c/d X -> c.X, $ X -> .cX, $ X -> .d, $ Which of the following statements related to merging of the two sets in the corresponding LALR parser is/are FALSE? Cannot be merged since look aheads are different.Can be merged but will result in S-R conflict.Can be merged but will result in R-R conflict.Cannot be merged since goto on c will lead to two different sets. Cannot be merged since look aheads are different. Can be merged but will result in S-R conflict. Can be merged but will result in R-R conflict. Cannot be merged since goto on c will lead to two different sets. (A) 1 only(B) 2 only(C) 1 and 4 only(D) 1, 2, 3, and 4Answer: (D)Explanation: The given two LR(1) set of items are : X -> c.X, c/d X -> .cX, c/d X -> .d, c/d and X -> c.X, $ X -> .cX, $ X -> .d, $ The symbols/terminals after the comma are Look-Ahead symbols. These are the sets of LR(1) ( LR(1) is also called CLR(1) ) items. The LALR(1) parser combines those set of LR(1) items which are identical with respect to their 1st component but different with respect to their 2nd component. In a production rule of a LR(1) set of items, ( A -> B , c ) , A->B is the 1st component , and the Look-Ahead set of symbols, which is c here, is the second component. Now we can see that in the sets given, 1st component of the corresponding production rule is identical in both sets, and they only differ in 2nd component ( i.e. their look-ahead symbols) hence we can combine these sets to make a a single set which would be : X -> c.X, c/d/$ X -> .cX, c/d/$ X -> .d, c/d/$ This is done to reduce the total number of parser states. Now we can check the statements given. Statement 1 : The statement is false, as merging has been done because 2nd components i.e. look-ahead were different. Statement 2 : In the merged set, we can’t see any Shift-Reduce conflict ( because no reduction even possible, reduction would be possible when a production of form P -> q. is present) Statement 3 : In the merged set, we can’t see any Reduce-Reduce conflict ( same reason as above, no reduction even possible, so no chances of R-R conflict ) Statement 4: This statement is also wrong, because goto is carried on Non-Terminals symbols, not on terminal symbols, and c is a terminal symbol. Thus, all statements are wrong, hence option D. GATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti Acharya - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0040:55 / 52:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2013 GATE-GATE CS 2013 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE CS 1996 | Question 63 GATE | Gate IT 2005 | Question 52 GATE | GATE-CS-2001 | Question 50 GATE | GATE CS 2012 | Question 18 GATE | GATE CS 2008 | Question 40
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2021" }, { "code": null, "e": 96, "s": 28, "text": "Consider the following two sets of LR(1) items of an LR(1) grammar." }, { "code": null, "e": 187, "s": 96, "text": "X -> c.X, c/d\n X -> .cX, c/d\n X -> .d, c/d\n X -> c.X, $\n X -> .cX, $\n X -> .d, $" }, { "code": null, "e": 303, "s": 187, "text": "Which of the following statements related to merging of the two sets in the corresponding LALR parser is/are FALSE?" }, { "code": null, "e": 510, "s": 303, "text": "Cannot be merged since look aheads are different.Can be merged but will result in S-R conflict.Can be merged but will result in R-R conflict.Cannot be merged since goto on c will lead to two different sets." }, { "code": null, "e": 560, "s": 510, "text": "Cannot be merged since look aheads are different." }, { "code": null, "e": 607, "s": 560, "text": "Can be merged but will result in S-R conflict." }, { "code": null, "e": 654, "s": 607, "text": "Can be merged but will result in R-R conflict." }, { "code": null, "e": 720, "s": 654, "text": "Cannot be merged since goto on c will lead to two different sets." }, { "code": null, "e": 837, "s": 720, "text": "(A) 1 only(B) 2 only(C) 1 and 4 only(D) 1, 2, 3, and 4Answer: (D)Explanation: The given two LR(1) set of items are :" }, { "code": null, "e": 919, "s": 837, "text": "\nX -> c.X, c/d\nX -> .cX, c/d\nX -> .d, c/d\nand\nX -> c.X, $\nX -> .cX, $\nX -> .d, $ " }, { "code": null, "e": 981, "s": 919, "text": "The symbols/terminals after the comma are Look-Ahead symbols." }, { "code": null, "e": 1048, "s": 981, "text": "These are the sets of LR(1) ( LR(1) is also called CLR(1) ) items." }, { "code": null, "e": 1208, "s": 1048, "text": "The LALR(1) parser combines those set of LR(1) items which are identical with respect to their 1st component but different with respect to their 2nd component." }, { "code": null, "e": 1376, "s": 1208, "text": "In a production rule of a LR(1) set of items, ( A -> B , c ) , A->B is the 1st component , and the Look-Ahead set of symbols, which is c here, is the second component." }, { "code": null, "e": 1636, "s": 1376, "text": "Now we can see that in the sets given, 1st component of the corresponding production rule is identical in both sets, and they only differ in 2nd component ( i.e. their look-ahead symbols) hence we can combine these sets to make a a single set which would be :" }, { "code": null, "e": 1684, "s": 1636, "text": "\nX -> c.X, c/d/$\nX -> .cX, c/d/$\nX -> .d, c/d/$" }, { "code": null, "e": 1742, "s": 1684, "text": "This is done to reduce the total number of parser states." }, { "code": null, "e": 1781, "s": 1742, "text": "Now we can check the statements given." }, { "code": null, "e": 1899, "s": 1781, "text": "Statement 1 : The statement is false, as merging has been done because 2nd components i.e. look-ahead were different." }, { "code": null, "e": 2083, "s": 1899, "text": "Statement 2 : In the merged set, we can’t see any Shift-Reduce conflict ( because no reduction even possible, reduction would be possible when a production of form P -> q. is present)" }, { "code": null, "e": 2240, "s": 2083, "text": "Statement 3 : In the merged set, we can’t see any Reduce-Reduce conflict ( same reason as above, no reduction even possible, so no chances of R-R conflict )" }, { "code": null, "e": 2386, "s": 2240, "text": "Statement 4: This statement is also wrong, because goto is carried on Non-Terminals symbols, not on terminal symbols, and c is a terminal symbol." }, { "code": null, "e": 2434, "s": 2386, "text": "Thus, all statements are wrong, hence option D." }, { "code": null, "e": 3402, "s": 2434, "text": "GATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti Acharya - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0040:55 / 52:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Sn5eIxvrNBc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 3415, "s": 3402, "text": "GATE-CS-2013" }, { "code": null, "e": 3433, "s": 3415, "text": "GATE-GATE CS 2013" }, { "code": null, "e": 3438, "s": 3433, "text": "GATE" }, { "code": null, "e": 3536, "s": 3438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3578, "s": 3536, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 3640, "s": 3578, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 3682, "s": 3640, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 3724, "s": 3682, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 3758, "s": 3724, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 3792, "s": 3758, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 3826, "s": 3792, "text": "GATE | Gate IT 2005 | Question 52" }, { "code": null, "e": 3860, "s": 3826, "text": "GATE | GATE-CS-2001 | Question 50" }, { "code": null, "e": 3894, "s": 3860, "text": "GATE | GATE CS 2012 | Question 18" } ]
Matplotlib.colors.to_rgb() in Python
07 Oct, 2021 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.colors.to_rgb() function is used convert c (ie, color) to an RGB color. It converts the color name into a array of RGB encoded colors. It returns an RGB tuple of three floats from 0-1. Syntax: matplotlib.colors.to_rgb(c)Parameters: c: This accepts a string that represents the name of the color. It can be an RGB or RGBA sequence or a string in any of several forms: a hex color string, like ‘#000FFF’ a standard name, like ‘green’ a letter from the set ‘rgbcmykw’ a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale a hex color string, like ‘#000FFF’ a standard name, like ‘green’ a letter from the set ‘rgbcmykw’ a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale a hex color string, like ‘#000FFF’ a standard name, like ‘green’ a letter from the set ‘rgbcmykw’ a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale Example 1: Python3 import matplotlib.pyplot as pltimport matplotlib.colors as mcolors # helper function to plot a color tabledef colortable(colors, title, colors_sort = True, emptycols = 0): # cell dimensions width = 212 height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sorting colors based on hue, saturation, # value and name. if colors_sort is True: to_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items()) names = [name for hsv, name in to_hsv] else: names = list(colors) length_of_names = len(names) length_cols = 4 - emptycols length_rows = length_of_names // length_cols + int(length_of_names % length_cols > 0) width2 = width * 4 + 2 * margin height2 = height * length_rows + margin + topmargin dpi = 72 figure, axes = plt.subplots(figsize =(width2 / dpi, height2 / dpi), dpi = dpi) figure.subplots_adjust(margin / width2, margin / height2, (width2-margin)/width2, (height2-topmargin)/height2) axes.set_xlim(0, width * 4) axes.set_ylim(height * (length_rows-0.5), -height / 2.) axes.yaxis.set_visible(False) axes.xaxis.set_visible(False) axes.set_axis_off() axes.set_title(title, fontsize = 24, loc ="left", pad = 10) for i, name in enumerate(names): rows = i % length_rows cols = i // length_rows y = rows * height swatch_start_x = width * cols swatch_end_x = width * cols + swatch_width text_pos_x = width * cols + swatch_width + 7 axes.text(text_pos_x, y, name, fontsize = 14, horizontalalignment ='left', verticalalignment ='center') axes.hlines(y, swatch_start_x, swatch_end_x, color = colors[name], linewidth = 18) return figure colortable(mcolors.BASE_COLORS, "Base Colors", colors_sort = False, emptycols = 1)colortable(mcolors.TABLEAU_COLORS, "Tableau Palette", colors_sort = False, emptycols = 2)colortable(mcolors.CSS4_COLORS, "CSS Colors") plt.show() Output: Example 2: Python3 from matplotlib import colorsimport matplotlib.pyplot as plt alpha = 0.5 kwargs = dict(edgecolors ='none', s = 3900, marker ='s') for i, color in enumerate(['pink', 'brown', 'green']): rgb = colors.to_rgb(color) plt.scatter([i], [0], color = color, **kwargs) plt.scatter([i], [1], color = color, alpha = alpha, **kwargs) plt.scatter([i], [2], color = rgb, **kwargs) Output: adnanirshad158 Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 241, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. " }, { "code": null, "e": 442, "s": 241, "text": "The matplotlib.colors.to_rgb() function is used convert c (ie, color) to an RGB color. It converts the color name into a array of RGB encoded colors. It returns an RGB tuple of three floats from 0-1. " }, { "code": null, "e": 491, "s": 442, "text": "Syntax: matplotlib.colors.to_rgb(c)Parameters: " }, { "code": null, "e": 808, "s": 491, "text": "c: This accepts a string that represents the name of the color. It can be an RGB or RGBA sequence or a string in any of several forms: a hex color string, like ‘#000FFF’ a standard name, like ‘green’ a letter from the set ‘rgbcmykw’ a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale " }, { "code": null, "e": 990, "s": 808, "text": "a hex color string, like ‘#000FFF’ a standard name, like ‘green’ a letter from the set ‘rgbcmykw’ a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale " }, { "code": null, "e": 1027, "s": 990, "text": "a hex color string, like ‘#000FFF’ " }, { "code": null, "e": 1059, "s": 1027, "text": "a standard name, like ‘green’ " }, { "code": null, "e": 1094, "s": 1059, "text": "a letter from the set ‘rgbcmykw’ " }, { "code": null, "e": 1175, "s": 1094, "text": "a string representation of a float, like ‘0.4’, indicating gray on a 0-1 scale " }, { "code": null, "e": 1190, "s": 1177, "text": "Example 1: " }, { "code": null, "e": 1198, "s": 1190, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltimport matplotlib.colors as mcolors # helper function to plot a color tabledef colortable(colors, title, colors_sort = True, emptycols = 0): # cell dimensions width = 212 height = 22 swatch_width = 48 margin = 12 topmargin = 40 # Sorting colors based on hue, saturation, # value and name. if colors_sort is True: to_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), name) for name, color in colors.items()) names = [name for hsv, name in to_hsv] else: names = list(colors) length_of_names = len(names) length_cols = 4 - emptycols length_rows = length_of_names // length_cols + int(length_of_names % length_cols > 0) width2 = width * 4 + 2 * margin height2 = height * length_rows + margin + topmargin dpi = 72 figure, axes = plt.subplots(figsize =(width2 / dpi, height2 / dpi), dpi = dpi) figure.subplots_adjust(margin / width2, margin / height2, (width2-margin)/width2, (height2-topmargin)/height2) axes.set_xlim(0, width * 4) axes.set_ylim(height * (length_rows-0.5), -height / 2.) axes.yaxis.set_visible(False) axes.xaxis.set_visible(False) axes.set_axis_off() axes.set_title(title, fontsize = 24, loc =\"left\", pad = 10) for i, name in enumerate(names): rows = i % length_rows cols = i // length_rows y = rows * height swatch_start_x = width * cols swatch_end_x = width * cols + swatch_width text_pos_x = width * cols + swatch_width + 7 axes.text(text_pos_x, y, name, fontsize = 14, horizontalalignment ='left', verticalalignment ='center') axes.hlines(y, swatch_start_x, swatch_end_x, color = colors[name], linewidth = 18) return figure colortable(mcolors.BASE_COLORS, \"Base Colors\", colors_sort = False, emptycols = 1)colortable(mcolors.TABLEAU_COLORS, \"Tableau Palette\", colors_sort = False, emptycols = 2)colortable(mcolors.CSS4_COLORS, \"CSS Colors\") plt.show()", "e": 3368, "s": 1198, "text": null }, { "code": null, "e": 3377, "s": 3368, "text": "Output: " }, { "code": null, "e": 3392, "s": 3379, "text": "Example 2: " }, { "code": null, "e": 3400, "s": 3392, "text": "Python3" }, { "code": "from matplotlib import colorsimport matplotlib.pyplot as plt alpha = 0.5 kwargs = dict(edgecolors ='none', s = 3900, marker ='s') for i, color in enumerate(['pink', 'brown', 'green']): rgb = colors.to_rgb(color) plt.scatter([i], [0], color = color, **kwargs) plt.scatter([i], [1], color = color, alpha = alpha, **kwargs) plt.scatter([i], [2], color = rgb, **kwargs)", "e": 3795, "s": 3400, "text": null }, { "code": null, "e": 3804, "s": 3795, "text": "Output: " }, { "code": null, "e": 3821, "s": 3806, "text": "adnanirshad158" }, { "code": null, "e": 3839, "s": 3821, "text": "Python-matplotlib" }, { "code": null, "e": 3846, "s": 3839, "text": "Python" }, { "code": null, "e": 3862, "s": 3846, "text": "Write From Home" } ]
Stream forEach() method in Java with examples
06 Dec, 2018 Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer<? super T> action) Where, Consumer is a functional interface and T is the type of stream elements. Note : The behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at whatever time and in whatever thread the library chooses. Example 1 : To perform print operation on each element of reversely sorted stream. // Java code for forEach// (Consumer action) in Java 8import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); // Using forEach(Consumer action) to // print the elements of stream // in reverse order list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); }} 10 8 6 4 2 Example 2 : To perform print operation on each element of string stream. // Java code for forEach// (Consumer action) in Java 8import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("GFG", "Geeks", "for", "GeeksforGeeks"); // Using forEach(Consumer action) to // print the elements of stream list.stream().forEach(System.out::println); }} GFG Geeks for GeeksforGeeks Example 3 : To perform print operation on each element of reversely sorted string stream. // Java code for forEach// (Consumer action) in Java 8import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of("GFG", "Geeks", "for", "GeeksforGeeks"); // Using forEach(Consumer action) to print // Character at index 1 in reverse order stream.sorted(Comparator.reverseOrder()) .flatMap(str -> Stream.of(str.charAt(1))) .forEach(System.out::println); }} o e e F Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2018" }, { "code": null, "e": 237, "s": 28, "text": "Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect." }, { "code": null, "e": 246, "s": 237, "text": "Syntax :" }, { "code": null, "e": 369, "s": 246, "text": "void forEach(Consumer<? super T> action)\n\nWhere, Consumer is a functional interface\nand T is the type of stream elements.\n" }, { "code": null, "e": 557, "s": 369, "text": "Note : The behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at whatever time and in whatever thread the library chooses." }, { "code": null, "e": 640, "s": 557, "text": "Example 1 : To perform print operation on each element of reversely sorted stream." }, { "code": "// Java code for forEach// (Consumer action) in Java 8import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); // Using forEach(Consumer action) to // print the elements of stream // in reverse order list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); }}", "e": 1096, "s": 640, "text": null }, { "code": null, "e": 1108, "s": 1096, "text": "10\n8\n6\n4\n2\n" }, { "code": null, "e": 1181, "s": 1108, "text": "Example 2 : To perform print operation on each element of string stream." }, { "code": "// Java code for forEach// (Consumer action) in Java 8import java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"GFG\", \"Geeks\", \"for\", \"GeeksforGeeks\"); // Using forEach(Consumer action) to // print the elements of stream list.stream().forEach(System.out::println); }}", "e": 1639, "s": 1181, "text": null }, { "code": null, "e": 1668, "s": 1639, "text": "GFG\nGeeks\nfor\nGeeksforGeeks\n" }, { "code": null, "e": 1758, "s": 1668, "text": "Example 3 : To perform print operation on each element of reversely sorted string stream." }, { "code": "// Java code for forEach// (Consumer action) in Java 8import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of(\"GFG\", \"Geeks\", \"for\", \"GeeksforGeeks\"); // Using forEach(Consumer action) to print // Character at index 1 in reverse order stream.sorted(Comparator.reverseOrder()) .flatMap(str -> Stream.of(str.charAt(1))) .forEach(System.out::println); }}", "e": 2356, "s": 1758, "text": null }, { "code": null, "e": 2365, "s": 2356, "text": "o\ne\ne\nF\n" }, { "code": null, "e": 2385, "s": 2365, "text": "Java - util package" }, { "code": null, "e": 2400, "s": 2385, "text": "Java-Functions" }, { "code": null, "e": 2412, "s": 2400, "text": "java-stream" }, { "code": null, "e": 2434, "s": 2412, "text": "Java-Stream interface" }, { "code": null, "e": 2439, "s": 2434, "text": "Java" }, { "code": null, "e": 2444, "s": 2439, "text": "Java" } ]
Stream In Java
Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream − Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements. Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements. Source − Stream takes Collections, Arrays, or I/O resources as input source. Source − Stream takes Collections, Arrays, or I/O resources as input source. Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Let us now see an example − Live Demo import java.util.Collection; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("25", "10", "15", "20", "25"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } } Collection = [100, 130, 150, 20, 200, 50, 80] Now, let us count the number of elements in the stream using the Java streams counting() method − Live Demo import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam"); // count long count = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } } Number of elements in the stream = 5
[ { "code": null, "e": 1202, "s": 1062, "text": "Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream −" }, { "code": null, "e": 1374, "s": 1202, "text": "Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements." }, { "code": null, "e": 1546, "s": 1374, "text": "Sequence of elements − A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes element on demand. It never stores the elements." }, { "code": null, "e": 1623, "s": 1546, "text": "Source − Stream takes Collections, Arrays, or I/O resources as input source." }, { "code": null, "e": 1700, "s": 1623, "text": "Source − Stream takes Collections, Arrays, or I/O resources as input source." }, { "code": null, "e": 1817, "s": 1700, "text": "Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on." }, { "code": null, "e": 1934, "s": 1817, "text": "Aggregate operations − Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on." }, { "code": null, "e": 2310, "s": 1934, "text": "Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream." }, { "code": null, "e": 2686, "s": 2310, "text": "Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream." }, { "code": null, "e": 2856, "s": 2686, "text": "Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required." }, { "code": null, "e": 3026, "s": 2856, "text": "Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required." }, { "code": null, "e": 3054, "s": 3026, "text": "Let us now see an example −" }, { "code": null, "e": 3065, "s": 3054, "text": " Live Demo" }, { "code": null, "e": 3477, "s": 3065, "text": "import java.util.Collection;\nimport java.util.TreeSet;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args) {\n Stream<String> stream = Stream.of(\"25\", \"10\", \"15\", \"20\", \"25\");\n Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));\n System.out.println(\"Collection = \"+collection);\n }\n}" }, { "code": null, "e": 3523, "s": 3477, "text": "Collection = [100, 130, 150, 20, 200, 50, 80]" }, { "code": null, "e": 3621, "s": 3523, "text": "Now, let us count the number of elements in the stream using the Java streams counting() method −" }, { "code": null, "e": 3632, "s": 3621, "text": " Live Demo" }, { "code": null, "e": 4017, "s": 3632, "text": "import java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args) {\n Stream<String> stream = Stream.of(\"Kevin\", \"Jofra\",\"Tom\", \"Chris\", \"Liam\");\n // count\n long count = stream.collect(Collectors.counting());\n System.out.println(\"Number of elements in the stream = \"+count);\n }\n}" }, { "code": null, "e": 4054, "s": 4017, "text": "Number of elements in the stream = 5" } ]
Deploying a Machine Learning Model Using Flask and Heroku | by Osasona Ifeoluwa | Towards Data Science
Cardiovascular diseases (which often leads to heart failures) are the number 1 cause of death globally, taking an estimated 17.9 million lives each year, which accounts for 31% of global deaths. Most cardiovascular diseases can be prevented by addressing behavioral risk factors such as tobacco use, unhealthy diet and obesity, physical inactivity, and harmful use of alcohol using population-wide strategies. However, people with cardiovascular disease or who are at high cardiovascular risk (due to the presence of one or more risk factors such as hypertension, diabetes, hyperlipidemia, or already established disease) need early detection and management wherein a machine learning model can be of great help. This machine learning model could help in estimating the probability of deaths caused by heart failure by taking in important features from the dataset and making predictions based on these features. The dataset consists of 12 variables/features, and 1 output variable/target variable. Let us examine the role of each feature in determining if a person is likely to have heart failure or not: Age: This variable shows the patient’s ageAnemia: is the decrease in red blood cells or hemoglobinCreatinine_phosphokinase: is the level of creatine kinase in the blood. This enzyme is important for muscle function.Diabetes: is a chronic disease that causes high blood sugarEjection fraction: is the percentage of blood leaving the heart at each contractionHigh blood pressure: is blood pressure that is higher than normalPlatelets: are tiny blood cells that help your body form clots to stop bleedingSerum creatinine: is the level of serum creatinine in the bloodSerum sodium: is the level of serum sodium in the bloodSex: gender of the patientTime: This captures the time of the eventDeath event: which is the predictor variable. Age: This variable shows the patient’s age Anemia: is the decrease in red blood cells or hemoglobin Creatinine_phosphokinase: is the level of creatine kinase in the blood. This enzyme is important for muscle function. Diabetes: is a chronic disease that causes high blood sugar Ejection fraction: is the percentage of blood leaving the heart at each contraction High blood pressure: is blood pressure that is higher than normal Platelets: are tiny blood cells that help your body form clots to stop bleeding Serum creatinine: is the level of serum creatinine in the blood Serum sodium: is the level of serum sodium in the blood Sex: gender of the patient Time: This captures the time of the event Death event: which is the predictor variable. Now that we know the function of each feature, Let's get started Step 1: Import Libraries Step 2: Import the Dataset The Dataset used in building this model was downloaded as a CSV file to my PC from Kaggle. Step 3: Data Cleaning and EDA This data was pretty much clean, so I didn’t have to do any more cleaning. However, some important pieces of information can still be explored. Next, I use Matplotlib to visualize the distribution of the target variable (Death_event). From the visualization, we can see that a greater percentage of the patients had a failed heart. df['DEATH_EVENT'].value_counts().plot(kind='bar') plt.show() I also visualized the Distribution of each feature to investigate how they are related to the target variable. Some important features are discussed: fig,ax = plt.subplots(1,2,figsize=(16,8)) ax[0].hist(df['age'],label = 'patients') ax[0].set_xlabel('Age') ax[0].set_ylabel('Number of Patients') ax[0].set_yticks([5,10,15,20,25,30,35,40,45,50,55,60]) ax[0].legend() ax[0].set_title('Age Distribution') ax[1].hist(x = [df[df['DEATH_EVENT']==1]['age'],df[df['DEATH_EVENT']==0]['age']],stacked=True,label=['Dead','Survived']) ax[1].set_xlabel('Age') ax[1].set_ylabel('Number of patients') ax[1].set_yticks([5,10,15,20,25,30,35,40,45,50,55,60]) ax[1].set_title('Distribution of age against Death_event') ax[1].legend() <matplotlib.legend.Legend at 0x23f47461a48> First, I explored the importance of the Age feature in determining If a patient is likely to have a heart failure or not. From the above, we can see that as the age increases, the probability of a death event also increases (i.e the older a patient is, the more likely he is to have a heart failure). Also, since the increase in one variable results in an increase in the other variable, we can deduce that these two variables are positively correlated. However, a correlation matrix will still be plotted for confirmation. fig,ax = plt.subplots(1,2,figsize=(16,8)) ax[0].hist(df['serum_creatinine'], label = 'patients') ax[0].set_xlabel('serum_creatinine') ax[0].set_ylabel('Number of Patients') ax[0].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]) ax[0].legend() ax[0].set_title('serum_creatinine Distribution') ax[1].hist(x = [df[df['DEATH_EVENT']==1]['serum_creatinine'],df[df['DEATH_EVENT']==0]['serum_creatinine']], stacked=True, label=['Dead','Survived']) ax[1].set_xlabel('serum_creatinine') ax[1].set_ylabel('Number of patients') ax[1].set_yticks(([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220])) ax[1].set_title('Distribution of serum_creatinine against Death_event') ax[1].legend() <matplotlib.legend.Legend at 0x1cb67ef52c8> In general, the normal creatinine levels range from 0.9–1.3, and from the distribution of serum_creatinine against Death_event visualized above, we can see that the chances of survival are higher within this range. fig,ax = plt.subplots(1,2,figsize=(20,10)) ax[0].hist(df['serum_sodium'], label = 'patients') ax[0].set_xlabel('serum_sodium') ax[0].set_ylabel('Number of Patients') ax[0].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]) ax[0].legend() ax[0].set_title('Serum sodium Distribution') ax[1].hist(x = [df[df['DEATH_EVENT']==1]['serum_sodium'],df[df['DEATH_EVENT']==0]['serum_sodium']], stacked=True, label=['Dead','Survived']) ax[1].set_xlabel('serum_sodium') ax[1].set_ylabel('Number of patients') ax[1].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]) ax[1].set_title('Distribution of serum_sodium against Death_event') ax[1].legend() <matplotlib.legend.Legend at 0x1cb6841af08> The reference range for serum sodium is between 135–147 mmol/L. From the visualization above, the survival rate only starts to increase at this range. This feature also has a considerable correlation with Death_Event To further evaluate the relationship between each input variable and the target variable, I use a heatmap, which gives a graphical representation of the relationship between the variables. plt.figure(figsize=[16,8]) corr = sns.heatmap(df.corr(), annot=True, cmap="RdYlGn") Step 4: Splitting the Train and Test Data Step 5: Data Preprocessing This brings the data to a state that the model can parse easily. For the purpose of this project, the Standard Scaler is used, which standardizes the features by subtracting the mean and then scaling to unit variance. Step 6: Model Selection The support vector machine (SVM), a supervised machine learning model that uses classification algorithms for two-group classification problems is used. After giving the SVM model sets of the preprocessed training data for each category, they’re able to categorize new output. The classification report shows an accuracy of 75%. Since this model will be deployed, it is saved into a pickle file (model.pkl) created by pickle, and this file will reflect in your project folder. Pickle is a python module that enables python objects to be written to files on the disk and read back into the python program runtime. Step 7: Deploying with Flask and Heroku Deploying a machine learning model means making the model available for end-users to make use of. Create the Webpage Here we will create a CSS webpage that has text boxes to take in input from users. The CSS file was named index.html and can be found here. Several templates for creating a CSS webpage can be found online. Deploy the model on the webpage using Flask In deploying this heart failure prediction model into production, a web application framework called Flask is used. Flask makes it easy to write applications, and also gives a variety of choices for developing web applications. To make use of this web application framework in deploying this model, we install Flask by running the following command: Next, a Flask environment with an API endpoint that takes in the model and enables it to receive input from users, and return output is setup. After this, a python file app.py is created, and the required libraries imported Create the Flask App Load the pickle Create an app route to render the HTML template as the home page Create an API that gets input from the user and computes a predicted value based on the model. Now, call the run function to start the Flask server. This should return an output that shows that your app is running. Simply copy the URL and paste it into your browser to test the app. Deploy the Flask APP to Heroku Heroku is a multi-language application platform that allows developers to deploy, and manage their applications. It is flexible and easy to use, offering developers the simplest path to getting their apps to market. The first thing to do in deploying the Flask app to Heroku is to Sign up and Log In to Heroku. After which you can create a Procfile and requirement.txt file, which handles the configuration part in order to deploy the model into the Heroku server. web: gunicorn is the fixed command for the Procfile. The requirements file consists of the project dependencies and can be installed with a single command: Next, you commit your code to Github and connect Github to Heroku. After you connect, there are 2 ways to deploy your app. You could either choose automatic deploy or manual deploy. The automatic deployment will take place whenever you commit anything into your Github repository.By selecting the branch and clicking on deploy, build starts. After a successful deployment, the app will be created. Click on the view and your app should open. A new URL will also be created and can be shared by users. Check Out my app via ‘https://heart-failure-prediction-app20.herokuapp.com/’ Conclusion It is one thing to build a Machine learning model, and it's another thing to deploy the model by integrating it into an existing production environment that can take in input from users and return an output. This article covered building and most importantly deploying a heart failure prediction machine learning model that could significantly help reduce the mortality rate amongst patients with cardiovascular diseases. It is important to note that asides from the Algorithm (SVM), web framework (Flask), and the Application platform (Heroku) used in this project, there are several other options that can be explored. The link to the Github Repository can be found here Dataset Authors: Davide Chicco, Giuseppe Jurman Link to Dataset This was my first machine learning Deployment project, and I hope someone finds this useful🙂.
[ { "code": null, "e": 367, "s": 172, "text": "Cardiovascular diseases (which often leads to heart failures) are the number 1 cause of death globally, taking an estimated 17.9 million lives each year, which accounts for 31% of global deaths." }, { "code": null, "e": 885, "s": 367, "text": "Most cardiovascular diseases can be prevented by addressing behavioral risk factors such as tobacco use, unhealthy diet and obesity, physical inactivity, and harmful use of alcohol using population-wide strategies. However, people with cardiovascular disease or who are at high cardiovascular risk (due to the presence of one or more risk factors such as hypertension, diabetes, hyperlipidemia, or already established disease) need early detection and management wherein a machine learning model can be of great help." }, { "code": null, "e": 1085, "s": 885, "text": "This machine learning model could help in estimating the probability of deaths caused by heart failure by taking in important features from the dataset and making predictions based on these features." }, { "code": null, "e": 1278, "s": 1085, "text": "The dataset consists of 12 variables/features, and 1 output variable/target variable. Let us examine the role of each feature in determining if a person is likely to have heart failure or not:" }, { "code": null, "e": 2010, "s": 1278, "text": "Age: This variable shows the patient’s ageAnemia: is the decrease in red blood cells or hemoglobinCreatinine_phosphokinase: is the level of creatine kinase in the blood. This enzyme is important for muscle function.Diabetes: is a chronic disease that causes high blood sugarEjection fraction: is the percentage of blood leaving the heart at each contractionHigh blood pressure: is blood pressure that is higher than normalPlatelets: are tiny blood cells that help your body form clots to stop bleedingSerum creatinine: is the level of serum creatinine in the bloodSerum sodium: is the level of serum sodium in the bloodSex: gender of the patientTime: This captures the time of the eventDeath event: which is the predictor variable." }, { "code": null, "e": 2053, "s": 2010, "text": "Age: This variable shows the patient’s age" }, { "code": null, "e": 2110, "s": 2053, "text": "Anemia: is the decrease in red blood cells or hemoglobin" }, { "code": null, "e": 2228, "s": 2110, "text": "Creatinine_phosphokinase: is the level of creatine kinase in the blood. This enzyme is important for muscle function." }, { "code": null, "e": 2288, "s": 2228, "text": "Diabetes: is a chronic disease that causes high blood sugar" }, { "code": null, "e": 2372, "s": 2288, "text": "Ejection fraction: is the percentage of blood leaving the heart at each contraction" }, { "code": null, "e": 2438, "s": 2372, "text": "High blood pressure: is blood pressure that is higher than normal" }, { "code": null, "e": 2518, "s": 2438, "text": "Platelets: are tiny blood cells that help your body form clots to stop bleeding" }, { "code": null, "e": 2582, "s": 2518, "text": "Serum creatinine: is the level of serum creatinine in the blood" }, { "code": null, "e": 2638, "s": 2582, "text": "Serum sodium: is the level of serum sodium in the blood" }, { "code": null, "e": 2665, "s": 2638, "text": "Sex: gender of the patient" }, { "code": null, "e": 2707, "s": 2665, "text": "Time: This captures the time of the event" }, { "code": null, "e": 2753, "s": 2707, "text": "Death event: which is the predictor variable." }, { "code": null, "e": 2818, "s": 2753, "text": "Now that we know the function of each feature, Let's get started" }, { "code": null, "e": 2843, "s": 2818, "text": "Step 1: Import Libraries" }, { "code": null, "e": 2870, "s": 2843, "text": "Step 2: Import the Dataset" }, { "code": null, "e": 2961, "s": 2870, "text": "The Dataset used in building this model was downloaded as a CSV file to my PC from Kaggle." }, { "code": null, "e": 2991, "s": 2961, "text": "Step 3: Data Cleaning and EDA" }, { "code": null, "e": 3135, "s": 2991, "text": "This data was pretty much clean, so I didn’t have to do any more cleaning. However, some important pieces of information can still be explored." }, { "code": null, "e": 3323, "s": 3135, "text": "Next, I use Matplotlib to visualize the distribution of the target variable (Death_event). From the visualization, we can see that a greater percentage of the patients had a failed heart." }, { "code": null, "e": 3384, "s": 3323, "text": "df['DEATH_EVENT'].value_counts().plot(kind='bar')\nplt.show()" }, { "code": null, "e": 3534, "s": 3384, "text": "I also visualized the Distribution of each feature to investigate how they are related to the target variable. Some important features are discussed:" }, { "code": null, "e": 4099, "s": 3534, "text": "fig,ax = plt.subplots(1,2,figsize=(16,8))\nax[0].hist(df['age'],label = 'patients')\nax[0].set_xlabel('Age')\nax[0].set_ylabel('Number of Patients')\nax[0].set_yticks([5,10,15,20,25,30,35,40,45,50,55,60])\nax[0].legend()\nax[0].set_title('Age Distribution')\nax[1].hist(x = [df[df['DEATH_EVENT']==1]['age'],df[df['DEATH_EVENT']==0]['age']],stacked=True,label=['Dead','Survived'])\nax[1].set_xlabel('Age')\nax[1].set_ylabel('Number of patients')\nax[1].set_yticks([5,10,15,20,25,30,35,40,45,50,55,60])\nax[1].set_title('Distribution of age against Death_event')\nax[1].legend()" }, { "code": null, "e": 4143, "s": 4099, "text": "<matplotlib.legend.Legend at 0x23f47461a48>" }, { "code": null, "e": 4667, "s": 4143, "text": "First, I explored the importance of the Age feature in determining If a patient is likely to have a heart failure or not. From the above, we can see that as the age increases, the probability of a death event also increases (i.e the older a patient is, the more likely he is to have a heart failure). Also, since the increase in one variable results in an increase in the other variable, we can deduce that these two variables are positively correlated. However, a correlation matrix will still be plotted for confirmation." }, { "code": null, "e": 5388, "s": 4667, "text": "fig,ax = plt.subplots(1,2,figsize=(16,8))\nax[0].hist(df['serum_creatinine'], label = 'patients')\nax[0].set_xlabel('serum_creatinine')\nax[0].set_ylabel('Number of Patients')\nax[0].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150])\nax[0].legend()\nax[0].set_title('serum_creatinine Distribution')\nax[1].hist(x = [df[df['DEATH_EVENT']==1]['serum_creatinine'],df[df['DEATH_EVENT']==0]['serum_creatinine']], stacked=True, label=['Dead','Survived'])\nax[1].set_xlabel('serum_creatinine')\nax[1].set_ylabel('Number of patients')\nax[1].set_yticks(([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220]))\nax[1].set_title('Distribution of serum_creatinine against Death_event')\nax[1].legend()" }, { "code": null, "e": 5432, "s": 5388, "text": "<matplotlib.legend.Legend at 0x1cb67ef52c8>" }, { "code": null, "e": 5647, "s": 5432, "text": "In general, the normal creatinine levels range from 0.9–1.3, and from the distribution of serum_creatinine against Death_event visualized above, we can see that the chances of survival are higher within this range." }, { "code": null, "e": 6311, "s": 5647, "text": "fig,ax = plt.subplots(1,2,figsize=(20,10))\nax[0].hist(df['serum_sodium'], label = 'patients')\nax[0].set_xlabel('serum_sodium')\nax[0].set_ylabel('Number of Patients')\nax[0].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150])\nax[0].legend()\nax[0].set_title('Serum sodium Distribution')\nax[1].hist(x = [df[df['DEATH_EVENT']==1]['serum_sodium'],df[df['DEATH_EVENT']==0]['serum_sodium']], stacked=True, label=['Dead','Survived'])\nax[1].set_xlabel('serum_sodium')\nax[1].set_ylabel('Number of patients')\nax[1].set_yticks([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150])\nax[1].set_title('Distribution of serum_sodium against Death_event')\nax[1].legend()" }, { "code": null, "e": 6355, "s": 6311, "text": "<matplotlib.legend.Legend at 0x1cb6841af08>" }, { "code": null, "e": 6572, "s": 6355, "text": "The reference range for serum sodium is between 135–147 mmol/L. From the visualization above, the survival rate only starts to increase at this range. This feature also has a considerable correlation with Death_Event" }, { "code": null, "e": 6761, "s": 6572, "text": "To further evaluate the relationship between each input variable and the target variable, I use a heatmap, which gives a graphical representation of the relationship between the variables." }, { "code": null, "e": 6845, "s": 6761, "text": "plt.figure(figsize=[16,8])\ncorr = sns.heatmap(df.corr(), annot=True, cmap=\"RdYlGn\")" }, { "code": null, "e": 6887, "s": 6845, "text": "Step 4: Splitting the Train and Test Data" }, { "code": null, "e": 6914, "s": 6887, "text": "Step 5: Data Preprocessing" }, { "code": null, "e": 7132, "s": 6914, "text": "This brings the data to a state that the model can parse easily. For the purpose of this project, the Standard Scaler is used, which standardizes the features by subtracting the mean and then scaling to unit variance." }, { "code": null, "e": 7156, "s": 7132, "text": "Step 6: Model Selection" }, { "code": null, "e": 7433, "s": 7156, "text": "The support vector machine (SVM), a supervised machine learning model that uses classification algorithms for two-group classification problems is used. After giving the SVM model sets of the preprocessed training data for each category, they’re able to categorize new output." }, { "code": null, "e": 7485, "s": 7433, "text": "The classification report shows an accuracy of 75%." }, { "code": null, "e": 7633, "s": 7485, "text": "Since this model will be deployed, it is saved into a pickle file (model.pkl) created by pickle, and this file will reflect in your project folder." }, { "code": null, "e": 7769, "s": 7633, "text": "Pickle is a python module that enables python objects to be written to files on the disk and read back into the python program runtime." }, { "code": null, "e": 7809, "s": 7769, "text": "Step 7: Deploying with Flask and Heroku" }, { "code": null, "e": 7907, "s": 7809, "text": "Deploying a machine learning model means making the model available for end-users to make use of." }, { "code": null, "e": 7926, "s": 7907, "text": "Create the Webpage" }, { "code": null, "e": 8066, "s": 7926, "text": "Here we will create a CSS webpage that has text boxes to take in input from users. The CSS file was named index.html and can be found here." }, { "code": null, "e": 8132, "s": 8066, "text": "Several templates for creating a CSS webpage can be found online." }, { "code": null, "e": 8176, "s": 8132, "text": "Deploy the model on the webpage using Flask" }, { "code": null, "e": 8404, "s": 8176, "text": "In deploying this heart failure prediction model into production, a web application framework called Flask is used. Flask makes it easy to write applications, and also gives a variety of choices for developing web applications." }, { "code": null, "e": 8526, "s": 8404, "text": "To make use of this web application framework in deploying this model, we install Flask by running the following command:" }, { "code": null, "e": 8669, "s": 8526, "text": "Next, a Flask environment with an API endpoint that takes in the model and enables it to receive input from users, and return output is setup." }, { "code": null, "e": 8750, "s": 8669, "text": "After this, a python file app.py is created, and the required libraries imported" }, { "code": null, "e": 8771, "s": 8750, "text": "Create the Flask App" }, { "code": null, "e": 8787, "s": 8771, "text": "Load the pickle" }, { "code": null, "e": 8852, "s": 8787, "text": "Create an app route to render the HTML template as the home page" }, { "code": null, "e": 8947, "s": 8852, "text": "Create an API that gets input from the user and computes a predicted value based on the model." }, { "code": null, "e": 9001, "s": 8947, "text": "Now, call the run function to start the Flask server." }, { "code": null, "e": 9135, "s": 9001, "text": "This should return an output that shows that your app is running. Simply copy the URL and paste it into your browser to test the app." }, { "code": null, "e": 9166, "s": 9135, "text": "Deploy the Flask APP to Heroku" }, { "code": null, "e": 9382, "s": 9166, "text": "Heroku is a multi-language application platform that allows developers to deploy, and manage their applications. It is flexible and easy to use, offering developers the simplest path to getting their apps to market." }, { "code": null, "e": 9631, "s": 9382, "text": "The first thing to do in deploying the Flask app to Heroku is to Sign up and Log In to Heroku. After which you can create a Procfile and requirement.txt file, which handles the configuration part in order to deploy the model into the Heroku server." }, { "code": null, "e": 9684, "s": 9631, "text": "web: gunicorn is the fixed command for the Procfile." }, { "code": null, "e": 9787, "s": 9684, "text": "The requirements file consists of the project dependencies and can be installed with a single command:" }, { "code": null, "e": 9854, "s": 9787, "text": "Next, you commit your code to Github and connect Github to Heroku." }, { "code": null, "e": 10129, "s": 9854, "text": "After you connect, there are 2 ways to deploy your app. You could either choose automatic deploy or manual deploy. The automatic deployment will take place whenever you commit anything into your Github repository.By selecting the branch and clicking on deploy, build starts." }, { "code": null, "e": 10288, "s": 10129, "text": "After a successful deployment, the app will be created. Click on the view and your app should open. A new URL will also be created and can be shared by users." }, { "code": null, "e": 10365, "s": 10288, "text": "Check Out my app via ‘https://heart-failure-prediction-app20.herokuapp.com/’" }, { "code": null, "e": 10376, "s": 10365, "text": "Conclusion" }, { "code": null, "e": 10798, "s": 10376, "text": "It is one thing to build a Machine learning model, and it's another thing to deploy the model by integrating it into an existing production environment that can take in input from users and return an output. This article covered building and most importantly deploying a heart failure prediction machine learning model that could significantly help reduce the mortality rate amongst patients with cardiovascular diseases." }, { "code": null, "e": 10997, "s": 10798, "text": "It is important to note that asides from the Algorithm (SVM), web framework (Flask), and the Application platform (Heroku) used in this project, there are several other options that can be explored." }, { "code": null, "e": 11049, "s": 10997, "text": "The link to the Github Repository can be found here" }, { "code": null, "e": 11097, "s": 11049, "text": "Dataset Authors: Davide Chicco, Giuseppe Jurman" }, { "code": null, "e": 11113, "s": 11097, "text": "Link to Dataset" } ]
C# | MaskedTextBox Class - GeeksforGeeks
05 Sep, 2019 In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. The MaskedTextBox class is used to represent the windows masked text box and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace.This class enhanced version of TextBox control, it supports a declarative syntax for receiving or rejecting the user input and when this control display at run time, it represents the mask as a sequence of prompt characters and optional literal characters. In C# you can create a MaskedTextBox in the windows form by using two different ways: 1. Design-Time: It is the easiest way to create a MaskedTextBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the MaskedTextBox control from the toolbox to the form. Step 3: After drag and drop you will go to the properties of the MaskedTextBox control to modify MaskedTextBox according to your requirement.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a MaskedTextBox control programmatically with the help of syntax provided by the MaskedTextBox class. The following steps show how to set the create MaskedTextBox dynamically: Step 1: Create a MaskedTextBox control using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox control MaskedTextBox mbox = new MaskedTextBox(); // Creating a MaskedTextBox control MaskedTextBox mbox = new MaskedTextBox(); Step 2: After creating MaskedTextBox control, set the property of the MaskedTextBox control provided by the MaskedTextBox class.// Setting the properties // of MaskedTextBox mbox.Location = new Point(374, 137); mbox.Mask = "000000000"; mbox.Size = new Size(176, 20); mbox.Name = "MyBox"; mbox.Font = new Font("Bauhaus 93", 18); // Setting the properties // of MaskedTextBox mbox.Location = new Point(374, 137); mbox.Mask = "000000000"; mbox.Size = new Size(176, 20); mbox.Name = "MyBox"; mbox.Font = new Font("Bauhaus 93", 18); Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox // control on the form this.Controls.Add(mbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp36 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bauhaus 93", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bauhaus 93", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox mbox = new MaskedTextBox(); mbox.Location = new Point(374, 137); mbox.Mask = "000000000"; mbox.Size = new Size(176, 20); mbox.Name = "MyBox"; mbox.Font = new Font("Bauhaus 93", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(mbox); }}}Output: // Adding MaskedTextBox // control on the form this.Controls.Add(mbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp36 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bauhaus 93", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bauhaus 93", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox mbox = new MaskedTextBox(); mbox.Location = new Point(374, 137); mbox.Mask = "000000000"; mbox.Size = new Size(176, 20); mbox.Name = "MyBox"; mbox.Font = new Font("Bauhaus 93", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(mbox); }}} Output: CSharp-Windows-Forms-Namespace 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 Introduction to .NET Framework HashSet in C# with Examples Common Language Runtime (CLR) in C# C# | Replace() Method How to find the length of an Array in C# C# | Dictionary.Add() Method C# Tutorial C# | Class and Object C# | How to use strings in switch statement
[ { "code": null, "e": 24025, "s": 23997, "text": "\n05 Sep, 2019" }, { "code": null, "e": 24790, "s": 24025, "text": "In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. The MaskedTextBox class is used to represent the windows masked text box and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace.This class enhanced version of TextBox control, it supports a declarative syntax for receiving or rejecting the user input and when this control display at run time, it represents the mask as a sequence of prompt characters and optional literal characters. In C# you can create a MaskedTextBox in the windows form by using two different ways:" }, { "code": null, "e": 24887, "s": 24790, "text": "1. Design-Time: It is the easiest way to create a MaskedTextBox as shown in the following steps:" }, { "code": null, "e": 25003, "s": 24887, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 25087, "s": 25003, "text": "Step 2: Next, drag and drop the MaskedTextBox control from the toolbox to the form." }, { "code": null, "e": 25236, "s": 25087, "text": "Step 3: After drag and drop you will go to the properties of the MaskedTextBox control to modify MaskedTextBox according to your requirement.Output:" }, { "code": null, "e": 25244, "s": 25236, "text": "Output:" }, { "code": null, "e": 25515, "s": 25244, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a MaskedTextBox control programmatically with the help of syntax provided by the MaskedTextBox class. The following steps show how to set the create MaskedTextBox dynamically:" }, { "code": null, "e": 25711, "s": 25515, "text": "Step 1: Create a MaskedTextBox control using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox control\nMaskedTextBox mbox = new MaskedTextBox(); \n" }, { "code": null, "e": 25791, "s": 25711, "text": "// Creating a MaskedTextBox control\nMaskedTextBox mbox = new MaskedTextBox(); \n" }, { "code": null, "e": 26126, "s": 25791, "text": "Step 2: After creating MaskedTextBox control, set the property of the MaskedTextBox control provided by the MaskedTextBox class.// Setting the properties \n// of MaskedTextBox\nmbox.Location = new Point(374, 137); \nmbox.Mask = \"000000000\"; \nmbox.Size = new Size(176, 20); \nmbox.Name = \"MyBox\"; \nmbox.Font = new Font(\"Bauhaus 93\", 18); \n" }, { "code": null, "e": 26333, "s": 26126, "text": "// Setting the properties \n// of MaskedTextBox\nmbox.Location = new Point(374, 137); \nmbox.Mask = \"000000000\"; \nmbox.Size = new Size(176, 20); \nmbox.Name = \"MyBox\"; \nmbox.Font = new Font(\"Bauhaus 93\", 18); \n" }, { "code": null, "e": 27972, "s": 26333, "text": "Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox \n// control on the form \nthis.Controls.Add(mbox); \nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp36 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bauhaus 93\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bauhaus 93\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox mbox = new MaskedTextBox(); mbox.Location = new Point(374, 137); mbox.Mask = \"000000000\"; mbox.Size = new Size(176, 20); mbox.Name = \"MyBox\"; mbox.Font = new Font(\"Bauhaus 93\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(mbox); }}}Output:" }, { "code": null, "e": 28048, "s": 27972, "text": "// Adding MaskedTextBox \n// control on the form \nthis.Controls.Add(mbox); \n" }, { "code": null, "e": 28057, "s": 28048, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp36 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bauhaus 93\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bauhaus 93\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox mbox = new MaskedTextBox(); mbox.Location = new Point(374, 137); mbox.Mask = \"000000000\"; mbox.Size = new Size(176, 20); mbox.Name = \"MyBox\"; mbox.Font = new Font(\"Bauhaus 93\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(mbox); }}}", "e": 29516, "s": 28057, "text": null }, { "code": null, "e": 29524, "s": 29516, "text": "Output:" }, { "code": null, "e": 29555, "s": 29524, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 29558, "s": 29555, "text": "C#" }, { "code": null, "e": 29656, "s": 29558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29665, "s": 29656, "text": "Comments" }, { "code": null, "e": 29678, "s": 29665, "text": "Old Comments" }, { "code": null, "e": 29716, "s": 29678, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 29747, "s": 29716, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29775, "s": 29747, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29811, "s": 29775, "text": "Common Language Runtime (CLR) in C#" }, { "code": null, "e": 29833, "s": 29811, "text": "C# | Replace() Method" }, { "code": null, "e": 29874, "s": 29833, "text": "How to find the length of an Array in C#" }, { "code": null, "e": 29903, "s": 29874, "text": "C# | Dictionary.Add() Method" }, { "code": null, "e": 29915, "s": 29903, "text": "C# Tutorial" }, { "code": null, "e": 29937, "s": 29915, "text": "C# | Class and Object" } ]
ByteBuffer compact() method in Java with Examples - GeeksforGeeks
06 Jun, 2021 The compact() method of java.nio.ByteBuffer class is used to compact the given buffer.The bytes between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index p = position() is copied to index zero, the byte at index p + 1 is copied to index one, and so forth until the byte at index limit() – 1 is copied to index n = limit() – 1 – p. The buffer’s position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded.The buffer’s position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method.Invoke this method after writing data from a buffer in case the write was incomplete. Syntax : public abstract ByteBuffer compact() Return Value: This method returns the new ByteBuffer with the same content as that of this buffer.Exception: This method throws the ReadOnlyBufferException, If this buffer is read-only.Below program illustrates the compact() method:Examples 1: Java // Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 7; // Creating the ByteBuffer // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb.array())); System.out.println("Position: " + bb.position()); System.out.println("limit: " + bb.limit()); // Creating a compacted ByteBuffer of same ByteBuffer // using compact() method ByteBuffer cbb = bb.compact(); // print the ByteBuffer System.out.println("\nCompacted ByteBuffer: " + Arrays.toString(cbb.array())); System.out.println("Position: " + cbb.position()); System.out.println("limit: " + cbb.limit()); // putting the int to byte typecast value in compacted ByteBuffer cbb.put((byte)50); // print the ByteBuffer System.out.println("\nUpdated Compacted ByteBuffer: " + Arrays.toString(cbb.array())); System.out.println("Position: " + cbb.position()); System.out.println("limit: " + cbb.limit()); }} Original ByteBuffer: [20, 30, 40, 0, 0, 0, 0] Position: 3 limit: 7 Compacted ByteBuffer: [0, 0, 0, 0, 0, 0, 0] Position: 4 limit: 7 Updated Compacted ByteBuffer: [0, 0, 0, 0, 50, 0, 0] Position: 5 limit: 7 Examples 2: Java // Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // print the ReadOnlyBuffer System.out.print("ReadOnlyBuffer ByteBuffer: "); while (bb1.hasRemaining()) System.out.print(bb1.get() + ", "); System.out.println(""); // print the Position of ByteBuffer bb System.out.println("\nPosition: " + bb.position()); // print the Limit of ByteBuffer bb System.out.println("\nlimit: " + bb.limit()); // Creating a compacted ByteBuffer of same ReadOnlyBuffer // using compact() method System.out.println("\nTrying to compact the ReadOnlyBuffer bb1"); ByteBuffer rbb = bb1.compact(); } catch (IllegalArgumentException e) { System.out.println("Exception throws " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws " + e); } }} ReadOnlyBuffer ByteBuffer: 20, 30, 40, 0, 0, Position: 0 limit: 5 Trying to compact the ReadOnlyBuffer bb1 Exception throws java.nio.ReadOnlyBufferException anikakapoor Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n06 Jun, 2021" }, { "code": null, "e": 24366, "s": 23557, "text": "The compact() method of java.nio.ByteBuffer class is used to compact the given buffer.The bytes between the buffer’s current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index p = position() is copied to index zero, the byte at index p + 1 is copied to index one, and so forth until the byte at index limit() – 1 is copied to index n = limit() – 1 – p. The buffer’s position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded.The buffer’s position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method.Invoke this method after writing data from a buffer in case the write was incomplete. Syntax : " }, { "code": null, "e": 24403, "s": 24366, "text": "public abstract ByteBuffer compact()" }, { "code": null, "e": 24649, "s": 24403, "text": "Return Value: This method returns the new ByteBuffer with the same content as that of this buffer.Exception: This method throws the ReadOnlyBufferException, If this buffer is read-only.Below program illustrates the compact() method:Examples 1: " }, { "code": null, "e": 24654, "s": 24649, "text": "Java" }, { "code": "// Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 7; // Creating the ByteBuffer // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb.array())); System.out.println(\"Position: \" + bb.position()); System.out.println(\"limit: \" + bb.limit()); // Creating a compacted ByteBuffer of same ByteBuffer // using compact() method ByteBuffer cbb = bb.compact(); // print the ByteBuffer System.out.println(\"\\nCompacted ByteBuffer: \" + Arrays.toString(cbb.array())); System.out.println(\"Position: \" + cbb.position()); System.out.println(\"limit: \" + cbb.limit()); // putting the int to byte typecast value in compacted ByteBuffer cbb.put((byte)50); // print the ByteBuffer System.out.println(\"\\nUpdated Compacted ByteBuffer: \" + Arrays.toString(cbb.array())); System.out.println(\"Position: \" + cbb.position()); System.out.println(\"limit: \" + cbb.limit()); }}", "e": 26201, "s": 24654, "text": null }, { "code": null, "e": 26409, "s": 26201, "text": "Original ByteBuffer: [20, 30, 40, 0, 0, 0, 0]\nPosition: 3\nlimit: 7\n\nCompacted ByteBuffer: [0, 0, 0, 0, 0, 0, 0]\nPosition: 4\nlimit: 7\n\nUpdated Compacted ByteBuffer: [0, 0, 0, 0, 50, 0, 0]\nPosition: 5\nlimit: 7" }, { "code": null, "e": 26425, "s": 26411, "text": "Examples 2: " }, { "code": null, "e": 26430, "s": 26425, "text": "Java" }, { "code": "// Java program to demonstrate// compact() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.rewind(); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // print the ReadOnlyBuffer System.out.print(\"ReadOnlyBuffer ByteBuffer: \"); while (bb1.hasRemaining()) System.out.print(bb1.get() + \", \"); System.out.println(\"\"); // print the Position of ByteBuffer bb System.out.println(\"\\nPosition: \" + bb.position()); // print the Limit of ByteBuffer bb System.out.println(\"\\nlimit: \" + bb.limit()); // Creating a compacted ByteBuffer of same ReadOnlyBuffer // using compact() method System.out.println(\"\\nTrying to compact the ReadOnlyBuffer bb1\"); ByteBuffer rbb = bb1.compact(); } catch (IllegalArgumentException e) { System.out.println(\"Exception throws \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws \" + e); } }}", "e": 28093, "s": 26430, "text": null }, { "code": null, "e": 28254, "s": 28093, "text": "ReadOnlyBuffer ByteBuffer: 20, 30, 40, 0, 0, \n\nPosition: 0\n\nlimit: 5\n\nTrying to compact the ReadOnlyBuffer bb1\nException throws java.nio.ReadOnlyBufferException" }, { "code": null, "e": 28268, "s": 28256, "text": "anikakapoor" }, { "code": null, "e": 28284, "s": 28268, "text": "Java-ByteBuffer" }, { "code": null, "e": 28299, "s": 28284, "text": "Java-Functions" }, { "code": null, "e": 28316, "s": 28299, "text": "Java-NIO package" }, { "code": null, "e": 28321, "s": 28316, "text": "Java" }, { "code": null, "e": 28326, "s": 28321, "text": "Java" }, { "code": null, "e": 28424, "s": 28326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28433, "s": 28424, "text": "Comments" }, { "code": null, "e": 28446, "s": 28433, "text": "Old Comments" }, { "code": null, "e": 28476, "s": 28446, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28491, "s": 28476, "text": "Stream In Java" }, { "code": null, "e": 28512, "s": 28491, "text": "Constructors in Java" }, { "code": null, "e": 28558, "s": 28512, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28577, "s": 28558, "text": "Exceptions in Java" }, { "code": null, "e": 28594, "s": 28577, "text": "Generics in Java" }, { "code": null, "e": 28637, "s": 28594, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28653, "s": 28637, "text": "Strings in Java" }, { "code": null, "e": 28702, "s": 28653, "text": "How to remove an element from ArrayList in Java?" } ]
Import a module in Python
A module is basically a file which has many lines of python code that can be referred or used by other python programs. A big python program should be organized to keep different parts of the program in different modules. That helps in all aspects like debugging, enhancements and packaging the program efficiently. To use a module in any python program we should first import it to the new program. All the functions, methods etc. from this module then will be available to the new program. Let’s create a file named profit.py which contains program for a specific calculation as shown below. def getprofit(cp, sp): result = ((sp-cp)/cp)*100 return result Next we want to use the above function in another python program. We can then use the import function in the new program to refer to this module and its function named getprofit. import profit perc=profit.getprofit(350,500) print(perc) Running the above code gives us the following result − 42.857142857142854 We can also import only a specific method from a module instead of the entire module. For that we use the from Module import statement as shown below. In the below example we import the value of pi from math module to be used in some calculation in the program. from math import pi x = 30*pi print(x) Running the above code gives us the following result − 94.24777960769379 If we want to know the location of various inbuilt modules we can use the sys module to find out. Similarly to know the various function available in a module we can use the dir method as shown below. import sys import math print(sys.path) print(dir(math)) Running the above code gives us the following result − [' ', 'C:\\Windows\\system32\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'C:\\Python38\\lib\\site-packages'] ['.....log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod',....]
[ { "code": null, "e": 1554, "s": 1062, "text": "A module is basically a file which has many lines of python code that can be referred or used by other python programs. A big python program should be organized to keep different parts of the program in different modules. That helps in all aspects like debugging, enhancements and packaging the program efficiently. To use a module in any python program we should first import it to the new program. All the functions, methods etc. from this module then will be available to the new program." }, { "code": null, "e": 1656, "s": 1554, "text": "Let’s create a file named profit.py which contains program for a specific calculation as shown below." }, { "code": null, "e": 1725, "s": 1656, "text": "def getprofit(cp, sp):\n result = ((sp-cp)/cp)*100\n return result" }, { "code": null, "e": 1904, "s": 1725, "text": "Next we want to use the above function in another python program. We can then use the import function in the new program to refer to this module and its function named getprofit." }, { "code": null, "e": 1962, "s": 1904, "text": "import profit\n\nperc=profit.getprofit(350,500)\nprint(perc)" }, { "code": null, "e": 2017, "s": 1962, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2036, "s": 2017, "text": "42.857142857142854" }, { "code": null, "e": 2298, "s": 2036, "text": "We can also import only a specific method from a module instead of the entire module. For that we use the from Module import statement as shown below. In the below example we import the value of pi from math module to be used in some calculation in the program." }, { "code": null, "e": 2338, "s": 2298, "text": "from math import pi\n\nx = 30*pi\nprint(x)" }, { "code": null, "e": 2393, "s": 2338, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2411, "s": 2393, "text": "94.24777960769379" }, { "code": null, "e": 2612, "s": 2411, "text": "If we want to know the location of various inbuilt modules we can use the sys module to find out. Similarly to know the various function available in a module we can use the dir method as shown below." }, { "code": null, "e": 2669, "s": 2612, "text": "import sys\nimport math\n\nprint(sys.path)\nprint(dir(math))" }, { "code": null, "e": 2724, "s": 2669, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2928, "s": 2724, "text": "[' ',\n'C:\\\\Windows\\\\system32\\\\python38.zip',\n'C:\\\\Python38\\\\DLLs',\n'C:\\\\Python38\\\\lib',\n'C:\\\\Python38',\n'C:\\\\Python38\\\\lib\\\\site-packages']\n\n['.....log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod',....]" } ]
How to pass data from one component to other component in ReactJS ? - GeeksforGeeks
25 May, 2021 In this article, We are going to see how to pass data from one component to another component. We have multiple ways of passing data among components. We can pass data from parent to child, from child to parent, and between siblings. So now let’s see how can we do so. Creating React Application: Step 1: Create a React application using the following command.npx create-react-app myapp npx create-react-app myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command.cd myapp cd myapp Project Structure: It will look like the following. We have created two Components named Child.js and Parent.js as shown below. We have created two Components named Child.js and Parent.js as shown in the above structure. For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only. Example: The following example covers how to pass data from Parent to Child Component in ReactJS. Parent.js import React from 'react'import Child from './Child'; const Parent = () => {const data = "Hello Everyone"; return( <div> <Child data={data}/> </div> );} export default Parent; Child.js import React from 'react'; const Child = (props) => { return( <h2> {props.data} </h2> );} export default Child; App.js import React from 'react';import "./index.css";import Parent from './Parent' const App = () => { return ( <div className="App"> <Parent/> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Passing data from Child to Parent Component: For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component. Example: The following example covers how to pass data from Child to Parent Component in ReactJS. Parent.js import React from 'react';import Child from './Child' class Parent extends React.Component{ state = { msg: "", } handleCallback = (childData) =>{ this.setState({msg: childData}) } render() { const {msg} = this.state; return( <div> <h1> {msg}</h1> <Child parentCallback = {this.handleCallback}/> </div> ); }} export default Parent; Child.js import React from "react"; class Child extends React.Component { onTrigger = () => { this.props.parentCallback("Welcome to GFG"); }; render() { return ( <div> <br></br> <br></br> <button onClick={this.onTrigger}>Click me</button> </div> ); }} export default Child; App.js import React from 'react';import "./index.css";import Parent from './Parent'; const App =() => { return ( <div className="App"> <Parent/> </div> );} export default App; Output: For passing data among siblings, there are multiple methods we can choose from as shown below: Combination of the above two methods (callback and use of props).Using Redux.ContextAPI Combination of the above two methods (callback and use of props). Using Redux. ContextAPI Example: In this example, we are passing data between siblings using ContextAPI. Hence, we have a different project for this. Project Structure: It will look like the following. We have created two Components named Child1.js and Child2.js as shown below. Child1.js import React, {createContext} from "react";import Child2 from './Child2'; const Name = createContext(); const Child1 = () => { return ( <> <Name.Provider value={'Archna'}> <Child2/> </Name.Provider> </> );} export default Child1;export {Name}; Child2.js import React from "react";import { Name } from "./Child1"; const Child2 = () => { return ( <> <Name.Consumer> {(fname) => { return <h1>My Name is {fname}</h1>; }} </Name.Consumer> </> );}; export default Child2; App.js import React from 'react';import "./index.css";import Child1 from './Child1'; const App =() => { return ( <div className="App"> <Child1/> </div> );} export default App; Output: Picked React-Questions ReactJS-Basics ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to redirect to another page in ReactJS ? ReactJS setState() Re-rendering Components in ReactJS ReactJS defaultProps How to set background images in ReactJS ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24300, "s": 24272, "text": "\n25 May, 2021" }, { "code": null, "e": 24569, "s": 24300, "text": "In this article, We are going to see how to pass data from one component to another component. We have multiple ways of passing data among components. We can pass data from parent to child, from child to parent, and between siblings. So now let’s see how can we do so." }, { "code": null, "e": 24597, "s": 24569, "text": "Creating React Application:" }, { "code": null, "e": 24687, "s": 24597, "text": "Step 1: Create a React application using the following command.npx create-react-app myapp" }, { "code": null, "e": 24714, "s": 24687, "text": "npx create-react-app myapp" }, { "code": null, "e": 24817, "s": 24714, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command.cd myapp" }, { "code": null, "e": 24826, "s": 24817, "text": "cd myapp" }, { "code": null, "e": 24954, "s": 24826, "text": "Project Structure: It will look like the following. We have created two Components named Child.js and Parent.js as shown below." }, { "code": null, "e": 25047, "s": 24954, "text": "We have created two Components named Child.js and Parent.js as shown in the above structure." }, { "code": null, "e": 25221, "s": 25047, "text": "For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only." }, { "code": null, "e": 25319, "s": 25221, "text": "Example: The following example covers how to pass data from Parent to Child Component in ReactJS." }, { "code": null, "e": 25329, "s": 25319, "text": "Parent.js" }, { "code": "import React from 'react'import Child from './Child'; const Parent = () => {const data = \"Hello Everyone\"; return( <div> <Child data={data}/> </div> );} export default Parent;", "e": 25536, "s": 25329, "text": null }, { "code": null, "e": 25545, "s": 25536, "text": "Child.js" }, { "code": "import React from 'react'; const Child = (props) => { return( <h2> {props.data} </h2> );} export default Child;", "e": 25670, "s": 25545, "text": null }, { "code": null, "e": 25677, "s": 25670, "text": "App.js" }, { "code": "import React from 'react';import \"./index.css\";import Parent from './Parent' const App = () => { return ( <div className=\"App\"> <Parent/> </div> );} export default App;", "e": 25861, "s": 25677, "text": null }, { "code": null, "e": 25974, "s": 25861, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 25984, "s": 25974, "text": "npm start" }, { "code": null, "e": 25992, "s": 25984, "text": "Output:" }, { "code": null, "e": 26037, "s": 25992, "text": "Passing data from Child to Parent Component:" }, { "code": null, "e": 26424, "s": 26037, "text": "For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component." }, { "code": null, "e": 26522, "s": 26424, "text": "Example: The following example covers how to pass data from Child to Parent Component in ReactJS." }, { "code": null, "e": 26532, "s": 26522, "text": "Parent.js" }, { "code": "import React from 'react';import Child from './Child' class Parent extends React.Component{ state = { msg: \"\", } handleCallback = (childData) =>{ this.setState({msg: childData}) } render() { const {msg} = this.state; return( <div> <h1> {msg}</h1> <Child parentCallback = {this.handleCallback}/> </div> ); }} export default Parent;", "e": 26974, "s": 26532, "text": null }, { "code": null, "e": 26983, "s": 26974, "text": "Child.js" }, { "code": "import React from \"react\"; class Child extends React.Component { onTrigger = () => { this.props.parentCallback(\"Welcome to GFG\"); }; render() { return ( <div> <br></br> <br></br> <button onClick={this.onTrigger}>Click me</button> </div> ); }} export default Child;", "e": 27311, "s": 26983, "text": null }, { "code": null, "e": 27318, "s": 27311, "text": "App.js" }, { "code": "import React from 'react';import \"./index.css\";import Parent from './Parent'; const App =() => { return ( <div className=\"App\"> <Parent/> </div> );} export default App;", "e": 27502, "s": 27318, "text": null }, { "code": null, "e": 27510, "s": 27502, "text": "Output:" }, { "code": null, "e": 27605, "s": 27510, "text": "For passing data among siblings, there are multiple methods we can choose from as shown below:" }, { "code": null, "e": 27693, "s": 27605, "text": "Combination of the above two methods (callback and use of props).Using Redux.ContextAPI" }, { "code": null, "e": 27759, "s": 27693, "text": "Combination of the above two methods (callback and use of props)." }, { "code": null, "e": 27772, "s": 27759, "text": "Using Redux." }, { "code": null, "e": 27783, "s": 27772, "text": "ContextAPI" }, { "code": null, "e": 27909, "s": 27783, "text": "Example: In this example, we are passing data between siblings using ContextAPI. Hence, we have a different project for this." }, { "code": null, "e": 28038, "s": 27909, "text": "Project Structure: It will look like the following. We have created two Components named Child1.js and Child2.js as shown below." }, { "code": null, "e": 28048, "s": 28038, "text": "Child1.js" }, { "code": "import React, {createContext} from \"react\";import Child2 from './Child2'; const Name = createContext(); const Child1 = () => { return ( <> <Name.Provider value={'Archna'}> <Child2/> </Name.Provider> </> );} export default Child1;export {Name};", "e": 28332, "s": 28048, "text": null }, { "code": null, "e": 28342, "s": 28332, "text": "Child2.js" }, { "code": "import React from \"react\";import { Name } from \"./Child1\"; const Child2 = () => { return ( <> <Name.Consumer> {(fname) => { return <h1>My Name is {fname}</h1>; }} </Name.Consumer> </> );}; export default Child2;", "e": 28615, "s": 28342, "text": null }, { "code": null, "e": 28622, "s": 28615, "text": "App.js" }, { "code": "import React from 'react';import \"./index.css\";import Child1 from './Child1'; const App =() => { return ( <div className=\"App\"> <Child1/> </div> );} export default App;", "e": 28806, "s": 28622, "text": null }, { "code": null, "e": 28814, "s": 28806, "text": "Output:" }, { "code": null, "e": 28821, "s": 28814, "text": "Picked" }, { "code": null, "e": 28837, "s": 28821, "text": "React-Questions" }, { "code": null, "e": 28852, "s": 28837, "text": "ReactJS-Basics" }, { "code": null, "e": 28860, "s": 28852, "text": "ReactJS" }, { "code": null, "e": 28877, "s": 28860, "text": "Web Technologies" }, { "code": null, "e": 28975, "s": 28877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29020, "s": 28975, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29039, "s": 29020, "text": "ReactJS setState()" }, { "code": null, "e": 29074, "s": 29039, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 29095, "s": 29074, "text": "ReactJS defaultProps" }, { "code": null, "e": 29137, "s": 29095, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29179, "s": 29137, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29212, "s": 29179, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29262, "s": 29212, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29324, "s": 29262, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to Install Julia on MacOS? - GeeksforGeeks
02 Jul, 2020 Julia is one of the new programming languages that is becoming popular with time. It is used mainly for scientific data calculations and mathematical analysis. It is becoming popular because it has very fast execution like C and simple syntax like python. It is an open-source language with high performance. Julia Codes can be written, compiled, and Run on multiple platforms like BBEdit on MacOS, Jupyter, etc. Many online IDE’s are also available for Julia. For using it on your own system one can install it in the following ways: Follow the steps given below to download and install Julia from its official site: Step 1: Open julialang.org and start downloading .dmg file for MacOS(64bit). Step 2: Start the installation from the dmg file and move the Julia file in the application folder. Step 3: Now click on Julia icon in applications, it will open terminal as follows : Step 4: Julia is installed in your system now you can run a file with the next step. Step 5: Now to run a sample program create a Julia file on any local IDE and save it with “.jl” extension and sample code as follows: # sample_codeprintln("Welcome to Julia") Step 6: Run the above file as follows Julia can also be directly installed from the terminal by following the steps given below: Step 1: Check for pre-installed versions: Open terminal on your Mac and type the following command: julia Step 2: Now download Julia (latest version) by using the following command in your terminal: brew cask install julia It will look like this after installation. Step 3: Now run the julia command as in point 1 and it should appear as following Step 4: Now to run a sample program go through Step 5 of Method 1. Now, your system is ready with Julia installed to function properly. How To Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Install Jupyter Notebook on MacOS? How to Check the OS Version in Linux? For loop in Julia Arrays in Julia Julia Dictionary Printing Output on Screen in Julia Vectors in Julia
[ { "code": null, "e": 24978, "s": 24950, "text": "\n02 Jul, 2020" }, { "code": null, "e": 25287, "s": 24978, "text": "Julia is one of the new programming languages that is becoming popular with time. It is used mainly for scientific data calculations and mathematical analysis. It is becoming popular because it has very fast execution like C and simple syntax like python. It is an open-source language with high performance." }, { "code": null, "e": 25513, "s": 25287, "text": "Julia Codes can be written, compiled, and Run on multiple platforms like BBEdit on MacOS, Jupyter, etc. Many online IDE’s are also available for Julia. For using it on your own system one can install it in the following ways:" }, { "code": null, "e": 25596, "s": 25513, "text": "Follow the steps given below to download and install Julia from its official site:" }, { "code": null, "e": 25942, "s": 25596, "text": "Step 1: Open julialang.org and start downloading .dmg file for MacOS(64bit). Step 2: Start the installation from the dmg file and move the Julia file in the application folder. Step 3: Now click on Julia icon in applications, it will open terminal as follows : Step 4: Julia is installed in your system now you can run a file with the next step." }, { "code": null, "e": 26076, "s": 25942, "text": "Step 5: Now to run a sample program create a Julia file on any local IDE and save it with “.jl” extension and sample code as follows:" }, { "code": "# sample_codeprintln(\"Welcome to Julia\")", "e": 26117, "s": 26076, "text": null }, { "code": null, "e": 26155, "s": 26117, "text": "Step 6: Run the above file as follows" }, { "code": null, "e": 26246, "s": 26155, "text": "Julia can also be directly installed from the terminal by following the steps given below:" }, { "code": null, "e": 26346, "s": 26246, "text": "Step 1: Check for pre-installed versions: Open terminal on your Mac and type the following command:" }, { "code": null, "e": 26352, "s": 26346, "text": "julia" }, { "code": null, "e": 26445, "s": 26352, "text": "Step 2: Now download Julia (latest version) by using the following command in your terminal:" }, { "code": null, "e": 26469, "s": 26445, "text": "brew cask install julia" }, { "code": null, "e": 26661, "s": 26469, "text": "It will look like this after installation. Step 3: Now run the julia command as in point 1 and it should appear as following Step 4: Now to run a sample program go through Step 5 of Method 1." }, { "code": null, "e": 26730, "s": 26661, "text": "Now, your system is ready with Julia installed to function properly." }, { "code": null, "e": 26737, "s": 26730, "text": "How To" }, { "code": null, "e": 26743, "s": 26737, "text": "Julia" }, { "code": null, "e": 26841, "s": 26743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26875, "s": 26841, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26924, "s": 26875, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26982, "s": 26924, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 27024, "s": 26982, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 27062, "s": 27024, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 27080, "s": 27062, "text": "For loop in Julia" }, { "code": null, "e": 27096, "s": 27080, "text": "Arrays in Julia" }, { "code": null, "e": 27113, "s": 27096, "text": "Julia Dictionary" }, { "code": null, "e": 27148, "s": 27113, "text": "Printing Output on Screen in Julia" } ]
Python - Filter Rows with Range Elements - GeeksforGeeks
11 Oct, 2020 Given a Matrix, filter all the rows which contain all elements in the given number range. Input : test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows. Input : test_list = [[3, 2, 4, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows. Method #1 : Using all() + list comprehension In this, we check for all the elements in range for presence using all() and list comprehension is used for the task of iteration of elements. Python3 # Python3 code to demonstrate working of# Filter Rows with Range Elements# Using all() + list comprehension # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]] # printing original listprint("The original list is : " + str(test_list)) # initializing rangei, j = 2, 5 # checking for presence of all elements using in operatorres = [sub for sub in test_list if all(ele in sub for ele in range(i, j + 1))] # printing resultprint("Extracted rows : " + str(res)) Output: The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Method #2 : Using filter() + lambda + all() In this, task of filtering is done using filter() and lambda function, all() is again used to ensure all elements presence in range. Python3 # Python3 code to demonstrate working of# Filter Rows with Range Elements# Using filter() + lambda + all() # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]] # printing original listprint("The original list is : " + str(test_list)) # initializing rangei, j = 2, 5 # filter() and lambda used to filter elementsres = list(filter(lambda sub: all( ele in sub for ele in range(i, j + 1)), test_list)) # printing resultprint("Extracted rows : " + str(res)) Output: The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Binary Search (Recursive and Iterative) Python | Split string into list of characters
[ { "code": null, "e": 23901, "s": 23873, "text": "\n11 Oct, 2020" }, { "code": null, "e": 23991, "s": 23901, "text": "Given a Matrix, filter all the rows which contain all elements in the given number range." }, { "code": null, "e": 24194, "s": 23991, "text": "Input : test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows." }, { "code": null, "e": 24378, "s": 24194, "text": "Input : test_list = [[3, 2, 4, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows. " }, { "code": null, "e": 24423, "s": 24378, "text": "Method #1 : Using all() + list comprehension" }, { "code": null, "e": 24567, "s": 24423, "text": "In this, we check for all the elements in range for presence using all() and list comprehension is used for the task of iteration of elements. " }, { "code": null, "e": 24575, "s": 24567, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Rows with Range Elements# Using all() + list comprehension # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangei, j = 2, 5 # checking for presence of all elements using in operatorres = [sub for sub in test_list if all(ele in sub for ele in range(i, j + 1))] # printing resultprint(\"Extracted rows : \" + str(res))", "e": 25095, "s": 24575, "text": null }, { "code": null, "e": 25103, "s": 25095, "text": "Output:" }, { "code": null, "e": 25247, "s": 25103, "text": "The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]" }, { "code": null, "e": 25291, "s": 25247, "text": "Method #2 : Using filter() + lambda + all()" }, { "code": null, "e": 25424, "s": 25291, "text": "In this, task of filtering is done using filter() and lambda function, all() is again used to ensure all elements presence in range." }, { "code": null, "e": 25432, "s": 25424, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Rows with Range Elements# Using filter() + lambda + all() # initializing listtest_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing rangei, j = 2, 5 # filter() and lambda used to filter elementsres = list(filter(lambda sub: all( ele in sub for ele in range(i, j + 1)), test_list)) # printing resultprint(\"Extracted rows : \" + str(res))", "e": 25949, "s": 25432, "text": null }, { "code": null, "e": 25957, "s": 25949, "text": "Output:" }, { "code": null, "e": 26101, "s": 25957, "text": "The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]" }, { "code": null, "e": 26122, "s": 26101, "text": "Python list-programs" }, { "code": null, "e": 26129, "s": 26122, "text": "Python" }, { "code": null, "e": 26145, "s": 26129, "text": "Python Programs" }, { "code": null, "e": 26243, "s": 26145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26252, "s": 26243, "text": "Comments" }, { "code": null, "e": 26265, "s": 26252, "text": "Old Comments" }, { "code": null, "e": 26301, "s": 26265, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26324, "s": 26301, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26363, "s": 26324, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26396, "s": 26363, "text": "Python | Convert set into a list" }, { "code": null, "e": 26445, "s": 26396, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26467, "s": 26445, "text": "Defaultdict in Python" }, { "code": null, "e": 26506, "s": 26467, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26544, "s": 26506, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 26603, "s": 26544, "text": "Python Program for Binary Search (Recursive and Iterative)" } ]
LINQ - Quick Guide
Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc. Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types. using System; using System.Linq; class Program { static void Main() { string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"}; //Get only short words var shortWords = from word in words where word.Length <= 5 select word; //Print each word out foreach (var word in shortWords) { Console.WriteLine(word); } Console.ReadLine(); } } Module Module1 Sub Main() Dim words As String() = {"hello", "wonderful", "LINQ", "beautiful", "world"} ' Get only short words Dim shortWords = From word In words _ Where word.Length <= 5 _ Select word ' Print each word out. For Each word In shortWords Console.WriteLine(word) Next Console.ReadLine() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − hello LINQ world There are two syntaxes of LINQ. These are the following ones. var longWords = words.Where( w ⇒ w.length > 10); Dim longWords = words.Where(Function(w) w.length > 10) var longwords = from w in words where w.length > 10; Dim longwords = from w in words where w.length > 10 The types of LINQ are mentioned below in brief. LINQ to Objects LINQ to XML(XLINQ) LINQ to DataSet LINQ to SQL (DLINQ) LINQ to Entities Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ. LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture is shown below. Query expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword "From". To access standard LINQ query operators, the namespace System.Query should be imported by default. These expressions are written within a declarative query syntax which was C# 3.0. Below is an example to show a complete query operation which consists of data source creation, query expression definition and query execution. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class LINQQueryExpressions { static void Main() { // Specify the data source. int[] scores = new int[] { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − 97 92 81 Introduced with .NET 3.5, Extension methods are declared in static classes only and allow inclusion of custom methods to objects to perform some precise query operations to extend a class without being an actual member of that class. These can be overloaded also. In a nutshell, extension methods are used to translate query expressions into traditional method calls (object-oriented). There is an array of differences existing between LINQ and Stored procedures. These differences are mentioned below. Stored procedures are much faster than a LINQ query as they follow an expected execution plan. Stored procedures are much faster than a LINQ query as they follow an expected execution plan. It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time. It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time. LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures. LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures. LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases. LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases. Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures. Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures. Prior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt. Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ. SqlConnection sqlConnection = new SqlConnection(connectString); SqlConnection.Open(); System.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = sqlConnection; sqlCommand.CommandText = "Select * from Customer"; return sqlCommand.ExecuteReader (CommandBehavior.CloseConnection) Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time. Northwind db = new Northwind(@"C:\Data\Northwnd.mdf"); var query = from c in db.Customers select c; LINQ offers a host of advantages and among them the foremost is its powerful expressiveness which enables developers to express declaratively. Some of the other advantages of LINQ are given below. LINQ offers syntax highlighting that proves helpful to find out mistakes during design time. LINQ offers syntax highlighting that proves helpful to find out mistakes during design time. LINQ offers IntelliSense which means writing more accurate queries easily. LINQ offers IntelliSense which means writing more accurate queries easily. Writing codes is quite faster in LINQ and thus development time also gets reduced significantly. Writing codes is quite faster in LINQ and thus development time also gets reduced significantly. LINQ makes easy debugging due to its integration in the C# language. LINQ makes easy debugging due to its integration in the C# language. Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time. Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time. LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation. LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation. LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types. LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types. LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug. LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug. LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data. LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data. Before starting with LINQ programs, it is best to first understand the nuances of setting up a LINQ environment. LINQ needs a .NET framework, a revolutionary platform to have a diverse kind of applications. A LINQ query can be written either in C# or Visual Basic conveniently. Microsoft offers tools for both of these languages i.e. C# and Visual Basic by means of Visual Studio. Our examples are all compiled and written in Visual Studio 2010. However, Visual Basic 2013 edition is also available for use. It is the latest version and has many similarities with Visual Studio 2012. Visual Studio can be installed either from an installation media like a DVD. Administrator credentials are required to install Visual Basic 2010 on your system successfully. It is vital to disconnect all removable USB from the system prior to installation otherwise the installation may get failed. Some of the hardware requirements essential to have for installation are the following ones. 1.6 GHz or more 1 GB RAM 3 GB(Available hard-disk space) 5400 RPM hard-disk drive DirectX 9 compatible video card DVD-ROM drive Step 1 − First after inserting the DVD with Visual Studio 2010 Package, click on Install or run program from your media appearing in a pop-up box on the screen. Step 2 − Now set up for Visual Studio will appear on the screen. Choose Install Microsoft Visual Studio 2010. Step 3 − As soon as you will click, it the process will get initiated and a set up window will appear on your screen. After completion of loading of the installation components which will take some time, click on Next button to move to the next step. Step 4 − This is the last step of installation and a start page will appear in which simply choose "I have read and accept the license terms" and click on Next button. Step 5 − Now select features to install from the options page appearing on your screen. You can either choose Full or Custom option. If you have less disk space than required shown in the disk space requirements, then go for Custom. Step 6 − When you choose Custom option, the following window will appear. Select the features that you want to install and click Update or else go to step 7. However, it is recommended not to go with the custom option as in future, you may need the features you have chosen to not have. Step 7 − Soon a pop up window will be shown and the installation will start which may take a long time. Remember, this is for installing all the components. Step 8 − Finally, you will be able to view a message in a window that the installation has been completed successfully. Click Finish. Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu. Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu. A new project dialog box will appear on your screen. A new project dialog box will appear on your screen. Now choose Visual C# as a category under installed templates and next choose Console Application template as shown in figure below. Now choose Visual C# as a category under installed templates and next choose Console Application template as shown in figure below. Give a name to your project in the bottom name box and press OK. Give a name to your project in the bottom name box and press OK. The new project will appear in the Solution Explorer in the right-hand side of a new dialog box on your screen. The new project will appear in the Solution Explorer in the right-hand side of a new dialog box on your screen. Now choose Program.cs from the Solution Explorer and you can view the code in the editor window which starts with ‘using System’. Now choose Program.cs from the Solution Explorer and you can view the code in the editor window which starts with ‘using System’. Here you can start to code your following C# program. Here you can start to code your following C# program. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World") Console.ReadKey(); } } } Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project. Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project. Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu. Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu. A new project dialog box will appear on your screen. A new project dialog box will appear on your screen. Now chose Visual Basic as a category under installed templates and next choose Console Application template. Now chose Visual Basic as a category under installed templates and next choose Console Application template. Give a name to your project in the bottom name box and press OK. Give a name to your project in the bottom name box and press OK. You will get a screen with Module1.vb. Start writing your VB code here using LINQ. You will get a screen with Module1.vb. Start writing your VB code here using LINQ. Module Module1 Sub Main() Console.WriteLine("Hello World") Console.ReadLine() End Sub End Module Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project. Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project. When the above code of C# or VB is cimpiled and run, it produces the following result − Hello World A set of extension methods forming a query pattern is known as LINQ Standard Query Operators. As building blocks of LINQ query expressions, these operators offer a range of query capabilities like filtering, sorting, projection, aggregation, etc. LINQ standard query operators can be categorized into the following ones on the basis of their functionality. Filtering Operators Join Operators Projection Operations Sorting Operators Grouping Operators Conversions Concatenation Aggregation Quantifier Operations Partition Operations Generation Operations Set Operations Equality Element Operators Filtering is an operation to restrict the result set such that it has only selected elements satisfying a particular condition. Show Examples Joining refers to an operation in which data sources with difficult to follow relationships with each other in a direct way are targeted. Show Examples Projection is an operation in which an object is transformed into an altogether new form with only specific properties. Show Examples A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes. Show Examples The operators put data into some groups based on a common shared attribute. Show Examples The operators change the type of input objects and are used in a diverse range of applications. Show Examples Performs concatenation of two sequences and is quite similar to the Union operator in terms of its operation except of the fact that this does not remove duplicates. Show Examples Performs any type of desired aggregation and allows creating custom aggregations in LINQ. Show Examples These operators return a Boolean value i.e. True or False when some or all elements within a sequence satisfy a specific condition. Show Examples Divide an input sequence into two separate sections without rearranging the elements of the sequence and then returning one of them. Show Examples A new sequence of values is created by generational operators. Show Examples There are four operators for the set operations, each yielding a result based on different criteria. Show Examples Compares two sentences (enumerable ) and determine are they an exact match or not. Show Examples Except the DefaultIfEmpty, all the rest eight standard query element operators return a single element from a collection. Show Examples LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the .NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution. After obtaining the results from the database, LINQ to SQL again translates them to objects. For most ASP.NET developers, LINQ to SQL (also known as DLINQ) is an electrifying part of Language Integrated Query as this allows querying data in SQL server database by using usual LINQ expressions. It also allows to update, delete, and insert data, but the only drawback from which it suffers is its limitation to the SQL server database. However, there are many benefits of LINQ to SQL over ADO.NET like reduced complexity, few lines of coding and many more. Below is a diagram showing the execution architecture of LINQ to SQL. Step 1 − Make a new “Data Connection” with database server. View &arrar; Server Explorer &arrar; Data Connections &arrar; Add Connection Step 2 − Add LINQ To SQL class file Step 3 − Select tables from database and drag and drop into the new LINQ to SQL class file. Step 4 − Added tables to class file. The rules for executing a query with LINQ to SQL is similar to that of a standard LINQ query i.e. query is executed either deferred or immediate. There are various components that play a role in execution of a query with LINQ to SQL and these are the following ones. LINQ to SQL API − requests query execution on behalf of an application and sent it to LINQ to SQL Provider. LINQ to SQL API − requests query execution on behalf of an application and sent it to LINQ to SQL Provider. LINQ to SQL Provider − converts query to Transact SQL(T-SQL) and sends the new query to the ADO Provider for execution. LINQ to SQL Provider − converts query to Transact SQL(T-SQL) and sends the new query to the ADO Provider for execution. ADO Provider − After execution of the query, send the results in the form of a DataReader to LINQ to SQL Provider which in turn converts it into a form of user object. ADO Provider − After execution of the query, send the results in the form of a DataReader to LINQ to SQL Provider which in turn converts it into a form of user object. It should be noted that before executing a LINQ to SQL query, it is vital to connect to the data source via DataContext class. C# using System; using System.Linq; namespace LINQtoSQL { class LinqToSQLCRUD { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); LinqToSQLDataContext db = new LinqToSQLDataContext(connectString); //Create new Employee Employee newEmployee = new Employee(); newEmployee.Name = "Michael"; newEmployee.Email = "yourname@companyname.com"; newEmployee.ContactNo = "343434343"; newEmployee.DepartmentId = 3; newEmployee.Address = "Michael - USA"; //Add new Employee to database db.Employees.InsertOnSubmit(newEmployee); //Save changes to Database. db.SubmitChanges(); //Get new Inserted Employee Employee insertedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("Michael")); Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}", insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email, insertedEmployee.ContactNo, insertedEmployee.Address); Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } VB Module Module1 Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim db As New LinqToSQLDataContext(connectString) Dim newEmployee As New Employee() newEmployee.Name = "Michael" newEmployee.Email = "yourname@companyname.com" newEmployee.ContactNo = "343434343" newEmployee.DepartmentId = 3 newEmployee.Address = "Michael - USA" db.Employees.InsertOnSubmit(newEmployee) db.SubmitChanges() Dim insertedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("Michael")) Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}", insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email, insertedEmployee.ContactNo, insertedEmployee.Address) Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or VB is compiled and run, it produces the following result − Emplyee ID = 4, Name = Michael, Email = yourname@companyname.com, ContactNo = 343434343, Address = Michael - USA Press any key to continue. C# using System; using System.Linq; namespace LINQtoSQL { class LinqToSQLCRUD { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); LinqToSQLDataContext db = new LinqToSQLDataContext(connectString); //Get Employee for update Employee employee = db.Employees.FirstOrDefault(e =>e.Name.Equals("Michael")); employee.Name = "George Michael"; employee.Email = "yourname@companyname.com"; employee.ContactNo = "99999999"; employee.DepartmentId = 2; employee.Address = "Michael George - UK"; //Save changes to Database. db.SubmitChanges(); //Get Updated Employee Employee updatedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("George Michael")); Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}", updatedEmployee.EmployeeId, updatedEmployee.Name, updatedEmployee.Email, updatedEmployee.ContactNo, updatedEmployee.Address); Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } VB Module Module1 Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim db As New LinqToSQLDataContext(connectString) Dim employee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("Michael")) employee.Name = "George Michael" employee.Email = "yourname@companyname.com" employee.ContactNo = "99999999" employee.DepartmentId = 2 employee.Address = "Michael George - UK" db.SubmitChanges() Dim updatedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("George Michael")) Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}", updatedEmployee.EmployeeId, updatedEmployee.Name, updatedEmployee.Email, updatedEmployee.ContactNo, updatedEmployee.Address) Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or Vb is compiled and run, it produces the following result − Emplyee ID = 4, Name = George Michael, Email = yourname@companyname.com, ContactNo = 999999999, Address = Michael George - UK Press any key to continue. C# using System; using System.Linq; namespace LINQtoSQL { class LinqToSQLCRUD { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); LinqToSQLDataContext db = newLinqToSQLDataContext(connectString); //Get Employee to Delete Employee deleteEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("George Michael")); //Delete Employee db.Employees.DeleteOnSubmit(deleteEmployee); //Save changes to Database. db.SubmitChanges(); //Get All Employee from Database var employeeList = db.Employees; foreach (Employee employee in employeeList) { Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}", employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } VB Module Module1 Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim db As New LinqToSQLDataContext(connectString) Dim deleteEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("George Michael")) db.Employees.DeleteOnSubmit(deleteEmployee) db.SubmitChanges() Dim employeeList = db.Employees For Each employee As Employee In employeeList Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}", employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or VB is compiled and run, it produces the following result − Emplyee ID = 1, Name = William, Email = abc@gy.co, ContactNo = 999999999 Emplyee ID = 2, Name = Miley, Email = amp@esds.sds, ContactNo = 999999999 Emplyee ID = 3, Name = Benjamin, Email = asdsad@asdsa.dsd, ContactNo = Press any key to continue. LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for accessing in-memory data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML. Queries in LINQ to Objects return variables of type usually IEnumerable<T> only. In short, LINQ to Objects offers a fresh approach to collections as earlier, it was vital to write long coding (foreach loops of much complexity) for retrieval of data from a collection which is now replaced by writing declarative code which clearly describes the desired data that is required to retrieve. There are also many advantages of LINQ to Objects over traditional foreach loops like more readability, powerful filtering, capability of grouping, enhanced ordering with minimal application coding. Such LINQ queries are also more compact in nature and are portable to any other data sources without any modification or with just a little modification. Below is a simple LINQ to Objects example − using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LINQtoObjects { class Program { static void Main(string[] args) { string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer", "Drill", "Sander" }; var list = from t in tools select t; StringBuilder sb = new StringBuilder(); foreach (string s in list) { sb.Append(s + Environment.NewLine); } Console.WriteLine(sb.ToString(), "Tools"); Console.ReadLine(); } } } In the example, an array of strings (tools) is used as the collection of objects to be queried using LINQ to Objects. Objects query is: var list = from t in tools select t; When the above code is compiled and executed, it produces the following result − Tablesaw Bandsaw Planer Jointer Drill Sander using System; using System.Collections.Generic; using System.Linq; namespace LINQtoObjects { class Department { public int DepartmentId { get; set; } public string Name { get; set; } } class LinqToObjects { static void Main(string[] args) { List<Department> departments = new List<Department>(); departments.Add(new Department { DepartmentId = 1, Name = "Account" }); departments.Add(new Department { DepartmentId = 2, Name = "Sales" }); departments.Add(new Department { DepartmentId = 3, Name = "Marketing" }); var departmentList = from d in departments select d; foreach (var dept in departmentList) { Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main(ByVal args As String()) Dim account As New Department With {.Name = "Account", .DepartmentId = 1} Dim sales As New Department With {.Name = "Sales", .DepartmentId = 2} Dim marketing As New Department With {.Name = "Marketing", .DepartmentId = 3} Dim departments As New System.Collections.Generic.List(Of Department)(New Department() {account, sales, marketing}) Dim departmentList = From d In departments For Each dept In departmentList Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Class Department Public Property Name As String Public Property DepartmentId As Integer End Class End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Id = 1, Department Name = Account Department Id = 2, Department Name = Sales Department Id = 3, Department Name = Marketing Press any key to continue. A Dataset offers an extremely useful data representation in memory and is used for a diverse range of data based applications. LINQ to Dataset as one of the technology of LINQ to ADO.NET facilitates performing queries on the data of a Dataset in a hassle-free manner and enhance productivity. LINQ to Dataset has made the task of querying simple for the developers. They don’t need to write queries in a specific query language instead the same can be written in programming language. LINQ to Dataset is also usable for querying where data is consolidated from multiple data sources. This also does not need any LINQ provider just like LINQ to SQL and LINQ to XML for accessing data from in memory collections. Below is a simple example of a LINQ to Dataset query in which a data source is first obtained and then the dataset is filled with two data tables. A relationship is established between both the tables and a LINQ query is created against both tables by the means of join clause. Finally, foreach loop is used to display the desired results. using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQtoDataset { class Program { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); string sqlSelect = "SELECT * FROM Department;" + "SELECT * FROM Employee;"; // Create the data adapter to retrieve data from the database SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString); // Create table mappings da.TableMappings.Add("Table", "Department"); da.TableMappings.Add("Table1", "Employee"); // Create and fill the DataSet DataSet ds = new DataSet(); da.Fill(ds); DataRelation dr = ds.Relations.Add("FK_Employee_Department", ds.Tables["Department"].Columns["DepartmentId"], ds.Tables["Employee"].Columns["DepartmentId"]); DataTable department = ds.Tables["Department"]; DataTable employee = ds.Tables["Employee"]; var query = from d in department.AsEnumerable() join e in employee.AsEnumerable() on d.Field<int>("DepartmentId") equals e.Field<int>("DepartmentId") select new { EmployeeId = e.Field<int>("EmployeeId"), Name = e.Field<string>("Name"), DepartmentId = d.Field<int>("DepartmentId"), DepartmentName = d.Field<string>("Name") }; foreach (var q in query) { Console.WriteLine("Employee Id = {0} , Name = {1} , Department Name = {2}", q.EmployeeId, q.Name, q.DepartmentName); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Data.SqlClient Imports System.Linq Module LinqToDataSet Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim sqlSelect As String = "SELECT * FROM Department;" + "SELECT * FROM Employee;" Dim sqlCnn As SqlConnection = New SqlConnection(connectString) sqlCnn.Open() Dim da As New SqlDataAdapter da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn) da.TableMappings.Add("Table", "Department") da.TableMappings.Add("Table1", "Employee") Dim ds As New DataSet() da.Fill(ds) Dim dr As DataRelation = ds.Relations.Add("FK_Employee_Department", ds.Tables("Department").Columns("DepartmentId"), ds.Tables("Employee").Columns("DepartmentId")) Dim department As DataTable = ds.Tables("Department") Dim employee As DataTable = ds.Tables("Employee") Dim query = From d In department.AsEnumerable() Join e In employee.AsEnumerable() On d.Field(Of Integer)("DepartmentId") Equals e.Field(Of Integer)("DepartmentId") Select New Person With { _ .EmployeeId = e.Field(Of Integer)("EmployeeId"), .EmployeeName = e.Field(Of String)("Name"), .DepartmentId = d.Field(Of Integer)("DepartmentId"), .DepartmentName = d.Field(Of String)("Name") } For Each e In query Console.WriteLine("Employee Id = {0} , Name = {1} , Department Name = {2}", e.EmployeeId, e.EmployeeName, e.DepartmentName) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Class Person Public Property EmployeeId As Integer Public Property EmployeeName As String Public Property DepartmentId As Integer Public Property DepartmentName As String End Class End Module When the above code of C# or VB is compiled and executed, it produces the following result − Employee Id = 1, Name = William, Department Name = Account Employee Id = 2, Name = Benjamin, Department Name = Account Employee Id = 3, Name = Miley, Department Name = Sales Press any key to continue. Before beginning querying a Dataset using LINQ to Dataset, it is vital to load data to a Dataset and this is done by either using DataAdapter class or by LINQ to SQL. Formulation of queries using LINQ to Dataset is quite similar to formulating queries by using LINQ alongside other LINQ enabled data sources. In the following single-table query, all online orders are collected from the SalesOrderHeaderTtable and then order ID, Order date as well as order number are displayed as output. C# using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinqToDataset { class SingleTable { static void Main(string[] args) { string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString(); string sqlSelect = "SELECT * FROM Department;"; // Create the data adapter to retrieve data from the database SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString); // Create table mappings da.TableMappings.Add("Table", "Department"); // Create and fill the DataSet DataSet ds = new DataSet(); da.Fill(ds); DataTable department = ds.Tables["Department"]; var query = from d in department.AsEnumerable() select new { DepartmentId = d.Field<int>("DepartmentId"), DepartmentName = d.Field<string>("Name") }; foreach (var q in query) { Console.WriteLine("Department Id = {0} , Name = {1}", q.DepartmentId, q.DepartmentName); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } VB Imports System.Data.SqlClient Imports System.Linq Module LinqToDataSet Sub Main() Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString() Dim sqlSelect As String = "SELECT * FROM Department;" Dim sqlCnn As SqlConnection = New SqlConnection(connectString) sqlCnn.Open() Dim da As New SqlDataAdapter da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn) da.TableMappings.Add("Table", "Department") Dim ds As New DataSet() da.Fill(ds) Dim department As DataTable = ds.Tables("Department") Dim query = From d In department.AsEnumerable() Select New DepartmentDetail With { .DepartmentId = d.Field(Of Integer)("DepartmentId"), .DepartmentName = d.Field(Of String)("Name") } For Each e In query Console.WriteLine("Department Id = {0} , Name = {1}", e.DepartmentId, e.DepartmentName) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub Public Class DepartmentDetail Public Property DepartmentId As Integer Public Property DepartmentName As String End Class End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Id = 1, Name = Account Department Id = 2, Name = Sales Department Id = 3, Name = Pre-Sales Department Id = 4, Name = Marketing Press any key to continue. LINQ to XML offers easy accessibility to all LINQ functionalities like standard query operators, programming interface, etc. Integrated in the .NET framework, LINQ to XML also makes the best use of .NET framework functionalities like debugging, compile-time checking, strong typing and many more to say. While using LINQ to XML, loading XML documents into memory is easy and more easier is querying and document modification. It is also possible to save XML documents existing in memory to disk and to serialize them. It eliminates the need for a developer to learn the XML query language which is somewhat complex. LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19 necessary classes to work with XML. These classes are the following ones. XAttribute XCData XComment XContainer XDeclaration XDocument XDocumentType XElement XName XNamespace XNode XNodeDocumentOrderComparer XNodeEqualityComparer XObject XObjectChange XObjectChangeEventArgs XObjectEventHandler XProcessingInstruction XText using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace LINQtoXML { class ExampleOfXML { static void Main(string[] args) { string myXML = @"<Departments> <Department>Account</Department> <Department>Sales</Department> <Department>Pre-Sales</Department> <Department>Marketing</Department> </Departments>"; XDocument xdoc = new XDocument(); xdoc = XDocument.Parse(myXML); var result = xdoc.Element("Departments").Descendants(); foreach (XElement item in result) { Console.WriteLine("Department Name - " + item.Value); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module Module1 Sub Main(ByVal args As String()) Dim myXML As String = "<Departments>" & vbCr & vbLf & "<Department>Account</Department>" & vbCr & vbLf & "<Department>Sales</Department>" & vbCr & vbLf & "<Department>Pre-Sales</Department>" & vbCr & vbLf & "<Department>Marketing</Department>" & vbCr & vbLf & "</Departments>" Dim xdoc As New XDocument() xdoc = XDocument.Parse(myXML) Dim result = xdoc.Element("Departments").Descendants() For Each item As XElement In result Console.WriteLine("Department Name - " + item.Value) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Name - Account Department Name - Sales Department Name - Pre-Sales Department Name - Marketing Press any key to continue. using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace LINQtoXML { class ExampleOfXML { static void Main(string[] args) { string myXML = @"<Departments> <Department>Account</Department> <Department>Sales</Department> <Department>Pre-Sales</Department> <Department>Marketing</Department> </Departments>"; XDocument xdoc = new XDocument(); xdoc = XDocument.Parse(myXML); //Add new Element xdoc.Element("Departments").Add(new XElement("Department", "Finance")); //Add new Element at First xdoc.Element("Departments").AddFirst(new XElement("Department", "Support")); var result = xdoc.Element("Departments").Descendants(); foreach (XElement item in result) { Console.WriteLine("Department Name - " + item.Value); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module Module1 Sub Main(ByVal args As String()) Dim myXML As String = "<Departments>" & vbCr & vbLf & "<Department>Account</Department>" & vbCr & vbLf & "<Department>Sales</Department>" & vbCr & vbLf & "<Department>Pre-Sales</Department>" & vbCr & vbLf & "<Department>Marketing</Department>" & vbCr & vbLf & "</Departments>" Dim xdoc As New XDocument() xdoc = XDocument.Parse(myXML) xdoc.Element("Departments").Add(New XElement("Department", "Finance")) xdoc.Element("Departments").AddFirst(New XElement("Department", "Support")) Dim result = xdoc.Element("Departments").Descendants() For Each item As XElement In result Console.WriteLine("Department Name - " + item.Value) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Name - Support Department Name - Account Department Name - Sales Department Name - Pre-Sales Department Name - Marketing Department Name - Finance Press any key to continue. using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace LINQtoXML { class ExampleOfXML { static void Main(string[] args) { string myXML = @"<Departments> <Department>Support</Department> <Department>Account</Department> <Department>Sales</Department> <Department>Pre-Sales</Department> <Department>Marketing</Department> <Department>Finance</Department> </Departments>"; XDocument xdoc = new XDocument(); xdoc = XDocument.Parse(myXML); //Remove Sales Department xdoc.Descendants().Where(s =>s.Value == "Sales").Remove(); var result = xdoc.Element("Departments").Descendants(); foreach (XElement item in result) { Console.WriteLine("Department Name - " + item.Value); } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } Imports System.Collections.Generic Imports System.Linq Imports System.Xml.Linq Module Module1 Sub Main(args As String()) Dim myXML As String = "<Departments>" & vbCr & vbLf & "<Department>Support</Department>" & vbCr & vbLf & "<Department>Account</Department>" & vbCr & vbLf & "<Department>Sales</Department>" & vbCr & vbLf & "<Department>Pre-Sales</Department>" & vbCr & vbLf & "<Department>Marketing</Department>" & vbCr & vbLf & "<Department>Finance</Department>" & vbCr & vbLf & "</Departments>" Dim xdoc As New XDocument() xdoc = XDocument.Parse(myXML) xdoc.Descendants().Where(Function(s) s.Value = "Sales").Remove() Dim result = xdoc.Element("Departments").Descendants() For Each item As XElement In result Console.WriteLine("Department Name - " + item.Value) Next Console.WriteLine(vbLf & "Press any key to continue.") Console.ReadKey() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − Department Name - Support Department Name - Account Department Name - Pre-Sales Department Name - Marketing Department Name - Finance Press any key to continue. A part of the ADO.NET Entity Framework, LINQ to Entities is more flexible than LINQ to SQL, but is not much popular because of its complexity and lack of key features. However, it does not have the limitations of LINQ to SQL that allows data query only in SQL server database as LINQ to Entities facilitates data query in a large number of data providers like Oracle, MySQL, etc. Moreover, it has got a major support from ASP.Net in the sense that users can make use of a data source control for executing a query via LINQ to Entities and facilitates binding of the results without any need of extra coding. LINQ to Entities has for these advantages become the standard mechanism for the usage of LINQ on databases nowadays. It is also possible with LINQ to Entities to change queried data details and committing a batch update easily. What is the most intriguing fact about LINQ to Entities is that it has same syntax like that of SQL and even has the same group of standard query operators like Join, Select, OrderBy, etc. Construction of an ObjectQuery instance out of an ObjectContext (Entity Connection) Construction of an ObjectQuery instance out of an ObjectContext (Entity Connection) Composing a query either in C# or Visual Basic (VB) by using the newly constructed instance Composing a query either in C# or Visual Basic (VB) by using the newly constructed instance Conversion of standard query operators of LINQ as well as LINQ expressions into command trees Conversion of standard query operators of LINQ as well as LINQ expressions into command trees Executing the query passing any exceptions encountered to the client directly Executing the query passing any exceptions encountered to the client directly Returning to the client all the query results Returning to the client all the query results ObjectContext is here the primary class that enables interaction with Entity Data Model or in other words acts as a bridge that connects LINQ to the database. Command trees are here query representation with compatibility with the Entity framework. The Entity Framework, on the other hand, is actually Object Relational Mapper abbreviated generally as ORM by the developers that does the generation of business objects as well as entities as per the database tables and facilitates various basic operations like create, update, delete and read. The following illustration shows the entity framework and its components. First add Entity Model by following below steps. Step 1 − Right click on project and click add new item will open window as per below. Select ADO.NET Entity Data Model and specify name and click on Add. Step 2 − Select Generate from database. Step 3 − Choose Database Connection from the drop-down menu. Step 4 − Select all the tables. Now write the following code. using DataAccess; using System; using System.Linq; namespace LINQTOSQLConsoleApp { public class LinqToEntityModel { static void Main(string[] args) { using (LinqToSQLDBEntities context = new LinqToSQLDBEntities()) { //Get the List of Departments from Database var departmentList = from d in context.Departments select d; foreach (var dept in departmentList) { Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name); } //Add new Department DataAccess.Department department = new DataAccess.Department(); department.Name = "Support"; context.Departments.Add(department); context.SaveChanges(); Console.WriteLine("Department Name = Support is inserted in Database"); //Update existing Department DataAccess.Department updateDepartment = context.Departments.FirstOrDefault(d ⇒d.DepartmentId == 1); updateDepartment.Name = "Account updated"; context.SaveChanges(); Console.WriteLine("Department Name = Account is updated in Database"); //Delete existing Department DataAccess.Department deleteDepartment = context.Departments.FirstOrDefault(d ⇒d.DepartmentId == 3); context.Departments.Remove(deleteDepartment); context.SaveChanges(); Console.WriteLine("Department Name = Pre-Sales is deleted in Database"); //Get the Updated List of Departments from Database departmentList = from d in context.Departments select d; foreach (var dept in departmentList) { Console.WriteLine("Department Id = {0} , Department Name = {1}", dept.DepartmentId, dept.Name); } } Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − The term ‘Lambda expression’ has derived its name from ‘lambda’ calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation’s executable part translate logic in a way at run time so it can pass on to the data source conveniently. However, lambda expressions are not just limited to find application in LINQ only. These expressions are expressed by the following syntax − (Input parameters) ⇒ Expression or statement block Here is an example of a lambda expression − y ⇒ y * y The above expression specifies a parameter named y and that value of y is squared. However, it is not possible to execute a lambda expression in this form. Example of a lambda expression in C# is shown below. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { delegate int del(int i); static void Main(string[] args) { del myDelegate = y ⇒ y * y; int j = myDelegate(5); Console.WriteLine(j); Console.ReadLine(); } } } Module Module1 Private Delegate Function del(ByVal i As Integer) As Integer Sub Main(ByVal args As String()) Dim myDelegate As del = Function(y) y * y Dim j As Integer = myDelegate(5) Console.WriteLine(j) Console.ReadLine() End Sub End Module When the above code of C# or VB is compiled and executed, it produces the following result − 25 As the expression in the syntax of lambda expression shown above is on the right hand side, these are also known as expression lambda. The lambda expression created by incorporating asynchronous processing by the use of async keyword is known as async lambdas. Below is an example of async lambda. Func<Task<string>> getWordAsync = async()⇒ “hello”; A lambda expression within a query operator is evaluated by the same upon demand and continually works on each of the elements in the input sequence and not the whole sequence. Developers are allowed by Lambda expression to feed their own logic into the standard query operators. In the below example, the developer has used the ‘Where’ operator to reclaim the odd values from given list by making use of a lambda expression. //Get the average of the odd Fibonacci numbers in the series... using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { static void Main(string[] args) { int[] fibNum = { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; double averageValue = fibNum.Where(num ⇒ num % 2 == 1).Average(); Console.WriteLine(averageValue); Console.ReadLine(); } } } Module Module1 Sub Main() Dim fibNum As Integer() = {1, 1, 2, 3, 5, 8, 13, 21, 34} Dim averageValue As Double = fibNum.Where(Function(num) num Mod 2 = 1).Average() Console.WriteLine(averageValue) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − 7.33333333333333 In C#, type inference is used conveniently in a variety of situations and that too without specifying the types explicitly. However in case of a lambda expression, type inference will work only when each type has been specified as the compiler must be satisfied. Let’s consider the following example. delegate int Transformer (int i); Here the compiler employ the type inference to draw upon the fact that x is an integer and this is done by examining the parameter type of the Transformer. There are some rules while using variable scope in a lambda expression like variables that are initiated within a lambda expression are not meant to be visible in an outer method. There is also a rule that a captured variable is not to be garbage collected unless the delegate referencing the same becomes eligible for the act of garbage collection. Moreover, there is a rule that prohibits a return statement within a lambda expression to cause return of an enclosing method. Here is an example to demonstrate variable scope in lambda expression. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { delegate bool D(); delegate bool D2(int i); class Test { D del; D2 del2; public void TestMethod(int input) { int j = 0; // Initialize the delegates with lambda expressions. // Note access to 2 outer variables. // del will be invoked within this method. del = () ⇒ { j = 10; return j > input; }; // del2 will be invoked after TestMethod goes out of scope. del2 = (x) ⇒ { return x == j; }; // Demonstrate value of j: // The delegate has not been invoked yet. Console.WriteLine("j = {0}", j); // Invoke the delegate. bool boolResult = del(); Console.WriteLine("j = {0}. b = {1}", j, boolResult); } static void Main() { Test test = new Test(); test.TestMethod(5); // Prove that del2 still has a copy of // local variable j from TestMethod. bool result = test.del2(10); Console.WriteLine(result); Console.ReadKey(); } } } } When the above code is compiled and executed, it produces the following result − j = 0 j = 10. b = True True Lambda expressions are used in Expression Tree construction extensively. An expression tree give away code in a data structure resembling a tree in which every node is itself an expression like a method call or can be a binary operation like x<y. Below is an example of usage of lambda expression for constructing an expression tree. There is also statement lambdas consisting of two or three statements, but are not used in construction of expression trees. A return statement must be written in a statement lambda. Syntax of statement lambda (params)⇒ {statements} using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace lambdaexample { class Program { static void Main(string[] args) { int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x ⇒ { if (x <= 3) return true; else if (x >= 7) return true; return false; } )) Console.WriteLine(i); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − 3 8 1 7 9 2 8 Lambdas are employed as arguments in LINQ queries based on methods and never allowed to have a place on the left side of operators like is or as just like anonymous methods. Although, Lambda expressions are much alike anonymous methods, these are not at all restricted to be used as delegates only. A lambda expression can return a value and may have parameters. A lambda expression can return a value and may have parameters. Parameters can be defined in a myriad of ways with a lambda expression. Parameters can be defined in a myriad of ways with a lambda expression. If there is single statement in a lambda expression, there is no need of curly brackets whereas if there are multiple statements, curly brackets as well as return value are essential to write. If there is single statement in a lambda expression, there is no need of curly brackets whereas if there are multiple statements, curly brackets as well as return value are essential to write. With lambda expressions, it is possible to access variables present outside of the lambda expression block by a feature known as closure. Use of closure should be done cautiously to avoid any problem. With lambda expressions, it is possible to access variables present outside of the lambda expression block by a feature known as closure. Use of closure should be done cautiously to avoid any problem. It is impossible to execute any unsafe code inside any lambda expression. It is impossible to execute any unsafe code inside any lambda expression. Lambda expressions are not meant to be used on the operator’s left side. Lambda expressions are not meant to be used on the operator’s left side. As a set of .NET framework extensions, LINQ is the preferred mechanism for data access by ASP.NET developers. ASP.NET 3.5 has a built-in tool LINQDataSource control that enables usage of LINQ easily in ASP.NET. ASP.NET uses the above-mentioned control as a data source. Real life projects mostly encompass websites or windows applications and so to understand better the concept of LINQ with ASP.NET, let’s start with creating a ASP.NET website that make use of the LINQ features. For this, it is essential to get installed Visual Studio and .NET framework on your system. Once you have opened Visual Studio, go to File → New → Website. A pop up window will open as shown in below figure. Now, under the templates in the left hand side, there will be two language options to create the website. Choose Visual C# and select ASP.NET Empty Web Site. Select the folder where you want to save new website on your system. Then press OK and soon Solution Explorer appears on your screen containing all the web files. Right click on Default.aspx in the Solution Explorer and choose View in Browser to view the default ASP.NET website in the browser. Soon your new ASP.NET website will open in the web browser, as shown in the following screenshot. .aspx is in fact the major file extension used in ASP.NET websites. Visual Studio by default creates all the necessary pages for a basic website like Home page and About Us page where you can place your content conveniently. The code for the website is generated automatically here and can be viewed too. It is possible to UPDATE, INSERT and DELETE data in the pages of ASP.NET website with the help of LINQDataSource control. There is absolutely no need for specification of SQL commands as LINQDataSource control employs dynamically created commands for such operations. The control enables a user to make use of LINQ in an ASP.NET web page conveniently by property setting in the markup text. LINQDataSource is very similar to that of controls like SqlDataSource as well as ObjectDataSource as it can be used in binding other ASP.NET controls present on a page to a data source. So, we must have a database to explain the various functions invoked by the LINQDataSource Control. Before going to start explanation of the control usage in ASP.NET web page form, it is essential to open the Microsoft Visual Studio Toolbox and drag and drop LINQDataSource control to .aspx page of ASP.NET website like below figure. The next step is to configure LINQDataSource by selecting all the columns for the employee record. Now add a GridView Control to the .aspx page and configure it like shown in below figure. The GridView control is powerful and offers flexibility to work with the data. Soon after configuring the control, it will appear in the browser. The coding that can be viewed now on your screen for the .aspx page will be − <!DOCTYPE html> <html> <head runat = "server"> <title></title> </head> <body> <form id = "form1" runat = "server"> <div> <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" DataKeyNames = "ContactID" DataSourceID = "LINQDataSource1"> <Columns> <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" InsertVisible = "False" ReadOnly="True" SortExpression = "ContactID" /> <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" /> <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" /> <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression="FirstName" /> <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" /> <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" /> <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" /> <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" /> </Columns> </asp:GridView> <br /> </div> <asp:LINQDataSource ID = "LINQDataSource1" runat = "server" ContextTypeName = "LINQWebApp1.AdventureWorksDataContext" EntityTypeName = "" TableName = "Contacts"> </asp:LINQDataSource> </form> </body> </html> Here it should be noted that it is vital to set the property ContextTypeName to that of the class representing the database. For example, here it is given as LINQWebApp1.AdventureWorksDataContext as this action will make the needed connection between LINQDataSource and the database. After completing all the above steps rigorously, choose the LINQDataSource Tasks from the LINQDataSource Control and choose all the three boxes for enable insert, enable update and enable delete from the same, as shown in the following screenshot. Soon the declarative markup will get displayed on your screen as the following one. <asp:LINQDataSource ContextTypeName = "LINQWebApp1.AdventureWorksDataContext" TableName = "Contacts" EnableUpdate = "true" EnableInsert = "true" EnableDelete = "true" ID = "LINQDataSource1" runat = "server"> </asp:LINQDataSource> Now since there are multiple rows and columns, it is better to add another control on your .aspx form named as Detail View or Master control below the Grid View control to display only the details of a selected row of the grid. Choose the Detail View Tasks from the Detail View control and select the check boxes as shown below. Now, just save the changes and press Ctrl + F5 to view the page in your browser where it is now possible to delete, update, insert any record on the detail view control. 23 Lectures 1.5 hours Anadi Sharma 37 Lectures 13 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 1935, "s": 1736, "text": "Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc." }, { "code": null, "e": 2175, "s": 1935, "text": "Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types." }, { "code": null, "e": 2595, "s": 2175, "text": "using System;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n \n string[] words = {\"hello\", \"wonderful\", \"LINQ\", \"beautiful\", \"world\"};\n\t\t\n //Get only short words\n var shortWords = from word in words where word.Length <= 5 select word;\n\t \n //Print each word out\n foreach (var word in shortWords) {\n Console.WriteLine(word);\n }\t \n\t\t\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2992, "s": 2595, "text": "Module Module1\n Sub Main()\n Dim words As String() = {\"hello\", \"wonderful\", \"LINQ\", \"beautiful\", \"world\"}\n \n ' Get only short words\n Dim shortWords = From word In words _ Where word.Length <= 5 _ Select word\n \n ' Print each word out.\n\t \n For Each word In shortWords\n Console.WriteLine(word)\n Next\n\t \n Console.ReadLine()\n End Sub\nEnd Module\t" }, { "code": null, "e": 3085, "s": 2992, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 3105, "s": 3085, "text": "hello \nLINQ \nworld\n" }, { "code": null, "e": 3167, "s": 3105, "text": "There are two syntaxes of LINQ. These are the following ones." }, { "code": null, "e": 3272, "s": 3167, "text": "var longWords = words.Where( w ⇒ w.length > 10);\nDim longWords = words.Where(Function(w) w.length > 10)\n" }, { "code": null, "e": 3378, "s": 3272, "text": "var longwords = from w in words where w.length > 10;\nDim longwords = from w in words where w.length > 10\n" }, { "code": null, "e": 3426, "s": 3378, "text": "The types of LINQ are mentioned below in brief." }, { "code": null, "e": 3442, "s": 3426, "text": "LINQ to Objects" }, { "code": null, "e": 3461, "s": 3442, "text": "LINQ to XML(XLINQ)" }, { "code": null, "e": 3477, "s": 3461, "text": "LINQ to DataSet" }, { "code": null, "e": 3497, "s": 3477, "text": "LINQ to SQL (DLINQ)" }, { "code": null, "e": 3514, "s": 3497, "text": "LINQ to Entities" }, { "code": null, "e": 3610, "s": 3514, "text": "Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ." }, { "code": null, "e": 3882, "s": 3610, "text": "LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture is shown below." }, { "code": null, "e": 4081, "s": 3882, "text": "Query expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword \"From\"." }, { "code": null, "e": 4262, "s": 4081, "text": "To access standard LINQ query operators, the namespace System.Query should be imported by default. These expressions are written within a declarative query syntax which was C# 3.0." }, { "code": null, "e": 4406, "s": 4262, "text": "Below is an example to show a complete query operation which consists of data source creation, query expression definition and query execution." }, { "code": null, "e": 4977, "s": 4406, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Operators {\n class LINQQueryExpressions {\n static void Main() {\n \n // Specify the data source.\n int[] scores = new int[] { 97, 92, 81, 60 };\n\n // Define the query expression.\n IEnumerable<int> scoreQuery = from score in scores where score > 80 select score;\n\n // Execute the query.\n\t\t \n foreach (int i in scoreQuery) {\n Console.Write(i + \" \");\n }\n\t\t \n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 5058, "s": 4977, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5068, "s": 5058, "text": "97 92 81\n" }, { "code": null, "e": 5332, "s": 5068, "text": "Introduced with .NET 3.5, Extension methods are declared in static classes only and allow inclusion of custom methods to objects to perform some precise query operations to extend a class without being an actual member of that class. These can be overloaded also." }, { "code": null, "e": 5454, "s": 5332, "text": "In a nutshell, extension methods are used to translate query expressions into traditional method calls (object-oriented)." }, { "code": null, "e": 5571, "s": 5454, "text": "There is an array of differences existing between LINQ and Stored procedures. These differences are mentioned below." }, { "code": null, "e": 5666, "s": 5571, "text": "Stored procedures are much faster than a LINQ query as they follow an expected execution plan." }, { "code": null, "e": 5761, "s": 5666, "text": "Stored procedures are much faster than a LINQ query as they follow an expected execution plan." }, { "code": null, "e": 5973, "s": 5761, "text": "It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time." }, { "code": null, "e": 6185, "s": 5973, "text": "It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time." }, { "code": null, "e": 6281, "s": 6185, "text": "LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures." }, { "code": null, "e": 6377, "s": 6281, "text": "LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures." }, { "code": null, "e": 6529, "s": 6377, "text": "LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases." }, { "code": null, "e": 6681, "s": 6529, "text": "LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases." }, { "code": null, "e": 6793, "s": 6681, "text": "Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures." }, { "code": null, "e": 6905, "s": 6793, "text": "Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures." }, { "code": null, "e": 7144, "s": 6905, "text": "Prior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt." }, { "code": null, "e": 7272, "s": 7144, "text": "Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ." }, { "code": null, "e": 7582, "s": 7272, "text": "SqlConnection sqlConnection = new SqlConnection(connectString);\nSqlConnection.Open();\n\nSystem.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand();\nsqlCommand.Connection = sqlConnection;\n\nsqlCommand.CommandText = \"Select * from Customer\";\nreturn sqlCommand.ExecuteReader (CommandBehavior.CloseConnection) " }, { "code": null, "e": 7817, "s": 7582, "text": "Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time." }, { "code": null, "e": 7917, "s": 7817, "text": "Northwind db = new Northwind(@\"C:\\Data\\Northwnd.mdf\");\nvar query = from c in db.Customers select c;" }, { "code": null, "e": 8114, "s": 7917, "text": "LINQ offers a host of advantages and among them the foremost is its powerful expressiveness which enables developers to express declaratively. Some of the other advantages of LINQ are given below." }, { "code": null, "e": 8207, "s": 8114, "text": "LINQ offers syntax highlighting that proves helpful to find out mistakes during design time." }, { "code": null, "e": 8300, "s": 8207, "text": "LINQ offers syntax highlighting that proves helpful to find out mistakes during design time." }, { "code": null, "e": 8375, "s": 8300, "text": "LINQ offers IntelliSense which means writing more accurate queries easily." }, { "code": null, "e": 8450, "s": 8375, "text": "LINQ offers IntelliSense which means writing more accurate queries easily." }, { "code": null, "e": 8547, "s": 8450, "text": "Writing codes is quite faster in LINQ and thus development time also gets reduced significantly." }, { "code": null, "e": 8644, "s": 8547, "text": "Writing codes is quite faster in LINQ and thus development time also gets reduced significantly." }, { "code": null, "e": 8713, "s": 8644, "text": "LINQ makes easy debugging due to its integration in the C# language." }, { "code": null, "e": 8782, "s": 8713, "text": "LINQ makes easy debugging due to its integration in the C# language." }, { "code": null, "e": 8945, "s": 8782, "text": "Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time." }, { "code": null, "e": 9108, "s": 8945, "text": "Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time." }, { "code": null, "e": 9245, "s": 9108, "text": "LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation." }, { "code": null, "e": 9382, "s": 9245, "text": "LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation." }, { "code": null, "e": 9487, "s": 9382, "text": "LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types." }, { "code": null, "e": 9592, "s": 9487, "text": "LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types." }, { "code": null, "e": 9747, "s": 9592, "text": "LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug." }, { "code": null, "e": 9902, "s": 9747, "text": "LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug." }, { "code": null, "e": 10017, "s": 9902, "text": "LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data." }, { "code": null, "e": 10132, "s": 10017, "text": "LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data." }, { "code": null, "e": 10410, "s": 10132, "text": "Before starting with LINQ programs, it is best to first understand the nuances of setting up a LINQ environment. LINQ needs a .NET framework, a revolutionary platform to have a diverse kind of applications. A LINQ query can be written either in C# or Visual Basic conveniently." }, { "code": null, "e": 10716, "s": 10410, "text": "Microsoft offers tools for both of these languages i.e. C# and Visual Basic by means of Visual Studio. Our examples are all compiled and written in Visual Studio 2010. However, Visual Basic 2013 edition is also available for use. It is the latest version and has many similarities with Visual Studio 2012." }, { "code": null, "e": 11108, "s": 10716, "text": "Visual Studio can be installed either from an installation media like a DVD. Administrator credentials are required to install Visual Basic 2010 on your system successfully. It is vital to disconnect all removable USB from the system prior to installation otherwise the installation may get failed. Some of the hardware requirements essential to have for installation are the following ones." }, { "code": null, "e": 11124, "s": 11108, "text": "1.6 GHz or more" }, { "code": null, "e": 11133, "s": 11124, "text": "1 GB RAM" }, { "code": null, "e": 11165, "s": 11133, "text": "3 GB(Available hard-disk space)" }, { "code": null, "e": 11190, "s": 11165, "text": "5400 RPM hard-disk drive" }, { "code": null, "e": 11222, "s": 11190, "text": "DirectX 9 compatible video card" }, { "code": null, "e": 11236, "s": 11222, "text": "DVD-ROM drive" }, { "code": null, "e": 11397, "s": 11236, "text": "Step 1 − First after inserting the DVD with Visual Studio 2010 Package, click on Install or run program from your media appearing in a pop-up box on the screen." }, { "code": null, "e": 11507, "s": 11397, "text": "Step 2 − Now set up for Visual Studio will appear on the screen. Choose Install Microsoft Visual Studio 2010." }, { "code": null, "e": 11758, "s": 11507, "text": "Step 3 − As soon as you will click, it the process will get initiated and a set up window will appear on your screen. After completion of loading of the installation components which will take some time, click on Next button to move to the next step." }, { "code": null, "e": 11926, "s": 11758, "text": "Step 4 − This is the last step of installation and a start page will appear in which simply choose \"I have read and accept the license terms\" and click on Next button." }, { "code": null, "e": 12159, "s": 11926, "text": "Step 5 − Now select features to install from the options page appearing on your screen. You can either choose Full or Custom option. If you have less disk space than required shown in the disk space requirements, then go for Custom." }, { "code": null, "e": 12446, "s": 12159, "text": "Step 6 − When you choose Custom option, the following window will appear. Select the features that you want to install and click Update or else go to step 7. However, it is recommended not to go with the custom option as in future, you may need the features you have chosen to not have." }, { "code": null, "e": 12603, "s": 12446, "text": "Step 7 − Soon a pop up window will be shown and the installation will start which may take a long time. Remember, this is for installing all the components." }, { "code": null, "e": 12737, "s": 12603, "text": "Step 8 − Finally, you will be able to view a message in a window that the installation has been completed successfully. Click Finish." }, { "code": null, "e": 12834, "s": 12737, "text": "Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu." }, { "code": null, "e": 12931, "s": 12834, "text": "Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu." }, { "code": null, "e": 12984, "s": 12931, "text": "A new project dialog box will appear on your screen." }, { "code": null, "e": 13037, "s": 12984, "text": "A new project dialog box will appear on your screen." }, { "code": null, "e": 13169, "s": 13037, "text": "Now choose Visual C# as a category under installed templates and next choose Console Application template as shown in figure below." }, { "code": null, "e": 13301, "s": 13169, "text": "Now choose Visual C# as a category under installed templates and next choose Console Application template as shown in figure below." }, { "code": null, "e": 13366, "s": 13301, "text": "Give a name to your project in the bottom name box and press OK." }, { "code": null, "e": 13431, "s": 13366, "text": "Give a name to your project in the bottom name box and press OK." }, { "code": null, "e": 13543, "s": 13431, "text": "The new project will appear in the Solution Explorer in the right-hand side of a new dialog box on your screen." }, { "code": null, "e": 13655, "s": 13543, "text": "The new project will appear in the Solution Explorer in the right-hand side of a new dialog box on your screen." }, { "code": null, "e": 13785, "s": 13655, "text": "Now choose Program.cs from the Solution Explorer and you can view the code in the editor window which starts with ‘using System’." }, { "code": null, "e": 13915, "s": 13785, "text": "Now choose Program.cs from the Solution Explorer and you can view the code in the editor window which starts with ‘using System’." }, { "code": null, "e": 13969, "s": 13915, "text": "Here you can start to code your following C# program." }, { "code": null, "e": 14023, "s": 13969, "text": "Here you can start to code your following C# program." }, { "code": null, "e": 14290, "s": 14023, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\t\t\t\nnamespace HelloWorld {\n class Program {\n static void Main(string[] args) {\n \n Console.WriteLine(\"Hello World\")\n Console.ReadKey();\n } \t\t\n }\n}" }, { "code": null, "e": 14426, "s": 14290, "text": "Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project." }, { "code": null, "e": 14562, "s": 14426, "text": "Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project." }, { "code": null, "e": 14659, "s": 14562, "text": "Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu." }, { "code": null, "e": 14756, "s": 14659, "text": "Start Visual Studio 2010 Ultimate edition and choose File followed by New Project from the menu." }, { "code": null, "e": 14809, "s": 14756, "text": "A new project dialog box will appear on your screen." }, { "code": null, "e": 14862, "s": 14809, "text": "A new project dialog box will appear on your screen." }, { "code": null, "e": 14971, "s": 14862, "text": "Now chose Visual Basic as a category under installed templates and next choose Console Application template." }, { "code": null, "e": 15080, "s": 14971, "text": "Now chose Visual Basic as a category under installed templates and next choose Console Application template." }, { "code": null, "e": 15145, "s": 15080, "text": "Give a name to your project in the bottom name box and press OK." }, { "code": null, "e": 15210, "s": 15145, "text": "Give a name to your project in the bottom name box and press OK." }, { "code": null, "e": 15293, "s": 15210, "text": "You will get a screen with Module1.vb. Start writing your VB code here using LINQ." }, { "code": null, "e": 15376, "s": 15293, "text": "You will get a screen with Module1.vb. Start writing your VB code here using LINQ." }, { "code": null, "e": 15499, "s": 15376, "text": "Module Module1\n\n Sub Main()\n Console.WriteLine(\"Hello World\")\n Console.ReadLine()\n End Sub\n \nEnd Module " }, { "code": null, "e": 15635, "s": 15499, "text": "Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project." }, { "code": null, "e": 15771, "s": 15635, "text": "Press F5 key and run your project. It is highly recommended to save the project by choosing File → Save All before running the project." }, { "code": null, "e": 15859, "s": 15771, "text": "When the above code of C# or VB is cimpiled and run, it produces the following result −" }, { "code": null, "e": 15872, "s": 15859, "text": "Hello World\n" }, { "code": null, "e": 16119, "s": 15872, "text": "A set of extension methods forming a query pattern is known as LINQ Standard Query Operators. As building blocks of LINQ query expressions, these operators offer a range of query capabilities like filtering, sorting, projection, aggregation, etc." }, { "code": null, "e": 16229, "s": 16119, "text": "LINQ standard query operators can be categorized into the following ones on the basis of their functionality." }, { "code": null, "e": 16249, "s": 16229, "text": "Filtering Operators" }, { "code": null, "e": 16264, "s": 16249, "text": "Join Operators" }, { "code": null, "e": 16286, "s": 16264, "text": "Projection Operations" }, { "code": null, "e": 16304, "s": 16286, "text": "Sorting Operators" }, { "code": null, "e": 16323, "s": 16304, "text": "Grouping Operators" }, { "code": null, "e": 16335, "s": 16323, "text": "Conversions" }, { "code": null, "e": 16349, "s": 16335, "text": "Concatenation" }, { "code": null, "e": 16361, "s": 16349, "text": "Aggregation" }, { "code": null, "e": 16383, "s": 16361, "text": "Quantifier Operations" }, { "code": null, "e": 16404, "s": 16383, "text": "Partition Operations" }, { "code": null, "e": 16426, "s": 16404, "text": "Generation Operations" }, { "code": null, "e": 16441, "s": 16426, "text": "Set Operations" }, { "code": null, "e": 16450, "s": 16441, "text": "Equality" }, { "code": null, "e": 16468, "s": 16450, "text": "Element Operators" }, { "code": null, "e": 16596, "s": 16468, "text": "Filtering is an operation to restrict the result set such that it has only selected elements satisfying a particular condition." }, { "code": null, "e": 16610, "s": 16596, "text": "Show Examples" }, { "code": null, "e": 16748, "s": 16610, "text": "Joining refers to an operation in which data sources with difficult to follow relationships with each other in a direct way are targeted." }, { "code": null, "e": 16762, "s": 16748, "text": "Show Examples" }, { "code": null, "e": 16882, "s": 16762, "text": "Projection is an operation in which an object is transformed into an altogether new form with only specific properties." }, { "code": null, "e": 16896, "s": 16882, "text": "Show Examples" }, { "code": null, "e": 17000, "s": 16896, "text": "A sorting operation allows ordering the elements of a sequence on basis of a single or more attributes." }, { "code": null, "e": 17014, "s": 17000, "text": "Show Examples" }, { "code": null, "e": 17090, "s": 17014, "text": "The operators put data into some groups based on a common shared attribute." }, { "code": null, "e": 17104, "s": 17090, "text": "Show Examples" }, { "code": null, "e": 17200, "s": 17104, "text": "The operators change the type of input objects and are used in a diverse range of applications." }, { "code": null, "e": 17214, "s": 17200, "text": "Show Examples" }, { "code": null, "e": 17380, "s": 17214, "text": "Performs concatenation of two sequences and is quite similar to the Union operator in terms of its operation except of the fact that this does not remove duplicates." }, { "code": null, "e": 17394, "s": 17380, "text": "Show Examples" }, { "code": null, "e": 17484, "s": 17394, "text": "Performs any type of desired aggregation and allows creating custom aggregations in LINQ." }, { "code": null, "e": 17498, "s": 17484, "text": "Show Examples" }, { "code": null, "e": 17630, "s": 17498, "text": "These operators return a Boolean value i.e. True or False when some or all elements within a sequence satisfy a specific condition." }, { "code": null, "e": 17644, "s": 17630, "text": "Show Examples" }, { "code": null, "e": 17777, "s": 17644, "text": "Divide an input sequence into two separate sections without rearranging the elements of the sequence and then returning one of them." }, { "code": null, "e": 17791, "s": 17777, "text": "Show Examples" }, { "code": null, "e": 17854, "s": 17791, "text": "A new sequence of values is created by generational operators." }, { "code": null, "e": 17868, "s": 17854, "text": "Show Examples" }, { "code": null, "e": 17969, "s": 17868, "text": "There are four operators for the set operations, each yielding a result based on different criteria." }, { "code": null, "e": 17983, "s": 17969, "text": "Show Examples" }, { "code": null, "e": 18066, "s": 17983, "text": "Compares two sentences (enumerable ) and determine are they an exact match or not." }, { "code": null, "e": 18080, "s": 18066, "text": "Show Examples" }, { "code": null, "e": 18202, "s": 18080, "text": "Except the DefaultIfEmpty, all the rest eight standard query element operators return a single element from a collection." }, { "code": null, "e": 18216, "s": 18202, "text": "Show Examples" }, { "code": null, "e": 18627, "s": 18216, "text": "LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the .NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution. After obtaining the results from the database, LINQ to SQL again translates them to objects." }, { "code": null, "e": 19090, "s": 18627, "text": "For most ASP.NET developers, LINQ to SQL (also known as DLINQ) is an electrifying part of Language Integrated Query as this allows querying data in SQL server database by using usual LINQ expressions. It also allows to update, delete, and insert data, but the only drawback from which it suffers is its limitation to the SQL server database. However, there are many benefits of LINQ to SQL over ADO.NET like reduced complexity, few lines of coding and many more." }, { "code": null, "e": 19160, "s": 19090, "text": "Below is a diagram showing the execution architecture of LINQ to SQL." }, { "code": null, "e": 19297, "s": 19160, "text": "Step 1 − Make a new “Data Connection” with database server. View &arrar; Server Explorer &arrar; Data Connections &arrar; Add Connection" }, { "code": null, "e": 19333, "s": 19297, "text": "Step 2 − Add LINQ To SQL class file" }, { "code": null, "e": 19425, "s": 19333, "text": "Step 3 − Select tables from database and drag and drop into the new LINQ to SQL class file." }, { "code": null, "e": 19462, "s": 19425, "text": "Step 4 − Added tables to class file." }, { "code": null, "e": 19729, "s": 19462, "text": "The rules for executing a query with LINQ to SQL is similar to that of a standard LINQ query i.e. query is executed either deferred or immediate. There are various components that play a role in execution of a query with LINQ to SQL and these are the following ones." }, { "code": null, "e": 19838, "s": 19729, "text": "LINQ to SQL API − requests query execution on behalf of an application and sent it to LINQ to SQL Provider." }, { "code": null, "e": 19947, "s": 19838, "text": "LINQ to SQL API − requests query execution on behalf of an application and sent it to LINQ to SQL Provider." }, { "code": null, "e": 20067, "s": 19947, "text": "LINQ to SQL Provider − converts query to Transact SQL(T-SQL) and sends the new query to the ADO Provider for execution." }, { "code": null, "e": 20187, "s": 20067, "text": "LINQ to SQL Provider − converts query to Transact SQL(T-SQL) and sends the new query to the ADO Provider for execution." }, { "code": null, "e": 20355, "s": 20187, "text": "ADO Provider − After execution of the query, send the results in the form of a DataReader to LINQ to SQL Provider which in turn converts it into a form of user object." }, { "code": null, "e": 20523, "s": 20355, "text": "ADO Provider − After execution of the query, send the results in the form of a DataReader to LINQ to SQL Provider which in turn converts it into a form of user object." }, { "code": null, "e": 20650, "s": 20523, "text": "It should be noted that before executing a LINQ to SQL query, it is vital to connect to the data source via DataContext class." }, { "code": null, "e": 20653, "s": 20650, "text": "C#" }, { "code": null, "e": 22016, "s": 20653, "text": "using System;\nusing System.Linq;\n\nnamespace LINQtoSQL {\n class LinqToSQLCRUD {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n LinqToSQLDataContext db = new LinqToSQLDataContext(connectString); \n\n //Create new Employee\n\t\t \n Employee newEmployee = new Employee();\n newEmployee.Name = \"Michael\";\n newEmployee.Email = \"yourname@companyname.com\";\n newEmployee.ContactNo = \"343434343\";\n newEmployee.DepartmentId = 3;\n newEmployee.Address = \"Michael - USA\";\n\n //Add new Employee to database\n db.Employees.InsertOnSubmit(newEmployee);\n\n //Save changes to Database.\n db.SubmitChanges();\n\n //Get new Inserted Employee \n Employee insertedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals(\"Michael\"));\n\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}\",\n insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email, \n insertedEmployee.ContactNo, insertedEmployee.Address);\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 22019, "s": 22016, "text": "VB" }, { "code": null, "e": 23066, "s": 22019, "text": "Module Module1\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim db As New LinqToSQLDataContext(connectString)\n\n Dim newEmployee As New Employee()\n\t \n newEmployee.Name = \"Michael\"\n newEmployee.Email = \"yourname@companyname.com\"\n newEmployee.ContactNo = \"343434343\"\n newEmployee.DepartmentId = 3\n newEmployee.Address = \"Michael - USA\"\n \n db.Employees.InsertOnSubmit(newEmployee)\n \n db.SubmitChanges()\n \n Dim insertedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals(\"Michael\"))\n\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, \n Address = {4}\", insertedEmployee.EmployeeId, insertedEmployee.Name,\n insertedEmployee.Email, insertedEmployee.ContactNo, insertedEmployee.Address)\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 23154, "s": 23066, "text": "When the above code of C# or VB is compiled and run, it produces the following result −" }, { "code": null, "e": 23297, "s": 23154, "text": "Emplyee ID = 4, Name = Michael, Email = yourname@companyname.com, ContactNo = \n343434343, Address = Michael - USA\n\nPress any key to continue.\n" }, { "code": null, "e": 23300, "s": 23297, "text": "C#" }, { "code": null, "e": 24594, "s": 23300, "text": "using System;\nusing System.Linq;\n\nnamespace LINQtoSQL {\n class LinqToSQLCRUD {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);\n\n //Get Employee for update\n Employee employee = db.Employees.FirstOrDefault(e =>e.Name.Equals(\"Michael\"));\n\n employee.Name = \"George Michael\";\n employee.Email = \"yourname@companyname.com\";\n employee.ContactNo = \"99999999\";\n employee.DepartmentId = 2;\n employee.Address = \"Michael George - UK\";\n\n //Save changes to Database.\n db.SubmitChanges();\n\n //Get Updated Employee \n Employee updatedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals(\"George Michael\"));\n\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}, Address = {4}\",\n updatedEmployee.EmployeeId, updatedEmployee.Name, updatedEmployee.Email, \n updatedEmployee.ContactNo, updatedEmployee.Address);\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 24597, "s": 24594, "text": "VB" }, { "code": null, "e": 25646, "s": 24597, "text": "Module Module1\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim db As New LinqToSQLDataContext(connectString)\n\n Dim employee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals(\"Michael\"))\n\n employee.Name = \"George Michael\"\n employee.Email = \"yourname@companyname.com\"\n employee.ContactNo = \"99999999\"\n employee.DepartmentId = 2\n employee.Address = \"Michael George - UK\"\n\n db.SubmitChanges()\n \n Dim updatedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals(\"George Michael\"))\n\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3},\n Address = {4}\", updatedEmployee.EmployeeId, updatedEmployee.Name, \n updatedEmployee.Email, updatedEmployee.ContactNo, updatedEmployee.Address)\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 25734, "s": 25646, "text": "When the above code of C# or Vb is compiled and run, it produces the following result −" }, { "code": null, "e": 25890, "s": 25734, "text": "Emplyee ID = 4, Name = George Michael, Email = yourname@companyname.com, ContactNo = \n999999999, Address = Michael George - UK\n\nPress any key to continue.\n" }, { "code": null, "e": 25893, "s": 25890, "text": "C#" }, { "code": null, "e": 26965, "s": 25893, "text": "using System;\nusing System.Linq;\n\nnamespace LINQtoSQL {\n class LinqToSQLCRUD {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n LinqToSQLDataContext db = newLinqToSQLDataContext(connectString);\n\n //Get Employee to Delete\n Employee deleteEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals(\"George Michael\"));\n\n //Delete Employee\n db.Employees.DeleteOnSubmit(deleteEmployee);\n\n //Save changes to Database.\n db.SubmitChanges();\n\n //Get All Employee from Database\n var employeeList = db.Employees;\n foreach (Employee employee in employeeList) {\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}\",\n employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo);\n } \n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 26968, "s": 26965, "text": "VB" }, { "code": null, "e": 27781, "s": 26968, "text": "Module Module1\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim db As New LinqToSQLDataContext(connectString)\n\n Dim deleteEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals(\"George Michael\"))\n\n db.Employees.DeleteOnSubmit(deleteEmployee)\n\n db.SubmitChanges()\n\n Dim employeeList = db.Employees\n\t \n For Each employee As Employee In employeeList\n Console.WriteLine(\"Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3}\",\n employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo)\n Next \n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n End Sub\n \nEnd Module" }, { "code": null, "e": 27869, "s": 27781, "text": "When the above code of C# or VB is compiled and run, it produces the following result −" }, { "code": null, "e": 28117, "s": 27869, "text": "Emplyee ID = 1, Name = William, Email = abc@gy.co, ContactNo = 999999999\nEmplyee ID = 2, Name = Miley, Email = amp@esds.sds, ContactNo = 999999999\nEmplyee ID = 3, Name = Benjamin, Email = asdsad@asdsa.dsd, ContactNo = \n\nPress any key to continue.\n" }, { "code": null, "e": 28312, "s": 28117, "text": "LINQ to Objects offers usage of any LINQ query supporting IEnumerable<T>for accessing in-memory data collections without any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to XML." }, { "code": null, "e": 28700, "s": 28312, "text": "Queries in LINQ to Objects return variables of type usually IEnumerable<T> only. In short, LINQ to Objects offers a fresh approach to collections as earlier, it was vital to write long coding (foreach loops of much complexity) for retrieval of data from a collection which is now replaced by writing declarative code which clearly describes the desired data that is required to retrieve." }, { "code": null, "e": 29054, "s": 28700, "text": "There are also many advantages of LINQ to Objects over traditional foreach loops like more readability, powerful filtering, capability of grouping, enhanced ordering with minimal application coding. Such LINQ queries are also more compact in nature and are portable to any other data sources without any modification or with just a little modification." }, { "code": null, "e": 29098, "s": 29054, "text": "Below is a simple LINQ to Objects example −" }, { "code": null, "e": 29664, "s": 29098, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace LINQtoObjects {\n class Program {\n static void Main(string[] args) {\n \n string[] tools = { \"Tablesaw\", \"Bandsaw\", \"Planer\", \"Jointer\", \"Drill\", \"Sander\" };\n var list = from t in tools select t;\n\n StringBuilder sb = new StringBuilder();\n\n foreach (string s in list) {\n sb.Append(s + Environment.NewLine);\n }\n\t\t \n Console.WriteLine(sb.ToString(), \"Tools\");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 29782, "s": 29664, "text": "In the example, an array of strings (tools) is used as the collection of objects to be queried using LINQ to Objects." }, { "code": null, "e": 29837, "s": 29782, "text": "Objects query is:\nvar list = from t in tools select t;" }, { "code": null, "e": 29918, "s": 29837, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 29964, "s": 29918, "text": "Tablesaw\nBandsaw\nPlaner\nJointer\nDrill\nSander\n" }, { "code": null, "e": 30935, "s": 29964, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace LINQtoObjects {\n class Department {\n public int DepartmentId { get; set; }\n public string Name { get; set; }\n }\n\n class LinqToObjects {\n static void Main(string[] args) {\n \n List<Department> departments = new List<Department>();\n\t\t\t\n departments.Add(new Department { DepartmentId = 1, Name = \"Account\" });\n departments.Add(new Department { DepartmentId = 2, Name = \"Sales\" });\n departments.Add(new Department { DepartmentId = 3, Name = \"Marketing\" });\n\n var departmentList = from d in departments\n select d;\n\n foreach (var dept in departmentList) {\n Console.WriteLine(\"Department Id = {0} , Department Name = {1}\",\n dept.DepartmentId, dept.Name);\n }\n\t\t \n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 31840, "s": 30935, "text": "Imports System.Collections.Generic\nImports System.Linq\n\nModule Module1\n\n Sub Main(ByVal args As String())\n\n Dim account As New Department With {.Name = \"Account\", .DepartmentId = 1}\n Dim sales As New Department With {.Name = \"Sales\", .DepartmentId = 2}\n Dim marketing As New Department With {.Name = \"Marketing\", .DepartmentId = 3}\n\n Dim departments As New System.Collections.Generic.List(Of Department)(New Department() {account, sales, marketing})\n\n Dim departmentList = From d In departments\n\n For Each dept In departmentList\n Console.WriteLine(\"Department Id = {0} , Department Name = {1}\", dept.DepartmentId, dept.Name)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n End Sub\n\n Class Department\n Public Property Name As String\n Public Property DepartmentId As Integer\n End Class\n \nEnd Module" }, { "code": null, "e": 31933, "s": 31840, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 32097, "s": 31933, "text": "Department Id = 1, Department Name = Account\nDepartment Id = 2, Department Name = Sales\nDepartment Id = 3, Department Name = Marketing\n\nPress any key to continue.\n" }, { "code": null, "e": 32390, "s": 32097, "text": "A Dataset offers an extremely useful data representation in memory and is used for a diverse range of data based applications. LINQ to Dataset as one of the technology of LINQ to ADO.NET facilitates performing queries on the data of a Dataset in a hassle-free manner and enhance productivity." }, { "code": null, "e": 32808, "s": 32390, "text": "LINQ to Dataset has made the task of querying simple for the developers. They don’t need to write queries in a specific query language instead the same can be written in programming language. LINQ to Dataset is also usable for querying where data is consolidated from multiple data sources. This also does not need any LINQ provider just like LINQ to SQL and LINQ to XML for accessing data from in memory collections." }, { "code": null, "e": 33148, "s": 32808, "text": "Below is a simple example of a LINQ to Dataset query in which a data source is first obtained and then the dataset is filled with two data tables. A relationship is established between both the tables and a LINQ query is created against both tables by the means of join clause. Finally, foreach loop is used to display the desired results." }, { "code": null, "e": 35268, "s": 33148, "text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace LINQtoDataset {\n class Program {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n string sqlSelect = \"SELECT * FROM Department;\" + \"SELECT * FROM Employee;\";\n\n // Create the data adapter to retrieve data from the database\n SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);\n \n // Create table mappings\n da.TableMappings.Add(\"Table\", \"Department\");\n da.TableMappings.Add(\"Table1\", \"Employee\");\n\n // Create and fill the DataSet\n DataSet ds = new DataSet();\n da.Fill(ds);\n\n DataRelation dr = ds.Relations.Add(\"FK_Employee_Department\",\n ds.Tables[\"Department\"].Columns[\"DepartmentId\"],\n ds.Tables[\"Employee\"].Columns[\"DepartmentId\"]);\n\n DataTable department = ds.Tables[\"Department\"];\n DataTable employee = ds.Tables[\"Employee\"];\n\n var query = from d in department.AsEnumerable()\n join e in employee.AsEnumerable()\n on d.Field<int>(\"DepartmentId\") equals\n e.Field<int>(\"DepartmentId\") \n select new {\n EmployeeId = e.Field<int>(\"EmployeeId\"),\n Name = e.Field<string>(\"Name\"), \n DepartmentId = d.Field<int>(\"DepartmentId\"), \n DepartmentName = d.Field<string>(\"Name\")\n };\n\n foreach (var q in query) {\n Console.WriteLine(\"Employee Id = {0} , Name = {1} , Department Name = {2}\",\n q.EmployeeId, q.Name, q.DepartmentName);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 37267, "s": 35268, "text": "Imports System.Data.SqlClient\nImports System.Linq\n\nModule LinqToDataSet\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim sqlSelect As String = \"SELECT * FROM Department;\" + \"SELECT * FROM Employee;\"\n Dim sqlCnn As SqlConnection = New SqlConnection(connectString)\n sqlCnn.Open()\n\n Dim da As New SqlDataAdapter\n da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)\n\n da.TableMappings.Add(\"Table\", \"Department\")\n da.TableMappings.Add(\"Table1\", \"Employee\")\n\n Dim ds As New DataSet()\n da.Fill(ds)\n\n Dim dr As DataRelation = ds.Relations.Add(\"FK_Employee_Department\", ds.Tables(\"Department\").Columns(\"DepartmentId\"), ds.Tables(\"Employee\").Columns(\"DepartmentId\"))\n\n Dim department As DataTable = ds.Tables(\"Department\")\n Dim employee As DataTable = ds.Tables(\"Employee\")\n\n Dim query = From d In department.AsEnumerable()\n Join e In employee.AsEnumerable() On d.Field(Of Integer)(\"DepartmentId\") Equals\n e.Field(Of Integer)(\"DepartmentId\")\n Select New Person With { _\n .EmployeeId = e.Field(Of Integer)(\"EmployeeId\"),\n .EmployeeName = e.Field(Of String)(\"Name\"),\n .DepartmentId = d.Field(Of Integer)(\"DepartmentId\"),\n .DepartmentName = d.Field(Of String)(\"Name\")\n }\n\n For Each e In query\n Console.WriteLine(\"Employee Id = {0} , Name = {1} , Department Name = {2}\", e.EmployeeId, e.EmployeeName, e.DepartmentName)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \n Class Person\n Public Property EmployeeId As Integer\n Public Property EmployeeName As String\n Public Property DepartmentId As Integer\n Public Property DepartmentName As String\n End Class\n \nEnd Module" }, { "code": null, "e": 37360, "s": 37267, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 37563, "s": 37360, "text": "Employee Id = 1, Name = William, Department Name = Account\nEmployee Id = 2, Name = Benjamin, Department Name = Account\nEmployee Id = 3, Name = Miley, Department Name = Sales\n\nPress any key to continue.\n" }, { "code": null, "e": 37872, "s": 37563, "text": "Before beginning querying a Dataset using LINQ to Dataset, it is vital to load data to a Dataset and this is done by either using DataAdapter class or by LINQ to SQL. Formulation of queries using LINQ to Dataset is quite similar to formulating queries by using LINQ alongside other LINQ enabled data sources." }, { "code": null, "e": 38052, "s": 37872, "text": "In the following single-table query, all online orders are collected from the SalesOrderHeaderTtable and then order ID, Order date as well as order number are displayed as output." }, { "code": null, "e": 38055, "s": 38052, "text": "C#" }, { "code": null, "e": 39420, "s": 38055, "text": "using System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace LinqToDataset {\n class SingleTable {\n static void Main(string[] args) {\n \n string connectString = System.Configuration.ConfigurationManager.ConnectionStrings[\"LinqToSQLDBConnectionString\"].ToString();\n\n string sqlSelect = \"SELECT * FROM Department;\";\n\n // Create the data adapter to retrieve data from the database\n SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);\n\n // Create table mappings\n da.TableMappings.Add(\"Table\", \"Department\"); \n\n // Create and fill the DataSet\n DataSet ds = new DataSet();\n da.Fill(ds);\n\n DataTable department = ds.Tables[\"Department\"]; \n\n var query = from d in department.AsEnumerable() \n select new {\n DepartmentId = d.Field<int>(\"DepartmentId\"),\n DepartmentName = d.Field<string>(\"Name\")\n };\n\n foreach (var q in query) {\n Console.WriteLine(\"Department Id = {0} , Name = {1}\",\n q.DepartmentId, q.DepartmentName);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 39423, "s": 39420, "text": "VB" }, { "code": null, "e": 40667, "s": 39423, "text": "Imports System.Data.SqlClient\nImports System.Linq\n\nModule LinqToDataSet\n\n Sub Main()\n \n Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings(\"LinqToSQLDBConnectionString\").ToString()\n\n Dim sqlSelect As String = \"SELECT * FROM Department;\"\n Dim sqlCnn As SqlConnection = New SqlConnection(connectString)\n sqlCnn.Open()\n\n Dim da As New SqlDataAdapter\n da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)\n\n da.TableMappings.Add(\"Table\", \"Department\")\n Dim ds As New DataSet()\n da.Fill(ds)\n\n Dim department As DataTable = ds.Tables(\"Department\")\n\n Dim query = From d In department.AsEnumerable()\n Select New DepartmentDetail With {\n .DepartmentId = d.Field(Of Integer)(\"DepartmentId\"),\n .DepartmentName = d.Field(Of String)(\"Name\")\n }\n\n For Each e In query\n Console.WriteLine(\"Department Id = {0} , Name = {1}\", e.DepartmentId, e.DepartmentName)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n End Sub\n\n Public Class DepartmentDetail\n Public Property DepartmentId As Integer\n Public Property DepartmentName As String\n End Class\n \nEnd Module" }, { "code": null, "e": 40760, "s": 40667, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 40927, "s": 40760, "text": "Department Id = 1, Name = Account\nDepartment Id = 2, Name = Sales\nDepartment Id = 3, Name = Pre-Sales\nDepartment Id = 4, Name = Marketing\n\nPress any key to continue.\n" }, { "code": null, "e": 41231, "s": 40927, "text": "LINQ to XML offers easy accessibility to all LINQ functionalities like standard query operators, programming interface, etc. Integrated in the .NET framework, LINQ to XML also makes the best use of .NET framework functionalities like debugging, compile-time checking, strong typing and many more to say." }, { "code": null, "e": 41543, "s": 41231, "text": "While using LINQ to XML, loading XML documents into memory is easy and more easier is querying and document modification. It is also possible to save XML documents existing in memory to disk and to serialize them. It eliminates the need for a developer to learn the XML query language which is somewhat complex." }, { "code": null, "e": 41697, "s": 41543, "text": "LINQ to XML has its power in the System.Xml.Linq namespace. This has all the 19 necessary classes to work with XML. These classes are the following ones." }, { "code": null, "e": 41708, "s": 41697, "text": "XAttribute" }, { "code": null, "e": 41715, "s": 41708, "text": "XCData" }, { "code": null, "e": 41724, "s": 41715, "text": "XComment" }, { "code": null, "e": 41735, "s": 41724, "text": "XContainer" }, { "code": null, "e": 41748, "s": 41735, "text": "XDeclaration" }, { "code": null, "e": 41758, "s": 41748, "text": "XDocument" }, { "code": null, "e": 41772, "s": 41758, "text": "XDocumentType" }, { "code": null, "e": 41781, "s": 41772, "text": "XElement" }, { "code": null, "e": 41787, "s": 41781, "text": "XName" }, { "code": null, "e": 41798, "s": 41787, "text": "XNamespace" }, { "code": null, "e": 41804, "s": 41798, "text": "XNode" }, { "code": null, "e": 41831, "s": 41804, "text": "XNodeDocumentOrderComparer" }, { "code": null, "e": 41853, "s": 41831, "text": "XNodeEqualityComparer" }, { "code": null, "e": 41861, "s": 41853, "text": "XObject" }, { "code": null, "e": 41875, "s": 41861, "text": "XObjectChange" }, { "code": null, "e": 41898, "s": 41875, "text": "XObjectChangeEventArgs" }, { "code": null, "e": 41918, "s": 41898, "text": "XObjectEventHandler" }, { "code": null, "e": 41941, "s": 41918, "text": "XProcessingInstruction" }, { "code": null, "e": 41947, "s": 41941, "text": "XText" }, { "code": null, "e": 42814, "s": 41947, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nnamespace LINQtoXML {\n class ExampleOfXML {\n static void Main(string[] args) {\n \n string myXML = @\"<Departments>\n <Department>Account</Department>\n <Department>Sales</Department>\n <Department>Pre-Sales</Department>\n <Department>Marketing</Department>\n </Departments>\";\n\n XDocument xdoc = new XDocument();\n xdoc = XDocument.Parse(myXML);\n\n var result = xdoc.Element(\"Departments\").Descendants();\n\n foreach (XElement item in result) {\n Console.WriteLine(\"Department Name - \" + item.Value);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 43738, "s": 42814, "text": "Imports System.Collections.Generic\nImports System.Linq\nImports System.Xml.Linq\n\nModule Module1\n\n Sub Main(ByVal args As String())\n \n Dim myXML As String = \"<Departments>\" & vbCr & vbLf & \n \"<Department>Account</Department>\" & vbCr & vbLf & \n \"<Department>Sales</Department>\" & vbCr & vbLf & \n \"<Department>Pre-Sales</Department>\" & vbCr & vbLf & \n \"<Department>Marketing</Department>\" & vbCr & vbLf & \n \"</Departments>\"\n\n Dim xdoc As New XDocument()\n xdoc = XDocument.Parse(myXML)\n\n Dim result = xdoc.Element(\"Departments\").Descendants()\n\n For Each item As XElement In result\n Console.WriteLine(\"Department Name - \" + item.Value)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 43831, "s": 43738, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 43967, "s": 43831, "text": "Department Name - Account\nDepartment Name - Sales\nDepartment Name - Pre-Sales\nDepartment Name - Marketing\n\nPress any key to continue. \n" }, { "code": null, "e": 45066, "s": 43967, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nnamespace LINQtoXML {\n class ExampleOfXML {\n static void Main(string[] args) {\n \n string myXML = @\"<Departments>\n <Department>Account</Department>\n <Department>Sales</Department>\n <Department>Pre-Sales</Department>\n <Department>Marketing</Department>\n </Departments>\";\n\n XDocument xdoc = new XDocument();\n xdoc = XDocument.Parse(myXML);\n\n //Add new Element\n xdoc.Element(\"Departments\").Add(new XElement(\"Department\", \"Finance\"));\n\n //Add new Element at First\n xdoc.Element(\"Departments\").AddFirst(new XElement(\"Department\", \"Support\"));\n\n var result = xdoc.Element(\"Departments\").Descendants();\n\n foreach (XElement item in result) {\n Console.WriteLine(\"Department Name - \" + item.Value);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 46146, "s": 45066, "text": "Imports System.Collections.Generic\nImports System.Linq\nImports System.Xml.Linq\n\nModule Module1\n\n Sub Main(ByVal args As String())\n \n Dim myXML As String = \"<Departments>\" & vbCr & vbLf & \n \t \"<Department>Account</Department>\" & vbCr & vbLf & \n \t \"<Department>Sales</Department>\" & vbCr & vbLf & \n \t \"<Department>Pre-Sales</Department>\" & vbCr & vbLf & \n \t \"<Department>Marketing</Department>\" & vbCr & vbLf & \n \t \"</Departments>\"\n\n Dim xdoc As New XDocument()\n xdoc = XDocument.Parse(myXML)\n\n xdoc.Element(\"Departments\").Add(New XElement(\"Department\", \"Finance\"))\n \n xdoc.Element(\"Departments\").AddFirst(New XElement(\"Department\", \"Support\"))\n\n Dim result = xdoc.Element(\"Departments\").Descendants()\n\n For Each item As XElement In result\n Console.WriteLine(\"Department Name - \" + item.Value)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 46239, "s": 46146, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 46426, "s": 46239, "text": "Department Name - Support\nDepartment Name - Account\nDepartment Name - Sales\nDepartment Name - Pre-Sales\nDepartment Name - Marketing\nDepartment Name - Finance\n\nPress any key to continue.\n" }, { "code": null, "e": 47510, "s": 46426, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Xml.Linq;\n\nnamespace LINQtoXML {\n class ExampleOfXML {\n static void Main(string[] args) {\n \n string myXML = @\"<Departments>\n <Department>Support</Department>\n <Department>Account</Department>\n <Department>Sales</Department>\n <Department>Pre-Sales</Department>\n <Department>Marketing</Department>\n <Department>Finance</Department>\n </Departments>\";\n\n XDocument xdoc = new XDocument();\n xdoc = XDocument.Parse(myXML);\n\n //Remove Sales Department\n xdoc.Descendants().Where(s =>s.Value == \"Sales\").Remove(); \n\n var result = xdoc.Element(\"Departments\").Descendants();\n\n foreach (XElement item in result) {\n Console.WriteLine(\"Department Name - \" + item.Value);\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 48651, "s": 47510, "text": "Imports System.Collections.Generic\nImports System.Linq\nImports System.Xml.Linq\n\nModule Module1\n\n Sub Main(args As String())\n \n Dim myXML As String = \"<Departments>\" & vbCr & vbLf & \n \t \"<Department>Support</Department>\" & vbCr & vbLf & \n \t \"<Department>Account</Department>\" & vbCr & vbLf & \n \t \"<Department>Sales</Department>\" & vbCr & vbLf & \n \t \"<Department>Pre-Sales</Department>\" & vbCr & vbLf & \n \t \"<Department>Marketing</Department>\" & vbCr & vbLf & \n \t \"<Department>Finance</Department>\" & vbCr & vbLf & \n \"</Departments>\"\n\n Dim xdoc As New XDocument()\n xdoc = XDocument.Parse(myXML)\n \n xdoc.Descendants().Where(Function(s) s.Value = \"Sales\").Remove()\n\n Dim result = xdoc.Element(\"Departments\").Descendants()\n\n For Each item As XElement In result\n Console.WriteLine(\"Department Name - \" + item.Value)\n Next\n\n Console.WriteLine(vbLf & \"Press any key to continue.\")\n Console.ReadKey()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 48744, "s": 48651, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 48908, "s": 48744, "text": "Department Name - Support\nDepartment Name - Account\nDepartment Name - Pre-Sales\nDepartment Name - Marketing\nDepartment Name - Finance\n\nPress any key to continue. \n" }, { "code": null, "e": 49290, "s": 48908, "text": "A part of the ADO.NET Entity Framework, LINQ to Entities is more flexible than LINQ to SQL, but is not much popular because of its complexity and lack of key features. However, it does not have the limitations of LINQ to SQL that allows data query only in SQL server database as LINQ to Entities facilitates data query in a large number of data providers like Oracle, MySQL, etc." }, { "code": null, "e": 49518, "s": 49290, "text": "Moreover, it has got a major support from ASP.Net in the sense that users can make use of a data source control for executing a query via LINQ to Entities and facilitates binding of the results without any need of extra coding." }, { "code": null, "e": 49935, "s": 49518, "text": "LINQ to Entities has for these advantages become the standard mechanism for the usage of LINQ on databases nowadays. It is also possible with LINQ to Entities to change queried data details and committing a batch update easily. What is the most intriguing fact about LINQ to Entities is that it has same syntax like that of SQL and even has the same group of standard query operators like Join, Select, OrderBy, etc." }, { "code": null, "e": 50019, "s": 49935, "text": "Construction of an ObjectQuery instance out of an ObjectContext (Entity Connection)" }, { "code": null, "e": 50103, "s": 50019, "text": "Construction of an ObjectQuery instance out of an ObjectContext (Entity Connection)" }, { "code": null, "e": 50195, "s": 50103, "text": "Composing a query either in C# or Visual Basic (VB) by using the newly constructed instance" }, { "code": null, "e": 50287, "s": 50195, "text": "Composing a query either in C# or Visual Basic (VB) by using the newly constructed instance" }, { "code": null, "e": 50381, "s": 50287, "text": "Conversion of standard query operators of LINQ as well as LINQ expressions into command trees" }, { "code": null, "e": 50475, "s": 50381, "text": "Conversion of standard query operators of LINQ as well as LINQ expressions into command trees" }, { "code": null, "e": 50553, "s": 50475, "text": "Executing the query passing any exceptions encountered to the client directly" }, { "code": null, "e": 50631, "s": 50553, "text": "Executing the query passing any exceptions encountered to the client directly" }, { "code": null, "e": 50677, "s": 50631, "text": "Returning to the client all the query results" }, { "code": null, "e": 50723, "s": 50677, "text": "Returning to the client all the query results" }, { "code": null, "e": 50972, "s": 50723, "text": "ObjectContext is here the primary class that enables interaction with Entity Data Model or in other words acts as a bridge that connects LINQ to the database. Command trees are here query representation with compatibility with the Entity framework." }, { "code": null, "e": 51342, "s": 50972, "text": "The Entity Framework, on the other hand, is actually Object Relational Mapper abbreviated generally as ORM by the developers that does the generation of business objects as well as entities as per the database tables and facilitates various basic operations like create, update, delete and read. The following illustration shows the entity framework and its components." }, { "code": null, "e": 51391, "s": 51342, "text": "First add Entity Model by following below steps." }, { "code": null, "e": 51545, "s": 51391, "text": "Step 1 − Right click on project and click add new item will open window as per below. Select ADO.NET Entity Data Model and specify name and click on Add." }, { "code": null, "e": 51585, "s": 51545, "text": "Step 2 − Select Generate from database." }, { "code": null, "e": 51646, "s": 51585, "text": "Step 3 − Choose Database Connection from the drop-down menu." }, { "code": null, "e": 51678, "s": 51646, "text": "Step 4 − Select all the tables." }, { "code": null, "e": 51708, "s": 51678, "text": "Now write the following code." }, { "code": null, "e": 53720, "s": 51708, "text": "using DataAccess;\nusing System;\nusing System.Linq;\n\nnamespace LINQTOSQLConsoleApp {\n public class LinqToEntityModel {\n static void Main(string[] args) {\n\n using (LinqToSQLDBEntities context = new LinqToSQLDBEntities()) {\n //Get the List of Departments from Database\n var departmentList = from d in context.Departments\n select d;\n\n foreach (var dept in departmentList) {\n Console.WriteLine(\"Department Id = {0} , Department Name = {1}\",\n dept.DepartmentId, dept.Name);\n }\n\n //Add new Department\n DataAccess.Department department = new DataAccess.Department();\n department.Name = \"Support\";\n\n context.Departments.Add(department);\n context.SaveChanges();\n\n Console.WriteLine(\"Department Name = Support is inserted in Database\");\n\n //Update existing Department\n DataAccess.Department updateDepartment = context.Departments.FirstOrDefault(d ⇒d.DepartmentId == 1);\n updateDepartment.Name = \"Account updated\";\n context.SaveChanges();\n\n Console.WriteLine(\"Department Name = Account is updated in Database\");\n\n //Delete existing Department\n DataAccess.Department deleteDepartment = context.Departments.FirstOrDefault(d ⇒d.DepartmentId == 3);\n context.Departments.Remove(deleteDepartment);\n context.SaveChanges();\n\n Console.WriteLine(\"Department Name = Pre-Sales is deleted in Database\");\n\n //Get the Updated List of Departments from Database\n departmentList = from d in context.Departments\n select d;\n\n foreach (var dept in departmentList) {\n Console.WriteLine(\"Department Id = {0} , Department Name = {1}\",\n dept.DepartmentId, dept.Name);\n }\n }\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 53801, "s": 53720, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 54174, "s": 53801, "text": "The term ‘Lambda expression’ has derived its name from ‘lambda’ calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation’s executable part translate logic in a way at run time so it can pass on to the data source conveniently. However, lambda expressions are not just limited to find application in LINQ only." }, { "code": null, "e": 54232, "s": 54174, "text": "These expressions are expressed by the following syntax −" }, { "code": null, "e": 54284, "s": 54232, "text": "(Input parameters) ⇒ Expression or statement block\n" }, { "code": null, "e": 54328, "s": 54284, "text": "Here is an example of a lambda expression −" }, { "code": null, "e": 54338, "s": 54328, "text": "y ⇒ y * y" }, { "code": null, "e": 54547, "s": 54338, "text": "The above expression specifies a parameter named y and that value of y is squared. However, it is not possible to execute a lambda expression in this form. Example of a lambda expression in C# is shown below." }, { "code": null, "e": 54896, "s": 54547, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace lambdaexample {\n class Program {\n\n delegate int del(int i);\n static void Main(string[] args) {\n\n del myDelegate = y ⇒ y * y;\n int j = myDelegate(5);\n Console.WriteLine(j);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 55188, "s": 54896, "text": "Module Module1\n Private Delegate Function del(ByVal i As Integer) As Integer\n \n Sub Main(ByVal args As String())\n \n Dim myDelegate As del = Function(y) y * y\n Dim j As Integer = myDelegate(5)\n Console.WriteLine(j)\n Console.ReadLine()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 55281, "s": 55188, "text": "When the above code of C# or VB is compiled and executed, it produces the following result −" }, { "code": null, "e": 55285, "s": 55281, "text": "25\n" }, { "code": null, "e": 55420, "s": 55285, "text": "As the expression in the syntax of lambda expression shown above is on the right hand side, these are also known as expression lambda." }, { "code": null, "e": 55583, "s": 55420, "text": "The lambda expression created by incorporating asynchronous processing by the use of async keyword is known as async lambdas. Below is an example of async lambda." }, { "code": null, "e": 55635, "s": 55583, "text": "Func<Task<string>> getWordAsync = async()⇒ “hello”;" }, { "code": null, "e": 56061, "s": 55635, "text": "A lambda expression within a query operator is evaluated by the same upon demand and continually works on each of the elements in the input sequence and not the whole sequence. Developers are allowed by Lambda expression to feed their own logic into the standard query operators. In the below example, the developer has used the ‘Where’ operator to reclaim the odd values from given list by making use of a lambda expression." }, { "code": null, "e": 56530, "s": 56061, "text": "//Get the average of the odd Fibonacci numbers in the series... \n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace lambdaexample {\n class Program { \n static void Main(string[] args) {\n \n int[] fibNum = { 1, 1, 2, 3, 5, 8, 13, 21, 34 };\n double averageValue = fibNum.Where(num ⇒ num % 2 == 1).Average();\n Console.WriteLine(averageValue);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 56811, "s": 56530, "text": "Module Module1\n\n Sub Main()\n \n Dim fibNum As Integer() = {1, 1, 2, 3, 5, 8, 13, 21, 34}\n Dim averageValue As Double = fibNum.Where(Function(num) num Mod 2 = 1).Average()\n\t \n Console.WriteLine(averageValue)\n Console.ReadLine()\n\t \n End Sub\n \nEnd Module" }, { "code": null, "e": 56892, "s": 56811, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 56910, "s": 56892, "text": "7.33333333333333\n" }, { "code": null, "e": 57211, "s": 56910, "text": "In C#, type inference is used conveniently in a variety of situations and that too without specifying the types explicitly. However in case of a lambda expression, type inference will work only when each type has been specified as the compiler must be satisfied. Let’s consider the following example." }, { "code": null, "e": 57245, "s": 57211, "text": "delegate int Transformer (int i);" }, { "code": null, "e": 57401, "s": 57245, "text": "Here the compiler employ the type inference to draw upon the fact that x is an integer and this is done by examining the parameter type of the Transformer." }, { "code": null, "e": 57878, "s": 57401, "text": "There are some rules while using variable scope in a lambda expression like variables that are initiated within a lambda expression are not meant to be visible in an outer method. There is also a rule that a captured variable is not to be garbage collected unless the delegate referencing the same becomes eligible for the act of garbage collection. Moreover, there is a rule that prohibits a return statement within a lambda expression to cause return of an enclosing method." }, { "code": null, "e": 57949, "s": 57878, "text": "Here is an example to demonstrate variable scope in lambda expression." }, { "code": null, "e": 59262, "s": 57949, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace lambdaexample {\n class Program {\n delegate bool D();\n delegate bool D2(int i);\n\n class Test {\n D del;\n D2 del2;\n\t\t\t\n public void TestMethod(int input) {\n int j = 0;\n // Initialize the delegates with lambda expressions.\n // Note access to 2 outer variables.\n // del will be invoked within this method.\n del = () ⇒ { j = 10; return j > input; };\n\n // del2 will be invoked after TestMethod goes out of scope.\n del2 = (x) ⇒ { return x == j; };\n\n // Demonstrate value of j: \n // The delegate has not been invoked yet.\n Console.WriteLine(\"j = {0}\", j); // Invoke the delegate.\n bool boolResult = del();\n \n Console.WriteLine(\"j = {0}. b = {1}\", j, boolResult);\n }\n\n static void Main() {\n Test test = new Test();\n test.TestMethod(5);\n\n // Prove that del2 still has a copy of\n // local variable j from TestMethod.\n bool result = test.del2(10);\n \n Console.WriteLine(result);\n\n Console.ReadKey();\n }\n }\n }\n}" }, { "code": null, "e": 59343, "s": 59262, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 59372, "s": 59343, "text": "j = 0\nj = 10. b = True\nTrue\n" }, { "code": null, "e": 59706, "s": 59372, "text": "Lambda expressions are used in Expression Tree construction extensively. An expression tree give away code in a data structure resembling a tree in which every node is itself an expression like a method call or can be a binary operation like x<y. Below is an example of usage of lambda expression for constructing an expression tree." }, { "code": null, "e": 59889, "s": 59706, "text": "There is also statement lambdas consisting of two or three statements, but are not used in construction of expression trees. A return statement must be written in a statement lambda." }, { "code": null, "e": 59916, "s": 59889, "text": "Syntax of statement lambda" }, { "code": null, "e": 59940, "s": 59916, "text": "(params)⇒ {statements}\n" }, { "code": null, "e": 60502, "s": 59940, "text": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Linq.Expressions;\n\nnamespace lambdaexample {\n class Program {\n static void Main(string[] args) {\n int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };\n\n foreach (int i in source.Where(x ⇒ \n {\n if (x <= 3)\n return true;\n else if (x >= 7)\n return true;\n return false;\n }\n ))\n Console.WriteLine(i);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 60583, "s": 60502, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 60598, "s": 60583, "text": "3\n8\n1\n7\n9\n2\n8\n" }, { "code": null, "e": 60897, "s": 60598, "text": "Lambdas are employed as arguments in LINQ queries based on methods and never allowed to have a place on the left side of operators like is or as just like anonymous methods. Although, Lambda expressions are much alike anonymous methods, these are not at all restricted to be used as delegates only." }, { "code": null, "e": 60961, "s": 60897, "text": "A lambda expression can return a value and may have parameters." }, { "code": null, "e": 61025, "s": 60961, "text": "A lambda expression can return a value and may have parameters." }, { "code": null, "e": 61097, "s": 61025, "text": "Parameters can be defined in a myriad of ways with a lambda expression." }, { "code": null, "e": 61169, "s": 61097, "text": "Parameters can be defined in a myriad of ways with a lambda expression." }, { "code": null, "e": 61362, "s": 61169, "text": "If there is single statement in a lambda expression, there is no need of curly brackets whereas if there are multiple statements, curly brackets as well as return value are essential to write." }, { "code": null, "e": 61555, "s": 61362, "text": "If there is single statement in a lambda expression, there is no need of curly brackets whereas if there are multiple statements, curly brackets as well as return value are essential to write." }, { "code": null, "e": 61756, "s": 61555, "text": "With lambda expressions, it is possible to access variables present outside of the lambda expression block by a feature known as closure. Use of closure should be done cautiously to avoid any problem." }, { "code": null, "e": 61957, "s": 61756, "text": "With lambda expressions, it is possible to access variables present outside of the lambda expression block by a feature known as closure. Use of closure should be done cautiously to avoid any problem." }, { "code": null, "e": 62031, "s": 61957, "text": "It is impossible to execute any unsafe code inside any lambda expression." }, { "code": null, "e": 62105, "s": 62031, "text": "It is impossible to execute any unsafe code inside any lambda expression." }, { "code": null, "e": 62179, "s": 62105, "text": "Lambda expressions are not meant to be used on the operator’s left side.\n" }, { "code": null, "e": 62252, "s": 62179, "text": "Lambda expressions are not meant to be used on the operator’s left side." }, { "code": null, "e": 62733, "s": 62252, "text": "As a set of .NET framework extensions, LINQ is the preferred mechanism for data access by ASP.NET developers. ASP.NET 3.5 has a built-in tool LINQDataSource control that enables usage of LINQ easily in ASP.NET. ASP.NET uses the above-mentioned control as a data source. Real life projects mostly encompass websites or windows applications and so to understand better the concept of LINQ with ASP.NET, let’s start with creating a ASP.NET website that make use of the LINQ features." }, { "code": null, "e": 62941, "s": 62733, "text": "For this, it is essential to get installed Visual Studio and .NET framework on your system. Once you have opened Visual Studio, go to File → New → Website. A pop up window will open as shown in below figure." }, { "code": null, "e": 63099, "s": 62941, "text": "Now, under the templates in the left hand side, there will be two language options to create the website. Choose Visual C# and select ASP.NET Empty Web Site." }, { "code": null, "e": 63492, "s": 63099, "text": "Select the folder where you want to save new website on your system. Then press OK and soon Solution Explorer appears on your screen containing all the web files. Right click on Default.aspx in the Solution Explorer and choose View in Browser to view the default ASP.NET website in the browser. Soon your new ASP.NET website will open in the web browser, as shown in the following screenshot." }, { "code": null, "e": 63797, "s": 63492, "text": ".aspx is in fact the major file extension used in ASP.NET websites. Visual Studio by default creates all the necessary pages for a basic website like Home page and About Us page where you can place your content conveniently. The code for the website is generated automatically here and can be viewed too." }, { "code": null, "e": 64065, "s": 63797, "text": "It is possible to UPDATE, INSERT and DELETE data in the pages of ASP.NET website with the help of LINQDataSource control. There is absolutely no need for specification of SQL commands as LINQDataSource control employs dynamically created commands for such operations." }, { "code": null, "e": 64474, "s": 64065, "text": "The control enables a user to make use of LINQ in an ASP.NET web page conveniently by property setting in the markup text. LINQDataSource is very similar to that of controls like SqlDataSource as well as ObjectDataSource as it can be used in binding other ASP.NET controls present on a page to a data source. So, we must have a database to explain the various functions invoked by the LINQDataSource Control." }, { "code": null, "e": 64708, "s": 64474, "text": "Before going to start explanation of the control usage in ASP.NET web page form, it is essential to open the Microsoft Visual Studio Toolbox and drag and drop LINQDataSource control to .aspx page of ASP.NET website like below figure." }, { "code": null, "e": 64807, "s": 64708, "text": "The next step is to configure LINQDataSource by selecting all the columns for the employee record." }, { "code": null, "e": 65043, "s": 64807, "text": "Now add a GridView Control to the .aspx page and configure it like shown in below figure. The GridView control is powerful and offers flexibility to work with the data. Soon after configuring the control, it will appear in the browser." }, { "code": null, "e": 65121, "s": 65043, "text": "The coding that can be viewed now on your screen for the .aspx page will be −" }, { "code": null, "e": 66929, "s": 65121, "text": "<!DOCTYPE html>\n\n<html>\n <head runat = \"server\">\n <title></title>\n </head>\n\n <body>\n <form id = \"form1\" runat = \"server\">\n <div>\n <asp:GridView ID = \"GridView1\" runat = \"server\" AutoGenerateColumns = \"False\"\n\t\t\t\n DataKeyNames = \"ContactID\" DataSourceID = \"LINQDataSource1\">\n <Columns>\n\t\t\t \n <asp:BoundField DataField = \"ContactID\" HeaderText = \"ContactID\"\n InsertVisible = \"False\" ReadOnly=\"True\" SortExpression = \"ContactID\" />\n <asp:CheckBoxField DataField = \"NameStyle\" HeaderText = \"NameStyle\"\n SortExpression = \"NameStyle\" />\n <asp:BoundField DataField = \"Title\" HeaderText = \"Title\" SortExpression = \"Title\" />\n <asp:BoundField DataField = \"FirstName\" HeaderText = \"FirstName\"\n SortExpression=\"FirstName\" />\n <asp:BoundField DataField = \"MiddleName\" HeaderText = \"MiddleName\"\n SortExpression = \"MiddleName\" />\n <asp:BoundField DataField = \"LastName\" HeaderText = \"LastName\"\n SortExpression = \"LastName\" />\n <asp:BoundField DataField = \"Suffix\" HeaderText = \"Suffix\"\n SortExpression = \"Suffix\" />\n <asp:BoundField DataField = \"EmailAddress\" HeaderText = \"EmailAddress\"\n SortExpression = \"EmailAddress\" />\n </Columns>\n\n </asp:GridView>\n\n <br />\n\n </div>\n\n <asp:LINQDataSource ID = \"LINQDataSource1\" runat = \"server\"\n\n ContextTypeName = \"LINQWebApp1.AdventureWorksDataContext\" EntityTypeName = \"\"\n TableName = \"Contacts\">\n\n </asp:LINQDataSource>\n </form>\n </body>\n</html>" }, { "code": null, "e": 67213, "s": 66929, "text": "Here it should be noted that it is vital to set the property ContextTypeName to that of the class representing the database. For example, here it is given as LINQWebApp1.AdventureWorksDataContext as this action will make the needed connection between LINQDataSource and the database." }, { "code": null, "e": 67461, "s": 67213, "text": "After completing all the above steps rigorously, choose the LINQDataSource Tasks from the LINQDataSource Control and choose all the three boxes for enable insert, enable update and enable delete from the same, as shown in the following screenshot." }, { "code": null, "e": 67545, "s": 67461, "text": "Soon the declarative markup will get displayed on your screen as the following one." }, { "code": null, "e": 67803, "s": 67545, "text": "<asp:LINQDataSource \n ContextTypeName = \"LINQWebApp1.AdventureWorksDataContext\" \n TableName = \"Contacts\" \n EnableUpdate = \"true\" \n EnableInsert = \"true\" \n EnableDelete = \"true\" \n ID = \"LINQDataSource1\" \n runat = \"server\">\n</asp:LINQDataSource>" }, { "code": null, "e": 68132, "s": 67803, "text": "Now since there are multiple rows and columns, it is better to add another control on your .aspx form named as Detail View or Master control below the Grid View control to display only the details of a selected row of the grid. Choose the Detail View Tasks from the Detail View control and select the check boxes as shown below." }, { "code": null, "e": 68302, "s": 68132, "text": "Now, just save the changes and press Ctrl + F5 to view the page in your browser where it is now possible to delete, update, insert any record on the detail view control." }, { "code": null, "e": 68337, "s": 68302, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 68351, "s": 68337, "text": " Anadi Sharma" }, { "code": null, "e": 68385, "s": 68351, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 68403, "s": 68385, "text": " Trevoir Williams" }, { "code": null, "e": 68410, "s": 68403, "text": " Print" }, { "code": null, "e": 68421, "s": 68410, "text": " Add Notes" } ]
Check if two expressions with brackets are same - GeeksforGeeks
30 Aug, 2021 Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, ‘+’, ‘-‘ and ‘( )’.Examples: Input : exp1 = "-(a+b+c)" exp2 = "-a-b-c" Output : Yes Input : exp1 = "-(c+b+a)" exp2 = "-c-b-a" Output : Yes Input : exp1 = "a-b-(c-d)" exp2 = "a-b-c-d" Output : No It may be assumed that there are at most 26 operands from ‘a’ to ‘z’ and every operand appears only once. A simple idea behind is to keep a record of the Global and Local Sign(+/-) through the expression. The Global Sign here means the multiplicative sign at each operand. The resultant sign for an operand is local sign multiplied by the global sign at that operand.For example, the expression a+b-(c-d) is evaluated as (+)+a(+)+b(-)+c(-)-d => a + b – c + d. The global sign (represented inside bracket) is multiplied to the local sign for each operand.In the given solution, stack is used to keep record of the global signs. A count vector records the counts of the operands(lowercase Latin letters here). Two expressions are evaluated in opposite manners and finally, it is checked if the all entries in the count vector are zeros. C++ Java Python3 C# Javascript // CPP program to check if two expressions// evaluate to same.#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // Return local sign of the operand. For example,// in the expr a-b-(c), local signs of the operands// are +a, -b, +cbool adjSign(string s, int i){ if (i == 0) return true; if (s[i - 1] == '-') return false; return true;}; // Evaluate expressions into the count vector of// the 26 alphabets.If add is true, then add count// to the count vector of the alphabets, else remove// count from the count vector.void eval(string s, vector<int>& v, bool add){ // stack stores the global sign // for operands. stack<bool> stk; stk.push(true); // + means true // global sign is positive initially int i = 0; while (s[i] != '\0') { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.top()); else stk.push(!stk.top()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.top()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; }}; // Returns true if expr1 and expr2 represent// same expressionsbool areSame(string expr1, string expr2){ // Create a vector for all operands and // initialize the vector as 0. vector<int> v(MAX_CHAR, 0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true;} // Driver codeint main(){ string expr1 = "-(a+b+c)", expr2 = "-a-b-c"; if (areSame(expr1, expr2)) cout << "Yes\n"; else cout << "No\n"; return 0;} // Java program to check if two expressions// evaluate to same.import java.io.*;import java.util.*; class GFG{ static final int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c static boolean adjSign(String s, int i) { if (i == 0) return true; if (s.charAt(i - 1) == '-') return false; return true; }; // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. static void eval(String s, int[] v, boolean add) { // stack stores the global sign // for operands. Stack<Boolean> stk = new Stack<>(); stk.push(true); // + means true // global sign is positive initially int i = 0; while (i < s.length()) { if (s.charAt(i) == '+' || s.charAt(i) == '-') { i++; continue; } if (s.charAt(i) == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.peek()); else stk.push(!stk.peek()); } // global sign is popped out which // was pushed in for the last bracket else if (s.charAt(i) == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.peek()) v[s.charAt(i) - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s.charAt(i) - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions static boolean areSame(String expr1, String expr2) { // Create a vector for all operands and // initialize the vector as 0. int[] v = new int[MAX_CHAR]; // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver Code public static void main(String[] args) { String expr1 = "-(a+b+c)", expr2 = "-a-b-c"; if (areSame(expr1, expr2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552 # Python3 program to check if two expressions# evaluate to same.MAX_CHAR = 26; # Return local sign of the operand. For example,# in the expr a-b-(c), local signs of the operands# are +a, -b, +cdef adjSign(s, i): if (i == 0): return True; if (s[i - 1] == '-'): return False; return True; # Evaluate expressions into the count vector of# the 26 alphabets.If add is True, then add count# to the count vector of the alphabets, else remove# count from the count vector.def eval(s, v, add): # stack stores the global sign # for operands. stk = [] stk.append(True); # + means True # global sign is positive initially i = 0; while (i < len(s)): if (s[i] == '+' or s[i] == '-'): i += 1 continue; if (s[i] == '('): # global sign for the bracket is # pushed to the stack if (adjSign(s, i)): stk.append(stk[-1]); else: stk.append(not stk[-1]); # global sign is popped out which # was pushed in for the last bracket elif (s[i] == ')'): stk.pop(); else: # global sign is positive (we use different # values in two calls of functions so that # we finally check if all vector elements # are 0. if (stk[-1]): v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1) # global sign is negative here else: v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1) i += 1 # Returns True if expr1 and expr2 represent# same expressionsdef areSame(expr1, expr2): # Create a vector for all operands and # initialize the vector as 0. v = [0 for i in range(MAX_CHAR)]; # Put signs of all operands in expr1 eval(expr1, v, True); # Subtract signs of operands in expr2 eval(expr2, v, False); # If expressions are same, vector must # be 0. for i in range(MAX_CHAR): if (v[i] != 0): return False; return True; # Driver Codeif __name__=='__main__': expr1 = "-(a+b+c)" expr2 = "-a-b-c"; if (areSame(expr1, expr2)): print("Yes"); else: print("No"); # This code is contributed by rutvik_56. // C# program to check if two expressions// evaluate to same.using System;using System.Collections.Generic;public class GFG{ static readonly int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c static bool adjSign(String s, int i) { if (i == 0) return true; if (s[i-1] == '-') return false; return true; } // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. static void eval(String s, int[] v, bool add) { // stack stores the global sign // for operands. Stack<Boolean> stk = new Stack<Boolean>(); stk.Push(true); // + means true // global sign is positive initially int i = 0; while (i < s.Length) { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.Push(stk.Peek()); else stk.Push(!stk.Peek()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.Pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.Peek()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } } // Returns true if expr1 and expr2 represent // same expressions static bool areSame(String expr1, String expr2) { // Create a vector for all operands and // initialize the vector as 0. int[] v = new int[MAX_CHAR]; // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver Code public static void Main(String[] args) { String expr1 = "-(a+b+c)", expr2 = "-a-b-c"; if (areSame(expr1, expr2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji <script> // Javascript program to check if two expressions // evaluate to same. let MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c function adjSign(s, i) { if (i == 0) return true; if (s[i - 1] == '-') return false; return true; } // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. function eval(s, v, add) { // stack stores the global sign // for operands. let stk = []; stk.push(true); // + means true // global sign is positive initially let i = 0; while (i < s.length) { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk[stk.length - 1]); else stk.push(!stk[stk.length - 1]); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk[stk.length - 1]) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions function areSame(expr1, expr2) { // Create a vector for all operands and // initialize the vector as 0. let v = new Array(MAX_CHAR); v.fill(0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (let i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } let expr1 = "-(a+b+c)", expr2 = "-a-b-c"; if (areSame(expr1, expr2)) document.write("YES"); else document.write("NO"); // This code is contributed by suresh07.</script> Output: YES This article is contributed by Amol Mejari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 Rajput-Ji rutvik_56 suresh07 Amazon cpp-vector Stack Strings Amazon Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for Tower of Hanoi Implement a stack using singly linked list Implement Stack using Queues Iterative Depth First Traversal of Graph Merge Overlapping Intervals Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24633, "s": 24605, "text": "\n30 Aug, 2021" }, { "code": null, "e": 24813, "s": 24633, "text": "Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, ‘+’, ‘-‘ and ‘( )’.Examples: " }, { "code": null, "e": 25011, "s": 24813, "text": "Input : exp1 = \"-(a+b+c)\"\n exp2 = \"-a-b-c\"\nOutput : Yes\n\nInput : exp1 = \"-(c+b+a)\"\n exp2 = \"-c-b-a\"\nOutput : Yes\n\nInput : exp1 = \"a-b-(c-d)\"\n exp2 = \"a-b-c-d\"\nOutput : No" }, { "code": null, "e": 25118, "s": 25011, "text": "It may be assumed that there are at most 26 operands from ‘a’ to ‘z’ and every operand appears only once. " }, { "code": null, "e": 25849, "s": 25118, "text": "A simple idea behind is to keep a record of the Global and Local Sign(+/-) through the expression. The Global Sign here means the multiplicative sign at each operand. The resultant sign for an operand is local sign multiplied by the global sign at that operand.For example, the expression a+b-(c-d) is evaluated as (+)+a(+)+b(-)+c(-)-d => a + b – c + d. The global sign (represented inside bracket) is multiplied to the local sign for each operand.In the given solution, stack is used to keep record of the global signs. A count vector records the counts of the operands(lowercase Latin letters here). Two expressions are evaluated in opposite manners and finally, it is checked if the all entries in the count vector are zeros. " }, { "code": null, "e": 25853, "s": 25849, "text": "C++" }, { "code": null, "e": 25858, "s": 25853, "text": "Java" }, { "code": null, "e": 25866, "s": 25858, "text": "Python3" }, { "code": null, "e": 25869, "s": 25866, "text": "C#" }, { "code": null, "e": 25880, "s": 25869, "text": "Javascript" }, { "code": "// CPP program to check if two expressions// evaluate to same.#include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // Return local sign of the operand. For example,// in the expr a-b-(c), local signs of the operands// are +a, -b, +cbool adjSign(string s, int i){ if (i == 0) return true; if (s[i - 1] == '-') return false; return true;}; // Evaluate expressions into the count vector of// the 26 alphabets.If add is true, then add count// to the count vector of the alphabets, else remove// count from the count vector.void eval(string s, vector<int>& v, bool add){ // stack stores the global sign // for operands. stack<bool> stk; stk.push(true); // + means true // global sign is positive initially int i = 0; while (s[i] != '\\0') { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.top()); else stk.push(!stk.top()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.top()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; }}; // Returns true if expr1 and expr2 represent// same expressionsbool areSame(string expr1, string expr2){ // Create a vector for all operands and // initialize the vector as 0. vector<int> v(MAX_CHAR, 0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true;} // Driver codeint main(){ string expr1 = \"-(a+b+c)\", expr2 = \"-a-b-c\"; if (areSame(expr1, expr2)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}", "e": 28434, "s": 25880, "text": null }, { "code": "// Java program to check if two expressions// evaluate to same.import java.io.*;import java.util.*; class GFG{ static final int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c static boolean adjSign(String s, int i) { if (i == 0) return true; if (s.charAt(i - 1) == '-') return false; return true; }; // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. static void eval(String s, int[] v, boolean add) { // stack stores the global sign // for operands. Stack<Boolean> stk = new Stack<>(); stk.push(true); // + means true // global sign is positive initially int i = 0; while (i < s.length()) { if (s.charAt(i) == '+' || s.charAt(i) == '-') { i++; continue; } if (s.charAt(i) == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.peek()); else stk.push(!stk.peek()); } // global sign is popped out which // was pushed in for the last bracket else if (s.charAt(i) == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.peek()) v[s.charAt(i) - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s.charAt(i) - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions static boolean areSame(String expr1, String expr2) { // Create a vector for all operands and // initialize the vector as 0. int[] v = new int[MAX_CHAR]; // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver Code public static void main(String[] args) { String expr1 = \"-(a+b+c)\", expr2 = \"-a-b-c\"; if (areSame(expr1, expr2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552", "e": 31475, "s": 28434, "text": null }, { "code": "# Python3 program to check if two expressions# evaluate to same.MAX_CHAR = 26; # Return local sign of the operand. For example,# in the expr a-b-(c), local signs of the operands# are +a, -b, +cdef adjSign(s, i): if (i == 0): return True; if (s[i - 1] == '-'): return False; return True; # Evaluate expressions into the count vector of# the 26 alphabets.If add is True, then add count# to the count vector of the alphabets, else remove# count from the count vector.def eval(s, v, add): # stack stores the global sign # for operands. stk = [] stk.append(True); # + means True # global sign is positive initially i = 0; while (i < len(s)): if (s[i] == '+' or s[i] == '-'): i += 1 continue; if (s[i] == '('): # global sign for the bracket is # pushed to the stack if (adjSign(s, i)): stk.append(stk[-1]); else: stk.append(not stk[-1]); # global sign is popped out which # was pushed in for the last bracket elif (s[i] == ')'): stk.pop(); else: # global sign is positive (we use different # values in two calls of functions so that # we finally check if all vector elements # are 0. if (stk[-1]): v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1) # global sign is negative here else: v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1) i += 1 # Returns True if expr1 and expr2 represent# same expressionsdef areSame(expr1, expr2): # Create a vector for all operands and # initialize the vector as 0. v = [0 for i in range(MAX_CHAR)]; # Put signs of all operands in expr1 eval(expr1, v, True); # Subtract signs of operands in expr2 eval(expr2, v, False); # If expressions are same, vector must # be 0. for i in range(MAX_CHAR): if (v[i] != 0): return False; return True; # Driver Codeif __name__=='__main__': expr1 = \"-(a+b+c)\" expr2 = \"-a-b-c\"; if (areSame(expr1, expr2)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by rutvik_56.", "e": 33616, "s": 31475, "text": null }, { "code": "// C# program to check if two expressions// evaluate to same.using System;using System.Collections.Generic;public class GFG{ static readonly int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c static bool adjSign(String s, int i) { if (i == 0) return true; if (s[i-1] == '-') return false; return true; } // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. static void eval(String s, int[] v, bool add) { // stack stores the global sign // for operands. Stack<Boolean> stk = new Stack<Boolean>(); stk.Push(true); // + means true // global sign is positive initially int i = 0; while (i < s.Length) { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.Push(stk.Peek()); else stk.Push(!stk.Peek()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.Pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.Peek()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } } // Returns true if expr1 and expr2 represent // same expressions static bool areSame(String expr1, String expr2) { // Create a vector for all operands and // initialize the vector as 0. int[] v = new int[MAX_CHAR]; // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver Code public static void Main(String[] args) { String expr1 = \"-(a+b+c)\", expr2 = \"-a-b-c\"; if (areSame(expr1, expr2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 36181, "s": 33616, "text": null }, { "code": "<script> // Javascript program to check if two expressions // evaluate to same. let MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c function adjSign(s, i) { if (i == 0) return true; if (s[i - 1] == '-') return false; return true; } // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. function eval(s, v, add) { // stack stores the global sign // for operands. let stk = []; stk.push(true); // + means true // global sign is positive initially let i = 0; while (i < s.length) { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk[stk.length - 1]); else stk.push(!stk[stk.length - 1]); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk[stk.length - 1]) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions function areSame(expr1, expr2) { // Create a vector for all operands and // initialize the vector as 0. let v = new Array(MAX_CHAR); v.fill(0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (let i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } let expr1 = \"-(a+b+c)\", expr2 = \"-a-b-c\"; if (areSame(expr1, expr2)) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by suresh07.</script>", "e": 39024, "s": 36181, "text": null }, { "code": null, "e": 39034, "s": 39024, "text": "Output: " }, { "code": null, "e": 39038, "s": 39034, "text": "YES" }, { "code": null, "e": 39458, "s": 39038, "text": "This article is contributed by Amol Mejari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39470, "s": 39458, "text": "sanjeev2552" }, { "code": null, "e": 39480, "s": 39470, "text": "Rajput-Ji" }, { "code": null, "e": 39490, "s": 39480, "text": "rutvik_56" }, { "code": null, "e": 39499, "s": 39490, "text": "suresh07" }, { "code": null, "e": 39506, "s": 39499, "text": "Amazon" }, { "code": null, "e": 39517, "s": 39506, "text": "cpp-vector" }, { "code": null, "e": 39523, "s": 39517, "text": "Stack" }, { "code": null, "e": 39531, "s": 39523, "text": "Strings" }, { "code": null, "e": 39538, "s": 39531, "text": "Amazon" }, { "code": null, "e": 39546, "s": 39538, "text": "Strings" }, { "code": null, "e": 39552, "s": 39546, "text": "Stack" }, { "code": null, "e": 39650, "s": 39552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39659, "s": 39650, "text": "Comments" }, { "code": null, "e": 39672, "s": 39659, "text": "Old Comments" }, { "code": null, "e": 39699, "s": 39672, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 39742, "s": 39699, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 39771, "s": 39742, "text": "Implement Stack using Queues" }, { "code": null, "e": 39812, "s": 39771, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 39840, "s": 39812, "text": "Merge Overlapping Intervals" }, { "code": null, "e": 39865, "s": 39840, "text": "Reverse a string in Java" }, { "code": null, "e": 39911, "s": 39865, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 39945, "s": 39911, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 40005, "s": 39945, "text": "Write a program to print all permutations of a given string" } ]
Inheritance and Polymorphism
Inheritance and polymorphism – this is a very important concept in Python. You must understand it better if you want to learn. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanisms to achieve the same. Inheritance allows programmer to create a general or a base class first and then later extend it to more specialized class. It allows programmer to write better code. Using inheritance you can use or inherit all the data fields and methods available in your base class. Later you can add you own methods and data fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch. In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and X is called subclass/child/derived class. One point to note here is that only data fields and method which are not private are accessible by child classes. Private data fields and methods are accessible only inside the class. syntax to create a derived class is − class BaseClass: Body of base class class DerivedClass(BaseClass): Body of derived class Now look at the below example − We first created a class called Date and pass the object as an argument, here-object is built-in class provided by Python. Later we created another class called time and called the Date class as an argument. Through this call we get access to all the data and attributes of Date class into the Time class. Because of that when we try to get the get_date method from the Time class object tm we created earlier possible. Object.Attribute Lookup Hierarchy The instance The class Any class from which this class inherits Let’s take a closure look into the inheritance example − Let’s create couple of classes to participate in examples − Animal − Class simulate an animal Cat − Subclass of Animal Dog − Subclass of Animal In Python, constructor of class used to create an object (instance), and assign the value for the attributes. Constructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes. In the above example, we see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class. If a subclass try to inherits methods or data from another subclass then it will through an error as we see when Dog class try to call swatstring() methods from that cat class, it throws an error(like AttributeError in our case). Polymorphism is an important feature of class definition in Python that is utilized when you have commonly named methods across classes or subclasses. This permits functions to use entities of different types at different times. So, it provides flexibility and loose coupling so that code can be extended and easily maintained over time. This allows functions to use objects of any of these polymorphic classes without needing to be aware of distinctions across the classes. Polymorphism can be carried out through inheritance, with subclasses making use of base class methods or overriding them. Let understand the concept of polymorphism with our previous inheritance example and add one common method called show_affection in both subclasses − From the example we can see, it refers to a design in which object of dissimilar type can be treated in the same manner or more specifically two or more classes with method of the same name or common interface because same method(show_affection in below example) is called with either type of objects. So, all animals show affections (show_affection), but they do differently. The “show_affection” behaviors is thus polymorphic in the sense that it acted differently depending on the animal. So, the abstract “animal” concept does not actually “show_affection”, but specific animals(like dogs and cats) have a concrete implementation of the action “show_affection”. Python itself have classes that are polymorphic. Example, the len() function can be used with multiple objects and all return the correct output based on the input parameter. In Python, when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling Super(Subclass, self).method instead of self.method. class Thought(object): def __init__(self): pass def message(self): print("Thought, always come and go") class Advice(Thought): def __init__(self): super(Advice, self).__init__() def message(self): print('Warning: Risk is always involved when you are dealing with market!') If we see from our previous inheritance example, __init__ was located in the parent class in the up ‘cause the child class dog or cat didn’t‘ve __init__ method in it. Python used the inheritance attribute lookup to find __init__ in animal class. When we created the child class, first it will look the __init__ method in the dog class, then it didn’t find it then looked into parent class Animal and found there and called that there. So as our class design became complex we may wish to initialize a instance firstly processing it through parent class constructor and then through child class constructor. In above example- all animals have a name and all dogs a particular breed. We called parent class constructor with super. So dog has its own __init__ but the first thing that happen is we call super. Super is built in function and it is designed to relate a class to its super class or its parent class. In this case we saying that get the super class of dog and pass the dog instance to whatever method we say here the constructor __init__. So in another words we are calling parent class Animal __init__ with the dog object. You may ask why we won’t just say Animal __init__ with the dog instance, we could do this but if the name of animal class were to change, sometime in the future. What if we wanna rearrange the class hierarchy,so the dog inherited from another class. Using super in this case allows us to keep things modular and easy to change and maintain. So in this example we are able to combine general __init__ functionality with more specific functionality. This gives us opportunity to separate common functionality from the specific functionality which can eliminate code duplication and relate class to one another in a way that reflects the system overall design. __init__ is like any other method; it can be inherited __init__ is like any other method; it can be inherited If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one. If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one. As soon as it finds one, Python calls it and stops looking As soon as it finds one, Python calls it and stops looking We can use the super () function to call methods in the parent class. We can use the super () function to call methods in the parent class. We may want to initialize in the parent as well as our own class. We may want to initialize in the parent as well as our own class. As its name indicates, multiple inheritance is Python is when a class inherits from multiple classes. For example, a child inherits personality traits from both parents (Mother and Father). To make a class inherits from multiple parents classes, we write the the names of these classes inside the parentheses to the derived class while defining it. We separate these names with comma. Below is an example of that − >>> class Mother: pass >>> class Father: pass >>> class Child(Mother, Father): pass >>> issubclass(Child, Mother) and issubclass(Child, Father) True Multiple inheritance refers to the ability of inheriting from two or more than two class. The complexity arises as child inherits from parent and parents inherits from the grandparent class. Python climbs an inheriting tree looking for attributes that is being requested to be read from an object. It will check the in the instance, within class then parent class and lastly from the grandparent class. Now the question arises in what order the classes will be searched - breath-first or depth-first. By default, Python goes with the depth-first. That’s is why in the below diagram the Python searches the dothis() method first in class A. So the method resolution order in the below example will be Mro- D→B→A→C Look at the below multiple inheritance diagram − Let’s go through an example to understand the “mro” feature of an Python. Let’s take another example of “diamond shape” multiple inheritance. Above diagram will be considered ambiguous. From our previous example understanding “method resolution order” .i.e. mro will be D→B→A→C→A but it’s not. On getting the second A from the C, Python will ignore the previous A. so the mro will be in this case will be D→B→C→A. Let’s create an example based on above diagram − Simple rule to understand the above output is- if the same class appear in the method resolution order, the earlier appearances of this class will be remove from the method resolution order. In conclusion − Any class can inherit from multiple classes Any class can inherit from multiple classes Python normally uses a “depth-first” order when searching inheriting classes. Python normally uses a “depth-first” order when searching inheriting classes. But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro. But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro. Functions(or methods) are created by def statement. Though methods works in exactly the same way as a function except one point where method first argument is instance object. We can classify methods based on how they behave, like Simple method − defined outside of a class. This function can access class attributes by feeding instance argument: Simple method − defined outside of a class. This function can access class attributes by feeding instance argument: def outside_func((): Instance method − Instance method − def func(self,) Class method − if we need to use class attributes Class method − if we need to use class attributes @classmethod def cfunc(cls,) Static method − do not have any info about the class Static method − do not have any info about the class @staticmethod def sfoo() Till now we have seen the instance method, now is the time to get some insight into the other two methods, The @classmethod decorator, is a builtin function decorator that gets passed the class it was called on or the class of the instance it was called on as first argument. The result of that evaluation shadows your function definition. class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: function that needs to be converted into a class method returns: a class method for function They have the access to this cls argument, it can’t modify object instance state. That would require access to self. It is bound to the class and not the object of the class. It is bound to the class and not the object of the class. Class methods can still modify class state that applies across all instances of the class. Class methods can still modify class state that applies across all instances of the class. A static method takes neither a self nor a cls(class) parameter but it’s free to accept an arbitrary number of other parameters. syntax class C(object): @staticmethod def fun(arg1, arg2, ...): ... returns: a static method for function funself. A static method can neither modify object state nor class state. They are restricted in what data they can access. We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases. We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases. We generally use static methods to create utility functions. We generally use static methods to create utility functions. 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 1937, "s": 1810, "text": "Inheritance and polymorphism – this is a very important concept in Python. You must understand it better if you want to learn." }, { "code": null, "e": 2232, "s": 1937, "text": "One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanisms to achieve the same. Inheritance allows programmer to create a general or a base class first and then later extend it to more specialized class. It allows programmer to write better code." }, { "code": null, "e": 2475, "s": 2232, "text": "Using inheritance you can use or inherit all the data fields and methods available in your base class. Later you can add you own methods and data fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch." }, { "code": null, "e": 2806, "s": 2475, "text": "In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and X is called subclass/child/derived class. One point to note here is that only data fields and method which are not private are accessible by child classes. Private data fields and methods are accessible only inside the class." }, { "code": null, "e": 2844, "s": 2806, "text": "syntax to create a derived class is −" }, { "code": null, "e": 2940, "s": 2844, "text": "class BaseClass:\n Body of base class\nclass DerivedClass(BaseClass):\n Body of derived class\n" }, { "code": null, "e": 2972, "s": 2940, "text": "Now look at the below example −" }, { "code": null, "e": 3392, "s": 2972, "text": "We first created a class called Date and pass the object as an argument, here-object is built-in class provided by Python. Later we created another class called time and called the Date class as an argument. Through this call we get access to all the data and attributes of Date class into the Time class. Because of that when we try to get the get_date method from the Time class object tm we created earlier possible." }, { "code": null, "e": 3426, "s": 3392, "text": "Object.Attribute Lookup Hierarchy" }, { "code": null, "e": 3439, "s": 3426, "text": "The instance" }, { "code": null, "e": 3449, "s": 3439, "text": "The class" }, { "code": null, "e": 3490, "s": 3449, "text": "Any class from which this class inherits" }, { "code": null, "e": 3547, "s": 3490, "text": "Let’s take a closure look into the inheritance example −" }, { "code": null, "e": 3607, "s": 3547, "text": "Let’s create couple of classes to participate in examples −" }, { "code": null, "e": 3641, "s": 3607, "text": "Animal − Class simulate an animal" }, { "code": null, "e": 3666, "s": 3641, "text": "Cat − Subclass of Animal" }, { "code": null, "e": 3691, "s": 3666, "text": "Dog − Subclass of Animal" }, { "code": null, "e": 3801, "s": 3691, "text": "In Python, constructor of class used to create an object (instance), and assign the value for the attributes." }, { "code": null, "e": 3981, "s": 3801, "text": "Constructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes." }, { "code": null, "e": 4162, "s": 3981, "text": "In the above example, we see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class." }, { "code": null, "e": 4392, "s": 4162, "text": "If a subclass try to inherits methods or data from another subclass then it will through an error as we see when Dog class try to call swatstring() methods from that cat class, it throws an error(like AttributeError in our case)." }, { "code": null, "e": 4730, "s": 4392, "text": "Polymorphism is an important feature of class definition in Python that is utilized when you have commonly named methods across classes or subclasses. This permits functions to use entities of different types at different times. So, it provides flexibility and loose coupling so that code can be extended and easily maintained over time." }, { "code": null, "e": 4867, "s": 4730, "text": "This allows functions to use objects of any of these polymorphic classes without needing to be aware of distinctions across the classes." }, { "code": null, "e": 4989, "s": 4867, "text": "Polymorphism can be carried out through inheritance, with subclasses making use of base class methods or overriding them." }, { "code": null, "e": 5139, "s": 4989, "text": "Let understand the concept of polymorphism with our previous inheritance example and add one common method called show_affection in both subclasses −" }, { "code": null, "e": 5441, "s": 5139, "text": "From the example we can see, it refers to a design in which object of dissimilar type can be treated in the same manner or more specifically two or more classes with method of the same name or common interface because same method(show_affection in below example) is called with either type of objects." }, { "code": null, "e": 5805, "s": 5441, "text": "So, all animals show affections (show_affection), but they do differently. The “show_affection” behaviors is thus polymorphic in the sense that it acted differently depending on the animal. So, the abstract “animal” concept does not actually “show_affection”, but specific animals(like dogs and cats) have a concrete implementation of the action “show_affection”." }, { "code": null, "e": 5980, "s": 5805, "text": "Python itself have classes that are polymorphic. Example, the len() function can be used with multiple objects and all return the correct output based on the input parameter." }, { "code": null, "e": 6119, "s": 5980, "text": "In Python, when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling" }, { "code": null, "e": 6172, "s": 6119, "text": "Super(Subclass, self).method instead of self.method." }, { "code": null, "e": 6482, "s": 6172, "text": "class Thought(object):\n def __init__(self):\n pass\n def message(self):\n print(\"Thought, always come and go\")\n\nclass Advice(Thought):\n def __init__(self):\n super(Advice, self).__init__()\n def message(self):\n print('Warning: Risk is always involved when you are dealing with market!')" }, { "code": null, "e": 7089, "s": 6482, "text": "If we see from our previous inheritance example, __init__ was located in the parent class in the up ‘cause the child class dog or cat didn’t‘ve __init__ method in it. Python used the inheritance attribute lookup to find __init__ in animal class. When we created the child class, first it will look the __init__ method in the dog class, then it didn’t find it then looked into parent class Animal and found there and called that there. So as our class design became complex we may wish to initialize a instance firstly processing it through parent class constructor and then through child class constructor." }, { "code": null, "e": 7393, "s": 7089, "text": "In above example- all animals have a name and all dogs a particular breed. We called parent class constructor with super. So dog has its own __init__ but the first thing that happen is we call super. Super is built in function and it is designed to relate a class to its super class or its parent class." }, { "code": null, "e": 7957, "s": 7393, "text": "In this case we saying that get the super class of dog and pass the dog instance to whatever method we say here the constructor __init__. So in another words we are calling parent class Animal __init__ with the dog object. You may ask why we won’t just say Animal __init__ with the dog instance, we could do this but if the name of animal class were to change, sometime in the future. What if we wanna rearrange the class hierarchy,so the dog inherited from another class. Using super in this case allows us to keep things modular and easy to change and maintain." }, { "code": null, "e": 8274, "s": 7957, "text": "So in this example we are able to combine general __init__ functionality with more specific functionality. This gives us opportunity to separate common functionality from the specific functionality which can eliminate code duplication and relate class to one another in a way that reflects the system overall design." }, { "code": null, "e": 8329, "s": 8274, "text": "__init__ is like any other method; it can be inherited" }, { "code": null, "e": 8384, "s": 8329, "text": "__init__ is like any other method; it can be inherited" }, { "code": null, "e": 8495, "s": 8384, "text": "If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one." }, { "code": null, "e": 8606, "s": 8495, "text": "If a class does not have a __init__ constructor, Python will check its parent class to see if it can find one." }, { "code": null, "e": 8665, "s": 8606, "text": "As soon as it finds one, Python calls it and stops looking" }, { "code": null, "e": 8724, "s": 8665, "text": "As soon as it finds one, Python calls it and stops looking" }, { "code": null, "e": 8794, "s": 8724, "text": "We can use the super () function to call methods in the parent class." }, { "code": null, "e": 8864, "s": 8794, "text": "We can use the super () function to call methods in the parent class." }, { "code": null, "e": 8930, "s": 8864, "text": "We may want to initialize in the parent as well as our own class." }, { "code": null, "e": 8996, "s": 8930, "text": "We may want to initialize in the parent as well as our own class." }, { "code": null, "e": 9098, "s": 8996, "text": "As its name indicates, multiple inheritance is Python is when a class inherits from multiple classes." }, { "code": null, "e": 9186, "s": 9098, "text": "For example, a child inherits personality traits from both parents (Mother and Father)." }, { "code": null, "e": 9381, "s": 9186, "text": "To make a class inherits from multiple parents classes, we write the the names of these classes inside the parentheses to the derived class while defining it. We separate these names with comma." }, { "code": null, "e": 9411, "s": 9381, "text": "Below is an example of that −" }, { "code": null, "e": 9572, "s": 9411, "text": ">>> class Mother:\n pass\n\n>>> class Father:\n pass\n\n>>> class Child(Mother, Father):\n pass\n\n>>> issubclass(Child, Mother) and issubclass(Child, Father)\nTrue" }, { "code": null, "e": 10119, "s": 9572, "text": "Multiple inheritance refers to the ability of inheriting from two or more than two class. The complexity arises as child inherits from parent and parents inherits from the grandparent class. Python climbs an inheriting tree looking for attributes that is being requested to be read from an object. It will check the in the instance, within class then parent class and lastly from the grandparent class. Now the question arises in what order the classes will be searched - breath-first or depth-first. By default, Python goes with the depth-first." }, { "code": null, "e": 10272, "s": 10119, "text": "That’s is why in the below diagram the Python searches the dothis() method first in class A. So the method resolution order in the below example will be" }, { "code": null, "e": 10285, "s": 10272, "text": "Mro- D→B→A→C" }, { "code": null, "e": 10334, "s": 10285, "text": "Look at the below multiple inheritance diagram −" }, { "code": null, "e": 10408, "s": 10334, "text": "Let’s go through an example to understand the “mro” feature of an Python." }, { "code": null, "e": 10476, "s": 10408, "text": "Let’s take another example of “diamond shape” multiple inheritance." }, { "code": null, "e": 10748, "s": 10476, "text": "Above diagram will be considered ambiguous. From our previous example understanding “method resolution order” .i.e. mro will be D→B→A→C→A but it’s not. On getting the second A from the C, Python will ignore the previous A. so the mro will be in this case will be D→B→C→A." }, { "code": null, "e": 10797, "s": 10748, "text": "Let’s create an example based on above diagram −" }, { "code": null, "e": 10988, "s": 10797, "text": "Simple rule to understand the above output is- if the same class appear in the method resolution order, the earlier appearances of this class will be remove from the method resolution order." }, { "code": null, "e": 11004, "s": 10988, "text": "In conclusion −" }, { "code": null, "e": 11048, "s": 11004, "text": "Any class can inherit from multiple classes" }, { "code": null, "e": 11092, "s": 11048, "text": "Any class can inherit from multiple classes" }, { "code": null, "e": 11170, "s": 11092, "text": "Python normally uses a “depth-first” order when searching inheriting classes." }, { "code": null, "e": 11248, "s": 11170, "text": "Python normally uses a “depth-first” order when searching inheriting classes." }, { "code": null, "e": 11366, "s": 11248, "text": "But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro." }, { "code": null, "e": 11484, "s": 11366, "text": "But when two classes inherit from the same class, Python eliminates the first appearances of that class from the mro." }, { "code": null, "e": 11536, "s": 11484, "text": "Functions(or methods) are created by def statement." }, { "code": null, "e": 11660, "s": 11536, "text": "Though methods works in exactly the same way as a function except one point where method first argument is instance object." }, { "code": null, "e": 11715, "s": 11660, "text": "We can classify methods based on how they behave, like" }, { "code": null, "e": 11831, "s": 11715, "text": "Simple method − defined outside of a class. This function can access class attributes by feeding instance argument:" }, { "code": null, "e": 11947, "s": 11831, "text": "Simple method − defined outside of a class. This function can access class attributes by feeding instance argument:" }, { "code": null, "e": 11969, "s": 11947, "text": "def outside_func(():\n" }, { "code": null, "e": 11988, "s": 11969, "text": "Instance method − " }, { "code": null, "e": 12007, "s": 11988, "text": "Instance method − " }, { "code": null, "e": 12024, "s": 12007, "text": "def func(self,)\n" }, { "code": null, "e": 12074, "s": 12024, "text": "Class method − if we need to use class attributes" }, { "code": null, "e": 12124, "s": 12074, "text": "Class method − if we need to use class attributes" }, { "code": null, "e": 12157, "s": 12124, "text": " @classmethod\ndef cfunc(cls,)\n" }, { "code": null, "e": 12210, "s": 12157, "text": "Static method − do not have any info about the class" }, { "code": null, "e": 12263, "s": 12210, "text": "Static method − do not have any info about the class" }, { "code": null, "e": 12295, "s": 12263, "text": " @staticmethod\ndef sfoo()\n" }, { "code": null, "e": 12402, "s": 12295, "text": "Till now we have seen the instance method, now is the time to get some insight into the other two methods," }, { "code": null, "e": 12635, "s": 12402, "text": "The @classmethod decorator, is a builtin function decorator that gets passed the class it was called on or the class of the instance it was called on as first argument. The result of that evaluation shadows your function definition." }, { "code": null, "e": 12812, "s": 12635, "text": "class C(object):\n @classmethod\n def fun(cls, arg1, arg2, ...):\n ....\nfun: function that needs to be converted into a class method\nreturns: a class method for function\n" }, { "code": null, "e": 12929, "s": 12812, "text": "They have the access to this cls argument, it can’t modify object instance state. That would require access to self." }, { "code": null, "e": 12987, "s": 12929, "text": "It is bound to the class and not the object of the class." }, { "code": null, "e": 13045, "s": 12987, "text": "It is bound to the class and not the object of the class." }, { "code": null, "e": 13136, "s": 13045, "text": "Class methods can still modify class state that applies across all instances of the class." }, { "code": null, "e": 13227, "s": 13136, "text": "Class methods can still modify class state that applies across all instances of the class." }, { "code": null, "e": 13356, "s": 13227, "text": "A static method takes neither a self nor a cls(class) parameter but it’s free to accept an arbitrary number of other parameters." }, { "code": null, "e": 13363, "s": 13356, "text": "syntax" }, { "code": null, "e": 13481, "s": 13363, "text": "class C(object):\n @staticmethod\n def fun(arg1, arg2, ...):\n ...\nreturns: a static method for function funself.\n" }, { "code": null, "e": 13546, "s": 13481, "text": "A static method can neither modify object state nor class state." }, { "code": null, "e": 13596, "s": 13546, "text": "They are restricted in what data they can access." }, { "code": null, "e": 13741, "s": 13596, "text": "We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases." }, { "code": null, "e": 13886, "s": 13741, "text": "We generally use class method to create factory methods. Factory methods return class object (similar to a constructor) for different use cases." }, { "code": null, "e": 13947, "s": 13886, "text": "We generally use static methods to create utility functions." }, { "code": null, "e": 14008, "s": 13947, "text": "We generally use static methods to create utility functions." }, { "code": null, "e": 14043, "s": 14008, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 14063, "s": 14043, "text": " Harshit Srivastava" }, { "code": null, "e": 14096, "s": 14063, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 14127, "s": 14096, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 14159, "s": 14127, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 14180, "s": 14159, "text": " Sandip Bhattacharya" }, { "code": null, "e": 14213, "s": 14180, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 14233, "s": 14213, "text": " Pranjal Srivastava" }, { "code": null, "e": 14264, "s": 14233, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 14281, "s": 14264, "text": " Frahaan Hussain" }, { "code": null, "e": 14316, "s": 14281, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14333, "s": 14316, "text": " Abhilash Nelson" }, { "code": null, "e": 14340, "s": 14333, "text": " Print" }, { "code": null, "e": 14351, "s": 14340, "text": " Add Notes" } ]
Explain Regular Expression "\w" Metacharacter in Java
The subexpression/metacharacter “\w” matches the word characters i.e. a to z and A to Z and 0 to 9. import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\\w to"; String input = "Hello how are you welcome to Tutorialspoint"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } } Number of matches: 1 Following example reads 5 string values and prints those that contain word characters − import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatchWordCharacters { public static void main( String args[] ) { String regex = "\\w.*$"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); System.out.println("Strings that contain word characters: "); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.matches()) { System.out.println(m.group()); } } } } Enter 5 input strings: sample test test23 hello## #$%&& Strings that contain word characters: sample test test23 hello##
[ { "code": null, "e": 1162, "s": 1062, "text": "The subexpression/metacharacter “\\w” matches the word characters i.e. a to z and A to Z and 0 to 9." }, { "code": null, "e": 1610, "s": 1162, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexExample {\n public static void main( String args[] ) {\n String regex = \"\\\\w to\";\n String input = \"Hello how are you welcome to Tutorialspoint\";\n Pattern p = Pattern.compile(regex);\n Matcher m = p.matcher(input);\n int count = 0;\n while(m.find()) {\n count++;\n }\n System.out.println(\"Number of matches: \"+count);\n }\n}" }, { "code": null, "e": 1631, "s": 1610, "text": "Number of matches: 1" }, { "code": null, "e": 1719, "s": 1631, "text": "Following example reads 5 string values and prints those that contain word characters −" }, { "code": null, "e": 2479, "s": 1719, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MatchWordCharacters {\n public static void main( String args[] ) {\n String regex = \"\\\\w.*$\";\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter 5 input strings: \");\n String input[] = new String[5];\n for (int i=0; i<5; i++) {\n input[i] = sc.nextLine();\n }\n //Creating a Pattern object\n Pattern p = Pattern.compile(regex);\n System.out.println(\"Strings that contain word characters: \");\n for(int i=0; i<5;i++) {\n //Creating a Matcher object\n Matcher m = p.matcher(input[i]);\n if(m.matches()) {\n System.out.println(m.group());\n }\n }\n }\n}" }, { "code": null, "e": 2600, "s": 2479, "text": "Enter 5 input strings:\nsample\ntest\ntest23\nhello##\n#$%&&\nStrings that contain word characters:\nsample\ntest\ntest23\nhello##" } ]
MapListHandler Class
The org.apache.commons.dbutils.MapListHandler is the implementation of ResultSetHandler interface and is responsible to convert the ResultSet rows into list of Maps. This class is thread safe. Following is the declaration for org.apache.commons.dbutils.MapListHandler class − public class MapListHandler extends AbstractListHandler<Map<String,Object>> Step 1 − Create a connection object. Step 1 − Create a connection object. Step 2 − Get implementation of ResultSetHandler as MapListHandler object. Step 2 − Get implementation of ResultSetHandler as MapListHandler object. Step 3 − Pass resultSetHandler to QueryRunner object, and make database operations. Step 3 − Pass resultSetHandler to QueryRunner object, and make database operations. Following example will demonstrate how to read a list of records using MapListHandler class. We'll read available records in Employees Table as list of maps. List<Map<String, Object>> result = queryRunner.query(conn, "SELECT * FROM employees", new MapListHandler()); Where, resultHandler − MapListHandler object to map result sets to list of maps. resultHandler − MapListHandler object to map result sets to list of maps. queryRunner − QueryRunner object to read employee object from database. queryRunner − QueryRunner object to read employee object from database. To understand the above-mentioned concepts related to DBUtils, let us write an example which will run a read query. To write our example, let us create a sample application. Following is the content of the Employee.java. public class Employee { private int id; private int age; private String first; private String last; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFirst() { return first; } public void setFirst(String first) { this.first = first; } public String getLast() { return last; } public void setLast(String last) { this.last = last; } } Following is the content of the MainApp.java file. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; public class MainApp { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/emp"; // Database credentials static final String USER = "root"; static final String PASS = "admin"; public static void main(String[] args) throws SQLException { Connection conn = null; QueryRunner queryRunner = new QueryRunner(); //Step 1: Register JDBC driver DbUtils.loadDriver(JDBC_DRIVER); //Step 2: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); try { List<Map<String, Object>> result = queryRunner.query( conn, "SELECT * FROM employees", new MapListHandler()); System.out.println(result); } finally { DbUtils.close(conn); } } } Once you are done creating the source files, let us run the application. If everything is fine with your application, it will print the following message. Connecting to database... [{id=100, age=18, first=Zara, last=Ali}, {id=101, age=25, first=Mahnaz, last=Fatma}, {id=102, age=30, first=Zaid, last=Khan}, {id=103, age=33, first=Sumit, last=Mittal}] Print Add Notes Bookmark this page
[ { "code": null, "e": 2345, "s": 2152, "text": "The org.apache.commons.dbutils.MapListHandler is the implementation of ResultSetHandler interface and is responsible to convert the ResultSet rows into list of Maps. This class is thread safe." }, { "code": null, "e": 2428, "s": 2345, "text": "Following is the declaration for org.apache.commons.dbutils.MapListHandler class −" }, { "code": null, "e": 2507, "s": 2428, "text": "public class MapListHandler\n extends AbstractListHandler<Map<String,Object>>" }, { "code": null, "e": 2544, "s": 2507, "text": "Step 1 − Create a connection object." }, { "code": null, "e": 2581, "s": 2544, "text": "Step 1 − Create a connection object." }, { "code": null, "e": 2655, "s": 2581, "text": "Step 2 − Get implementation of ResultSetHandler as MapListHandler object." }, { "code": null, "e": 2729, "s": 2655, "text": "Step 2 − Get implementation of ResultSetHandler as MapListHandler object." }, { "code": null, "e": 2813, "s": 2729, "text": "Step 3 − Pass resultSetHandler to QueryRunner object, and make database operations." }, { "code": null, "e": 2897, "s": 2813, "text": "Step 3 − Pass resultSetHandler to QueryRunner object, and make database operations." }, { "code": null, "e": 3055, "s": 2897, "text": "Following example will demonstrate how to read a list of records using MapListHandler class. We'll read available records in Employees Table as list of maps." }, { "code": null, "e": 3165, "s": 3055, "text": "List<Map<String, Object>> result = queryRunner.query(conn, \"SELECT * FROM employees\", new MapListHandler());\n" }, { "code": null, "e": 3172, "s": 3165, "text": "Where," }, { "code": null, "e": 3246, "s": 3172, "text": "resultHandler − MapListHandler object to map result sets to list of maps." }, { "code": null, "e": 3320, "s": 3246, "text": "resultHandler − MapListHandler object to map result sets to list of maps." }, { "code": null, "e": 3392, "s": 3320, "text": "queryRunner − QueryRunner object to read employee object from database." }, { "code": null, "e": 3464, "s": 3392, "text": "queryRunner − QueryRunner object to read employee object from database." }, { "code": null, "e": 3638, "s": 3464, "text": "To understand the above-mentioned concepts related to DBUtils, let us write an example which will run a read query. To write our example, let us create a sample application." }, { "code": null, "e": 3685, "s": 3638, "text": "Following is the content of the Employee.java." }, { "code": null, "e": 4255, "s": 3685, "text": "public class Employee {\n private int id;\n private int age;\n private String first;\n private String last;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getFirst() {\n return first;\n }\n public void setFirst(String first) {\n this.first = first;\n }\n public String getLast() {\n return last;\n }\n public void setLast(String last) {\n this.last = last;\n }\n}" }, { "code": null, "e": 4306, "s": 4255, "text": "Following is the content of the MainApp.java file." }, { "code": null, "e": 5538, "s": 4306, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.dbutils.DbUtils;\nimport org.apache.commons.dbutils.QueryRunner;\nimport org.apache.commons.dbutils.handlers.MapListHandler;\n\npublic class MainApp {\n // JDBC driver name and database URL\n static final String JDBC_DRIVER = \"com.mysql.jdbc.Driver\"; \n static final String DB_URL = \"jdbc:mysql://localhost:3306/emp\";\n\n // Database credentials\n static final String USER = \"root\";\n static final String PASS = \"admin\";\n\n public static void main(String[] args) throws SQLException {\n Connection conn = null;\n QueryRunner queryRunner = new QueryRunner();\n \n //Step 1: Register JDBC driver\n DbUtils.loadDriver(JDBC_DRIVER);\n\n //Step 2: Open a connection\n System.out.println(\"Connecting to database...\");\n conn = DriverManager.getConnection(DB_URL, USER, PASS); \n\n try {\n List<Map<String, Object>> result = queryRunner.query(\n conn, \"SELECT * FROM employees\", new MapListHandler()); \n System.out.println(result);\n } finally {\n DbUtils.close(conn);\n } \n }\n}" }, { "code": null, "e": 5693, "s": 5538, "text": "Once you are done creating the source files, let us run the application. If everything is fine with your application, it will print the following message." }, { "code": null, "e": 5893, "s": 5693, "text": "Connecting to database...\n[{id=100, age=18, first=Zara, last=Ali}, \n{id=101, age=25, first=Mahnaz, last=Fatma}, \n{id=102, age=30, first=Zaid, last=Khan}, \n{id=103, age=33, first=Sumit, last=Mittal}]\n" }, { "code": null, "e": 5900, "s": 5893, "text": " Print" }, { "code": null, "e": 5911, "s": 5900, "text": " Add Notes" } ]
How to define a class in Arduino?
You can define a class in Arduino just like in C, with public and private variables and methods.The example below demonstrates the definition of a Student class, which has the constructor,two methods (add_science_marks and get_roll_no) and 3 private variables, _division, _roll_no and _science_marks. class Student { public: Student(char division, int roll_no); void add_science_marks(int marks); int get_roll_no(); private: char _division; int _roll_no; int _science_marks; }; Student::Student(char division, int roll_no){ _division = division; _roll_no = roll_no; } void Student::add_science_marks(int marks){ _science_marks = marks; } int Student::get_roll_no(){ return _roll_no; } void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); Student Yash('A',26); Serial.print("Roll number of the student is: "); Serial.println(Yash.get_roll_no()); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is shown below − The class declaration in the above code could have well been within a Student.h file, and the function definitions within Student.cpp file. This way, you can define your own library in Arduino.
[ { "code": null, "e": 1363, "s": 1062, "text": "You can define a class in Arduino just like in C, with public and private variables and methods.The example below demonstrates the definition of a Student class, which has the constructor,two methods (add_science_marks and get_roll_no) and 3 private variables, _division, _roll_no and _science_marks." }, { "code": null, "e": 2095, "s": 1363, "text": "class Student\n{\n public:\n Student(char division, int roll_no);\n void add_science_marks(int marks);\n int get_roll_no();\n private:\n char _division;\n int _roll_no;\n int _science_marks;\n};\n\nStudent::Student(char division, int roll_no){\n _division = division;\n _roll_no = roll_no;\n}\n\nvoid Student::add_science_marks(int marks){\n _science_marks = marks;\n}\n\nint Student::get_roll_no(){\n return _roll_no;\n}\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n Student Yash('A',26);\n\n Serial.print(\"Roll number of the student is: \");\n Serial.println(Yash.get_roll_no());\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2138, "s": 2095, "text": "The Serial Monitor output is shown below −" }, { "code": null, "e": 2332, "s": 2138, "text": "The class declaration in the above code could have well been within a Student.h file, and the function definitions within Student.cpp file. This way, you can define your own library in Arduino." } ]
How to handle BigData Files on Low Memory? | by Puneet Grover | Towards Data Science
This is one of the post from my posts from Tackle category, which can be found on my github repo here. (Edit-31/01/2019) — Added info on dask.distributed.LocalCluster for BigData (Edit-12/4/2019) — Added new sections on dataset size reduction and File Type Usage [Not Complete yet, still you can take ideas from there to apply.] IntroductionColumn Memory Reduction (pd.Series.astype()) [:Not Completed]File Types (for less memory usage) [:Not Completed]Data ExplorationPreprocessingIncremental Learning (with Pandas)Dask (Explore+Prep+FitPredict)Further ReadingReferences Introduction Column Memory Reduction (pd.Series.astype()) [:Not Completed] File Types (for less memory usage) [:Not Completed] Data Exploration Preprocessing Incremental Learning (with Pandas) Dask (Explore+Prep+FitPredict) Further Reading References NOTE:This post goes along with Jupyter Notebook available in my Repo on Github:[HowToHandleBigData] (with dummy data)and Kaggle:[HowToHandleBigData] (with Kaggle competition data) With data size increasing exponentially, we are not able to fit our data, and even our models, within our PC’s memory. And we all can’t afford to buy a high end assembled desktop beasts. For example a recent kaggle competition has dataset which is not able to fit in 17GB of RAM in kaggle kernels or in Colab. It has nearly 2 million rows, and to top that some columns have very large JSON data as strings. How should we tackle this? To whom can we turn to? Incremental Learning and/or Dask comes to rescue! You might already know that neural networks are Incremental Learners by nature, so we can tackle this problem there. And many of sklearn’s models provide a method called partial_fit using which we can fit to model in batches. And some of Boosting libraries like XGBoost and LightGBM provide a way to learn incrementally to tackle big data. Here we will look into incremental solutions provided by some of the Boosting algorithms. And then we will use Dask on the same dataset and use its models to predict. ^ # I don't know who the original author of this function is,# but you can use this function to reduce memory# consumption by 60-70%!def reduce_mem_usage(df): """ iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024**2 print(('Memory usage of dataframe is {:.2f}' 'MB').format(start_mem)) for col in df.columns: col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max <\ np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max <\ np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max <\ np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max <\ np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max <\ np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max <\ np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() / 1024**2 print(('Memory usage after optimization is: {:.2f}' 'MB').format(end_mem)) print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem)) return df TK ^ HDF5, parquet etc. Note: If you don’t want to fall into this section, you can just look into HDF5. That should be sufficient. And move to next section. Hierarchical Data Format — Wikipedia (HDF5) Apache Parquet Hadoop File Formats: Its not just CSV anymore — Kevin Haas (Don’t scare away after reading Hadoop, you can get away with just using Parquet format only and by using pd.DataFrame.to_parquet and pd.DataFrame.read_parquet methods.) Also, if you are interested: Parquet vs Avro [I would recommend you to watch it anyway.] TK Firstly we will get a feel of what our data looks like by looking at first few rows by using the command: part = pd.read_csv("train.csv.zip", nrows=10)part.head() By this you will have basic info on how different columns are structured, how to process each column etc. Make a lists of different type of columns as numerical_columns, obj_columns, dictionary_columns, etc. which will hold all corresponding columns. Now to explore data we will go column by column like this: # For dictionary columns you can do:# 'idx' is index of corresponding column in DataFrame.# You can find it by using np.where(col==df.columns)for col in dictionary_columns: df = pd.read_csv("train.csv.zip", usecols = [idx], converters={col: json.loads}) column_as_df = json_normalize(df[col]) # ... plot each column ... # ... check if you want to drop any column ... You can keep a dictionary with all the column names as keys and methods applied to it in a list as a pipeline for that column. You can also pickle dump your dictionary, for future use: with open("preprocessing_pipeline.pickle", "wb") as fle: pickle.dump(preprocessing_pipeline, fle) If even one of the column is too big for your memory, which actually was case for one of the rows in kaggle competition I mentioned above. You can even open one column Incrementally and can do basic stuff like calculating mean, standard deviation etc. manually. Or you can also use Dask for it and use nearly the same API as pandas and calculate them using it. See last section for Dask. For preprocessing data we will make use of the dictionary we made earlier, which has info on which columns we want to keep (as keys) and what methods to apply to each column (as values), to make a method. This method will be called for each batch of data during the incremental learning process. Now one thing to notice here is that we fitted methods (like LabelEncoder’s, Scalars’s etc.) during exploration of whole data column and we will use that to transform data at every incremental step here. Because, in each batch, there might be some data missing and if we had used different LabelEncoder’s, Scalar’s etc. for each batch, these methods wouldn’t have given same result for same category (say). That’s why we already have fitted to whole columns during exploration. Here is how you can preprocess data: def preprocess(df): df.reset_index(drop=True, inplace=True) # For dict columns: for col in dict_columns: col_df = json_normalize(df[col]) # json.loads during pd.read_csv to convert string to dict. col_df.columns = [f"{col}.{subcolumn}" for subcolumn in col_df.columns] # Select all columns which we selected before. selected_columns = [c for c in dictionary.keys() if c in col_df.columns()] to_drop = [c for c in col_df.columns if not in selected_columns] # Drop all previously unselected columns. col_df = col_df.drop(to_drop, axis=1) df = df.drop(col, axis=1).merge(col_df, right_index=True, left_index=True) # And so on... # And then apply all Scalars, LabelEncoder's to all columns selected... return df To read data file incrementally using pandas, you have to use a parameter chunksize which specifies number of rows to read/write at a time. incremental_dataframe = pd.read_csv("train.csv", chunksize=100000) # Number of lines to read.# This method will return a sequential file reader (TextFileReader)# reading 'chunksize' lines every time. To read file from # starting again, you will have to call this method again. Then you can train on your data incrementally using XGBoost1 or LightGBM. For LightGBM you have to pass in a argument keep_training_booster=True to its .train method and three arguments to XGBoost's .train method. # First one necessary for incremental learning:lgb_params = { 'keep_training_booster': True, 'objective': 'regression', 'verbosity': 100,}# First three are for incremental learning:xgb_params = { 'update':'refresh', 'process_type': 'update', 'refresh_leaf': True, 'silent': False, } On each step we will save our estimator and then pass it as an argument during next step. # For saving regressor for next use.lgb_estimator = Nonexgb_estimator = Nonefor df in incremental_dataframe: df = preprocess(df) xtrain, ytrain, xvalid, yvalid = # Split data as you like lgb_estimator = lgb.train(lgb_params, # Pass partially trained model: init_model=lgb_estimator, train_set=lgb.Dataset(xtrain, ytrain), valid_sets=lgb.Dataset(xvalid, yvalid), num_boost_round=10) xgb_model = xgb.train(xgb_params, dtrain=xgb.DMatrix(xtrain, ytrain), evals=(xgb.DMatrix(xvalid, yvalid),"Valid"), # Pass partially trained model: xgb_model = xgb_estimator) del df, xtrain, ytrain, xvalid, yvalid gc.collect() CatBoost's incremental learning method is in progress.2 To speed things up a bit more and if your chunks a still sufficiently big, you can parallelize your preprocessing method using Python's multiprocessing library functions like this: n_jobs = 4for df in incremental_dataframe: p = Pool(n_jobs) f_ = p.map(preprocess, np.array_split(df, n_jobs)) f_ = pd.concat(f_, axis=0, ignore_index=True) p.close() p.join() # And then your model training ... For an introduction on Parallel programming in Python read my post here. Dask helps to tap into big data resources in a sequentially-parallel manner. For introduction to Dask read my post here. You can apply functions from pandas API here in a similar manner. You can check if there is some null value like this: df.isnull().sum().compute() To scale a column you can convert them to array and use its Scaler functions in a similar manner: rsc = dask_ml.preprocessing.RobustScaler()result = rsc.fit_transform(X[:,i].reshape(-1, 1)) # for ith column To handle JSON or any other semi structured data like log files etc. you can use functions provided by Dask's Bag container. df[key] = df[dict_col].to_bag().pluck(key).to_dataframe().iloc[:,0] And after preprocessing you can use one of Dask's models to train your data. For full code readDask section in Jupyter Notebook here. Note:You should only use Dask in case of Big Data, where it is not able to fit in your memory. Otherwise in-memory learning with pandas and sklearn will be lot faster.Note: (Local Cluster)You can perform almost any BigData related query/tasks with the help of LocalCluster. You can, specifically, use 'memory_limit' parameter to constrict Dask's memory usage to a specific amount. Also, at times you might notice that Dask is exceeding memory use, even though it is dividing tasks. It could be happening to you because of the function you are trying to use on your dataset wants most of your data for processing, and multiprocessing can make things worse as all workers might try to copy dataset to memory. This can happen in aggregating cases.In these cases you can use Dask.distributed.LocalCluster parameters and pass them to Client() to make a LocalCluster using cores of your Local machines.from dask.distributed import Client, LocalClusterclient = Client(n_workers=1, threads_per_worker=1, processes=False, memory_limit='25GB', scheduler_port=0, silence_logs=False, diagnostics_port=0)client'scheduler_port=0' and 'diagnostics_port=0' will choose random port number for this particular client. With 'processes=False' dask's client won't copy dataset, which would have happened for every process you might have made.You can tune your client as per your needs or limitations, and for more info you can look into parameters of LocalCluster.You can also use multiple clients on same machine at different ports. https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-updhttps://github.com/dmlc/xgboost/issues/3055#issuecomment-359505122https://www.kaggle.com/ogrellier/create-extracted-json-fields-datasethttps://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.pyReducing DataFrame memory size by ~65% | Kaggle7 Ways to Handle Large Data Files for Machine Learning — Machine Learning Mastery https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-upd https://github.com/dmlc/xgboost/issues/3055#issuecomment-359505122 https://www.kaggle.com/ogrellier/create-extracted-json-fields-dataset https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.py Reducing DataFrame memory size by ~65% | Kaggle 7 Ways to Handle Large Data Files for Machine Learning — Machine Learning Mastery https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-updhttps://www.kaggle.com/ogrellier/create-extracted-json-fields-datasethttps://gist.github.com/goraj/6df8f22a49534e042804a299d81bf2d6https://github.com/dmlc/xgboost/issues/3055https://github.com/catboost/catboost/issues/464https://github.com/Microsoft/LightGBM/issues/987https://gist.github.com/ylogx/53fef94cc61d6a3e9b3eb900482f41e0 https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-upd https://www.kaggle.com/ogrellier/create-extracted-json-fields-dataset https://gist.github.com/goraj/6df8f22a49534e042804a299d81bf2d6 https://github.com/dmlc/xgboost/issues/3055 https://github.com/catboost/catboost/issues/464 https://github.com/Microsoft/LightGBM/issues/987 https://gist.github.com/ylogx/53fef94cc61d6a3e9b3eb900482f41e0 Suggestions and reviews are welcome.Thank you for reading! Signed: Some rights reserved
[ { "code": null, "e": 274, "s": 171, "text": "This is one of the post from my posts from Tackle category, which can be found on my github repo here." }, { "code": null, "e": 350, "s": 274, "text": "(Edit-31/01/2019) — Added info on dask.distributed.LocalCluster for BigData" }, { "code": null, "e": 500, "s": 350, "text": "(Edit-12/4/2019) — Added new sections on dataset size reduction and File Type Usage [Not Complete yet, still you can take ideas from there to apply.]" }, { "code": null, "e": 743, "s": 500, "text": "IntroductionColumn Memory Reduction (pd.Series.astype()) [:Not Completed]File Types (for less memory usage) [:Not Completed]Data ExplorationPreprocessingIncremental Learning (with Pandas)Dask (Explore+Prep+FitPredict)Further ReadingReferences" }, { "code": null, "e": 756, "s": 743, "text": "Introduction" }, { "code": null, "e": 818, "s": 756, "text": "Column Memory Reduction (pd.Series.astype()) [:Not Completed]" }, { "code": null, "e": 870, "s": 818, "text": "File Types (for less memory usage) [:Not Completed]" }, { "code": null, "e": 887, "s": 870, "text": "Data Exploration" }, { "code": null, "e": 901, "s": 887, "text": "Preprocessing" }, { "code": null, "e": 936, "s": 901, "text": "Incremental Learning (with Pandas)" }, { "code": null, "e": 967, "s": 936, "text": "Dask (Explore+Prep+FitPredict)" }, { "code": null, "e": 983, "s": 967, "text": "Further Reading" }, { "code": null, "e": 994, "s": 983, "text": "References" }, { "code": null, "e": 1175, "s": 994, "text": "NOTE:This post goes along with Jupyter Notebook available in my Repo on Github:[HowToHandleBigData] (with dummy data)and Kaggle:[HowToHandleBigData] (with Kaggle competition data)" }, { "code": null, "e": 1362, "s": 1175, "text": "With data size increasing exponentially, we are not able to fit our data, and even our models, within our PC’s memory. And we all can’t afford to buy a high end assembled desktop beasts." }, { "code": null, "e": 1633, "s": 1362, "text": "For example a recent kaggle competition has dataset which is not able to fit in 17GB of RAM in kaggle kernels or in Colab. It has nearly 2 million rows, and to top that some columns have very large JSON data as strings. How should we tackle this? To whom can we turn to?" }, { "code": null, "e": 1683, "s": 1633, "text": "Incremental Learning and/or Dask comes to rescue!" }, { "code": null, "e": 2023, "s": 1683, "text": "You might already know that neural networks are Incremental Learners by nature, so we can tackle this problem there. And many of sklearn’s models provide a method called partial_fit using which we can fit to model in batches. And some of Boosting libraries like XGBoost and LightGBM provide a way to learn incrementally to tackle big data." }, { "code": null, "e": 2190, "s": 2023, "text": "Here we will look into incremental solutions provided by some of the Boosting algorithms. And then we will use Dask on the same dataset and use its models to predict." }, { "code": null, "e": 2192, "s": 2190, "text": "^" }, { "code": null, "e": 4245, "s": 2192, "text": "# I don't know who the original author of this function is,# but you can use this function to reduce memory# consumption by 60-70%!def reduce_mem_usage(df): \"\"\" iterate through all the columns of a dataframe and modify the data type to reduce memory usage. \"\"\" start_mem = df.memory_usage().sum() / 1024**2 print(('Memory usage of dataframe is {:.2f}' 'MB').format(start_mem)) for col in df.columns: col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_max = df[col].max() if str(col_type)[:3] == 'int': if c_min > np.iinfo(np.int8).min and c_max <\\ np.iinfo(np.int8).max: df[col] = df[col].astype(np.int8) elif c_min > np.iinfo(np.int16).min and c_max <\\ np.iinfo(np.int16).max: df[col] = df[col].astype(np.int16) elif c_min > np.iinfo(np.int32).min and c_max <\\ np.iinfo(np.int32).max: df[col] = df[col].astype(np.int32) elif c_min > np.iinfo(np.int64).min and c_max <\\ np.iinfo(np.int64).max: df[col] = df[col].astype(np.int64) else: if c_min > np.finfo(np.float16).min and c_max <\\ np.finfo(np.float16).max: df[col] = df[col].astype(np.float16) elif c_min > np.finfo(np.float32).min and c_max <\\ np.finfo(np.float32).max: df[col] = df[col].astype(np.float32) else: df[col] = df[col].astype(np.float64) else: df[col] = df[col].astype('category') end_mem = df.memory_usage().sum() / 1024**2 print(('Memory usage after optimization is: {:.2f}' 'MB').format(end_mem)) print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem)) return df" }, { "code": null, "e": 4248, "s": 4245, "text": "TK" }, { "code": null, "e": 4250, "s": 4248, "text": "^" }, { "code": null, "e": 4269, "s": 4250, "text": "HDF5, parquet etc." }, { "code": null, "e": 4402, "s": 4269, "text": "Note: If you don’t want to fall into this section, you can just look into HDF5. That should be sufficient. And move to next section." }, { "code": null, "e": 4446, "s": 4402, "text": "Hierarchical Data Format — Wikipedia (HDF5)" }, { "code": null, "e": 4461, "s": 4446, "text": "Apache Parquet" }, { "code": null, "e": 4690, "s": 4461, "text": "Hadoop File Formats: Its not just CSV anymore — Kevin Haas (Don’t scare away after reading Hadoop, you can get away with just using Parquet format only and by using pd.DataFrame.to_parquet and pd.DataFrame.read_parquet methods.)" }, { "code": null, "e": 4779, "s": 4690, "text": "Also, if you are interested: Parquet vs Avro [I would recommend you to watch it anyway.]" }, { "code": null, "e": 4782, "s": 4779, "text": "TK" }, { "code": null, "e": 4888, "s": 4782, "text": "Firstly we will get a feel of what our data looks like by looking at first few rows by using the command:" }, { "code": null, "e": 4945, "s": 4888, "text": "part = pd.read_csv(\"train.csv.zip\", nrows=10)part.head()" }, { "code": null, "e": 5196, "s": 4945, "text": "By this you will have basic info on how different columns are structured, how to process each column etc. Make a lists of different type of columns as numerical_columns, obj_columns, dictionary_columns, etc. which will hold all corresponding columns." }, { "code": null, "e": 5255, "s": 5196, "text": "Now to explore data we will go column by column like this:" }, { "code": null, "e": 5634, "s": 5255, "text": "# For dictionary columns you can do:# 'idx' is index of corresponding column in DataFrame.# You can find it by using np.where(col==df.columns)for col in dictionary_columns: df = pd.read_csv(\"train.csv.zip\", usecols = [idx], converters={col: json.loads}) column_as_df = json_normalize(df[col]) # ... plot each column ... # ... check if you want to drop any column ..." }, { "code": null, "e": 5819, "s": 5634, "text": "You can keep a dictionary with all the column names as keys and methods applied to it in a list as a pipeline for that column. You can also pickle dump your dictionary, for future use:" }, { "code": null, "e": 5918, "s": 5819, "text": "with open(\"preprocessing_pipeline.pickle\", \"wb\") as fle: pickle.dump(preprocessing_pipeline, fle)" }, { "code": null, "e": 6306, "s": 5918, "text": "If even one of the column is too big for your memory, which actually was case for one of the rows in kaggle competition I mentioned above. You can even open one column Incrementally and can do basic stuff like calculating mean, standard deviation etc. manually. Or you can also use Dask for it and use nearly the same API as pandas and calculate them using it. See last section for Dask." }, { "code": null, "e": 6511, "s": 6306, "text": "For preprocessing data we will make use of the dictionary we made earlier, which has info on which columns we want to keep (as keys) and what methods to apply to each column (as values), to make a method." }, { "code": null, "e": 6602, "s": 6511, "text": "This method will be called for each batch of data during the incremental learning process." }, { "code": null, "e": 7080, "s": 6602, "text": "Now one thing to notice here is that we fitted methods (like LabelEncoder’s, Scalars’s etc.) during exploration of whole data column and we will use that to transform data at every incremental step here. Because, in each batch, there might be some data missing and if we had used different LabelEncoder’s, Scalar’s etc. for each batch, these methods wouldn’t have given same result for same category (say). That’s why we already have fitted to whole columns during exploration." }, { "code": null, "e": 7117, "s": 7080, "text": "Here is how you can preprocess data:" }, { "code": null, "e": 7947, "s": 7117, "text": "def preprocess(df): df.reset_index(drop=True, inplace=True) # For dict columns: for col in dict_columns: col_df = json_normalize(df[col]) # json.loads during pd.read_csv to convert string to dict. col_df.columns = [f\"{col}.{subcolumn}\" for subcolumn in col_df.columns] # Select all columns which we selected before. selected_columns = [c for c in dictionary.keys() if c in col_df.columns()] to_drop = [c for c in col_df.columns if not in selected_columns] # Drop all previously unselected columns. col_df = col_df.drop(to_drop, axis=1) df = df.drop(col, axis=1).merge(col_df, right_index=True, left_index=True) # And so on... # And then apply all Scalars, LabelEncoder's to all columns selected... return df" }, { "code": null, "e": 8087, "s": 7947, "text": "To read data file incrementally using pandas, you have to use a parameter chunksize which specifies number of rows to read/write at a time." }, { "code": null, "e": 8387, "s": 8087, "text": "incremental_dataframe = pd.read_csv(\"train.csv\", chunksize=100000) # Number of lines to read.# This method will return a sequential file reader (TextFileReader)# reading 'chunksize' lines every time. To read file from # starting again, you will have to call this method again." }, { "code": null, "e": 8601, "s": 8387, "text": "Then you can train on your data incrementally using XGBoost1 or LightGBM. For LightGBM you have to pass in a argument keep_training_booster=True to its .train method and three arguments to XGBoost's .train method." }, { "code": null, "e": 8892, "s": 8601, "text": "# First one necessary for incremental learning:lgb_params = { 'keep_training_booster': True, 'objective': 'regression', 'verbosity': 100,}# First three are for incremental learning:xgb_params = { 'update':'refresh', 'process_type': 'update', 'refresh_leaf': True, 'silent': False, }" }, { "code": null, "e": 8982, "s": 8892, "text": "On each step we will save our estimator and then pass it as an argument during next step." }, { "code": null, "e": 9817, "s": 8982, "text": "# For saving regressor for next use.lgb_estimator = Nonexgb_estimator = Nonefor df in incremental_dataframe: df = preprocess(df) xtrain, ytrain, xvalid, yvalid = # Split data as you like lgb_estimator = lgb.train(lgb_params, # Pass partially trained model: init_model=lgb_estimator, train_set=lgb.Dataset(xtrain, ytrain), valid_sets=lgb.Dataset(xvalid, yvalid), num_boost_round=10) xgb_model = xgb.train(xgb_params, dtrain=xgb.DMatrix(xtrain, ytrain), evals=(xgb.DMatrix(xvalid, yvalid),\"Valid\"), # Pass partially trained model: xgb_model = xgb_estimator) del df, xtrain, ytrain, xvalid, yvalid gc.collect()" }, { "code": null, "e": 9873, "s": 9817, "text": "CatBoost's incremental learning method is in progress.2" }, { "code": null, "e": 10054, "s": 9873, "text": "To speed things up a bit more and if your chunks a still sufficiently big, you can parallelize your preprocessing method using Python's multiprocessing library functions like this:" }, { "code": null, "e": 10273, "s": 10054, "text": "n_jobs = 4for df in incremental_dataframe: p = Pool(n_jobs) f_ = p.map(preprocess, np.array_split(df, n_jobs)) f_ = pd.concat(f_, axis=0, ignore_index=True) p.close() p.join() # And then your model training ..." }, { "code": null, "e": 10346, "s": 10273, "text": "For an introduction on Parallel programming in Python read my post here." }, { "code": null, "e": 10423, "s": 10346, "text": "Dask helps to tap into big data resources in a sequentially-parallel manner." }, { "code": null, "e": 10467, "s": 10423, "text": "For introduction to Dask read my post here." }, { "code": null, "e": 10586, "s": 10467, "text": "You can apply functions from pandas API here in a similar manner. You can check if there is some null value like this:" }, { "code": null, "e": 10614, "s": 10586, "text": "df.isnull().sum().compute()" }, { "code": null, "e": 10712, "s": 10614, "text": "To scale a column you can convert them to array and use its Scaler functions in a similar manner:" }, { "code": null, "e": 10821, "s": 10712, "text": "rsc = dask_ml.preprocessing.RobustScaler()result = rsc.fit_transform(X[:,i].reshape(-1, 1)) # for ith column" }, { "code": null, "e": 10946, "s": 10821, "text": "To handle JSON or any other semi structured data like log files etc. you can use functions provided by Dask's Bag container." }, { "code": null, "e": 11014, "s": 10946, "text": "df[key] = df[dict_col].to_bag().pluck(key).to_dataframe().iloc[:,0]" }, { "code": null, "e": 11091, "s": 11014, "text": "And after preprocessing you can use one of Dask's models to train your data." }, { "code": null, "e": 11148, "s": 11091, "text": "For full code readDask section in Jupyter Notebook here." }, { "code": null, "e": 12692, "s": 11148, "text": "Note:You should only use Dask in case of Big Data, where it is not able to fit in your memory. Otherwise in-memory learning with pandas and sklearn will be lot faster.Note: (Local Cluster)You can perform almost any BigData related query/tasks with the help of LocalCluster. You can, specifically, use 'memory_limit' parameter to constrict Dask's memory usage to a specific amount. Also, at times you might notice that Dask is exceeding memory use, even though it is dividing tasks. It could be happening to you because of the function you are trying to use on your dataset wants most of your data for processing, and multiprocessing can make things worse as all workers might try to copy dataset to memory. This can happen in aggregating cases.In these cases you can use Dask.distributed.LocalCluster parameters and pass them to Client() to make a LocalCluster using cores of your Local machines.from dask.distributed import Client, LocalClusterclient = Client(n_workers=1, threads_per_worker=1, processes=False, memory_limit='25GB', scheduler_port=0, silence_logs=False, diagnostics_port=0)client'scheduler_port=0' and 'diagnostics_port=0' will choose random port number for this particular client. With 'processes=False' dask's client won't copy dataset, which would have happened for every process you might have made.You can tune your client as per your needs or limitations, and for more info you can look into parameters of LocalCluster.You can also use multiple clients on same machine at different ports." }, { "code": null, "e": 13122, "s": 12692, "text": "https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-updhttps://github.com/dmlc/xgboost/issues/3055#issuecomment-359505122https://www.kaggle.com/ogrellier/create-extracted-json-fields-datasethttps://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.pyReducing DataFrame memory size by ~65% | Kaggle7 Ways to Handle Large Data Files for Machine Learning — Machine Learning Mastery" }, { "code": null, "e": 13198, "s": 13122, "text": "https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-upd" }, { "code": null, "e": 13265, "s": 13198, "text": "https://github.com/dmlc/xgboost/issues/3055#issuecomment-359505122" }, { "code": null, "e": 13335, "s": 13265, "text": "https://www.kaggle.com/ogrellier/create-extracted-json-fields-dataset" }, { "code": null, "e": 13427, "s": 13335, "text": "https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.py" }, { "code": null, "e": 13475, "s": 13427, "text": "Reducing DataFrame memory size by ~65% | Kaggle" }, { "code": null, "e": 13557, "s": 13475, "text": "7 Ways to Handle Large Data Files for Machine Learning — Machine Learning Mastery" }, { "code": null, "e": 13964, "s": 13557, "text": "https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-updhttps://www.kaggle.com/ogrellier/create-extracted-json-fields-datasethttps://gist.github.com/goraj/6df8f22a49534e042804a299d81bf2d6https://github.com/dmlc/xgboost/issues/3055https://github.com/catboost/catboost/issues/464https://github.com/Microsoft/LightGBM/issues/987https://gist.github.com/ylogx/53fef94cc61d6a3e9b3eb900482f41e0" }, { "code": null, "e": 14040, "s": 13964, "text": "https://www.kaggle.com/mlisovyi/bigdata-dask-pandas-flat-json-trim-data-upd" }, { "code": null, "e": 14110, "s": 14040, "text": "https://www.kaggle.com/ogrellier/create-extracted-json-fields-dataset" }, { "code": null, "e": 14173, "s": 14110, "text": "https://gist.github.com/goraj/6df8f22a49534e042804a299d81bf2d6" }, { "code": null, "e": 14217, "s": 14173, "text": "https://github.com/dmlc/xgboost/issues/3055" }, { "code": null, "e": 14265, "s": 14217, "text": "https://github.com/catboost/catboost/issues/464" }, { "code": null, "e": 14314, "s": 14265, "text": "https://github.com/Microsoft/LightGBM/issues/987" }, { "code": null, "e": 14377, "s": 14314, "text": "https://gist.github.com/ylogx/53fef94cc61d6a3e9b3eb900482f41e0" }, { "code": null, "e": 14436, "s": 14377, "text": "Suggestions and reviews are welcome.Thank you for reading!" }, { "code": null, "e": 14444, "s": 14436, "text": "Signed:" } ]
Word Ladder (Length of shortest chain to reach a target word) in C++
In this problem, we are given a dictionary and two words ‘start’ and ‘target’. Our task is to generate a chain (ladder) from start work to target word, the chain is created such that each word differs the other character by only one word and the word should also exist in the dictionary. The target word exists in the dictionary and also the length of all words is the same. The program will return the length of the shortest path from start to target. Let’s take an example to understand the problem, Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’} Start = ‘HELL’ Target = ‘THAE’ 6 HELL - HEAL - HEAT - TEAT - THAT - THAE To solve this problem, we will do Breadth-first search of the dictionary. Now, step by step find all elements that are one letter away from the previous character. And create a ladder from start to target. Program to show the implementation of our solution, Live Demo #include <bits/stdc++.h> using namespace std; int wordLadder(string start, string target, set<string>& dictionary) { if (dictionary.find(target) == dictionary.end()) return 0; int level = 0, wordlength = start.size(); queue<string> ladder; ladder.push(start); while (!ladder.empty()) { ++level; int sizeOfLadder = ladder.size(); for (int i = 0; i < sizeOfLadder; ++i) { string word = ladder.front(); ladder.pop(); for (int pos = 0; pos < wordlength; ++pos) { char orig_char = word[pos]; for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; if (word == target) return level + 1; if (dictionary.find(word) == dictionary.end()) continue; dictionary.erase(word); ladder.push(word); } word[pos] = orig_char; } } } return 0; } int main() { set<string> dictionary; dictionary.insert("heal"); dictionary.insert("heat"); dictionary.insert("teat"); dictionary.insert("that"); dictionary.insert("what"); dictionary.insert("thae"); dictionary.insert("hlle"); string start = "hell"; string target = "thae"; cout<<"Length of shortest chain from '"<<start<<"' to '"<<target<<"' is: "<<wordLadder(start, target, dictionary); return 0; } Length of shortest chain from 'hell' to 'thae' is: 6
[ { "code": null, "e": 1515, "s": 1062, "text": "In this problem, we are given a dictionary and two words ‘start’ and ‘target’. Our task is to generate a chain (ladder) from start work to target word, the chain is created such that each word differs the other character by only one word and the word should also exist in the dictionary. The target word exists in the dictionary and also the length of all words is the same. The program will return the length of the shortest path from start to target." }, { "code": null, "e": 1564, "s": 1515, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1673, "s": 1564, "text": "Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’}\nStart = ‘HELL’\nTarget = ‘THAE’" }, { "code": null, "e": 1675, "s": 1673, "text": "6" }, { "code": null, "e": 1715, "s": 1675, "text": "HELL - HEAL - HEAT - TEAT - THAT - THAE" }, { "code": null, "e": 1921, "s": 1715, "text": "To solve this problem, we will do Breadth-first search of the dictionary. Now, step by step find all elements that are one letter away from the previous character. And create a ladder from start to target." }, { "code": null, "e": 1973, "s": 1921, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 1984, "s": 1973, "text": " Live Demo" }, { "code": null, "e": 3382, "s": 1984, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint wordLadder(string start, string target, set<string>& dictionary) {\n if (dictionary.find(target) == dictionary.end())\n return 0;\n int level = 0, wordlength = start.size();\n queue<string> ladder;\n ladder.push(start);\n while (!ladder.empty()) {\n ++level;\n int sizeOfLadder = ladder.size();\n for (int i = 0; i < sizeOfLadder; ++i) {\n string word = ladder.front();\n ladder.pop();\n for (int pos = 0; pos < wordlength; ++pos) {\n char orig_char = word[pos];\n for (char c = 'a'; c <= 'z'; ++c) {\n word[pos] = c;\n if (word == target)\n return level + 1;\n if (dictionary.find(word) == dictionary.end())\n continue;\n dictionary.erase(word);\n ladder.push(word);\n }\n word[pos] = orig_char;\n }\n }\n }\n return 0;\n}\nint main() {\n set<string> dictionary;\n dictionary.insert(\"heal\");\n dictionary.insert(\"heat\");\n dictionary.insert(\"teat\");\n dictionary.insert(\"that\");\n dictionary.insert(\"what\");\n dictionary.insert(\"thae\");\n dictionary.insert(\"hlle\");\n string start = \"hell\";\n string target = \"thae\";\n cout<<\"Length of shortest chain from '\"<<start<<\"' to '\"<<target<<\"' is: \"<<wordLadder(start, target, dictionary);\n return 0;\n}" }, { "code": null, "e": 3435, "s": 3382, "text": "Length of shortest chain from 'hell' to 'thae' is: 6" } ]
Convert String to Byte Array in Java Using getBytes(Charset) Method - GeeksforGeeks
28 Jan, 2021 In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class. Here, in this method we use an instance of Charset class, this class provides a named mapping between a sequence of the chars and a sequence of bytes. There are many charset defined and are discussed below. US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 UTF-8: Eight-bit UCS Transformation Format UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark. Syntax: public byte[] getBytes(Charset charset) Parameter: This function takes one argument, that is the charset which is used to encode the string Return type: This function returns the resulting byte array. Note: This method always replaces malformed input and unmappable character sequence with its charset’s default replacement byte array. If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException. The length of the byte array is not the same as the given string, it depends upon the character encoding. Let us discuss how to convert a string into a byte array with the help of the given examples: Example 1: Java // Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset) import java.io.*; class GFG{ public static void main (String[] args) { // Initializing String String ss = "Hello GeeksforGeeks"; // Display the string before conversion System.out.println("String: " + ss); try { // Converting string to byte array // Using getBytes(Charset charset) method // Here, we converts into UTF-16 values byte[] res = ss.getBytes("UTF-16"); // Displaying converted string after conversion // into UTF-16 System.out.println("Result : "); for(int i = 0; i < res.length; i++) { System.out.print(res[i]); } } catch (UnsupportedEncodingException g) { System.out.println("Unsupported character set" + g); } }} String: Hello GeeksforGeeks Result : -2-1072010101080108011103207101010101010701150102011101140710101010101070115 Example 2: Java // Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset) import java.io.*;import java.util.Arrays; class GFG{ public static void main (String[] args) { // Initializing String String ss = "Hello GFG"; // Display the string before conversion System.out.println("String: " + ss); try { // Converting string to byte array // Using getBytes(Charset charset) method // Here, we converts into US-ASCII values byte[] res = ss.getBytes("US-ASCII"); // Displaying converted string after conversion // into US-ASCII System.out.println("Byte Array:" + Arrays.toString(res)); } catch (UnsupportedEncodingException g) { System.out.println("Unsupported character set" + g); } }} String: Hello GFG Byte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71] Java-Array-Programs Java-Strings Picked Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25426, "s": 25398, "text": "\n28 Jan, 2021" }, { "code": null, "e": 25943, "s": 25426, "text": "In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class. Here, in this method we use an instance of Charset class, this class provides a named mapping between a sequence of the chars and a sequence of bytes. There are many charset defined and are discussed below." }, { "code": null, "e": 26046, "s": 25943, "text": "US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set" }, { "code": null, "e": 26103, "s": 26046, "text": "ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1" }, { "code": null, "e": 26146, "s": 26103, "text": "UTF-8: Eight-bit UCS Transformation Format" }, { "code": null, "e": 26217, "s": 26146, "text": "UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order" }, { "code": null, "e": 26291, "s": 26217, "text": "UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order" }, { "code": null, "e": 26392, "s": 26291, "text": "UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark." }, { "code": null, "e": 26400, "s": 26392, "text": "Syntax:" }, { "code": null, "e": 26440, "s": 26400, "text": "public byte[] getBytes(Charset charset)" }, { "code": null, "e": 26541, "s": 26440, "text": "Parameter: This function takes one argument, that is the charset which is used to encode the string " }, { "code": null, "e": 26603, "s": 26541, "text": "Return type: This function returns the resulting byte array. " }, { "code": null, "e": 26609, "s": 26603, "text": "Note:" }, { "code": null, "e": 26738, "s": 26609, "text": "This method always replaces malformed input and unmappable character sequence with its charset’s default replacement byte array." }, { "code": null, "e": 26841, "s": 26738, "text": "If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException." }, { "code": null, "e": 26947, "s": 26841, "text": "The length of the byte array is not the same as the given string, it depends upon the character encoding." }, { "code": null, "e": 27041, "s": 26947, "text": "Let us discuss how to convert a string into a byte array with the help of the given examples:" }, { "code": null, "e": 27052, "s": 27041, "text": "Example 1:" }, { "code": null, "e": 27057, "s": 27052, "text": "Java" }, { "code": "// Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset) import java.io.*; class GFG{ public static void main (String[] args) { // Initializing String String ss = \"Hello GeeksforGeeks\"; // Display the string before conversion System.out.println(\"String: \" + ss); try { // Converting string to byte array // Using getBytes(Charset charset) method // Here, we converts into UTF-16 values byte[] res = ss.getBytes(\"UTF-16\"); // Displaying converted string after conversion // into UTF-16 System.out.println(\"Result : \"); for(int i = 0; i < res.length; i++) { System.out.print(res[i]); } } catch (UnsupportedEncodingException g) { System.out.println(\"Unsupported character set\" + g); } }}", "e": 27967, "s": 27057, "text": null }, { "code": null, "e": 28082, "s": 27967, "text": "String: Hello GeeksforGeeks\nResult : \n-2-1072010101080108011103207101010101010701150102011101140710101010101070115" }, { "code": null, "e": 28093, "s": 28082, "text": "Example 2:" }, { "code": null, "e": 28098, "s": 28093, "text": "Java" }, { "code": "// Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset) import java.io.*;import java.util.Arrays; class GFG{ public static void main (String[] args) { // Initializing String String ss = \"Hello GFG\"; // Display the string before conversion System.out.println(\"String: \" + ss); try { // Converting string to byte array // Using getBytes(Charset charset) method // Here, we converts into US-ASCII values byte[] res = ss.getBytes(\"US-ASCII\"); // Displaying converted string after conversion // into US-ASCII System.out.println(\"Byte Array:\" + Arrays.toString(res)); } catch (UnsupportedEncodingException g) { System.out.println(\"Unsupported character set\" + g); } }}", "e": 28934, "s": 28098, "text": null }, { "code": null, "e": 29005, "s": 28934, "text": "String: Hello GFG\nByte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71]\n" }, { "code": null, "e": 29025, "s": 29005, "text": "Java-Array-Programs" }, { "code": null, "e": 29038, "s": 29025, "text": "Java-Strings" }, { "code": null, "e": 29045, "s": 29038, "text": "Picked" }, { "code": null, "e": 29050, "s": 29045, "text": "Java" }, { "code": null, "e": 29064, "s": 29050, "text": "Java Programs" }, { "code": null, "e": 29077, "s": 29064, "text": "Java-Strings" }, { "code": null, "e": 29082, "s": 29077, "text": "Java" }, { "code": null, "e": 29180, "s": 29082, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29189, "s": 29180, "text": "Comments" }, { "code": null, "e": 29202, "s": 29189, "text": "Old Comments" }, { "code": null, "e": 29232, "s": 29202, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29264, "s": 29232, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29315, "s": 29264, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29334, "s": 29315, "text": "Interfaces in Java" }, { "code": null, "e": 29352, "s": 29334, "text": "ArrayList in Java" }, { "code": null, "e": 29380, "s": 29352, "text": "Initializing a List in Java" }, { "code": null, "e": 29424, "s": 29380, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 29450, "s": 29424, "text": "Java Programming Examples" }, { "code": null, "e": 29484, "s": 29450, "text": "Convert Double to Integer in Java" } ]
A Guide to Args, Kwargs, Packing and Unpacking in Python | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin. We’ve all heard of arguments and keyword arguments (args and kwargs) when discussing Python functions. Arguments usually consist of numerical values, while keyword arguments, as the name suggests, are semantic. When writing functions, *args and **kwargs are often passed directly into a function definition. This function can handle any number of args and kwargs because of the asterisk(s) used in the function definition. These asterisks are packing and unpacking operators. When this file is run, the following output is generated. Notice that the arguments on line 5, two args and one kwarg, get correctly placed into the print statement based on their type. Also of note are the parenthesis and curly brackets in the output. Args have been packed into a tuple and kwargs a dictionary. Before we get more into packing and unpacking values in Python, let's talk a little more about function arguments. There are 2 kinds of arguments in Python, positional arguments and keyword arguments, the former are specified according to their position and the latter are the arguments are key-value pairs. Arguments without defaults cannot be omitted when calling a function. They must be passed in the correct order and position. Let's talk a little about packing and unpacking. The asterisks are unpacking operators that unpack the values from iterable objects in Python. The single asterisk operator (*) commonly associated with args can be used on any iterable. The double asterisk (**) associated with kwargs can only be used on dictionaries. These asterisks are an operator for packing and unpacking. However, you can pack and unpack without them. Check out the code below. In this gist, we have the tuple, t, being unpacked into three variables; a, b and c. When we print these vars, we will see the individual elements of the tuple. 123 Let’s use this same unpacking pattern on a dictionary. When k and v are printed, we see: Hello15 This example is a little more complicated, as you can see on line 3. We use .items() to iterate over a dictionary, tuple() to convert the dictionary to a tuple so that we can use [0] to pull the first element of the tuple. All of this packs the key-value pair into k and v . Now that you know a little about unpacking values in Python, let's get into the operators * and **. Take a look at this example of both packing and unpacking with the single asterisk. We use the same pattern of unpacking by setting three variables equal to a list. However, here we add the packing operator to the variable b. Can you guess what the print statements will look like? 1[2,3,4,5]6 We can see that a was set equal to the first element in the list, c to the last element and all the elements in between were packed into b . This could be useful when you know how many variables you want to define but are unsure how many elements you are placing into each. The double asterisk allows us to make some otherwise complex dictionary processes occur quite elegantly. For example, we can use the double-asterisk to merge two uniquely keyed dictionaries. When we run this file, we see the following output. Notice that the return statement in merge_two_dictionaries is wrapped in curly brackets. This ensures our function returns a dictionary. Now let's move to a discussion about *args and **kwargs . Note that args is just a name. You’re not required to use the name args. All that matters here is that you use the unpacking operator (*). It is, however, canonical to use args. Bear in mind that the iterable object you’ll get using the unpacking operator * is not a list but a tuple. When you use the * operator to unpack a list and pass arguments to a function, it’s exactly as though you’re passing every single argument alone. Let’s show the power of *args with a common coding interview question. You are tasked with writing a Python function that will sum integers. Sounds easy enough, right? My initial code might look something like this. Fits the bill of ‘sums integers’ for sure. Let’s say we run it against these tests. Can you see what will go wrong? Our first two tests work no problem, but the third, summing three integers, generates an error. It looks like our sum function can only take two positional arguments. Let’s see if we can code a better addition function using *args. Now we have a function that can take in an arbitrary number of arguments. The sum is calculated by looping through these arguments and adding their value to total. Now let's run it past some tests. This new function passes all of them! When we want to take in many arguments, but we are not sure how many, *args is a great option. Once again, you’re not required to use the name kwargs. All that matters here is that you use the unpacking operator (**). It is, however, canonical to use the name kwargs. In function definitions **kwargs works like *args, but instead of accepting positional arguments, it accepts arbitrarily many keyword arguments. **kwargs is often used to preserve a message as it is passed between objects. We can see this is the decorator code below. If you would like to learn more about decorators, check out the article this code is from. towardsdatascience.com On line 8, we see that tracefunc_closure takes **kwargs as an argument. This allows whatever we pass to tracefunc to be preserved as it is passed between objects. Let's trace a function with this decorator to see this firsthand. Here is the print statement output. Notice that tracefunc recognizes the dataframes as args and the keyword arguments for pd.merge as kwargs. Additionally, we didn't have to do anything to tracefunc to make it compatible with pd.merge. Tracefunc is able to take in these kwargs and pass them to pd.merge. This represents interface preservation. We can see examples of both keyword arguments and **kwargs in the pandas documentation. Here we see that dataframe.info can take 6 different keyword arguments. In cases like this, we must use the proper keywords or place the values in thier positional order. This later case however unnecessarily sacrifices readiblilty. The dataframe.assign takes**kwargs as its only argument. That sounds simple, however **kwargs is very flexible. When passing key-value pairs as **kwargs to df.assign our values can be a simple list or a more complex lambda function. The list and lambda-function processing is implemented in the source code for .assign. The significance of **kwargs is that this function can take any key and use it. It doesn't matter if we name the key state or temp_f . Whether writing functions to take an arbitrary number of arguments and keyword arguments, or to pack and unpack values from lists and dictionaries *args and **kwargs allow for some remarkably flexible, readable and useful code. Additionally, *args and **kwargs are fundamental to understanding broader programming and function writing concepts in Python.
[ { "code": null, "e": 212, "s": 171, "text": "By: Edward Krueger and Douglas Franklin." }, { "code": null, "e": 520, "s": 212, "text": "We’ve all heard of arguments and keyword arguments (args and kwargs) when discussing Python functions. Arguments usually consist of numerical values, while keyword arguments, as the name suggests, are semantic. When writing functions, *args and **kwargs are often passed directly into a function definition." }, { "code": null, "e": 688, "s": 520, "text": "This function can handle any number of args and kwargs because of the asterisk(s) used in the function definition. These asterisks are packing and unpacking operators." }, { "code": null, "e": 746, "s": 688, "text": "When this file is run, the following output is generated." }, { "code": null, "e": 1001, "s": 746, "text": "Notice that the arguments on line 5, two args and one kwarg, get correctly placed into the print statement based on their type. Also of note are the parenthesis and curly brackets in the output. Args have been packed into a tuple and kwargs a dictionary." }, { "code": null, "e": 1116, "s": 1001, "text": "Before we get more into packing and unpacking values in Python, let's talk a little more about function arguments." }, { "code": null, "e": 1309, "s": 1116, "text": "There are 2 kinds of arguments in Python, positional arguments and keyword arguments, the former are specified according to their position and the latter are the arguments are key-value pairs." }, { "code": null, "e": 1434, "s": 1309, "text": "Arguments without defaults cannot be omitted when calling a function. They must be passed in the correct order and position." }, { "code": null, "e": 1483, "s": 1434, "text": "Let's talk a little about packing and unpacking." }, { "code": null, "e": 1751, "s": 1483, "text": "The asterisks are unpacking operators that unpack the values from iterable objects in Python. The single asterisk operator (*) commonly associated with args can be used on any iterable. The double asterisk (**) associated with kwargs can only be used on dictionaries." }, { "code": null, "e": 1883, "s": 1751, "text": "These asterisks are an operator for packing and unpacking. However, you can pack and unpack without them. Check out the code below." }, { "code": null, "e": 2044, "s": 1883, "text": "In this gist, we have the tuple, t, being unpacked into three variables; a, b and c. When we print these vars, we will see the individual elements of the tuple." }, { "code": null, "e": 2048, "s": 2044, "text": "123" }, { "code": null, "e": 2103, "s": 2048, "text": "Let’s use this same unpacking pattern on a dictionary." }, { "code": null, "e": 2137, "s": 2103, "text": "When k and v are printed, we see:" }, { "code": null, "e": 2145, "s": 2137, "text": "Hello15" }, { "code": null, "e": 2420, "s": 2145, "text": "This example is a little more complicated, as you can see on line 3. We use .items() to iterate over a dictionary, tuple() to convert the dictionary to a tuple so that we can use [0] to pull the first element of the tuple. All of this packs the key-value pair into k and v ." }, { "code": null, "e": 2604, "s": 2420, "text": "Now that you know a little about unpacking values in Python, let's get into the operators * and **. Take a look at this example of both packing and unpacking with the single asterisk." }, { "code": null, "e": 2802, "s": 2604, "text": "We use the same pattern of unpacking by setting three variables equal to a list. However, here we add the packing operator to the variable b. Can you guess what the print statements will look like?" }, { "code": null, "e": 2814, "s": 2802, "text": "1[2,3,4,5]6" }, { "code": null, "e": 3088, "s": 2814, "text": "We can see that a was set equal to the first element in the list, c to the last element and all the elements in between were packed into b . This could be useful when you know how many variables you want to define but are unsure how many elements you are placing into each." }, { "code": null, "e": 3279, "s": 3088, "text": "The double asterisk allows us to make some otherwise complex dictionary processes occur quite elegantly. For example, we can use the double-asterisk to merge two uniquely keyed dictionaries." }, { "code": null, "e": 3331, "s": 3279, "text": "When we run this file, we see the following output." }, { "code": null, "e": 3468, "s": 3331, "text": "Notice that the return statement in merge_two_dictionaries is wrapped in curly brackets. This ensures our function returns a dictionary." }, { "code": null, "e": 3526, "s": 3468, "text": "Now let's move to a discussion about *args and **kwargs ." }, { "code": null, "e": 3811, "s": 3526, "text": "Note that args is just a name. You’re not required to use the name args. All that matters here is that you use the unpacking operator (*). It is, however, canonical to use args. Bear in mind that the iterable object you’ll get using the unpacking operator * is not a list but a tuple." }, { "code": null, "e": 4028, "s": 3811, "text": "When you use the * operator to unpack a list and pass arguments to a function, it’s exactly as though you’re passing every single argument alone. Let’s show the power of *args with a common coding interview question." }, { "code": null, "e": 4098, "s": 4028, "text": "You are tasked with writing a Python function that will sum integers." }, { "code": null, "e": 4125, "s": 4098, "text": "Sounds easy enough, right?" }, { "code": null, "e": 4173, "s": 4125, "text": "My initial code might look something like this." }, { "code": null, "e": 4289, "s": 4173, "text": "Fits the bill of ‘sums integers’ for sure. Let’s say we run it against these tests. Can you see what will go wrong?" }, { "code": null, "e": 4456, "s": 4289, "text": "Our first two tests work no problem, but the third, summing three integers, generates an error. It looks like our sum function can only take two positional arguments." }, { "code": null, "e": 4521, "s": 4456, "text": "Let’s see if we can code a better addition function using *args." }, { "code": null, "e": 4685, "s": 4521, "text": "Now we have a function that can take in an arbitrary number of arguments. The sum is calculated by looping through these arguments and adding their value to total." }, { "code": null, "e": 4719, "s": 4685, "text": "Now let's run it past some tests." }, { "code": null, "e": 4852, "s": 4719, "text": "This new function passes all of them! When we want to take in many arguments, but we are not sure how many, *args is a great option." }, { "code": null, "e": 5025, "s": 4852, "text": "Once again, you’re not required to use the name kwargs. All that matters here is that you use the unpacking operator (**). It is, however, canonical to use the name kwargs." }, { "code": null, "e": 5170, "s": 5025, "text": "In function definitions **kwargs works like *args, but instead of accepting positional arguments, it accepts arbitrarily many keyword arguments." }, { "code": null, "e": 5384, "s": 5170, "text": "**kwargs is often used to preserve a message as it is passed between objects. We can see this is the decorator code below. If you would like to learn more about decorators, check out the article this code is from." }, { "code": null, "e": 5407, "s": 5384, "text": "towardsdatascience.com" }, { "code": null, "e": 5636, "s": 5407, "text": "On line 8, we see that tracefunc_closure takes **kwargs as an argument. This allows whatever we pass to tracefunc to be preserved as it is passed between objects. Let's trace a function with this decorator to see this firsthand." }, { "code": null, "e": 5672, "s": 5636, "text": "Here is the print statement output." }, { "code": null, "e": 5981, "s": 5672, "text": "Notice that tracefunc recognizes the dataframes as args and the keyword arguments for pd.merge as kwargs. Additionally, we didn't have to do anything to tracefunc to make it compatible with pd.merge. Tracefunc is able to take in these kwargs and pass them to pd.merge. This represents interface preservation." }, { "code": null, "e": 6302, "s": 5981, "text": "We can see examples of both keyword arguments and **kwargs in the pandas documentation. Here we see that dataframe.info can take 6 different keyword arguments. In cases like this, we must use the proper keywords or place the values in thier positional order. This later case however unnecessarily sacrifices readiblilty." }, { "code": null, "e": 6359, "s": 6302, "text": "The dataframe.assign takes**kwargs as its only argument." }, { "code": null, "e": 6757, "s": 6359, "text": "That sounds simple, however **kwargs is very flexible. When passing key-value pairs as **kwargs to df.assign our values can be a simple list or a more complex lambda function. The list and lambda-function processing is implemented in the source code for .assign. The significance of **kwargs is that this function can take any key and use it. It doesn't matter if we name the key state or temp_f ." } ]