title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
A Beginner’s Guide to Machine Learning in Python | by Natassha Selvaraj | Towards Data Science
There are two approaches you can take to study any topic — top-down, and bottom-up. When you learnt subjects like math and science in school, you would’ve been taught using the bottom-up approach. First, you were taught the foundations of the topic, and then gradually progressed through the material. However, when learning subjects like data science and machine learning, the top-down approach is often easier to grasp — especially if you don’t have a strong mathematical background. This is easy to do due to the number of packages available in languages like Python and R. The democratization of machine learning allows you to create end-to-end machine learning models with little understanding of how they work and the math behind the algorithm. Of course, you still need to gain understand how these algorithms work, but this can come later (once you’ve learnt how to build these models in practice). In this article, I am going to walk you through an end-to-end machine learning project with the Pima Indian Diabetes dataset on Kaggle. I will provide codes for data pre-processing, analysis, model training, and evaluation. You can use this as starter code for any machine learning project you work on in the future. I will also provide additional learning resources for each technique and algorithm I use, so you can read up on them and gain a better understanding of they work. Note: I have already done a data analysis tutorial on the same dataset, which you can check out here. For that reason, I will not be going into too much detail on data analysis and visualization in this article. Instead, I will put more focus into building the machine learning algorithms. To follow along to this tutorial, you need to have a Python IDE installed on your computer. I suggest using a Jupyter Notebook because that’s what I used to create this tutorial, and Jupyter allows you to display visualizations in the same document that your code is in. You also need to have the following packages pre-installed — Pandas, Numpy, Matplotlib, Seaborn, and Scikit-Learn. Follow the instructions in their documentation to install these libraries. This is the dataset we will be using throughout the tutorial. Once you have downloaded it and have your environment ready, run the following lines of code: # importsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns# Reading the data-framedf = pd.read_csv('pima.csv') Once you have read the data-frame, run the following lines of code to take a look at the different variables: df.head() You will see the following output: The different variables in the data-frame include: Pregnancies — Number of times pregnant Glucose — Plasma glucose concentration a 2 hours in an oral glucose tolerance test Blood Pressure — Diastolic blood pressure SkinThickness — Triceps skin fold thickness Insulin — 2-Hour serum insulin BMI — Body Mass Index DiabetesPedigreeFunction — Diabetes pedigree function Age — Age Outcome — Whether or not the person is diabetic The outcome variable is our target, and all other variables are the predictors. We need to use the remaining variables to predict the outcome with a machine learning model. To take a look at some descriptive statistics, run the following lines of code: df.describe() We can see some simple dataset statistics: Now, we can run a few lines of code to view the relationship between all the variables in the dataset: # pairplot:sns.pairplot(df,hue='Outcome') The following plot is rendered:*I didn’t include the entire image because it was too large A pair plot is a very useful visualization. It allows you to take a look at the relationship between all the variables in the dataset at once. At a first glance, you will be able to notice strong relationships between variables that stand out. You can then go on to examine these relationships, and remove highly correlated attributes that might cause any multicollinearity in your model. Now, we can check for missing values in the data-frame: print(df.isnull().values.any()) The lines above should return False. There are no missing values in the data frame. Now, we are going to standardize our variables to get all of them around the same scale. You can read more about why standardization is important here. If you prefer watching over reading, I suggest taking a look at Krish Naik’s explanation on the importance of feature scaling. We will be doing something called the Z-Score standardization. This will take all our variables and transform them to follow a normal distribution having a mean of 0 and a standard deviation of 1. Run the following lines of code: X = df.drop('Outcome',axis=1)y = df['Outcome']# standardizationX = (X-X.mean())/X.std() Once this is done, inspect the head of the data frame again: X.head() The transformed data frame will look like this: Now that we are done with data pre-processing, we can start building the machine learning model. First, we need to split the data frame into a train and test set. We will be training the model on one set of data, and then evaluating its performance on data that it has never seen before. There are many ways to perform model validation, one of the most popular being K-fold cross validation. You can read about the different cross-validation methods here. However, I will cover the simplest validation approach in this article — dividing the dataset into two, and holding out one set of data for testing. Here is some code to do this: from sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25) After doing this, we will get separate datasets to train and test our model. We can now start with model creation. The first model we will build is a logistic regression classifier. This model fits a logistic function onto data to identify the class that each data point belongs to. If you have learnt about linear regression, you should know that logistic regression uses the same linear function (y=a+bX) to separate values of each class. However, it modifies the linear function a little such that the values will not go below 0 or above 1. As a result, a logistic regression classifier outputs probabilities. By default, the model prediction is the class with the highest probability. You can change this by tailoring the threshold value of the logistic regression model to your needs. By default, it is 0.5. We will be using this default threshold value of 0.5 in this tutorial. If you want to learn more about logistic regression, I suggest watching this video. You can run the following lines of code to fit a logistic regression model onto the training data: from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train,y_train) Now, we can make predictions on our test data: lr_preds = lr.predict(X_test) And we’re done! Now, we can fit the data on the next model. A decision tree classifier is a tree-based model. It will take all the variables in the dataset and split on them. At each split, it either assigns the data point to a class or splits on a different variable. This process continues until there are no more features to split on, or a stopping criteria is reached. The decision tree classifier decides what to split on by selecting the feature that minimizes the loss at each split. The Gini index and entropy are two common loss functions used in decision tree classifiers. You can watch this video to gain a better understanding of how decision trees work. To fit a decision tree classifier on the data, run the following lines of code: from sklearn.tree import DecisionTreeClassifierdt = DecisionTreeClassifier()dt.fit(X_train,y_train) Lets use this model to make predictions on the test data: dt_preds = dt.predict(X_test) Done! Lets move on to the next model. A random forest model uses multiple decision trees to come up with a prediction. In practice, random forests often outperform decision trees and linear classifiers. It uses a technique called bagging, which stands for bootstrap aggregation. The training dataset is randomly sampled many times, and a decision tree is fit onto each data sample. Only a subset of features are considered for division at each node, ensuring a fair representation of each variable in the model. In classification problems like this one, the output is the majority class prediction of all the decision trees. To learn more about how a random forest algorithm works, you can read this article. If you learn better visually, you can watch this video instead. Run the following lines of code to fit the random forest classifier on the training set: from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier()rf.fit(X_train,y_train) Now, run the line below to make predictions on the test set: rf_preds = rf.predict(X_test) Done! Lets move on to the final model we will be building for this tutorial. Another extension of tree based models, an XGBoost classifier uses a technique called boosting to improve the performance of decision trees. The way gradient boosting algorithms work is pretty intuitive. A base learner is first implemented that makes an initial prediction. The residuals of the initial model is calculated, and a second decision tree is added, that predicts the residuals of the initial model. Just like this, a chain of decision trees are added to form a sequential model that minimizes the overall residual. To learn more about gradient boosting, you can watch this video. Gradient boosting is one of the most popular supervised learning technique, and it used often by data scientists in Kaggle competitions. In practice, they tend to perform a lot better than decision trees. from xgboost import XGBClassifierxgb = XGBClassifier()xgb.fit(X_train,y_train) Now, run these lines of code to make predictions on the test set: xgb_preds = xgb.predict(X_test) And that’s it! We are done training the model and saving their predictions. Lets take a look at model performance now. We will take a look at the simplest metric used to evaluate model performance — accuracy. The following lines of code will create a bar chart that displays the accuracy score of all four models: model = np.array(['Logistic Regression','Decision Tree','Random Forest','Gradient Boosting'])from sklearn.metrics import accuracy_scorescores = np.array([accuracy_score(lr_preds,y_test),accuracy_score(dt_preds,y_test),accuracy_score(rf_preds,y_test),accuracy_score(xgb_preds,y_test)])df = {'model': model, 'scores': scores}sns.barplot(x='model',y='scores',data=df) These lines of code will render a chart that looks like this: The accuracy of each model are as follows: Logistic Regression— 0.73 Decision Tree Classifier — 0.77 Random Forest Classifier — 0.81 XGBoost Classifier — 0.79 It looks like the random forest classifier has outperformed the other models, and XGBoost is a close second. Keep in mind that your results may differ slightly from mine when you run the same lines of code, because the data will be partitioned differently every time you do a train-test split. Also, there are other important classification metrics that you need to keep in mind to ensure that your model is performing well — such as precision and recall. If you are working on problems like disease classification where one class of data is under-represented in your dataset, you might run into an issue where your model only predicts the majority class. Having high validation accuracy isn’t the only indicator of a well performing model. If you want to learn more about other classification metrics, you can watch this video. To learn more about solving the imbalanced dataset issue in classification problems, you can follow along to this tutorial. That’s all for this article! I hope you learnt something from this tutorial. Please do take a look at the additional resources I linked throughout the article. Now that you have a high level understanding of how machine learning modelling works, these resources will help you build a strong understanding of everything you implemented. They will help cement your understanding of the different data pre-processing techniques, how different algorithms work, and the different metrics you can use to assess model performance.
[ { "code": null, "e": 256, "s": 172, "text": "There are two approaches you can take to study any topic — top-down, and bottom-up." }, { "code": null, "e": 369, "s": 256, "text": "When you learnt subjects like math and science in school, you would’ve been taught using the bottom-up approach." }, { "code": null, "e": 474, "s": 369, "text": "First, you were taught the foundations of the topic, and then gradually progressed through the material." }, { "code": null, "e": 658, "s": 474, "text": "However, when learning subjects like data science and machine learning, the top-down approach is often easier to grasp — especially if you don’t have a strong mathematical background." }, { "code": null, "e": 749, "s": 658, "text": "This is easy to do due to the number of packages available in languages like Python and R." }, { "code": null, "e": 923, "s": 749, "text": "The democratization of machine learning allows you to create end-to-end machine learning models with little understanding of how they work and the math behind the algorithm." }, { "code": null, "e": 1079, "s": 923, "text": "Of course, you still need to gain understand how these algorithms work, but this can come later (once you’ve learnt how to build these models in practice)." }, { "code": null, "e": 1215, "s": 1079, "text": "In this article, I am going to walk you through an end-to-end machine learning project with the Pima Indian Diabetes dataset on Kaggle." }, { "code": null, "e": 1396, "s": 1215, "text": "I will provide codes for data pre-processing, analysis, model training, and evaluation. You can use this as starter code for any machine learning project you work on in the future." }, { "code": null, "e": 1559, "s": 1396, "text": "I will also provide additional learning resources for each technique and algorithm I use, so you can read up on them and gain a better understanding of they work." }, { "code": null, "e": 1565, "s": 1559, "text": "Note:" }, { "code": null, "e": 1849, "s": 1565, "text": "I have already done a data analysis tutorial on the same dataset, which you can check out here. For that reason, I will not be going into too much detail on data analysis and visualization in this article. Instead, I will put more focus into building the machine learning algorithms." }, { "code": null, "e": 1941, "s": 1849, "text": "To follow along to this tutorial, you need to have a Python IDE installed on your computer." }, { "code": null, "e": 2120, "s": 1941, "text": "I suggest using a Jupyter Notebook because that’s what I used to create this tutorial, and Jupyter allows you to display visualizations in the same document that your code is in." }, { "code": null, "e": 2310, "s": 2120, "text": "You also need to have the following packages pre-installed — Pandas, Numpy, Matplotlib, Seaborn, and Scikit-Learn. Follow the instructions in their documentation to install these libraries." }, { "code": null, "e": 2466, "s": 2310, "text": "This is the dataset we will be using throughout the tutorial. Once you have downloaded it and have your environment ready, run the following lines of code:" }, { "code": null, "e": 2617, "s": 2466, "text": "# importsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns# Reading the data-framedf = pd.read_csv('pima.csv')" }, { "code": null, "e": 2727, "s": 2617, "text": "Once you have read the data-frame, run the following lines of code to take a look at the different variables:" }, { "code": null, "e": 2737, "s": 2727, "text": "df.head()" }, { "code": null, "e": 2772, "s": 2737, "text": "You will see the following output:" }, { "code": null, "e": 2823, "s": 2772, "text": "The different variables in the data-frame include:" }, { "code": null, "e": 2862, "s": 2823, "text": "Pregnancies — Number of times pregnant" }, { "code": null, "e": 2945, "s": 2862, "text": "Glucose — Plasma glucose concentration a 2 hours in an oral glucose tolerance test" }, { "code": null, "e": 2987, "s": 2945, "text": "Blood Pressure — Diastolic blood pressure" }, { "code": null, "e": 3031, "s": 2987, "text": "SkinThickness — Triceps skin fold thickness" }, { "code": null, "e": 3062, "s": 3031, "text": "Insulin — 2-Hour serum insulin" }, { "code": null, "e": 3084, "s": 3062, "text": "BMI — Body Mass Index" }, { "code": null, "e": 3138, "s": 3084, "text": "DiabetesPedigreeFunction — Diabetes pedigree function" }, { "code": null, "e": 3148, "s": 3138, "text": "Age — Age" }, { "code": null, "e": 3196, "s": 3148, "text": "Outcome — Whether or not the person is diabetic" }, { "code": null, "e": 3369, "s": 3196, "text": "The outcome variable is our target, and all other variables are the predictors. We need to use the remaining variables to predict the outcome with a machine learning model." }, { "code": null, "e": 3449, "s": 3369, "text": "To take a look at some descriptive statistics, run the following lines of code:" }, { "code": null, "e": 3463, "s": 3449, "text": "df.describe()" }, { "code": null, "e": 3506, "s": 3463, "text": "We can see some simple dataset statistics:" }, { "code": null, "e": 3609, "s": 3506, "text": "Now, we can run a few lines of code to view the relationship between all the variables in the dataset:" }, { "code": null, "e": 3651, "s": 3609, "text": "# pairplot:sns.pairplot(df,hue='Outcome')" }, { "code": null, "e": 3742, "s": 3651, "text": "The following plot is rendered:*I didn’t include the entire image because it was too large" }, { "code": null, "e": 3885, "s": 3742, "text": "A pair plot is a very useful visualization. It allows you to take a look at the relationship between all the variables in the dataset at once." }, { "code": null, "e": 4131, "s": 3885, "text": "At a first glance, you will be able to notice strong relationships between variables that stand out. You can then go on to examine these relationships, and remove highly correlated attributes that might cause any multicollinearity in your model." }, { "code": null, "e": 4187, "s": 4131, "text": "Now, we can check for missing values in the data-frame:" }, { "code": null, "e": 4219, "s": 4187, "text": "print(df.isnull().values.any())" }, { "code": null, "e": 4303, "s": 4219, "text": "The lines above should return False. There are no missing values in the data frame." }, { "code": null, "e": 4582, "s": 4303, "text": "Now, we are going to standardize our variables to get all of them around the same scale. You can read more about why standardization is important here. If you prefer watching over reading, I suggest taking a look at Krish Naik’s explanation on the importance of feature scaling." }, { "code": null, "e": 4779, "s": 4582, "text": "We will be doing something called the Z-Score standardization. This will take all our variables and transform them to follow a normal distribution having a mean of 0 and a standard deviation of 1." }, { "code": null, "e": 4812, "s": 4779, "text": "Run the following lines of code:" }, { "code": null, "e": 4900, "s": 4812, "text": "X = df.drop('Outcome',axis=1)y = df['Outcome']# standardizationX = (X-X.mean())/X.std()" }, { "code": null, "e": 4961, "s": 4900, "text": "Once this is done, inspect the head of the data frame again:" }, { "code": null, "e": 4970, "s": 4961, "text": "X.head()" }, { "code": null, "e": 5018, "s": 4970, "text": "The transformed data frame will look like this:" }, { "code": null, "e": 5115, "s": 5018, "text": "Now that we are done with data pre-processing, we can start building the machine learning model." }, { "code": null, "e": 5306, "s": 5115, "text": "First, we need to split the data frame into a train and test set. We will be training the model on one set of data, and then evaluating its performance on data that it has never seen before." }, { "code": null, "e": 5474, "s": 5306, "text": "There are many ways to perform model validation, one of the most popular being K-fold cross validation. You can read about the different cross-validation methods here." }, { "code": null, "e": 5623, "s": 5474, "text": "However, I will cover the simplest validation approach in this article — dividing the dataset into two, and holding out one set of data for testing." }, { "code": null, "e": 5653, "s": 5623, "text": "Here is some code to do this:" }, { "code": null, "e": 5776, "s": 5653, "text": "from sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25)" }, { "code": null, "e": 5891, "s": 5776, "text": "After doing this, we will get separate datasets to train and test our model. We can now start with model creation." }, { "code": null, "e": 6059, "s": 5891, "text": "The first model we will build is a logistic regression classifier. This model fits a logistic function onto data to identify the class that each data point belongs to." }, { "code": null, "e": 6320, "s": 6059, "text": "If you have learnt about linear regression, you should know that logistic regression uses the same linear function (y=a+bX) to separate values of each class. However, it modifies the linear function a little such that the values will not go below 0 or above 1." }, { "code": null, "e": 6465, "s": 6320, "text": "As a result, a logistic regression classifier outputs probabilities. By default, the model prediction is the class with the highest probability." }, { "code": null, "e": 6660, "s": 6465, "text": "You can change this by tailoring the threshold value of the logistic regression model to your needs. By default, it is 0.5. We will be using this default threshold value of 0.5 in this tutorial." }, { "code": null, "e": 6744, "s": 6660, "text": "If you want to learn more about logistic regression, I suggest watching this video." }, { "code": null, "e": 6843, "s": 6744, "text": "You can run the following lines of code to fit a logistic regression model onto the training data:" }, { "code": null, "e": 6943, "s": 6843, "text": "from sklearn.linear_model import LogisticRegressionlr = LogisticRegression()lr.fit(X_train,y_train)" }, { "code": null, "e": 6990, "s": 6943, "text": "Now, we can make predictions on our test data:" }, { "code": null, "e": 7020, "s": 6990, "text": "lr_preds = lr.predict(X_test)" }, { "code": null, "e": 7080, "s": 7020, "text": "And we’re done! Now, we can fit the data on the next model." }, { "code": null, "e": 7195, "s": 7080, "text": "A decision tree classifier is a tree-based model. It will take all the variables in the dataset and split on them." }, { "code": null, "e": 7393, "s": 7195, "text": "At each split, it either assigns the data point to a class or splits on a different variable. This process continues until there are no more features to split on, or a stopping criteria is reached." }, { "code": null, "e": 7603, "s": 7393, "text": "The decision tree classifier decides what to split on by selecting the feature that minimizes the loss at each split. The Gini index and entropy are two common loss functions used in decision tree classifiers." }, { "code": null, "e": 7687, "s": 7603, "text": "You can watch this video to gain a better understanding of how decision trees work." }, { "code": null, "e": 7767, "s": 7687, "text": "To fit a decision tree classifier on the data, run the following lines of code:" }, { "code": null, "e": 7867, "s": 7767, "text": "from sklearn.tree import DecisionTreeClassifierdt = DecisionTreeClassifier()dt.fit(X_train,y_train)" }, { "code": null, "e": 7925, "s": 7867, "text": "Lets use this model to make predictions on the test data:" }, { "code": null, "e": 7955, "s": 7925, "text": "dt_preds = dt.predict(X_test)" }, { "code": null, "e": 7993, "s": 7955, "text": "Done! Lets move on to the next model." }, { "code": null, "e": 8158, "s": 7993, "text": "A random forest model uses multiple decision trees to come up with a prediction. In practice, random forests often outperform decision trees and linear classifiers." }, { "code": null, "e": 8337, "s": 8158, "text": "It uses a technique called bagging, which stands for bootstrap aggregation. The training dataset is randomly sampled many times, and a decision tree is fit onto each data sample." }, { "code": null, "e": 8467, "s": 8337, "text": "Only a subset of features are considered for division at each node, ensuring a fair representation of each variable in the model." }, { "code": null, "e": 8580, "s": 8467, "text": "In classification problems like this one, the output is the majority class prediction of all the decision trees." }, { "code": null, "e": 8728, "s": 8580, "text": "To learn more about how a random forest algorithm works, you can read this article. If you learn better visually, you can watch this video instead." }, { "code": null, "e": 8817, "s": 8728, "text": "Run the following lines of code to fit the random forest classifier on the training set:" }, { "code": null, "e": 8921, "s": 8817, "text": "from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier()rf.fit(X_train,y_train)" }, { "code": null, "e": 8982, "s": 8921, "text": "Now, run the line below to make predictions on the test set:" }, { "code": null, "e": 9012, "s": 8982, "text": "rf_preds = rf.predict(X_test)" }, { "code": null, "e": 9089, "s": 9012, "text": "Done! Lets move on to the final model we will be building for this tutorial." }, { "code": null, "e": 9230, "s": 9089, "text": "Another extension of tree based models, an XGBoost classifier uses a technique called boosting to improve the performance of decision trees." }, { "code": null, "e": 9500, "s": 9230, "text": "The way gradient boosting algorithms work is pretty intuitive. A base learner is first implemented that makes an initial prediction. The residuals of the initial model is calculated, and a second decision tree is added, that predicts the residuals of the initial model." }, { "code": null, "e": 9616, "s": 9500, "text": "Just like this, a chain of decision trees are added to form a sequential model that minimizes the overall residual." }, { "code": null, "e": 9681, "s": 9616, "text": "To learn more about gradient boosting, you can watch this video." }, { "code": null, "e": 9886, "s": 9681, "text": "Gradient boosting is one of the most popular supervised learning technique, and it used often by data scientists in Kaggle competitions. In practice, they tend to perform a lot better than decision trees." }, { "code": null, "e": 9965, "s": 9886, "text": "from xgboost import XGBClassifierxgb = XGBClassifier()xgb.fit(X_train,y_train)" }, { "code": null, "e": 10031, "s": 9965, "text": "Now, run these lines of code to make predictions on the test set:" }, { "code": null, "e": 10063, "s": 10031, "text": "xgb_preds = xgb.predict(X_test)" }, { "code": null, "e": 10182, "s": 10063, "text": "And that’s it! We are done training the model and saving their predictions. Lets take a look at model performance now." }, { "code": null, "e": 10272, "s": 10182, "text": "We will take a look at the simplest metric used to evaluate model performance — accuracy." }, { "code": null, "e": 10377, "s": 10272, "text": "The following lines of code will create a bar chart that displays the accuracy score of all four models:" }, { "code": null, "e": 10742, "s": 10377, "text": "model = np.array(['Logistic Regression','Decision Tree','Random Forest','Gradient Boosting'])from sklearn.metrics import accuracy_scorescores = np.array([accuracy_score(lr_preds,y_test),accuracy_score(dt_preds,y_test),accuracy_score(rf_preds,y_test),accuracy_score(xgb_preds,y_test)])df = {'model': model, 'scores': scores}sns.barplot(x='model',y='scores',data=df)" }, { "code": null, "e": 10804, "s": 10742, "text": "These lines of code will render a chart that looks like this:" }, { "code": null, "e": 10847, "s": 10804, "text": "The accuracy of each model are as follows:" }, { "code": null, "e": 10873, "s": 10847, "text": "Logistic Regression— 0.73" }, { "code": null, "e": 10905, "s": 10873, "text": "Decision Tree Classifier — 0.77" }, { "code": null, "e": 10937, "s": 10905, "text": "Random Forest Classifier — 0.81" }, { "code": null, "e": 10963, "s": 10937, "text": "XGBoost Classifier — 0.79" }, { "code": null, "e": 11072, "s": 10963, "text": "It looks like the random forest classifier has outperformed the other models, and XGBoost is a close second." }, { "code": null, "e": 11257, "s": 11072, "text": "Keep in mind that your results may differ slightly from mine when you run the same lines of code, because the data will be partitioned differently every time you do a train-test split." }, { "code": null, "e": 11419, "s": 11257, "text": "Also, there are other important classification metrics that you need to keep in mind to ensure that your model is performing well — such as precision and recall." }, { "code": null, "e": 11619, "s": 11419, "text": "If you are working on problems like disease classification where one class of data is under-represented in your dataset, you might run into an issue where your model only predicts the majority class." }, { "code": null, "e": 11704, "s": 11619, "text": "Having high validation accuracy isn’t the only indicator of a well performing model." }, { "code": null, "e": 11916, "s": 11704, "text": "If you want to learn more about other classification metrics, you can watch this video. To learn more about solving the imbalanced dataset issue in classification problems, you can follow along to this tutorial." }, { "code": null, "e": 11993, "s": 11916, "text": "That’s all for this article! I hope you learnt something from this tutorial." }, { "code": null, "e": 12076, "s": 11993, "text": "Please do take a look at the additional resources I linked throughout the article." }, { "code": null, "e": 12252, "s": 12076, "text": "Now that you have a high level understanding of how machine learning modelling works, these resources will help you build a strong understanding of everything you implemented." } ]
How to install PostgreSql on Mac - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here we will see how to install PostgreSQL on Mac with homebrew. Mac OS Big Sur 11.04 Homebrew 3.2.3 Make sure you have to install homebrew first, if you don’t have it yet, it’s straightforward. It’s always recommended to update homebrew before installing any package. chandra~ % brew update Updated 1 tap (homebrew/core). ==> Updated Formulae luv You have 10 outdated formulae and 2 outdated casks installed. You can upgrade them with brew upgrade or list them with brew outdated. The above brew update command gave me 10 outdated formulae and 2 casks. It may be different for you. chandra ~ % brew upgrade ==> Upgrading 10 outdated packages: pyenv 2.0.0 -> 2.0.3 vim 8.2.3050 -> 8.2.3175 terraform 0.14.8 -> 1.0.2 aws/tap/aws-sam-cli 1.24.1 -> 1.26.0 pivotal/tap/gemfire 9.10.6 -> 9.10.8 poetry 1.1.6 -> 1.1.7 pcre2 10.36 -> 10.37_1 ruby 3.0.1 -> 3.0.2 git 2.31.0 -> 2.32.0 python@3.9 3.9.5 -> 3.9.6 ==> Upgrading ruby 3.0.1 -> 3.0.2 ==> Downloading https://ghcr.io/v2/homebrew/core/ruby/manifests/3.0.2 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/ruby/blobs/sha256:39da97472055c844b0d23fc3c6030393d8fb8cde17098cf4eae0c590a95e6990 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:39da97472055c844b0d23fc3c6030393d8fb8cde17098cf4eae0c590a95e6990?se=2021-07-19T17%3A30%3A00Z&sig=n6lGnCqUmAlKP5NIVpN16pTgBYxmH1GmfB%2FTA5g5SgE%3D&sp=r&spr=https&sr=b&sv= ######################################################################## 100.0% ==> Pouring ruby--3.0.2.big_sur.bottle.tar.gz 🍺 /usr/local/Cellar/ruby/3.0.2: 16,390 files, 38.5MB Removing: /usr/local/Cellar/ruby/3.0.1... (16,358 files, 38.4MB) Removing: /Users/chandra/Library/Caches/Homebrew/ruby--3.0.1... (11.0MB) ==> Upgrading vim 8.2.3050 -> 8.2.3175 ==> Downloading https://ghcr.io/v2/homebrew/core/python/3.9/manifests/3.9.6 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/python/3.9/blobs/sha256:1397f8fbb9c5858aa02b0177787cb74b8eb0dfede69fc37b64e2787d76baf2fe ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:1397f8fbb9c5858aa02b0177787cb74b8eb0dfede69fc37b64e2787d76baf2fe?se=2021-07-19T17%3A30%3A00Z&sig=fm3Mzi19ThnhN50Kyp8n48rdZwByOKsg03RLZgsy2aE%3D&sp=r&spr=https&sr=b&sv=20 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/vim/manifests/8.2.3175 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/vim/blobs/sha256:c146d3ba4da3dfe873b670e0c5f396a7ecdffbe0befce600855561f04a1f8665 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:c146d3ba4da3dfe873b670e0c5f396a7ecdffbe0befce600855561f04a1f8665?se=2021-07-19T17%3A30%3A00Z&sig=QAiCQ%2BbpgVXdlq%2BTec7yeCOezEc47qv0KUHUBEe9w%2Fg%3D&sp=r&spr=https&sr=b ######################################################################## 100.0% ==> Installing dependencies for vim: python@3.9 ==> Installing vim dependency: python@3.9 ==> Pouring python@3.9--3.9.6.big_sur.bottle.tar.gz ..... ..... So far, the prerequisites were done. Now let’s initiate our actual process with brew install postgresql chandra ~ % brew install postgresql ==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/manifests/69.1 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/blobs/sha256:d46b8ec5c3db629e7848e9fd31e5ec99ed952d9c81c8936a2511fae803d831fd ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:d46b8ec5c3db629e7848e9fd31e5ec99ed952d9c81c8936a2511fae803d831fd?se=2021-07-19T17%3A25%3A00Z&sig=xHAdE8MjfV6UUK5HbaXtrl%2FkReEBcnTYJaeWH5U%2FeHE%3D&sp=r&spr=https&sr=b&s ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/krb5/manifests/1.19.1 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/krb5/blobs/sha256:d544c1111503eb27b253e190998b948889ea224b1ebecbceb6a4dd912317eb53 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:d544c1111503eb27b253e190998b948889ea224b1ebecbceb6a4dd912317eb53?se=2021-07-19T17%3A25%3A00Z&sig=sdQrYAuIhcUTLUmngoAOlTTQ0WV3PdV4uGHQmdDNcI0%3D&sp=r&spr=https&sr=b&sv=20 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/postgresql/manifests/13.3 ######################################################################## 100.0% ==> Downloading https://ghcr.io/v2/homebrew/core/postgresql/blobs/sha256:eaf28965ead970ecfb327b121ec6a07f0a4e39865797a1a0383605a17e5911e3 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:eaf28965ead970ecfb327b121ec6a07f0a4e39865797a1a0383605a17e5911e3?se=2021-07-19T17%3A25%3A00Z&sig=jZPXwrBY21IOMMZvx%2BHqiohONqM2g8dtdcuEzFsssRs%3D&sp=r&spr=https&sr=b&sv= ######################################################################## 100.0% ==> Installing dependencies for postgresql: icu4c and krb5 ==> Installing postgresql dependency: icu4c ==> Pouring icu4c--69.1.big_sur.bottle.tar.gz 🍺 /usr/local/Cellar/icu4c/69.1: 259 files, 72.8MB ==> Installing postgresql dependency: krb5 ==> Pouring krb5--1.19.1.big_sur.bottle.tar.gz 🍺 /usr/local/Cellar/krb5/1.19.1: 162 files, 5.2MB ==> Installing postgresql ==> Pouring postgresql--13.3.big_sur.bottle.tar.gz ==> /usr/local/Cellar/postgresql/13.3/bin/initdb --locale=C -E UTF-8 /usr/local/var/postgres ==> Caveats To migrate existing data from a previous major version of PostgreSQL run: brew postgresql-upgrade-database This formula has created a default database cluster with: initdb --locale=C -E UTF-8 /usr/local/var/postgres For more details, read: https://www.postgresql.org/docs/13/app-initdb.html To have launchd start postgresql now and restart at login: brew services start postgresql Or, if you don't want/need a background service you can just run: pg_ctl -D /usr/local/var/postgres start ==> Summary 🍺 /usr/local/Cellar/postgresql/13.3: 3,225 files, 42.7MB ==> Caveats ==> postgresql To migrate existing data from a previous major version of PostgreSQL run: brew postgresql-upgrade-database This formula has created a default database cluster with: initdb --locale=C -E UTF-8 /usr/local/var/postgres For more details, read: https://www.postgresql.org/docs/13/app-initdb.html To have launchd start postgresql now and restart at login: brew services start postgresql Or, if you don't want/need a background service you can just run: pg_ctl -D /usr/local/var/postgres start Homebrew installs PostgreSQL as a service in the Mac, so it is our task to start or stop the service. brew services start postgresqlcommand helps us to start the service, similarly brew services stop postgresqlused to stop the service. chandra~ % brew services start postgresql ==> Tapping homebrew/services Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'... remote: Enumerating objects: 1327, done. remote: Counting objects: 100% (206/206), done. remote: Compressing objects: 100% (146/146), done. remote: Total 1327 (delta 79), reused 173 (delta 57), pack-reused 1121 Receiving objects: 100% (1327/1327), 391.28 KiB | 682.00 KiB/s, done. Resolving deltas: 100% (555/555), done. Tapped 1 command (28 files, 473.4KB). ==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql) So far we have installed the PostgreSQL DB server on Mac successfully, but to get access to the DB we need user credentials, so let’s create a user and password for it. The psql postgrescommand allows you to get into the PostgreSQL terminal. chandra ~ % psql postgres psql (13.3) Type "help" for help. postgres=# As per the above output we get into the PostgreSQL REPL. Create a user with a login password goes like below. postgres=# CREATE ROLE otp WITH LOGIN PASSWORD ‘123456’; CREATE ROLE The above command creates a user without having any roles associated with it, now let’s assign create DB role. ALTER ROLE otp CREATEDB; ALTER ROLE Now we have a user and password to login into the PostgreSQL DB. Let’s log in with the user. chandra ~ % psql postgres -U otp psql (13.3) Type "help" for help. postgres=> We successfully get into the PostgreSQL console now. Let’s check the privileges bypassing the \ducommand. postgres=> \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- chandra | Superuser, Create role, Create DB, Replication, Bypass RLS | {} otp | Create DB | {} You can find the two users in the output, the first one is superuser, which was created while installing PostgreSQL itself, since it is a superuser it has almost all privileges. Next to that, we have our otpuser which we created in the previous step, it has Create DB role only. Done! We can change the password using ALTER command like the following. ALTER USER user_name WITH PASSWORD 'new_password'; The following command gives you the result. ~ % sudo find / -name "postgresql.conf" /usr/local/var/postgres/postgresql.conf In my case the postgresql.conf file found at /usr/local/var/postgres/ PostgreSQL installation Happy Learning 🙂 How to install Java on Mac OS How to install Apache Kafka on Ubuntu 18.04 Install Docker Desktop on Windows 10 How to install SOAPUI on Windows 10 Python – How to install the Flask framework? How set AWS Access Keys in Windows or Mac Environment How to setup or install MongoDB on Windows 10 How to Install Kubernetes on Ubuntu 18.04 Flask – How to install/setup Flask SQLAlchemy ? C How to Pass Arrays to Functions How to push docker image to docker hub ? How to install PuTTY on windows 10 How to install RabbitMQ on Windows 10 How to take Screenshot in Mac OS X How to install Elasticsearch on Windows 10 How to install Java on Mac OS How to install Apache Kafka on Ubuntu 18.04 Install Docker Desktop on Windows 10 How to install SOAPUI on Windows 10 Python – How to install the Flask framework? How set AWS Access Keys in Windows or Mac Environment How to setup or install MongoDB on Windows 10 How to Install Kubernetes on Ubuntu 18.04 Flask – How to install/setup Flask SQLAlchemy ? C How to Pass Arrays to Functions How to push docker image to docker hub ? How to install PuTTY on windows 10 How to install RabbitMQ on Windows 10 How to take Screenshot in Mac OS X How to install Elasticsearch on Windows 10
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 463, "s": 398, "text": "Here we will see how to install PostgreSQL on Mac with homebrew." }, { "code": null, "e": 484, "s": 463, "text": "Mac OS Big Sur 11.04" }, { "code": null, "e": 499, "s": 484, "text": "Homebrew 3.2.3" }, { "code": null, "e": 593, "s": 499, "text": "Make sure you have to install homebrew first, if you don’t have it yet, it’s straightforward." }, { "code": null, "e": 667, "s": 593, "text": "It’s always recommended to update homebrew before installing any package." }, { "code": null, "e": 881, "s": 667, "text": "chandra~ % brew update\nUpdated 1 tap (homebrew/core).\n==> Updated Formulae\nluv\n\nYou have 10 outdated formulae and 2 outdated casks installed.\nYou can upgrade them with brew upgrade\nor list them with brew outdated." }, { "code": null, "e": 982, "s": 881, "text": "The above brew update command gave me 10 outdated formulae and 2 casks. It may be different for you." }, { "code": null, "e": 3639, "s": 982, "text": "chandra ~ % brew upgrade\n==> Upgrading 10 outdated packages:\npyenv 2.0.0 -> 2.0.3\nvim 8.2.3050 -> 8.2.3175\nterraform 0.14.8 -> 1.0.2\naws/tap/aws-sam-cli 1.24.1 -> 1.26.0\npivotal/tap/gemfire 9.10.6 -> 9.10.8\npoetry 1.1.6 -> 1.1.7\npcre2 10.36 -> 10.37_1\nruby 3.0.1 -> 3.0.2\ngit 2.31.0 -> 2.32.0\npython@3.9 3.9.5 -> 3.9.6\n==> Upgrading ruby\n 3.0.1 -> 3.0.2 \n\n==> Downloading https://ghcr.io/v2/homebrew/core/ruby/manifests/3.0.2\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/ruby/blobs/sha256:39da97472055c844b0d23fc3c6030393d8fb8cde17098cf4eae0c590a95e6990\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:39da97472055c844b0d23fc3c6030393d8fb8cde17098cf4eae0c590a95e6990?se=2021-07-19T17%3A30%3A00Z&sig=n6lGnCqUmAlKP5NIVpN16pTgBYxmH1GmfB%2FTA5g5SgE%3D&sp=r&spr=https&sr=b&sv=\n######################################################################## 100.0%\n==> Pouring ruby--3.0.2.big_sur.bottle.tar.gz\n🍺 /usr/local/Cellar/ruby/3.0.2: 16,390 files, 38.5MB\nRemoving: /usr/local/Cellar/ruby/3.0.1... (16,358 files, 38.4MB)\nRemoving: /Users/chandra/Library/Caches/Homebrew/ruby--3.0.1... (11.0MB)\n==> Upgrading vim\n 8.2.3050 -> 8.2.3175 \n\n==> Downloading https://ghcr.io/v2/homebrew/core/python/3.9/manifests/3.9.6\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/python/3.9/blobs/sha256:1397f8fbb9c5858aa02b0177787cb74b8eb0dfede69fc37b64e2787d76baf2fe\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:1397f8fbb9c5858aa02b0177787cb74b8eb0dfede69fc37b64e2787d76baf2fe?se=2021-07-19T17%3A30%3A00Z&sig=fm3Mzi19ThnhN50Kyp8n48rdZwByOKsg03RLZgsy2aE%3D&sp=r&spr=https&sr=b&sv=20\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/vim/manifests/8.2.3175\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/vim/blobs/sha256:c146d3ba4da3dfe873b670e0c5f396a7ecdffbe0befce600855561f04a1f8665\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:c146d3ba4da3dfe873b670e0c5f396a7ecdffbe0befce600855561f04a1f8665?se=2021-07-19T17%3A30%3A00Z&sig=QAiCQ%2BbpgVXdlq%2BTec7yeCOezEc47qv0KUHUBEe9w%2Fg%3D&sp=r&spr=https&sr=b\n######################################################################## 100.0%\n==> Installing dependencies for vim: python@3.9\n==> Installing vim dependency: python@3.9\n==> Pouring python@3.9--3.9.6.big_sur.bottle.tar.gz\n.....\n.....\n" }, { "code": null, "e": 3676, "s": 3639, "text": "So far, the prerequisites were done." }, { "code": null, "e": 3743, "s": 3676, "text": "Now let’s initiate our actual process with brew install postgresql" }, { "code": null, "e": 7262, "s": 3743, "text": "chandra ~ % brew install postgresql \n==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/manifests/69.1\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/icu4c/blobs/sha256:d46b8ec5c3db629e7848e9fd31e5ec99ed952d9c81c8936a2511fae803d831fd\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:d46b8ec5c3db629e7848e9fd31e5ec99ed952d9c81c8936a2511fae803d831fd?se=2021-07-19T17%3A25%3A00Z&sig=xHAdE8MjfV6UUK5HbaXtrl%2FkReEBcnTYJaeWH5U%2FeHE%3D&sp=r&spr=https&sr=b&s\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/krb5/manifests/1.19.1\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/krb5/blobs/sha256:d544c1111503eb27b253e190998b948889ea224b1ebecbceb6a4dd912317eb53\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:d544c1111503eb27b253e190998b948889ea224b1ebecbceb6a4dd912317eb53?se=2021-07-19T17%3A25%3A00Z&sig=sdQrYAuIhcUTLUmngoAOlTTQ0WV3PdV4uGHQmdDNcI0%3D&sp=r&spr=https&sr=b&sv=20\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/postgresql/manifests/13.3\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/postgresql/blobs/sha256:eaf28965ead970ecfb327b121ec6a07f0a4e39865797a1a0383605a17e5911e3\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:eaf28965ead970ecfb327b121ec6a07f0a4e39865797a1a0383605a17e5911e3?se=2021-07-19T17%3A25%3A00Z&sig=jZPXwrBY21IOMMZvx%2BHqiohONqM2g8dtdcuEzFsssRs%3D&sp=r&spr=https&sr=b&sv=\n######################################################################## 100.0%\n==> Installing dependencies for postgresql: icu4c and krb5\n==> Installing postgresql dependency: icu4c\n==> Pouring icu4c--69.1.big_sur.bottle.tar.gz\n🍺 /usr/local/Cellar/icu4c/69.1: 259 files, 72.8MB\n==> Installing postgresql dependency: krb5\n==> Pouring krb5--1.19.1.big_sur.bottle.tar.gz\n🍺 /usr/local/Cellar/krb5/1.19.1: 162 files, 5.2MB\n==> Installing postgresql\n==> Pouring postgresql--13.3.big_sur.bottle.tar.gz\n==> /usr/local/Cellar/postgresql/13.3/bin/initdb --locale=C -E UTF-8 /usr/local/var/postgres\n==> Caveats\nTo migrate existing data from a previous major version of PostgreSQL run:\n brew postgresql-upgrade-database\n\nThis formula has created a default database cluster with:\n initdb --locale=C -E UTF-8 /usr/local/var/postgres\nFor more details, read:\n https://www.postgresql.org/docs/13/app-initdb.html\n\nTo have launchd start postgresql now and restart at login:\n brew services start postgresql\nOr, if you don't want/need a background service you can just run:\n pg_ctl -D /usr/local/var/postgres start\n==> Summary\n🍺 /usr/local/Cellar/postgresql/13.3: 3,225 files, 42.7MB\n==> Caveats\n==> postgresql\nTo migrate existing data from a previous major version of PostgreSQL run:\n brew postgresql-upgrade-database\n\nThis formula has created a default database cluster with:\n initdb --locale=C -E UTF-8 /usr/local/var/postgres\nFor more details, read:\n https://www.postgresql.org/docs/13/app-initdb.html\n\nTo have launchd start postgresql now and restart at login:\n brew services start postgresql\nOr, if you don't want/need a background service you can just run:\n pg_ctl -D /usr/local/var/postgres start" }, { "code": null, "e": 7364, "s": 7262, "text": "Homebrew installs PostgreSQL as a service in the Mac, so it is our task to start or stop the service." }, { "code": null, "e": 7498, "s": 7364, "text": "brew services start postgresqlcommand helps us to start the service, similarly brew services stop postgresqlused to stop the service." }, { "code": null, "e": 8079, "s": 7498, "text": "chandra~ % brew services start postgresql\n==> Tapping homebrew/services\nCloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'...\nremote: Enumerating objects: 1327, done.\nremote: Counting objects: 100% (206/206), done.\nremote: Compressing objects: 100% (146/146), done.\nremote: Total 1327 (delta 79), reused 173 (delta 57), pack-reused 1121\nReceiving objects: 100% (1327/1327), 391.28 KiB | 682.00 KiB/s, done.\nResolving deltas: 100% (555/555), done.\nTapped 1 command (28 files, 473.4KB).\n==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)" }, { "code": null, "e": 8248, "s": 8079, "text": "So far we have installed the PostgreSQL DB server on Mac successfully, but to get access to the DB we need user credentials, so let’s create a user and password for it." }, { "code": null, "e": 8321, "s": 8248, "text": "The psql postgrescommand allows you to get into the PostgreSQL terminal." }, { "code": null, "e": 8394, "s": 8321, "text": "chandra ~ % psql postgres \npsql (13.3)\nType \"help\" for help.\n\npostgres=#" }, { "code": null, "e": 8451, "s": 8394, "text": "As per the above output we get into the PostgreSQL REPL." }, { "code": null, "e": 8504, "s": 8451, "text": "Create a user with a login password goes like below." }, { "code": null, "e": 8573, "s": 8504, "text": "postgres=# CREATE ROLE otp WITH LOGIN PASSWORD ‘123456’;\nCREATE ROLE" }, { "code": null, "e": 8684, "s": 8573, "text": "The above command creates a user without having any roles associated with it, now let’s assign create DB role." }, { "code": null, "e": 8720, "s": 8684, "text": "ALTER ROLE otp CREATEDB;\nALTER ROLE" }, { "code": null, "e": 8813, "s": 8720, "text": "Now we have a user and password to login into the PostgreSQL DB. Let’s log in with the user." }, { "code": null, "e": 8892, "s": 8813, "text": "chandra ~ % psql postgres -U otp\npsql (13.3)\nType \"help\" for help.\n\npostgres=>" }, { "code": null, "e": 8999, "s": 8892, "text": "We successfully get into the PostgreSQL console now. Let’s check the privileges bypassing the \\ducommand." }, { "code": null, "e": 9388, "s": 8999, "text": "postgres=> \\du\n List of roles\n Role name | Attributes | Member of \n-----------+------------------------------------------------------------+-----------\n chandra | Superuser, Create role, Create DB, Replication, Bypass RLS | {}\n otp | Create DB | {}\n\n" }, { "code": null, "e": 9667, "s": 9388, "text": "You can find the two users in the output, the first one is superuser, which was created while installing PostgreSQL itself, since it is a superuser it has almost all privileges. Next to that, we have our otpuser which we created in the previous step, it has Create DB role only." }, { "code": null, "e": 9673, "s": 9667, "text": "Done!" }, { "code": null, "e": 9740, "s": 9673, "text": "We can change the password using ALTER command like the following." }, { "code": null, "e": 9791, "s": 9740, "text": "ALTER USER user_name WITH PASSWORD 'new_password';" }, { "code": null, "e": 9835, "s": 9791, "text": "The following command gives you the result." }, { "code": null, "e": 9922, "s": 9835, "text": "~ % sudo find / -name \"postgresql.conf\" \n/usr/local/var/postgres/postgresql.conf" }, { "code": null, "e": 9992, "s": 9922, "text": "In my case the postgresql.conf file found at /usr/local/var/postgres/" }, { "code": null, "e": 10016, "s": 9992, "text": "PostgreSQL installation" }, { "code": null, "e": 10033, "s": 10016, "text": "Happy Learning 🙂" }, { "code": null, "e": 10643, "s": 10033, "text": "\nHow to install Java on Mac OS\nHow to install Apache Kafka on Ubuntu 18.04\nInstall Docker Desktop on Windows 10\nHow to install SOAPUI on Windows 10\nPython – How to install the Flask framework?\nHow set AWS Access Keys in Windows or Mac Environment\nHow to setup or install MongoDB on Windows 10\nHow to Install Kubernetes on Ubuntu 18.04\nFlask – How to install/setup Flask SQLAlchemy ?\nC How to Pass Arrays to Functions\nHow to push docker image to docker hub ?\nHow to install PuTTY on windows 10\nHow to install RabbitMQ on Windows 10\nHow to take Screenshot in Mac OS X\nHow to install Elasticsearch on Windows 10\n" }, { "code": null, "e": 10673, "s": 10643, "text": "How to install Java on Mac OS" }, { "code": null, "e": 10717, "s": 10673, "text": "How to install Apache Kafka on Ubuntu 18.04" }, { "code": null, "e": 10754, "s": 10717, "text": "Install Docker Desktop on Windows 10" }, { "code": null, "e": 10790, "s": 10754, "text": "How to install SOAPUI on Windows 10" }, { "code": null, "e": 10835, "s": 10790, "text": "Python – How to install the Flask framework?" }, { "code": null, "e": 10889, "s": 10835, "text": "How set AWS Access Keys in Windows or Mac Environment" }, { "code": null, "e": 10935, "s": 10889, "text": "How to setup or install MongoDB on Windows 10" }, { "code": null, "e": 10977, "s": 10935, "text": "How to Install Kubernetes on Ubuntu 18.04" }, { "code": null, "e": 11025, "s": 10977, "text": "Flask – How to install/setup Flask SQLAlchemy ?" }, { "code": null, "e": 11059, "s": 11025, "text": "C How to Pass Arrays to Functions" }, { "code": null, "e": 11100, "s": 11059, "text": "How to push docker image to docker hub ?" }, { "code": null, "e": 11135, "s": 11100, "text": "How to install PuTTY on windows 10" }, { "code": null, "e": 11173, "s": 11135, "text": "How to install RabbitMQ on Windows 10" }, { "code": null, "e": 11208, "s": 11173, "text": "How to take Screenshot in Mac OS X" } ]
How to convert InputStream object to a String in Java?
Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc. There are two types of streams available − InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination. This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images. You can convert an InputStream Object int to a String in several ways using core Java. You can also use external libraries like IOUtils, Guava for this purpose. Following are some ways to convert an InputStream object to String in Java (not including external libraries). The readLine() method of the BufferedReader class reads a single line from the contents of the current reader. To convert an InputStream Object int to a String using this method. Instantiate an InputStreamReader class by passing your InputStream object as parameter. Then, create a BufferedReader, by passing above obtained InputStreamReader object as a parameter. Now, read each line from this reader using the readLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method. import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToString{ public static void main(String args[]) throws IOException { //Creating an InputStream object InputStream inputStream = new FileInputStream("D:/sample.txt"); //creating an InputStreamReader object InputStreamReader isReader = new InputStreamReader(inputStream); //Creating a BufferedReader object BufferedReader reader = new BufferedReader(isReader); StringBuffer sb = new StringBuffer(); String str; while((str = reader.readLine())!= null){ sb.append(str); } System.out.println(sb.toString()); } } Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The nextLine() method of the Scanner class reads the contents of the underlying inputStream line by line. To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method. import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class InputStreamToString { public static void main(String args[]) throws IOException { //Creating an InputStream object InputStream inputStream = new FileInputStream("D:/sample.txt"); //Creating a Scanner object Scanner sc = new Scanner(inputStream); //Reading line by line from scanner to StringBuffer StringBuffer sb = new StringBuffer(); while(sc.hasNext()){ sb.append(sc.nextLine()); } System.out.println(sb.toString()); } } Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The read() method of the InputStreamReader class accepts a character array as a parameter and reads the contents of the current Stream to the given array. To convert an InputStream Object int to a String using this method. Instantiate an InputStreamReader class by passing your InputStream object as parameter. Read the contents of the current stream reader to a character array using the read() method of the InputStreamReader class. Finally convert the character to a String by passing it as a parameter to its constructor. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileInputStreamExample { public static void main(String args[]) throws IOException { //Creating a File object File file = new File("D:/sample.txt"); //Creating an InputStream object InputStream inputStream = new FileInputStream(file); //creating an InputStreamReader object InputStreamReader isReader = new InputStreamReader(inputStream); //Creating a character array char charArray[] = new char[(int) file.length()]; //Reading the contents of the reader isReader.read(charArray); //Converting character array to a String String contents = new String(charArray); System.out.println(contents); } } Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
[ { "code": null, "e": 1233, "s": 1062, "text": "Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc." }, { "code": null, "e": 1276, "s": 1233, "text": "There are two types of streams available −" }, { "code": null, "e": 1344, "s": 1276, "text": "InputStream − This is used to read (sequential) data from a source." }, { "code": null, "e": 1404, "s": 1344, "text": "OutputStream − This is used to write data to a destination." }, { "code": null, "e": 1549, "s": 1404, "text": "This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images." }, { "code": null, "e": 1821, "s": 1549, "text": "You can convert an InputStream Object int to a String in several ways using core Java. You can also use external libraries like IOUtils, Guava for this purpose. Following are some ways to convert an InputStream object to String in Java (not including external libraries)." }, { "code": null, "e": 2000, "s": 1821, "text": "The readLine() method of the BufferedReader class reads a single line from the contents of the current reader. To convert an InputStream Object int to a String using this method." }, { "code": null, "e": 2088, "s": 2000, "text": "Instantiate an InputStreamReader class by passing your InputStream object as parameter." }, { "code": null, "e": 2186, "s": 2088, "text": "Then, create a BufferedReader, by passing above obtained InputStreamReader object as a parameter." }, { "code": null, "e": 2291, "s": 2186, "text": "Now, read each line from this reader using the readLine() method and append it to a StringBuffer object." }, { "code": null, "e": 2363, "s": 2291, "text": "Finally convert the StringBuffer to String using the toString() method." }, { "code": null, "e": 3129, "s": 2363, "text": "import java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\npublic class InputStreamToString{\n public static void main(String args[]) throws IOException {\n //Creating an InputStream object\n InputStream inputStream = new FileInputStream(\"D:/sample.txt\");\n //creating an InputStreamReader object\n InputStreamReader isReader = new InputStreamReader(inputStream);\n //Creating a BufferedReader object\n BufferedReader reader = new BufferedReader(isReader);\n StringBuffer sb = new StringBuffer();\n String str;\n while((str = reader.readLine())!= null){\n sb.append(str);\n }\n System.out.println(sb.toString());\n }\n}" }, { "code": null, "e": 3336, "s": 3129, "text": "Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line\ncontent and prefer to learn new skills at their own pace from the comforts of their drawing rooms." }, { "code": null, "e": 3510, "s": 3336, "text": "The nextLine() method of the Scanner class reads the contents of the underlying inputStream line by line. To convert an InputStream Object int to a String using this method." }, { "code": null, "e": 3589, "s": 3510, "text": "Instantiate the Scanner class by passing your InputStream object as parameter." }, { "code": null, "e": 3690, "s": 3589, "text": "Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object." }, { "code": null, "e": 3762, "s": 3690, "text": "Finally convert the StringBuffer to String using the toString() method." }, { "code": null, "e": 4382, "s": 3762, "text": "import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Scanner;\npublic class InputStreamToString {\n public static void main(String args[]) throws IOException {\n //Creating an InputStream object\n InputStream inputStream = new FileInputStream(\"D:/sample.txt\");\n //Creating a Scanner object\n Scanner sc = new Scanner(inputStream);\n //Reading line by line from scanner to StringBuffer\n StringBuffer sb = new StringBuffer();\n while(sc.hasNext()){\n sb.append(sc.nextLine());\n }\n System.out.println(sb.toString());\n }\n}" }, { "code": null, "e": 4589, "s": 4382, "text": "Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line\ncontent and prefer to learn new skills at their own pace from the comforts of their drawing rooms." }, { "code": null, "e": 4812, "s": 4589, "text": "The read() method of the InputStreamReader class accepts a character array as a parameter and reads the contents of the current Stream to the given array. To convert an InputStream Object int to a String using this method." }, { "code": null, "e": 4900, "s": 4812, "text": "Instantiate an InputStreamReader class by passing your InputStream object as parameter." }, { "code": null, "e": 5024, "s": 4900, "text": "Read the contents of the current stream reader to a character array using the read() method of the InputStreamReader class." }, { "code": null, "e": 5115, "s": 5024, "text": "Finally convert the character to a String by passing it as a parameter to its constructor." }, { "code": null, "e": 5952, "s": 5115, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\npublic class FileInputStreamExample {\n public static void main(String args[]) throws IOException {\n //Creating a File object\n File file = new File(\"D:/sample.txt\");\n //Creating an InputStream object\n InputStream inputStream = new FileInputStream(file);\n //creating an InputStreamReader object\n InputStreamReader isReader = new InputStreamReader(inputStream);\n //Creating a character array\n char charArray[] = new char[(int) file.length()];\n //Reading the contents of the reader\n isReader.read(charArray);\n //Converting character array to a String\n String contents = new String(charArray);\n System.out.println(contents);\n }\n}" }, { "code": null, "e": 6160, "s": 5952, "text": "Tutorials Point originated from the idea that there exists a class of readers who respond better to on-line \ncontent and prefer to learn new skills at their own pace from the comforts of their drawing rooms." } ]
Calculate score of parentheses from a given string - GeeksforGeeks
10 Jun, 2021 Given string str of length N, consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules: “()” has a score of 1. “a b” has a score of a + b, where a and b are individual pairs of balanced parentheses. “(a)” has a score twice of a i.e., the score is 2 * score of a. Examples: Input: str = “()()” Output: 2 Explanation: The string str is of the form “ab”, that makes the total score = (score of a) + (score of b) = 1 + 1 = 2. Input: str = “(()(()))”Output: 6Explanation: The string str is of the form “(a(b))” which makes the total score = 2 * ((score of a) + 2*(score of b)) = 2*(1 + 2*(1)) = 6. Tree-based Approach: Refer to the previous post of this article for the tree-based approach. Time Complexity: O(N)Auxiliary Space: O(N) Stack-based Approach: The idea is to traverse the string and while traversing the string str, if the parenthesis ‘)’ is encountered, then calculate the score of this pair of parentheses. Follow the steps below to solve the problem: Initialize a stack, say S, to keep track of the score and initially push 0 into the stack. Traverse the string str using the variable i and perform the following steps:If the value of str[i] is equal to ‘(‘, push 0 to the stack S.Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack. If the value of str[i] is equal to ‘(‘, push 0 to the stack S. Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack. Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack. If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack. After completing the above steps, print the value of the top of the stack as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the score// of the parentheses using stackvoid scoreOfParentheses(string s){ // To keep track of the score stack<int> stack; // Initially, push 0 to stack stack.push(0); // Traverse the string s for (char c : s) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.top(); stack.pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.top() += val; } } // Print the score cout << stack.top();} // Driver Codeint main(){ string S = "(()(()))"; scoreOfParentheses(S); return 0;} // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to calculate the score // of the parentheses using stack static void scoreOfParentheses(String s) { // To keep track of the score Stack<Integer> stack = new Stack<>(); // Initially, push 0 to stack stack.push(0); // Traverse the string s for (char c : s.toCharArray()) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.push(stack.pop() + val); } } // Print the score System.out.println(stack.peek()); } // Driver code public static void main(String[] args) { String S = "(()(()))"; // Function call scoreOfParentheses(S); }} // This code is contributed by Kingash. # Python 3 program for the above approach # Function to calculate the score# of the parentheses using stackdef scoreOfParentheses(s): # To keep track of the score stack = [] # Initially, push 0 to stack stack.append(0) # Traverse the string s for c in s: # If '(' is encountered, # then push 0 to stack if (c == '('): stack.append(0) # Otherwise else: # Balance the last '(', and store # the score of inner parentheses tmp = stack[len(stack) - 1] stack = stack[:-1] val = 0 # If tmp is not zero, it means # inner parentheses exists if (tmp > 0): val = tmp * 2 # Otherwise, it means no # inner parentheses exists else: val = 1 # Pass the score of this level # to parent parentheses stack[len(stack) - 1] += val # Print the score print(stack[len(stack) - 1]) # Driver Codeif __name__ == '__main__': S = "(()(()))" scoreOfParentheses(S) # This code is contributed by bgangwar59. // C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ // Function to calculate the score // of the parentheses using stack static void scoreOfParentheses(String s) { // To keep track of the score Stack<int> stack = new Stack<int>(); // Initially, push 0 to stack stack.Push(0); // Traverse the string s foreach (char c in s.ToCharArray()) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.Push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.Pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.Push(stack.Pop() + val); } } // Print the score Console.WriteLine(stack.Peek()); } // Driver code public static void Main(String[] args) { String S = "(()(()))"; // Function call scoreOfParentheses(S); }} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // Function to calculate the score// of the parentheses using stackfunction scoreOfParentheses(s){ // To keep track of the score var stack = []; // Initially, push 0 to stack stack.push(0); // Traverse the string s s.split('').forEach(c => { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses var tmp = stack[stack.length-1]; stack.pop(); var val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack[stack.length-1] += val; } }); // Print the score document.write( stack[stack.length-1]);} // Driver Codevar S = "(()(()))";scoreOfParentheses(S); </script> 6 Time Complexity: O(N)Auxiliary Space: O(N) bgangwar59 Kingash 29AjayKumar rrrtnx cpp-stack Parentheses-Problems Mathematical Stack Strings Strings Mathematical Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Prime Numbers Modulo Operator (%) in C/C++ with Examples Find all factors of a natural number | Set 1 Program to find sum of elements in a given array Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Inorder Tree Traversal without Recursion Queue using Stacks
[ { "code": null, "e": 24747, "s": 24719, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24903, "s": 24747, "text": "Given string str of length N, consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules:" }, { "code": null, "e": 24926, "s": 24903, "text": "“()” has a score of 1." }, { "code": null, "e": 25014, "s": 24926, "text": "“a b” has a score of a + b, where a and b are individual pairs of balanced parentheses." }, { "code": null, "e": 25078, "s": 25014, "text": "“(a)” has a score twice of a i.e., the score is 2 * score of a." }, { "code": null, "e": 25088, "s": 25078, "text": "Examples:" }, { "code": null, "e": 25237, "s": 25088, "text": "Input: str = “()()” Output: 2 Explanation: The string str is of the form “ab”, that makes the total score = (score of a) + (score of b) = 1 + 1 = 2." }, { "code": null, "e": 25408, "s": 25237, "text": "Input: str = “(()(()))”Output: 6Explanation: The string str is of the form “(a(b))” which makes the total score = 2 * ((score of a) + 2*(score of b)) = 2*(1 + 2*(1)) = 6." }, { "code": null, "e": 25544, "s": 25408, "text": "Tree-based Approach: Refer to the previous post of this article for the tree-based approach. Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 25776, "s": 25544, "text": "Stack-based Approach: The idea is to traverse the string and while traversing the string str, if the parenthesis ‘)’ is encountered, then calculate the score of this pair of parentheses. Follow the steps below to solve the problem:" }, { "code": null, "e": 25867, "s": 25776, "text": "Initialize a stack, say S, to keep track of the score and initially push 0 into the stack." }, { "code": null, "e": 26289, "s": 25867, "text": "Traverse the string str using the variable i and perform the following steps:If the value of str[i] is equal to ‘(‘, push 0 to the stack S.Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack." }, { "code": null, "e": 26352, "s": 26289, "text": "If the value of str[i] is equal to ‘(‘, push 0 to the stack S." }, { "code": null, "e": 26635, "s": 26352, "text": "Otherwise, perform the following steps:Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack.If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack." }, { "code": null, "e": 26736, "s": 26635, "text": "Store the top of the stack S in a variable, say temp, and pop the element from the top of the stack." }, { "code": null, "e": 26880, "s": 26736, "text": "If the value of temp is non-zero, then inner parentheses exist. Add 2 * temp to the top of the stack. Otherwise, add 1 to the top of the stack." }, { "code": null, "e": 26969, "s": 26880, "text": "After completing the above steps, print the value of the top of the stack as the result." }, { "code": null, "e": 27021, "s": 26969, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27025, "s": 27021, "text": "C++" }, { "code": null, "e": 27030, "s": 27025, "text": "Java" }, { "code": null, "e": 27038, "s": 27030, "text": "Python3" }, { "code": null, "e": 27041, "s": 27038, "text": "C#" }, { "code": null, "e": 27052, "s": 27041, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the score// of the parentheses using stackvoid scoreOfParentheses(string s){ // To keep track of the score stack<int> stack; // Initially, push 0 to stack stack.push(0); // Traverse the string s for (char c : s) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.top(); stack.pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.top() += val; } } // Print the score cout << stack.top();} // Driver Codeint main(){ string S = \"(()(()))\"; scoreOfParentheses(S); return 0;}", "e": 28235, "s": 27052, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to calculate the score // of the parentheses using stack static void scoreOfParentheses(String s) { // To keep track of the score Stack<Integer> stack = new Stack<>(); // Initially, push 0 to stack stack.push(0); // Traverse the string s for (char c : s.toCharArray()) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.push(stack.pop() + val); } } // Print the score System.out.println(stack.peek()); } // Driver code public static void main(String[] args) { String S = \"(()(()))\"; // Function call scoreOfParentheses(S); }} // This code is contributed by Kingash.", "e": 29503, "s": 28235, "text": null }, { "code": "# Python 3 program for the above approach # Function to calculate the score# of the parentheses using stackdef scoreOfParentheses(s): # To keep track of the score stack = [] # Initially, push 0 to stack stack.append(0) # Traverse the string s for c in s: # If '(' is encountered, # then push 0 to stack if (c == '('): stack.append(0) # Otherwise else: # Balance the last '(', and store # the score of inner parentheses tmp = stack[len(stack) - 1] stack = stack[:-1] val = 0 # If tmp is not zero, it means # inner parentheses exists if (tmp > 0): val = tmp * 2 # Otherwise, it means no # inner parentheses exists else: val = 1 # Pass the score of this level # to parent parentheses stack[len(stack) - 1] += val # Print the score print(stack[len(stack) - 1]) # Driver Codeif __name__ == '__main__': S = \"(()(()))\" scoreOfParentheses(S) # This code is contributed by bgangwar59.", "e": 30676, "s": 29503, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ // Function to calculate the score // of the parentheses using stack static void scoreOfParentheses(String s) { // To keep track of the score Stack<int> stack = new Stack<int>(); // Initially, push 0 to stack stack.Push(0); // Traverse the string s foreach (char c in s.ToCharArray()) { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.Push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses int tmp = stack.Pop(); int val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack.Push(stack.Pop() + val); } } // Print the score Console.WriteLine(stack.Peek()); } // Driver code public static void Main(String[] args) { String S = \"(()(()))\"; // Function call scoreOfParentheses(S); }} // This code is contributed by 29AjayKumar", "e": 31944, "s": 30676, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to calculate the score// of the parentheses using stackfunction scoreOfParentheses(s){ // To keep track of the score var stack = []; // Initially, push 0 to stack stack.push(0); // Traverse the string s s.split('').forEach(c => { // If '(' is encountered, // then push 0 to stack if (c == '(') stack.push(0); // Otherwise else { // Balance the last '(', and store // the score of inner parentheses var tmp = stack[stack.length-1]; stack.pop(); var val = 0; // If tmp is not zero, it means // inner parentheses exists if (tmp > 0) val = tmp * 2; // Otherwise, it means no // inner parentheses exists else val = 1; // Pass the score of this level // to parent parentheses stack[stack.length-1] += val; } }); // Print the score document.write( stack[stack.length-1]);} // Driver Codevar S = \"(()(()))\";scoreOfParentheses(S); </script>", "e": 33126, "s": 31944, "text": null }, { "code": null, "e": 33131, "s": 33129, "text": "6" }, { "code": null, "e": 33177, "s": 33133, "text": "Time Complexity: O(N)Auxiliary Space: O(N) " }, { "code": null, "e": 33188, "s": 33177, "text": "bgangwar59" }, { "code": null, "e": 33196, "s": 33188, "text": "Kingash" }, { "code": null, "e": 33208, "s": 33196, "text": "29AjayKumar" }, { "code": null, "e": 33215, "s": 33208, "text": "rrrtnx" }, { "code": null, "e": 33225, "s": 33215, "text": "cpp-stack" }, { "code": null, "e": 33246, "s": 33225, "text": "Parentheses-Problems" }, { "code": null, "e": 33259, "s": 33246, "text": "Mathematical" }, { "code": null, "e": 33265, "s": 33259, "text": "Stack" }, { "code": null, "e": 33273, "s": 33265, "text": "Strings" }, { "code": null, "e": 33281, "s": 33273, "text": "Strings" }, { "code": null, "e": 33294, "s": 33281, "text": "Mathematical" }, { "code": null, "e": 33300, "s": 33294, "text": "Stack" }, { "code": null, "e": 33398, "s": 33300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33407, "s": 33398, "text": "Comments" }, { "code": null, "e": 33420, "s": 33407, "text": "Old Comments" }, { "code": null, "e": 33444, "s": 33420, "text": "Merge two sorted arrays" }, { "code": null, "e": 33458, "s": 33444, "text": "Prime Numbers" }, { "code": null, "e": 33501, "s": 33458, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33546, "s": 33501, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 33595, "s": 33546, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33643, "s": 33595, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33663, "s": 33643, "text": "Stack Class in Java" }, { "code": null, "e": 33679, "s": 33663, "text": "Stack in Python" }, { "code": null, "e": 33720, "s": 33679, "text": "Inorder Tree Traversal without Recursion" } ]
Working with Hive using AWS S3 and Python | by Nishakanthi Angulgamuwa | Towards Data Science
In this article, I’m going to share my experience of maintaining a Hive schema. This will be useful to the freshers who are willing to step into Big Data technologies. Mainly this will describe how to connect to Hive using python and How to use AWS S3 as the data storage. If you are not familiar with Hive concepts please go through the article on Wikipedia. The main objective of this article is to provide a guide to connect Hive through python and execute queries. I’m using “Pyhive” library for that. I’m creating my connection class as “HiveConnection” and Hive queries will be passed into the functions. AWS S3 will be used as the file storage for Hive tables. import pandas as pdfrom pyhive import hiveclass HiveConnection: @staticmethod def select_query(query_str: str, database:str =HIVE_SCHEMA) -> pd.DataFrame: """ Execute a select query which returns a result set :param query_str: select query to be executed :param database: Hive Schema :return: """ conn = hive.Connection(host=HIVE_URL, port=HIVE_PORT, database=database, username=HIVE_USER) try: result = pd.read_sql(query_str, conn) return result finally: conn.close() @staticmethod def execute_query(query_str: str, database: str=HIVE_SCHEMA): """ execute an query which does not return a result set. ex: INSERT, CREATE, DROP, ALTER TABLE :param query_str: Hive query to be executed :param database: Hive Schema :return: """ conn = hive.Connection(host=HIVE_URL, port=HIVE_PORT, database=database, username=HIVE_USER) cur = conn.cursor() # Make sure to set the staging default to HDFS to avoid some potential S3 related errors cur.execute("SET hive.exec.stagingdir=/tmp/hive/") cur.execute("SET hive.exec.scratchdir=/tmp/hive/") try: cur.execute(query_str) return "SUCCESS" finally: conn.close() I’m keeping the queries as separated strings. This way you can format the queries with external parameters when necessary. Hive configurations (HIVE_URL, HIVE_PORT, HIVE_USER, HIVE_SCHEMA) as constants. Function “select_query” will be use to retrieve data and function “execute_query” will be used for other queries. Hive provides a shell interactive tool to initiate databases, tables and manipulate the data in tables. We can go into the Hive command line by typing command “hive”. You can execute all the queries given in this article in the shell also. Schema is a collection of tables which is similar to a database. Both keywords SCHEMA and DATABASE are allowed in Hive. We can pick either. Here we use SCHEMA instead of DATABASE. Schema can be created with “CREATE SCHEMA”. To go inside the schema, the keyword “USE” is available. CREATE SCHEMA userdb;USE userdb; There are three types of Hive tables. They are Internal, External and Temporary. Internal tables store metadata of the table inside the database as well as the table data. But external tables store metadata inside the database while table data is stored in a remote location like AWS S3 and hdfs. When dropping an internal table, all the table data will be erased with the metadata. When dropping an external table, only the metadata will be erased; not the table data. In this way, actual data will be protected. If you point a new table to the same location, data will be visible through the new table. Hive is a data warehouse and uses MapReduce Framework. So the speed of the data retrieving may not fair enough for small queries. Hive tables can be partitioned in order to increase the performance. Partitioning technique can be applied to both external and internal tables. Concepts like bucketing are also there. You can choose any of these techniques to enhance performance. Temporary tables are useful when copying data from one place to another. It acts as a temporary location to hold the data within a database session. All the temporary tables are cleared after the session timeout. Creating a temporary table is not useful with “Pyhive” library as multiple queries are not supported in a single session. Even though we created a table, the same session will no longer be available to access the table. But this is possible in the Hive command line. You can create a temporary table and then select data from that table in a single session. The following query is to create an internal table with a remote data storage, AWS S3. The file format is CSV and field are terminated by a comma. “s3_location” points to the S3 directory where the data files are. This is a user-defined external parameter for the query string. It should be passed in the time of query formatting. CREATE TABLE `user_info` (`business_unit` INT,`employee_id` INT,`email` VARCHAR(250),`first_name` VARCHAR(250),`last_name` VARCHAR(250),`gender` VARCHAR(250),`birthday` DATE,`created_date` DATE,`updated_date` DATE)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ESCAPED BY '\\'LOCATION '{s3_location}'TBLPROPERTIES ("s3select.format" = "csv","skip.header.line.count" = "1"); If the data strings contain commas, it will break the table structure. So I have defined an escape character and all the unnecessary commas needed to be preceded by this escape character before creating the table. Following is an example record. Note that email contains a comma. 1,1,ann,smith@gamil.com,Ann,Smith,female,'1992–07–01','2019–09–01','2019–12–31' above record need to be formatted like this :1,1,ann\\,smith@gamil.com,Ann,Smith,female,'1992–07–01','2019–09–01','2019–12–31' Here, I have partitioned “user_info” table with “business_unit” and “created_date” CREATE EXTERNAL TABLE `user_info` ( `employee_id` INT, `email` VARCHAR(250), `first_name` VARCHAR(250), `last_name` VARCHAR(250), `gender` VARCHAR(250), `birthday` DATE, `updated_date` DATE) partitioned by(`business_unit` INT, `created_date` DATE,)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ESCAPED BY '\\'STORED ASINPUTFORMAT'com.amazonaws.emr.s3select.hive.S3SelectableTextInputFormat'OUTPUTFORMAT'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION '{s3_location}' TBLPROPERTIES ("s3select.format" = "csv","s3select.headerInfo" = "ignore"); Query for creating a temporary table. CREATE TEMPORARY TABLE `user_info` ( `business_unit` INT, `employee_id` VARCHAR(250), `email` VARCHAR(250), `first_name` VARCHAR(250), `last_name` VARCHAR(250), `gender` VARCHAR(250), `birthday` DATE, `created_date` DATE, `updated_date` DATE) ; Query to drop a table. If you are dropping an external table data in remote file storage will not be erased. DROP TABLE IF EXISTS `user_info`; Once the table is created with an external file storage, data in the remote location will be visible through a table with no partition. But this is not true when it comes to a table with partitions. Which means data can not be directly copied into a partitioned table. We need to create a temporary table with no partition and insert data into the partitioned table by providing the partition values. The following query describes how to insert records to such a table. INSERT INTO TABLE user_static_info PARTITION (business_unit={business_unit}, `created_date`='{execution_date}')SELECT Employee_id, email, secondary_email, first_name, last_name, orig_gender, gender, signup_channel , signup_from_fb , birthday, signup_date, updated_date, last_activity_date, subscription_statusFROM tmp_user_static_infoWHERE business_id={business_unit} Since “Pyhive” is not supported for multiple queries in a single session; I had to create the internal table “tmp_user_static_info” which points to S3 data directory without partitions. Then it was dropped after inserting data to the external, partitioned table. SELECT queries are used to retrieve data in Hive. These are much similar to SQL SELECT queries. It has the following form. You can build the query for your requirements. SELECT [ALL | DISTINCT] select_expr, select_expr, ...FROM table_reference[WHERE where_condition][GROUP BY col_list][HAVING having_condition][CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]][LIMIT number]; Hive does not support UPDATE and DELETE data directly. If you want to change anything from a table; copy the necessary data to a new table with SELECT queries. Then you can replace the old table with a new table by dropping the old table and renaming the new table. Table alterations are possible in Hive. But this needs to be done very carefully without affecting the existing data. Because we can’t alter the data. As an example, adding a new field in the middle will not shift data. If we add a new field as the second field, data that belong to the third column will still appear in the second column and fourth field data in the 3rd field and so on. The last field will not contain any data. This is because of the restriction of updating hive table data. If we added a new field as the last field, there will be an empty field and we can insert data into that field. ALTER TABLE user_static_info ADD COLUMNS (last_sign_in DATE); If we want to drop external data we can use the following steps. ALTER TABLE user_static_info SET TBLPROPERTIES('EXTERNAL'='False');DROP TABLE user_static_info; Finally, the following code shows how to execute a query using “execute_query” function in “HiveConnection” class. from src.database.hive_con import HiveConnectioncreate_temp_table_query_str = """CREATE TABLE `user_info` (`business_unit` INT,`employee_id` INT,`email` VARCHAR(250),`first_name` VARCHAR(250),`last_name` VARCHAR(250),`gender` VARCHAR(250),`birthday` DATE,`created_date` DATE,`updated_date` DATE)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ESCAPED BY '\\'LOCATION '{s3_location}'TBLPROPERTIES ("s3select.format" = "csv","skip.header.line.count" = "1");""".format( s3_location="s3://hive-test/data/user_info/")HiveConnection.execute_query(query_str=create_temp_table_query_str, database=userdb)
[ { "code": null, "e": 407, "s": 47, "text": "In this article, I’m going to share my experience of maintaining a Hive schema. This will be useful to the freshers who are willing to step into Big Data technologies. Mainly this will describe how to connect to Hive using python and How to use AWS S3 as the data storage. If you are not familiar with Hive concepts please go through the article on Wikipedia." }, { "code": null, "e": 715, "s": 407, "text": "The main objective of this article is to provide a guide to connect Hive through python and execute queries. I’m using “Pyhive” library for that. I’m creating my connection class as “HiveConnection” and Hive queries will be passed into the functions. AWS S3 will be used as the file storage for Hive tables." }, { "code": null, "e": 2051, "s": 715, "text": "import pandas as pdfrom pyhive import hiveclass HiveConnection: @staticmethod def select_query(query_str: str, database:str =HIVE_SCHEMA) -> pd.DataFrame: \"\"\" Execute a select query which returns a result set :param query_str: select query to be executed :param database: Hive Schema :return: \"\"\" conn = hive.Connection(host=HIVE_URL, port=HIVE_PORT, database=database, username=HIVE_USER) try: result = pd.read_sql(query_str, conn) return result finally: conn.close() @staticmethod def execute_query(query_str: str, database: str=HIVE_SCHEMA): \"\"\" execute an query which does not return a result set. ex: INSERT, CREATE, DROP, ALTER TABLE :param query_str: Hive query to be executed :param database: Hive Schema :return: \"\"\" conn = hive.Connection(host=HIVE_URL, port=HIVE_PORT, database=database, username=HIVE_USER) cur = conn.cursor() # Make sure to set the staging default to HDFS to avoid some potential S3 related errors cur.execute(\"SET hive.exec.stagingdir=/tmp/hive/\") cur.execute(\"SET hive.exec.scratchdir=/tmp/hive/\") try: cur.execute(query_str) return \"SUCCESS\" finally: conn.close()" }, { "code": null, "e": 2368, "s": 2051, "text": "I’m keeping the queries as separated strings. This way you can format the queries with external parameters when necessary. Hive configurations (HIVE_URL, HIVE_PORT, HIVE_USER, HIVE_SCHEMA) as constants. Function “select_query” will be use to retrieve data and function “execute_query” will be used for other queries." }, { "code": null, "e": 2608, "s": 2368, "text": "Hive provides a shell interactive tool to initiate databases, tables and manipulate the data in tables. We can go into the Hive command line by typing command “hive”. You can execute all the queries given in this article in the shell also." }, { "code": null, "e": 2889, "s": 2608, "text": "Schema is a collection of tables which is similar to a database. Both keywords SCHEMA and DATABASE are allowed in Hive. We can pick either. Here we use SCHEMA instead of DATABASE. Schema can be created with “CREATE SCHEMA”. To go inside the schema, the keyword “USE” is available." }, { "code": null, "e": 2922, "s": 2889, "text": "CREATE SCHEMA userdb;USE userdb;" }, { "code": null, "e": 3527, "s": 2922, "text": "There are three types of Hive tables. They are Internal, External and Temporary. Internal tables store metadata of the table inside the database as well as the table data. But external tables store metadata inside the database while table data is stored in a remote location like AWS S3 and hdfs. When dropping an internal table, all the table data will be erased with the metadata. When dropping an external table, only the metadata will be erased; not the table data. In this way, actual data will be protected. If you point a new table to the same location, data will be visible through the new table." }, { "code": null, "e": 3905, "s": 3527, "text": "Hive is a data warehouse and uses MapReduce Framework. So the speed of the data retrieving may not fair enough for small queries. Hive tables can be partitioned in order to increase the performance. Partitioning technique can be applied to both external and internal tables. Concepts like bucketing are also there. You can choose any of these techniques to enhance performance." }, { "code": null, "e": 4476, "s": 3905, "text": "Temporary tables are useful when copying data from one place to another. It acts as a temporary location to hold the data within a database session. All the temporary tables are cleared after the session timeout. Creating a temporary table is not useful with “Pyhive” library as multiple queries are not supported in a single session. Even though we created a table, the same session will no longer be available to access the table. But this is possible in the Hive command line. You can create a temporary table and then select data from that table in a single session." }, { "code": null, "e": 4807, "s": 4476, "text": "The following query is to create an internal table with a remote data storage, AWS S3. The file format is CSV and field are terminated by a comma. “s3_location” points to the S3 directory where the data files are. This is a user-defined external parameter for the query string. It should be passed in the time of query formatting." }, { "code": null, "e": 5180, "s": 4807, "text": "CREATE TABLE `user_info` (`business_unit` INT,`employee_id` INT,`email` VARCHAR(250),`first_name` VARCHAR(250),`last_name` VARCHAR(250),`gender` VARCHAR(250),`birthday` DATE,`created_date` DATE,`updated_date` DATE)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ESCAPED BY '\\\\'LOCATION '{s3_location}'TBLPROPERTIES (\"s3select.format\" = \"csv\",\"skip.header.line.count\" = \"1\");" }, { "code": null, "e": 5394, "s": 5180, "text": "If the data strings contain commas, it will break the table structure. So I have defined an escape character and all the unnecessary commas needed to be preceded by this escape character before creating the table." }, { "code": null, "e": 5460, "s": 5394, "text": "Following is an example record. Note that email contains a comma." }, { "code": null, "e": 5540, "s": 5460, "text": "1,1,ann,smith@gamil.com,Ann,Smith,female,'1992–07–01','2019–09–01','2019–12–31'" }, { "code": null, "e": 5667, "s": 5540, "text": "above record need to be formatted like this :1,1,ann\\\\,smith@gamil.com,Ann,Smith,female,'1992–07–01','2019–09–01','2019–12–31'" }, { "code": null, "e": 5750, "s": 5667, "text": "Here, I have partitioned “user_info” table with “business_unit” and “created_date”" }, { "code": null, "e": 6315, "s": 5750, "text": "CREATE EXTERNAL TABLE `user_info` ( `employee_id` INT, `email` VARCHAR(250), `first_name` VARCHAR(250), `last_name` VARCHAR(250), `gender` VARCHAR(250), `birthday` DATE, `updated_date` DATE) partitioned by(`business_unit` INT, `created_date` DATE,)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ESCAPED BY '\\\\'STORED ASINPUTFORMAT'com.amazonaws.emr.s3select.hive.S3SelectableTextInputFormat'OUTPUTFORMAT'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION '{s3_location}' TBLPROPERTIES (\"s3select.format\" = \"csv\",\"s3select.headerInfo\" = \"ignore\");" }, { "code": null, "e": 6353, "s": 6315, "text": "Query for creating a temporary table." }, { "code": null, "e": 6598, "s": 6353, "text": "CREATE TEMPORARY TABLE `user_info` ( `business_unit` INT, `employee_id` VARCHAR(250), `email` VARCHAR(250), `first_name` VARCHAR(250), `last_name` VARCHAR(250), `gender` VARCHAR(250), `birthday` DATE, `created_date` DATE, `updated_date` DATE) ;" }, { "code": null, "e": 6707, "s": 6598, "text": "Query to drop a table. If you are dropping an external table data in remote file storage will not be erased." }, { "code": null, "e": 6741, "s": 6707, "text": "DROP TABLE IF EXISTS `user_info`;" }, { "code": null, "e": 7211, "s": 6741, "text": "Once the table is created with an external file storage, data in the remote location will be visible through a table with no partition. But this is not true when it comes to a table with partitions. Which means data can not be directly copied into a partitioned table. We need to create a temporary table with no partition and insert data into the partitioned table by providing the partition values. The following query describes how to insert records to such a table." }, { "code": null, "e": 7609, "s": 7211, "text": "INSERT INTO TABLE user_static_info PARTITION (business_unit={business_unit}, `created_date`='{execution_date}')SELECT Employee_id, email, secondary_email, first_name, last_name, orig_gender, gender, signup_channel , signup_from_fb , birthday, signup_date, updated_date, last_activity_date, subscription_statusFROM tmp_user_static_infoWHERE business_id={business_unit}" }, { "code": null, "e": 7872, "s": 7609, "text": "Since “Pyhive” is not supported for multiple queries in a single session; I had to create the internal table “tmp_user_static_info” which points to S3 data directory without partitions. Then it was dropped after inserting data to the external, partitioned table." }, { "code": null, "e": 8042, "s": 7872, "text": "SELECT queries are used to retrieve data in Hive. These are much similar to SQL SELECT queries. It has the following form. You can build the query for your requirements." }, { "code": null, "e": 8265, "s": 8042, "text": "SELECT [ALL | DISTINCT] select_expr, select_expr, ...FROM table_reference[WHERE where_condition][GROUP BY col_list][HAVING having_condition][CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]][LIMIT number];" }, { "code": null, "e": 8531, "s": 8265, "text": "Hive does not support UPDATE and DELETE data directly. If you want to change anything from a table; copy the necessary data to a new table with SELECT queries. Then you can replace the old table with a new table by dropping the old table and renaming the new table." }, { "code": null, "e": 9138, "s": 8531, "text": "Table alterations are possible in Hive. But this needs to be done very carefully without affecting the existing data. Because we can’t alter the data. As an example, adding a new field in the middle will not shift data. If we add a new field as the second field, data that belong to the third column will still appear in the second column and fourth field data in the 3rd field and so on. The last field will not contain any data. This is because of the restriction of updating hive table data. If we added a new field as the last field, there will be an empty field and we can insert data into that field." }, { "code": null, "e": 9200, "s": 9138, "text": "ALTER TABLE user_static_info ADD COLUMNS (last_sign_in DATE);" }, { "code": null, "e": 9265, "s": 9200, "text": "If we want to drop external data we can use the following steps." }, { "code": null, "e": 9361, "s": 9265, "text": "ALTER TABLE user_static_info SET TBLPROPERTIES('EXTERNAL'='False');DROP TABLE user_static_info;" }, { "code": null, "e": 9476, "s": 9361, "text": "Finally, the following code shows how to execute a query using “execute_query” function in “HiveConnection” class." } ]
C program to sort names in alphabetical order using structures
Structure is a collection of different datatype variables, grouped together under a single name. The features of structure in the C programming language are as follows − It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator. It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator. For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures. For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures. It is possible to pass an entire structure, individual elements of structure and an address of structure to a function. It is possible to pass an entire structure, individual elements of structure and an address of structure to a function. It is possible to create structure pointers. It is possible to create structure pointers. General form of structure declaration is as follows − datatype member1; struct tagname{ datatype member2; datatype member n; }; Here, struct is the keyword. tagname specifies name of structure. member1, member2 are the data items. For example, struct book{ int pages; char author [30]; float price; }; Following is the C program to sort the names in an alphabetical order by using the structures − Live Demo #include<stdio.h> #include<string.h> struct tag{ char name[10]; int rno; }; typedef struct tag node; node s[5]; sort(int no){ int i,j; node temp; for(i=0;i<no-1;i++) for(j=i+1;j<no;j++) if(strcmp(s[i].name,s[j].name)>0){ temp=s[i]; s[i]=s[j]; s[j]=temp; } } void main(){ int no,i; fflush(stdin); printf("Enter The Number Of Students:"); scanf("%d",&no); for(i=0;i<no;i++){ printf("Enter The Name:"); fflush(stdin); gets(s[i].name); printf("Enter the Roll:"); scanf("%d",&s[i].rno); } sort(no); for(i=0;i<no;i++){ printf("%s\t",s[i].name); printf("%d\n",s[i].rno); } } When the above program is executed, it produces the following result − Enter The Number of Students:5 Enter The Name:Priya Enter the Roll:3 Enter The Name:Hari Enter the Roll:5 Enter The Name:Pinky Enter the Roll:7 Enter The Name:Lucky Enter the Roll:1 Enter The Name:Krishna Enter the Roll:2 Hari 5 Krishna 2 Lucky 1 Pinky 7 Priya 3
[ { "code": null, "e": 1159, "s": 1062, "text": "Structure is a collection of different datatype variables, grouped together under a single name." }, { "code": null, "e": 1232, "s": 1159, "text": "The features of structure in the C programming language are as follows −" }, { "code": null, "e": 1396, "s": 1232, "text": "It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator." }, { "code": null, "e": 1560, "s": 1396, "text": "It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator." }, { "code": null, "e": 1690, "s": 1560, "text": "For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures." }, { "code": null, "e": 1820, "s": 1690, "text": "For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures." }, { "code": null, "e": 1940, "s": 1820, "text": "It is possible to pass an entire structure, individual elements of structure and an address of structure to a function." }, { "code": null, "e": 2060, "s": 1940, "text": "It is possible to pass an entire structure, individual elements of structure and an address of structure to a function." }, { "code": null, "e": 2105, "s": 2060, "text": "It is possible to create structure pointers." }, { "code": null, "e": 2150, "s": 2105, "text": "It is possible to create structure pointers." }, { "code": null, "e": 2204, "s": 2150, "text": "General form of structure declaration is as follows −" }, { "code": null, "e": 2293, "s": 2204, "text": "datatype member1;\n struct tagname{\n datatype member2;\n datatype member n;\n};" }, { "code": null, "e": 2299, "s": 2293, "text": "Here," }, { "code": null, "e": 2322, "s": 2299, "text": "struct is the keyword." }, { "code": null, "e": 2359, "s": 2322, "text": "tagname specifies name of structure." }, { "code": null, "e": 2396, "s": 2359, "text": "member1, member2 are the data items." }, { "code": null, "e": 2409, "s": 2396, "text": "For example," }, { "code": null, "e": 2476, "s": 2409, "text": "struct book{\n int pages;\n char author [30];\n float price;\n};" }, { "code": null, "e": 2572, "s": 2476, "text": "Following is the C program to sort the names in an alphabetical order by using the structures −" }, { "code": null, "e": 2583, "s": 2572, "text": " Live Demo" }, { "code": null, "e": 3262, "s": 2583, "text": "#include<stdio.h>\n#include<string.h>\nstruct tag{\n char name[10];\n int rno;\n};\ntypedef struct tag node;\nnode s[5];\nsort(int no){\n int i,j;\n node temp;\n for(i=0;i<no-1;i++)\n for(j=i+1;j<no;j++)\n if(strcmp(s[i].name,s[j].name)>0){\n temp=s[i];\n s[i]=s[j];\n s[j]=temp;\n }\n}\nvoid main(){\n int no,i;\n fflush(stdin);\n printf(\"Enter The Number Of Students:\");\n scanf(\"%d\",&no);\n for(i=0;i<no;i++){\n printf(\"Enter The Name:\");\n fflush(stdin);\n gets(s[i].name);\n printf(\"Enter the Roll:\");\n scanf(\"%d\",&s[i].rno);\n }\n sort(no);\n for(i=0;i<no;i++){\n printf(\"%s\\t\",s[i].name);\n printf(\"%d\\n\",s[i].rno);\n }\n}" }, { "code": null, "e": 3333, "s": 3262, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3596, "s": 3333, "text": "Enter The Number of Students:5\nEnter The Name:Priya\nEnter the Roll:3\nEnter The Name:Hari\nEnter the Roll:5\nEnter The Name:Pinky\nEnter the Roll:7\nEnter The Name:Lucky\nEnter the Roll:1\nEnter The Name:Krishna\nEnter the Roll:2\nHari 5\nKrishna 2\nLucky 1\nPinky 7\nPriya 3" } ]
GATE | GATE-CS-2015 (Set 1) | Question 42 - GeeksforGeeks
28 Jun, 2021 Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4. Now consider that a value 35 is inserted into this heap. After insertion, the new heap is(A) 40, 30, 20, 10, 15, 16, 17, 8, 4, 35(B) 40, 35, 20, 10, 30, 16, 17, 8, 4, 15(C) 40, 30, 20, 10, 35, 16, 17, 8, 4, 15(D) 40, 35, 20, 10, 15, 16, 17, 8, 4, 30Answer: (B)Explanation: The array 40, 30, 20, 10, 15, 16, 17, 8, 4 represents following heap 40 / \ 30 20 / \ / \ 10 15 16 17 / \ 8 4 After insertion of 35, we get 40 / \ 30 20 / \ / \ 10 15 16 17 / \ / 8 4 35 After swapping 35 with 15 and swapping 35 againwith 30, we get 40 / \ 35 20 / \ / \ 10 30 16 17 / \ / 8 4 15 Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE CS 2010 | Question 24 GATE | Gate IT 2007 | Question 30
[ { "code": null, "e": 24518, "s": 24490, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24941, "s": 24518, "text": "Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4. Now consider that a value 35 is inserted into this heap. After insertion, the new heap is(A) 40, 30, 20, 10, 15, 16, 17, 8, 4, 35(B) 40, 35, 20, 10, 30, 16, 17, 8, 4, 15(C) 40, 30, 20, 10, 35, 16, 17, 8, 4, 15(D) 40, 35, 20, 10, 15, 16, 17, 8, 4, 30Answer: (B)Explanation: The array 40, 30, 20, 10, 15, 16, 17, 8, 4 represents following heap" }, { "code": null, "e": 25033, "s": 24941, "text": "\n 40\n / \\\n 30 20\n / \\ / \\\n 10 15 16 17\n / \\\n 8 4" }, { "code": null, "e": 25063, "s": 25033, "text": "After insertion of 35, we get" }, { "code": null, "e": 25163, "s": 25063, "text": " 40\n / \\\n 30 20\n / \\ / \\\n 10 15 16 17\n / \\ /\n 8 4 35 " }, { "code": null, "e": 25226, "s": 25163, "text": "After swapping 35 with 15 and swapping 35 againwith 30, we get" }, { "code": null, "e": 25326, "s": 25226, "text": " 40\n / \\\n 35 20\n / \\ / \\\n 10 30 16 17\n / \\ /\n 8 4 15 " }, { "code": null, "e": 25348, "s": 25326, "text": "Quiz of this Question" }, { "code": null, "e": 25369, "s": 25348, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25395, "s": 25369, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 25400, "s": 25395, "text": "GATE" }, { "code": null, "e": 25498, "s": 25400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25532, "s": 25498, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25566, "s": 25532, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25608, "s": 25566, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25642, "s": 25608, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25684, "s": 25642, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25717, "s": 25684, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25751, "s": 25717, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 25793, "s": 25751, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 25827, "s": 25793, "text": "GATE | GATE CS 2010 | Question 24" } ]
5 Reasons why you should Switch from Jupyter Notebook to Scripts | by Khuyen Tran | Towards Data Science
Like most people, the first tool I used when started learning data science is Jupyter Notebook. Most of the online data science courses use Jupyter Notebook as a medium to teach. This makes sense because it is easier for beginners to start writing code in Jupyter Notebook’s cells than writing a script with classes and functions. Another reason why Jupyter Notebook is such a common tool in data science is that Jupyter Notebook makes it easy to explore and plot the data. When we type ‘Shift + Enter’, we will immediately see the results of the code, which makes it easy for us to identify whether our code works or not. However, I realized several fallbacks of Jupyter Notebook as I work with more data science projects: Unorganized: As my code gets bigger, it becomes increasingly difficult for me to keep track of what I write. No matter how many markdowns I use to separate the notebook into different sections, the disconnected cells make it difficult for me to concentrate on what the code does. Difficult to experiment: You may want to test with different methods of processing your data, choose different parameters for your machine learning algorithm to see if the accuracy increases. But every time you experiment with new methods, you need to find and rerun the related cells. This is confusing and time-consuming, especially when the processing procedure or the training takes a long time to run. Not ideal for reproducibility: If you want to use new data with a slightly different structure, it would be difficult to identify the source of error in your notebook. Difficult to debug: When you get an error in your code, it is difficult to know whether the reason for the error is the code or the change in data. If the error is in the code, which part of the code is causing the problem? Not ideal for production: Jupyter Notebook does not play very well with other tools. It is not easy to run the code from Jupyter Notebook while using other tools. I knew there must be a better way to handle my code so I decided to give scripts a try. To make it less confusing, I refer to .py file when using word “script” in this article. These are the benefits I found when using scripts: The cells in Jupyter Notebook make it difficult to organize the code into different parts. With a script, we could create several small functions with each function specifies what the code does like this Better yet, if these functions could be categorized in the same category such as functions to process the data, we could put them in the same class! Whenever we want to process our data, we know the functions in the class Preprocess can be used for this purpose. When we want to experiment with a different approach to preprocess data, we could just add or remove a function by commenting out like this without being afraid to break the code! Even if we happen to break the code, we know exactly where to fix it. With classes and functions, we could make the code general enough so that it will be able to work with other data. For example, if we want to drop different columns in my new data, we just need to change columns_to_drop to a list of columns, we want to drop and the code will run smoothly! I can also create a pipeline that specifies steps to process and train the data! Once I have a pipeline, all I need to do is to use pipline.fit_transform(data) to apply the same processing to both the train and test data. With functions, it is easier to test whether that function produces the output we expect. We can quickly spot out where in the code we should change to produce the output we want If all of the tests pass but there is still an error in running our code, we know the data is where we should look next. For example, after passing the test above, I still have a TypeError when running the script, which gives me the idea that my data has null values. I just need to take care of that to run the code smoothly. I wrote an article on how to use Pytest for testing here. We can use different functions in multiple scripts on top of something else like this or to add a config file to control the values of the variables. This prevents us from wasting time tracking down a specific variable in the code just to change its value. We could also easily add tools to track the experiment such as MLFlow or tools to handle configuration such as Hydra.cc! If you don’t know about hydra, it is a Python tool to configure your data science projects. This tool allows you to experiment with different parameters and models without spending hours fixing your code. I used to use Jupyter Notebook all the time. When some data scientists advise me to switch from Jupyter Notebook to script to prevent some problems listed above, I didn’t understand and felt resistant to do so. I didn’t like the uncertainty of not being able to see the outcome when I run the cell. But the disadvantage of Jupyter Notebook grew as I started my first real data science project in my new company so I decided to push myself out of my comfort zone and experiment with scripts. In the beginning, I felt uncomfortable but started to notice the benefits of using scripts. I started to feel more organized when my code is organized into different functions, classes, and into multiple scripts with each script serving different purposes such as preprocessing, training, and testing. Don’t get me wrong. I still use Jupyter Notebook if my code is small and if I don’t plan to put my code into production. I use Jupyter Notebook when I want to explore and visualize the data. I also use it to explain how to use some python libraries. For example, I write use mostly Jupyter Notebooks in this repository as the medium to explain the code mentioned in all of my articles. If you don’t feel comfortable with coding everything in scripts, you could use both scripts and Jupyter Notebook for different purposes. For example, you could create classes and functions in scripts then import them in the notebook so that the notebook is less messy. Another alternative is to turn the notebook into the script after writing the notebook. I personally don't prefer this approach because it often takes me longer to organize the code in my notebook such as put them into functions and classes and write test functions. I find writing a small function then writing a small test function is faster and safer. If I happen to want to speeds up my code with the new Python library, I could use the test function I already wrote to make sure it still works as I expected. With that being said, I believe there are more ways to solve the disadvantage of Jupyter Notebook than what I mentioned here such as how Netflix uses put the notebook into production and schedule the notebook to run at a certain time. Everybody has their own way to make their workflow more efficient and to me, it is to leverage the utility of scripts. If you have just switched from Jupyter Notebook to script, it might not be intuitive to write code in scripts, but trust me, you will get used to using scripts eventually. Once that happens, you will start to realize many benefits of the scripts over the messy Jupyter Notebook and want to write most of your code in scripts. If you are looking for methods to switch from Jupyter Notebook, this article provides some good tips to make your code reproducible, automatable, and deployable with scripts. If you don’t feel comfortable with the big change, start small. Big changes start with small steps I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these
[ { "code": null, "e": 503, "s": 172, "text": "Like most people, the first tool I used when started learning data science is Jupyter Notebook. Most of the online data science courses use Jupyter Notebook as a medium to teach. This makes sense because it is easier for beginners to start writing code in Jupyter Notebook’s cells than writing a script with classes and functions." }, { "code": null, "e": 795, "s": 503, "text": "Another reason why Jupyter Notebook is such a common tool in data science is that Jupyter Notebook makes it easy to explore and plot the data. When we type ‘Shift + Enter’, we will immediately see the results of the code, which makes it easy for us to identify whether our code works or not." }, { "code": null, "e": 896, "s": 795, "text": "However, I realized several fallbacks of Jupyter Notebook as I work with more data science projects:" }, { "code": null, "e": 1176, "s": 896, "text": "Unorganized: As my code gets bigger, it becomes increasingly difficult for me to keep track of what I write. No matter how many markdowns I use to separate the notebook into different sections, the disconnected cells make it difficult for me to concentrate on what the code does." }, { "code": null, "e": 1583, "s": 1176, "text": "Difficult to experiment: You may want to test with different methods of processing your data, choose different parameters for your machine learning algorithm to see if the accuracy increases. But every time you experiment with new methods, you need to find and rerun the related cells. This is confusing and time-consuming, especially when the processing procedure or the training takes a long time to run." }, { "code": null, "e": 1751, "s": 1583, "text": "Not ideal for reproducibility: If you want to use new data with a slightly different structure, it would be difficult to identify the source of error in your notebook." }, { "code": null, "e": 1975, "s": 1751, "text": "Difficult to debug: When you get an error in your code, it is difficult to know whether the reason for the error is the code or the change in data. If the error is in the code, which part of the code is causing the problem?" }, { "code": null, "e": 2138, "s": 1975, "text": "Not ideal for production: Jupyter Notebook does not play very well with other tools. It is not easy to run the code from Jupyter Notebook while using other tools." }, { "code": null, "e": 2366, "s": 2138, "text": "I knew there must be a better way to handle my code so I decided to give scripts a try. To make it less confusing, I refer to .py file when using word “script” in this article. These are the benefits I found when using scripts:" }, { "code": null, "e": 2570, "s": 2366, "text": "The cells in Jupyter Notebook make it difficult to organize the code into different parts. With a script, we could create several small functions with each function specifies what the code does like this" }, { "code": null, "e": 2719, "s": 2570, "text": "Better yet, if these functions could be categorized in the same category such as functions to process the data, we could put them in the same class!" }, { "code": null, "e": 2833, "s": 2719, "text": "Whenever we want to process our data, we know the functions in the class Preprocess can be used for this purpose." }, { "code": null, "e": 3083, "s": 2833, "text": "When we want to experiment with a different approach to preprocess data, we could just add or remove a function by commenting out like this without being afraid to break the code! Even if we happen to break the code, we know exactly where to fix it." }, { "code": null, "e": 3198, "s": 3083, "text": "With classes and functions, we could make the code general enough so that it will be able to work with other data." }, { "code": null, "e": 3373, "s": 3198, "text": "For example, if we want to drop different columns in my new data, we just need to change columns_to_drop to a list of columns, we want to drop and the code will run smoothly!" }, { "code": null, "e": 3505, "s": 3373, "text": "I can also create a pipeline that specifies steps to process and train the data! Once I have a pipeline, all I need to do is to use" }, { "code": null, "e": 3533, "s": 3505, "text": "pipline.fit_transform(data)" }, { "code": null, "e": 3595, "s": 3533, "text": "to apply the same processing to both the train and test data." }, { "code": null, "e": 3774, "s": 3595, "text": "With functions, it is easier to test whether that function produces the output we expect. We can quickly spot out where in the code we should change to produce the output we want" }, { "code": null, "e": 3895, "s": 3774, "text": "If all of the tests pass but there is still an error in running our code, we know the data is where we should look next." }, { "code": null, "e": 4101, "s": 3895, "text": "For example, after passing the test above, I still have a TypeError when running the script, which gives me the idea that my data has null values. I just need to take care of that to run the code smoothly." }, { "code": null, "e": 4159, "s": 4101, "text": "I wrote an article on how to use Pytest for testing here." }, { "code": null, "e": 4245, "s": 4159, "text": "We can use different functions in multiple scripts on top of something else like this" }, { "code": null, "e": 4416, "s": 4245, "text": "or to add a config file to control the values of the variables. This prevents us from wasting time tracking down a specific variable in the code just to change its value." }, { "code": null, "e": 4537, "s": 4416, "text": "We could also easily add tools to track the experiment such as MLFlow or tools to handle configuration such as Hydra.cc!" }, { "code": null, "e": 4742, "s": 4537, "text": "If you don’t know about hydra, it is a Python tool to configure your data science projects. This tool allows you to experiment with different parameters and models without spending hours fixing your code." }, { "code": null, "e": 5041, "s": 4742, "text": "I used to use Jupyter Notebook all the time. When some data scientists advise me to switch from Jupyter Notebook to script to prevent some problems listed above, I didn’t understand and felt resistant to do so. I didn’t like the uncertainty of not being able to see the outcome when I run the cell." }, { "code": null, "e": 5233, "s": 5041, "text": "But the disadvantage of Jupyter Notebook grew as I started my first real data science project in my new company so I decided to push myself out of my comfort zone and experiment with scripts." }, { "code": null, "e": 5535, "s": 5233, "text": "In the beginning, I felt uncomfortable but started to notice the benefits of using scripts. I started to feel more organized when my code is organized into different functions, classes, and into multiple scripts with each script serving different purposes such as preprocessing, training, and testing." }, { "code": null, "e": 5921, "s": 5535, "text": "Don’t get me wrong. I still use Jupyter Notebook if my code is small and if I don’t plan to put my code into production. I use Jupyter Notebook when I want to explore and visualize the data. I also use it to explain how to use some python libraries. For example, I write use mostly Jupyter Notebooks in this repository as the medium to explain the code mentioned in all of my articles." }, { "code": null, "e": 6190, "s": 5921, "text": "If you don’t feel comfortable with coding everything in scripts, you could use both scripts and Jupyter Notebook for different purposes. For example, you could create classes and functions in scripts then import them in the notebook so that the notebook is less messy." }, { "code": null, "e": 6457, "s": 6190, "text": "Another alternative is to turn the notebook into the script after writing the notebook. I personally don't prefer this approach because it often takes me longer to organize the code in my notebook such as put them into functions and classes and write test functions." }, { "code": null, "e": 6704, "s": 6457, "text": "I find writing a small function then writing a small test function is faster and safer. If I happen to want to speeds up my code with the new Python library, I could use the test function I already wrote to make sure it still works as I expected." }, { "code": null, "e": 6939, "s": 6704, "text": "With that being said, I believe there are more ways to solve the disadvantage of Jupyter Notebook than what I mentioned here such as how Netflix uses put the notebook into production and schedule the notebook to run at a certain time." }, { "code": null, "e": 7230, "s": 6939, "text": "Everybody has their own way to make their workflow more efficient and to me, it is to leverage the utility of scripts. If you have just switched from Jupyter Notebook to script, it might not be intuitive to write code in scripts, but trust me, you will get used to using scripts eventually." }, { "code": null, "e": 7384, "s": 7230, "text": "Once that happens, you will start to realize many benefits of the scripts over the messy Jupyter Notebook and want to write most of your code in scripts." }, { "code": null, "e": 7559, "s": 7384, "text": "If you are looking for methods to switch from Jupyter Notebook, this article provides some good tips to make your code reproducible, automatable, and deployable with scripts." }, { "code": null, "e": 7623, "s": 7559, "text": "If you don’t feel comfortable with the big change, start small." }, { "code": null, "e": 7658, "s": 7623, "text": "Big changes start with small steps" }, { "code": null, "e": 7818, "s": 7658, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Validate IP Address in C#
An IP Address is an Internet Protocol address that is a series of numbers assigned to each device on a computer network. In C#, the class IPAddress class in the namespace System.Net deals with IP addresses. A program that is used to validate an IP address is given as follows − Live Demo using System; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; namespace IPaddressDemo { class Example { public static void Main() { IPAddress IP; Console.WriteLine("Enter the IP Address: "); string ipAddr = Console.ReadLine(); bool flag = IPAddress.TryParse(ipAddr, out IP); if (flag) Console.WriteLine("{0} is a valid IP address", ipAddr); else Console.WriteLine("{0} is not a valid IP address", ipAddr); } } } The output of the above program is as follows. Enter the IP Address: 130.45.78.200 130.45.78.200 is a valid IP address Now, let us understand the above program. An object IP is created of the IPAddress class. Then the required IP address is obtained from the user. The IP address is validated using the method TryParse() in the class IPAddress as this methods validates if a string is an IP address or not. The result is stored in flag. Then the if statement is used to print if the string is IP address or not depending on the value in flag. The code snippet for this is as follows − IPAddress IP; Console.WriteLine("Enter the IP Address: "); string ipAddr = Console.ReadLine(); bool flag = IPAddress.TryParse(ipAddr, out IP); if (flag) Console.WriteLine("{0} is a valid IP address", ipAddr); else Console.WriteLine("{0} is not a valid IP address", ipAddr);
[ { "code": null, "e": 1269, "s": 1062, "text": "An IP Address is an Internet Protocol address that is a series of numbers assigned to each device on a computer network. In C#, the class IPAddress class in the namespace System.Net deals with IP addresses." }, { "code": null, "e": 1340, "s": 1269, "text": "A program that is used to validate an IP address is given as follows −" }, { "code": null, "e": 1351, "s": 1340, "text": " Live Demo" }, { "code": null, "e": 1887, "s": 1351, "text": "using System;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text.RegularExpressions;\nnamespace IPaddressDemo {\n class Example {\n public static void Main() {\n IPAddress IP;\n Console.WriteLine(\"Enter the IP Address: \");\n string ipAddr = Console.ReadLine();\n bool flag = IPAddress.TryParse(ipAddr, out IP);\n if (flag)\n Console.WriteLine(\"{0} is a valid IP address\", ipAddr);\n else\n Console.WriteLine(\"{0} is not a valid IP address\", ipAddr);\n }\n }\n}" }, { "code": null, "e": 1934, "s": 1887, "text": "The output of the above program is as follows." }, { "code": null, "e": 2006, "s": 1934, "text": "Enter the IP Address: 130.45.78.200\n130.45.78.200 is a valid IP address" }, { "code": null, "e": 2048, "s": 2006, "text": "Now, let us understand the above program." }, { "code": null, "e": 2472, "s": 2048, "text": "An object IP is created of the IPAddress class. Then the required IP address is obtained from the user. The IP address is validated using the method TryParse() in the class IPAddress as this methods validates if a string is an IP address or not. The result is stored in flag. Then the if statement is used to print if the string is IP address or not depending on the value in flag. The code snippet for this is as follows −" }, { "code": null, "e": 2746, "s": 2472, "text": "IPAddress IP;\nConsole.WriteLine(\"Enter the IP Address: \");\nstring ipAddr = Console.ReadLine();\nbool flag = IPAddress.TryParse(ipAddr, out IP);\nif (flag)\nConsole.WriteLine(\"{0} is a valid IP address\", ipAddr);\nelse\nConsole.WriteLine(\"{0} is not a valid IP address\", ipAddr);" } ]
How to convert a date to quarter and year in R?
Most of the times the date data is available only in date format and there is not information about the quarter of the year. The quarter of the year is required when we want compare the quarters or do some time series analysis. For the conversion of date into quarter and year can be done by using as.yearqtr function from zoo package as shown in the below examples. library(zoo) as.yearqtr("2021-01-19",format="%Y-%m-%d") [1] "2021 Q1" as.yearqtr("2021-04-19",format="%Y-%m-%d") [1] "2021 Q2" as.yearqtr(c("2021-04-19","2020-05-24","2020-11-09"),format="%Y-%m-%d") [1] "2021 Q2" "2020 Q2" "2020 Q4" Live Demo x1<-sample(c("2021-04-19","2020-05-24","2020-11-09"),50,replace=TRUE) x1 [1] "2020-05-24" "2020-05-24" "2021-04-19" "2021-04-19" "2021-04-19" [6] "2021-04-19" "2021-04-19" "2020-11-09" "2020-11-09" "2020-11-09" [11] "2020-05-24" "2021-04-19" "2020-05-24" "2020-05-24" "2020-05-24" [16] "2020-11-09" "2020-05-24" "2020-05-24" "2020-11-09" "2021-04-19" [21] "2020-11-09" "2021-04-19" "2020-05-24" "2021-04-19" "2020-05-24" [26] "2020-05-24" "2020-05-24" "2020-11-09" "2020-05-24" "2020-05-24" [31] "2020-05-24" "2020-11-09" "2020-05-24" "2020-05-24" "2021-04-19" [36] "2021-04-19" "2020-05-24" "2020-11-09" "2021-04-19" "2020-05-24" [41] "2021-04-19" "2020-11-09" "2021-04-19" "2020-11-09" "2020-11-09" [46] "2020-11-09" "2020-05-24" "2020-11-09" "2021-04-19" "2020-05-24" as.yearqtr(x1,format="%Y-%m-%d") [1] "2020 Q2" "2020 Q2" "2021 Q2" "2021 Q2" "2021 Q2" "2021 Q2" "2021 Q2" [8] "2020 Q4" "2020 Q4" "2020 Q4" "2020 Q2" "2021 Q2" "2020 Q2" "2020 Q2" [15] "2020 Q2" "2020 Q4" "2020 Q2" "2020 Q2" "2020 Q4" "2021 Q2" "2020 Q4" [22] "2021 Q2" "2020 Q2" "2021 Q2" "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q4" [29] "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q4" "2020 Q2" "2020 Q2" "2021 Q2" [36] "2021 Q2" "2020 Q2" "2020 Q4" "2021 Q2" "2020 Q2" "2021 Q2" "2020 Q4" [43] "2021 Q2" "2020 Q4" "2020 Q4" "2020 Q4" "2020 Q2" "2020 Q4" "2021 Q2" [50] "2020 Q2" Live Demo x2<-sample(c("2020-02-05","2020-08-24","2020-06-17","2021-04-19","2020-05-24","2020-11-09"),80,replace=TRUE) x2 [1] "2020-02-05" "2020-08-24" "2020-05-24" "2020-11-09" "2020-02-05" [6] "2020-02-05" "2020-08-24" "2020-11-09" "2020-11-09" "2020-05-24" [11] "2020-02-05" "2020-06-17" "2021-04-19" "2020-06-17" "2020-08-24" [16] "2020-06-17" "2020-08-24" "2021-04-19" "2020-06-17" "2020-08-24" [21] "2020-06-17" "2020-05-24" "2020-02-05" "2020-06-17" "2020-05-24" [26] "2020-05-24" "2020-06-17" "2020-02-05" "2020-11-09" "2020-02-05" [31] "2021-04-19" "2020-05-24" "2020-06-17" "2020-02-05" "2020-02-05" [36] "2020-11-09" "2020-05-24" "2020-06-17" "2020-06-17" "2020-06-17" [41] "2020-11-09" "2020-08-24" "2020-08-24" "2020-06-17" "2021-04-19" [46] "2020-06-17" "2020-11-09" "2020-08-24" "2020-05-24" "2020-08-24" [51] "2020-02-05" "2020-11-09" "2020-11-09" "2020-06-17" "2020-11-09" [56] "2020-02-05" "2020-11-09" "2020-06-17" "2020-05-24" "2021-04-19" [61] "2020-11-09" "2021-04-19" "2020-02-05" "2020-06-17" "2020-06-17" [66] "2021-04-19" "2021-04-19" "2021-04-19" "2020-11-09" "2020-06-17" [71] "2020-11-09" "2021-04-19" "2021-04-19" "2020-02-05" "2020-05-24" [76] "2020-02-05" "2020-02-05" "2020-11-09" "2020-02-05" "2020-06-17" as.yearqtr(x2,format="%Y-%m-%d") [1] "2020 Q1" "2020 Q3" "2020 Q2" "2020 Q4" "2020 Q1" "2020 Q1" "2020 Q3" [8] "2020 Q4" "2020 Q4" "2020 Q2" "2020 Q1" "2020 Q2" "2021 Q2" "2020 Q2" [15] "2020 Q3" "2020 Q2" "2020 Q3" "2021 Q2" "2020 Q2" "2020 Q3" "2020 Q2" [22] "2020 Q2" "2020 Q1" "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q1" [29] "2020 Q4" "2020 Q1" "2021 Q2" "2020 Q2" "2020 Q2" "2020 Q1" "2020 Q1" [36] "2020 Q4" "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q2" "2020 Q4" "2020 Q3" [43] "2020 Q3" "2020 Q2" "2021 Q2" "2020 Q2" "2020 Q4" "2020 Q3" "2020 Q2" [50] "2020 Q3" "2020 Q1" "2020 Q4" "2020 Q4" "2020 Q2" "2020 Q4" "2020 Q1" [57] "2020 Q4" "2020 Q2" "2020 Q2" "2021 Q2" "2020 Q4" "2021 Q2" "2020 Q1" [64] "2020 Q2" "2020 Q2" "2021 Q2" "2021 Q2" "2021 Q2" "2020 Q4" "2020 Q2" [71] "2020 Q4" "2021 Q2" "2021 Q2" "2020 Q1" "2020 Q2" "2020 Q1" "2020 Q1" [78] "2020 Q4" "2020 Q1" "2020 Q2"
[ { "code": null, "e": 1429, "s": 1062, "text": "Most of the times the date data is available only in date format and there is not information about the quarter of the year. The quarter of the year is required when we want compare the quarters or do some time series analysis. For the conversion of date into quarter and year can be done by using as.yearqtr function from zoo package as shown in the below examples." }, { "code": null, "e": 1485, "s": 1429, "text": "library(zoo)\nas.yearqtr(\"2021-01-19\",format=\"%Y-%m-%d\")" }, { "code": null, "e": 1499, "s": 1485, "text": "[1] \"2021 Q1\"" }, { "code": null, "e": 1542, "s": 1499, "text": "as.yearqtr(\"2021-04-19\",format=\"%Y-%m-%d\")" }, { "code": null, "e": 1556, "s": 1542, "text": "[1] \"2021 Q2\"" }, { "code": null, "e": 1628, "s": 1556, "text": "as.yearqtr(c(\"2021-04-19\",\"2020-05-24\",\"2020-11-09\"),format=\"%Y-%m-%d\")" }, { "code": null, "e": 1663, "s": 1628, "text": "[1] \"2021 Q2\" \"2020 Q2\" \"2020 Q4\"\n" }, { "code": null, "e": 1674, "s": 1663, "text": " Live Demo" }, { "code": null, "e": 1747, "s": 1674, "text": "x1<-sample(c(\"2021-04-19\",\"2020-05-24\",\"2020-11-09\"),50,replace=TRUE)\nx1" }, { "code": null, "e": 2447, "s": 1747, "text": "[1] \"2020-05-24\" \"2020-05-24\" \"2021-04-19\" \"2021-04-19\" \"2021-04-19\"\n[6] \"2021-04-19\" \"2021-04-19\" \"2020-11-09\" \"2020-11-09\" \"2020-11-09\"\n[11] \"2020-05-24\" \"2021-04-19\" \"2020-05-24\" \"2020-05-24\" \"2020-05-24\"\n[16] \"2020-11-09\" \"2020-05-24\" \"2020-05-24\" \"2020-11-09\" \"2021-04-19\"\n[21] \"2020-11-09\" \"2021-04-19\" \"2020-05-24\" \"2021-04-19\" \"2020-05-24\"\n[26] \"2020-05-24\" \"2020-05-24\" \"2020-11-09\" \"2020-05-24\" \"2020-05-24\"\n[31] \"2020-05-24\" \"2020-11-09\" \"2020-05-24\" \"2020-05-24\" \"2021-04-19\"\n[36] \"2021-04-19\" \"2020-05-24\" \"2020-11-09\" \"2021-04-19\" \"2020-05-24\"\n[41] \"2021-04-19\" \"2020-11-09\" \"2021-04-19\" \"2020-11-09\" \"2020-11-09\"\n[46] \"2020-11-09\" \"2020-05-24\" \"2020-11-09\" \"2021-04-19\" \"2020-05-24\"" }, { "code": null, "e": 2480, "s": 2447, "text": "as.yearqtr(x1,format=\"%Y-%m-%d\")" }, { "code": null, "e": 3020, "s": 2480, "text": "[1] \"2020 Q2\" \"2020 Q2\" \"2021 Q2\" \"2021 Q2\" \"2021 Q2\" \"2021 Q2\" \"2021 Q2\"\n[8] \"2020 Q4\" \"2020 Q4\" \"2020 Q4\" \"2020 Q2\" \"2021 Q2\" \"2020 Q2\" \"2020 Q2\"\n[15] \"2020 Q2\" \"2020 Q4\" \"2020 Q2\" \"2020 Q2\" \"2020 Q4\" \"2021 Q2\" \"2020 Q4\"\n[22] \"2021 Q2\" \"2020 Q2\" \"2021 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q4\"\n[29] \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q4\" \"2020 Q2\" \"2020 Q2\" \"2021 Q2\"\n[36] \"2021 Q2\" \"2020 Q2\" \"2020 Q4\" \"2021 Q2\" \"2020 Q2\" \"2021 Q2\" \"2020 Q4\"\n[43] \"2021 Q2\" \"2020 Q4\" \"2020 Q4\" \"2020 Q4\" \"2020 Q2\" \"2020 Q4\" \"2021 Q2\"\n[50] \"2020 Q2\"" }, { "code": null, "e": 3031, "s": 3020, "text": " Live Demo" }, { "code": null, "e": 3143, "s": 3031, "text": "x2<-sample(c(\"2020-02-05\",\"2020-08-24\",\"2020-06-17\",\"2021-04-19\",\"2020-05-24\",\"2020-11-09\"),80,replace=TRUE)\nx2" }, { "code": null, "e": 4263, "s": 3143, "text": "[1] \"2020-02-05\" \"2020-08-24\" \"2020-05-24\" \"2020-11-09\" \"2020-02-05\"\n[6] \"2020-02-05\" \"2020-08-24\" \"2020-11-09\" \"2020-11-09\" \"2020-05-24\"\n[11] \"2020-02-05\" \"2020-06-17\" \"2021-04-19\" \"2020-06-17\" \"2020-08-24\"\n[16] \"2020-06-17\" \"2020-08-24\" \"2021-04-19\" \"2020-06-17\" \"2020-08-24\"\n[21] \"2020-06-17\" \"2020-05-24\" \"2020-02-05\" \"2020-06-17\" \"2020-05-24\"\n[26] \"2020-05-24\" \"2020-06-17\" \"2020-02-05\" \"2020-11-09\" \"2020-02-05\"\n[31] \"2021-04-19\" \"2020-05-24\" \"2020-06-17\" \"2020-02-05\" \"2020-02-05\"\n[36] \"2020-11-09\" \"2020-05-24\" \"2020-06-17\" \"2020-06-17\" \"2020-06-17\"\n[41] \"2020-11-09\" \"2020-08-24\" \"2020-08-24\" \"2020-06-17\" \"2021-04-19\"\n[46] \"2020-06-17\" \"2020-11-09\" \"2020-08-24\" \"2020-05-24\" \"2020-08-24\"\n[51] \"2020-02-05\" \"2020-11-09\" \"2020-11-09\" \"2020-06-17\" \"2020-11-09\"\n[56] \"2020-02-05\" \"2020-11-09\" \"2020-06-17\" \"2020-05-24\" \"2021-04-19\"\n[61] \"2020-11-09\" \"2021-04-19\" \"2020-02-05\" \"2020-06-17\" \"2020-06-17\"\n[66] \"2021-04-19\" \"2021-04-19\" \"2021-04-19\" \"2020-11-09\" \"2020-06-17\"\n[71] \"2020-11-09\" \"2021-04-19\" \"2021-04-19\" \"2020-02-05\" \"2020-05-24\"\n[76] \"2020-02-05\" \"2020-02-05\" \"2020-11-09\" \"2020-02-05\" \"2020-06-17\"" }, { "code": null, "e": 4296, "s": 4263, "text": "as.yearqtr(x2,format=\"%Y-%m-%d\")" }, { "code": null, "e": 5154, "s": 4296, "text": "[1] \"2020 Q1\" \"2020 Q3\" \"2020 Q2\" \"2020 Q4\" \"2020 Q1\" \"2020 Q1\" \"2020 Q3\"\n[8] \"2020 Q4\" \"2020 Q4\" \"2020 Q2\" \"2020 Q1\" \"2020 Q2\" \"2021 Q2\" \"2020 Q2\"\n[15] \"2020 Q3\" \"2020 Q2\" \"2020 Q3\" \"2021 Q2\" \"2020 Q2\" \"2020 Q3\" \"2020 Q2\"\n[22] \"2020 Q2\" \"2020 Q1\" \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q1\"\n[29] \"2020 Q4\" \"2020 Q1\" \"2021 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q1\" \"2020 Q1\"\n[36] \"2020 Q4\" \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q2\" \"2020 Q4\" \"2020 Q3\"\n[43] \"2020 Q3\" \"2020 Q2\" \"2021 Q2\" \"2020 Q2\" \"2020 Q4\" \"2020 Q3\" \"2020 Q2\"\n[50] \"2020 Q3\" \"2020 Q1\" \"2020 Q4\" \"2020 Q4\" \"2020 Q2\" \"2020 Q4\" \"2020 Q1\"\n[57] \"2020 Q4\" \"2020 Q2\" \"2020 Q2\" \"2021 Q2\" \"2020 Q4\" \"2021 Q2\" \"2020 Q1\"\n[64] \"2020 Q2\" \"2020 Q2\" \"2021 Q2\" \"2021 Q2\" \"2021 Q2\" \"2020 Q4\" \"2020 Q2\"\n[71] \"2020 Q4\" \"2021 Q2\" \"2021 Q2\" \"2020 Q1\" \"2020 Q2\" \"2020 Q1\" \"2020 Q1\"\n[78] \"2020 Q4\" \"2020 Q1\" \"2020 Q2\"" } ]
Datalake File Ingestion: From FTP to AWS S3 | by Furqan Butt | Towards Data Science
Hello everyone. When developing Datalake pipe lines, data ingestion is an important step in the entire process. We need a reliable, secure and fault tolerant method to bring our files from source(client FTP server) to our target( AWS S3). Considering how important this step is, I developed an implementation in python that can be used to ingest files from an FTP server to AWS s3. I have designed the code in such manner that it can be used in a managed(AWS Glue) or un-managed(local machine) environment to transfer files from an FTP server to AWS s3. In this article I will explain how we can transfer files present on an FTP server such as FileZilla to Amazon s3 using the Paramiko Library in Python. The file ingestion code can be found on my GitHub repository. The file ingestion code does the following things: Creates a secure ssh SFTP connection with the File server using Paramiko. Automatically handles single part and multipart upload depending upon the file size (multipart on 100MB or more). Automatically handles retires in case of failed parts uploads during multipart upload. Partitions the data in s3 based on current year,month,day,hour. Ensures which file has been uploaded Can be used as a python job in AWS Glue to transfer files from FTP to S3 using AWS Glue. I will do a step by step walk through of each section of the code for better understanding. So lets get started. Before we get started we need to do a little installation setup on our local machine and a directory setup on our FTP server. I’m assuming you guys have python already installed on you machines. Visit this link to install python on your machine if you haven’t already.Before getting towards the code we need to make sure we have the following modules installed: First we’ll install Paramiko. pip install paramiko Since we’ll be uploading files to s3 we will be needing the boto3 client. pip install boto3 We need to create a few directories on our FTP server that we’ll be using in the implementation. Note: this directory setup is a one time thing and we won’t have to do it every single time. Connect to your FTP sever. I’m using FileZilla in my case. Goto site manager. Select the SFTP option in the protocol drop down menu. Enter your host, ip, username and password and press connect. Once you are connected create two directories on your FTP server: A parent directory where you will upload your files. a processed directory. This directory will be used to keep track of which files have been uploaded to s3. After doing the above two steps we now we have all the necessary modules installed and directory structure setup. We can now get started with the actual implementation. Let’s first briefly go through the two files that are in the git repository. Our entire FTPIngestion class implementation is as follows. I’ll explain each section of the code one by one. Note: I called it a python glue job because we can run the same code in a AWS Glue python shell environment and achieve the same FTP file transfer functionality using AWS Glue. This file is being to define all our configurations such as host-name, IP, port, username, password, s3 bucket name, ftp directory paths etc. It is a good programming practice to keep all the configurations in a separate file. This makes our code more manageable. We use this file by importing it in our python_glue_ingestion_job.py file. Our config.py file looks as follows: After having a brief overview of both of our files let’s dive into each section of the code. Our code kicks off from the main method. We first create an object ftp_obj of Our FTPIngestion class. On object creation the __init(self)__ method is called which sets up all the configuration values. The ftp_obj then calls the initiate_ingestion(self) method which will first create an ssh connection with our FTP server using the create_ssh_connection(self) method. On successful connection, an SFTP connection is then created using the create_sftp_connection(self) method which we will use to access the FTP server. Once SFTP connection is established we do the following change current directory to parent directory self.sftp_client.chdir(self.ftp_directory_path) get all the files that are to be uploaded to S3 files_to_upload = self.sftp_client.listdir() create s3 partition structure using the create_s3_partition(self) method. I’m using the current date time to setup the partition structure as follows: /<directory_name>/year = <year>/ month = <month>/ day = <day>/ hour = <hour>/file after this we start uploading the files one by one. Each file in the list is passed to the s3_upload_file_multipart() method. If file size is greater than 100Mb files will be uploaded via multipart, otherwise as a standard file. for ftp_file in files_to_upload: sftp_file_obj = self.sftp_client.file(ftp_file, mode='r') if self.s3_upload_file_multipart(sftp_file_obj, s3_partition+ftp_file): print('file uploaded to s3') files_to_move.append(ftp_file) On each successful upload the file gets moved to the processed directory using the move_files_to_processed() method that we created on the FTP server. This is done in order to keep track of all the files that have been successfully uploaded to s3. if files_to_move: for uploaded_file in files_to_move: self.move_files_to_processed(uploaded_file)else: print("nothing to upload") after all the files have been successfully upload we close all the connections using the close_connections(self) method. Lets now discuss each section of our FTPIngestion class in some detail. This is the init method also called as the constructor of our class. When we create an object of our FTPIngestion class all the attributes get set at object creation time. Values for each attribute are being fetched from the config.py class where we have defined their values. We import the config.py file as cfg and set each attribute with its corresponding value. Recommendation: instead of using the config.py class we can use AWS SSM where we define our key value pairs for each of our attribute just like we did in our config.py file. Using SSM is more robust and secure. This method creates a secure ssh connection with our FTP server using the given credentials. On successful connection it sets the self.ssh_ok attribute to True and returns. Otherwise self.ssh_ok is set to False and returned. one thing to notice in this method is the self.ssh_client.set_missing_host_key_policy( paramiko.AutoAddPolicy()). We configured it to set the missing host keys with a auto generated policy. If you’re going to run this in AWS Glue as python shell job, instead of adding the auto add policy, use the host policies. For this, do the following in the code #self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())# in production, use load_system_host_keys self.ssh_client.load_system_host_keys() This method calls the create_ssh_connection method creates the ssh connection and then proceeds to open the SFTP connection. On successful connection it sets the self.sftp_ok to True and on failure sets it to False and returns the value. This method is called in the initiate_ingestion method after the file is successfully uploaded to s3. This method take the file name as argument. Sets the source and destination paths on the FTP server as src and dest, and then executes the following command which will move the file from the src path to the dest path. try: _, _, _ = self.ssh_client.exec_command("mv " + src+" " + dest) except Exception as error: print("error moving files to processed directory, error: ", error) Our move_files_to_processed method is as follows: This method creates the s3 partition structure. The partition consists of root directory name followed by year, month,day,hour. In this way we can have a time based partitioned data. This method uploads the files to the specified s3 bucket. It uses the TransferConfig class to handle the multipart upload. We specify the configurations for TransferConfig as follows: config = TransferConfig(multipart_threshold=cfg.MULTIPART_THRESHOLD, multipart_chunksize=cfg.MULTIPART_CHUNKSIZE, max_concurrency=cfg.MAX_CONCURRENCY, use_threads=cfg.USER_THREADS ) the multipart_threshold parameter determines the minimum size of file that should be after which the file will be uploaded via multipart. AWS recommends all files greater than 100MB be uploaded via multipart, so I have set this parameter to 100MB. This can be changed in the config.py file. the multipart_chunksize parameter determines the size of each part during multipart upload. I have set it to 20MB. the max_concurrency parameter determines the maximum number of concurrent S3 API transfer operations that should be used to upload each part. Default is 10. lastly the use_threads parameter determines whether transfer operations use threads to implement concurrency. Thread use can be disabled by setting the use_threads attribute to False. If thread use is disabled, transfer concurrency does not occur. Accordingly, the value of the max_concurrency attribute is ignored. We pass this config object to our s3.upload_fileobj as parameter self.s3.upload_fileobj(source_file, self.s3_bucket_name, s3_target_file, Config=config) The TransferConfig class automatically checks whether to upload the file as a single part or via multipart. It automatically handles the failed uploads and takes care of retries in case of failures. This method initiates the calls to establish ssh and sftp connections. Changes FTP directory path to specified path where the files reside. Gets list of all the files in the FTP specified path and starts upload to s3. Files Successfully uploaded to S3 gets moved into the processed directory on FTP server. Once all files are uploaded closes all the connections. This mehtod is used to close the ssh and sftp connections. As mentioned earlier, the same implementation can be used in a managed environment such as AWS Glue. If user has files arriving on the FTP server at a certain time period (hour, day, month etc) he can schedule the job to run at a specific time to ingest all the files from the FTP server to s3. We have to modify a few things in our code to be able to run this implementation as an AWS Glue Python shell job In our imports section of python_glue_injestion_job.py file uncomment the following import. We are using easy install to install the paramiko module in the Glue Environment since it does not come with default Python installation. install_path = os.environ['GLUE_INSTALLATION']easy_install.main( ["--install-dir", install_path, "https://files.pythonhosted.org/packages/ac/15/4351003352e11300b9f44 a13576bff52dcdc6e4a911129c07447bda0a358/paramiko-2.7.1.tar.gz"] )reload(site) in create_ssh_connection method comment following #self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) and uncomment the follwoing self.ssh_client.load_system_host_keys() what we are doing is instead of using an auto generated policy we are using the host keys of the environment we are in. After doing above steps we can run this code in as a Python shell job in AWS Glue. In this article, we looked at how can perform the data ingestion step of a Datalake pipeline. We learned how we can use the paramiko library to create a secure ssh SFTP connection with a FTP server and upload files from the server to our AWS S3 buckets. We also briefly looked at how we can use the given implementation in a managed environment such as AWS Glue. Link to my Github repository:
[ { "code": null, "e": 726, "s": 172, "text": "Hello everyone. When developing Datalake pipe lines, data ingestion is an important step in the entire process. We need a reliable, secure and fault tolerant method to bring our files from source(client FTP server) to our target( AWS S3). Considering how important this step is, I developed an implementation in python that can be used to ingest files from an FTP server to AWS s3. I have designed the code in such manner that it can be used in a managed(AWS Glue) or un-managed(local machine) environment to transfer files from an FTP server to AWS s3." }, { "code": null, "e": 877, "s": 726, "text": "In this article I will explain how we can transfer files present on an FTP server such as FileZilla to Amazon s3 using the Paramiko Library in Python." }, { "code": null, "e": 990, "s": 877, "text": "The file ingestion code can be found on my GitHub repository. The file ingestion code does the following things:" }, { "code": null, "e": 1064, "s": 990, "text": "Creates a secure ssh SFTP connection with the File server using Paramiko." }, { "code": null, "e": 1178, "s": 1064, "text": "Automatically handles single part and multipart upload depending upon the file size (multipart on 100MB or more)." }, { "code": null, "e": 1265, "s": 1178, "text": "Automatically handles retires in case of failed parts uploads during multipart upload." }, { "code": null, "e": 1329, "s": 1265, "text": "Partitions the data in s3 based on current year,month,day,hour." }, { "code": null, "e": 1366, "s": 1329, "text": "Ensures which file has been uploaded" }, { "code": null, "e": 1455, "s": 1366, "text": "Can be used as a python job in AWS Glue to transfer files from FTP to S3 using AWS Glue." }, { "code": null, "e": 1568, "s": 1455, "text": "I will do a step by step walk through of each section of the code for better understanding. So lets get started." }, { "code": null, "e": 1694, "s": 1568, "text": "Before we get started we need to do a little installation setup on our local machine and a directory setup on our FTP server." }, { "code": null, "e": 1930, "s": 1694, "text": "I’m assuming you guys have python already installed on you machines. Visit this link to install python on your machine if you haven’t already.Before getting towards the code we need to make sure we have the following modules installed:" }, { "code": null, "e": 1960, "s": 1930, "text": "First we’ll install Paramiko." }, { "code": null, "e": 1981, "s": 1960, "text": "pip install paramiko" }, { "code": null, "e": 2055, "s": 1981, "text": "Since we’ll be uploading files to s3 we will be needing the boto3 client." }, { "code": null, "e": 2073, "s": 2055, "text": "pip install boto3" }, { "code": null, "e": 2170, "s": 2073, "text": "We need to create a few directories on our FTP server that we’ll be using in the implementation." }, { "code": null, "e": 2263, "s": 2170, "text": "Note: this directory setup is a one time thing and we won’t have to do it every single time." }, { "code": null, "e": 2458, "s": 2263, "text": "Connect to your FTP sever. I’m using FileZilla in my case. Goto site manager. Select the SFTP option in the protocol drop down menu. Enter your host, ip, username and password and press connect." }, { "code": null, "e": 2524, "s": 2458, "text": "Once you are connected create two directories on your FTP server:" }, { "code": null, "e": 2577, "s": 2524, "text": "A parent directory where you will upload your files." }, { "code": null, "e": 2683, "s": 2577, "text": "a processed directory. This directory will be used to keep track of which files have been uploaded to s3." }, { "code": null, "e": 2852, "s": 2683, "text": "After doing the above two steps we now we have all the necessary modules installed and directory structure setup. We can now get started with the actual implementation." }, { "code": null, "e": 2929, "s": 2852, "text": "Let’s first briefly go through the two files that are in the git repository." }, { "code": null, "e": 3039, "s": 2929, "text": "Our entire FTPIngestion class implementation is as follows. I’ll explain each section of the code one by one." }, { "code": null, "e": 3216, "s": 3039, "text": "Note: I called it a python glue job because we can run the same code in a AWS Glue python shell environment and achieve the same FTP file transfer functionality using AWS Glue." }, { "code": null, "e": 3480, "s": 3216, "text": "This file is being to define all our configurations such as host-name, IP, port, username, password, s3 bucket name, ftp directory paths etc. It is a good programming practice to keep all the configurations in a separate file. This makes our code more manageable." }, { "code": null, "e": 3592, "s": 3480, "text": "We use this file by importing it in our python_glue_ingestion_job.py file. Our config.py file looks as follows:" }, { "code": null, "e": 3685, "s": 3592, "text": "After having a brief overview of both of our files let’s dive into each section of the code." }, { "code": null, "e": 3886, "s": 3685, "text": "Our code kicks off from the main method. We first create an object ftp_obj of Our FTPIngestion class. On object creation the __init(self)__ method is called which sets up all the configuration values." }, { "code": null, "e": 4204, "s": 3886, "text": "The ftp_obj then calls the initiate_ingestion(self) method which will first create an ssh connection with our FTP server using the create_ssh_connection(self) method. On successful connection, an SFTP connection is then created using the create_sftp_connection(self) method which we will use to access the FTP server." }, { "code": null, "e": 4260, "s": 4204, "text": "Once SFTP connection is established we do the following" }, { "code": null, "e": 4305, "s": 4260, "text": "change current directory to parent directory" }, { "code": null, "e": 4353, "s": 4305, "text": "self.sftp_client.chdir(self.ftp_directory_path)" }, { "code": null, "e": 4401, "s": 4353, "text": "get all the files that are to be uploaded to S3" }, { "code": null, "e": 4446, "s": 4401, "text": "files_to_upload = self.sftp_client.listdir()" }, { "code": null, "e": 4597, "s": 4446, "text": "create s3 partition structure using the create_s3_partition(self) method. I’m using the current date time to setup the partition structure as follows:" }, { "code": null, "e": 4679, "s": 4597, "text": "/<directory_name>/year = <year>/ month = <month>/ day = <day>/ hour = <hour>/file" }, { "code": null, "e": 4908, "s": 4679, "text": "after this we start uploading the files one by one. Each file in the list is passed to the s3_upload_file_multipart() method. If file size is greater than 100Mb files will be uploaded via multipart, otherwise as a standard file." }, { "code": null, "e": 5207, "s": 4908, "text": "for ftp_file in files_to_upload: sftp_file_obj = self.sftp_client.file(ftp_file, mode='r') if self.s3_upload_file_multipart(sftp_file_obj, s3_partition+ftp_file): print('file uploaded to s3') files_to_move.append(ftp_file)" }, { "code": null, "e": 5455, "s": 5207, "text": "On each successful upload the file gets moved to the processed directory using the move_files_to_processed() method that we created on the FTP server. This is done in order to keep track of all the files that have been successfully uploaded to s3." }, { "code": null, "e": 5618, "s": 5455, "text": "if files_to_move: for uploaded_file in files_to_move: self.move_files_to_processed(uploaded_file)else: print(\"nothing to upload\")" }, { "code": null, "e": 5739, "s": 5618, "text": "after all the files have been successfully upload we close all the connections using the close_connections(self) method." }, { "code": null, "e": 5811, "s": 5739, "text": "Lets now discuss each section of our FTPIngestion class in some detail." }, { "code": null, "e": 6177, "s": 5811, "text": "This is the init method also called as the constructor of our class. When we create an object of our FTPIngestion class all the attributes get set at object creation time. Values for each attribute are being fetched from the config.py class where we have defined their values. We import the config.py file as cfg and set each attribute with its corresponding value." }, { "code": null, "e": 6388, "s": 6177, "text": "Recommendation: instead of using the config.py class we can use AWS SSM where we define our key value pairs for each of our attribute just like we did in our config.py file. Using SSM is more robust and secure." }, { "code": null, "e": 6613, "s": 6388, "text": "This method creates a secure ssh connection with our FTP server using the given credentials. On successful connection it sets the self.ssh_ok attribute to True and returns. Otherwise self.ssh_ok is set to False and returned." }, { "code": null, "e": 6965, "s": 6613, "text": "one thing to notice in this method is the self.ssh_client.set_missing_host_key_policy( paramiko.AutoAddPolicy()). We configured it to set the missing host keys with a auto generated policy. If you’re going to run this in AWS Glue as python shell job, instead of adding the auto add policy, use the host policies. For this, do the following in the code" }, { "code": null, "e": 7130, "s": 6965, "text": "#self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())# in production, use load_system_host_keys self.ssh_client.load_system_host_keys()" }, { "code": null, "e": 7368, "s": 7130, "text": "This method calls the create_ssh_connection method creates the ssh connection and then proceeds to open the SFTP connection. On successful connection it sets the self.sftp_ok to True and on failure sets it to False and returns the value." }, { "code": null, "e": 7688, "s": 7368, "text": "This method is called in the initiate_ingestion method after the file is successfully uploaded to s3. This method take the file name as argument. Sets the source and destination paths on the FTP server as src and dest, and then executes the following command which will move the file from the src path to the dest path." }, { "code": null, "e": 7863, "s": 7688, "text": "try: _, _, _ = self.ssh_client.exec_command(\"mv \" + src+\" \" + dest) except Exception as error: print(\"error moving files to processed directory, error: \", error)" }, { "code": null, "e": 7913, "s": 7863, "text": "Our move_files_to_processed method is as follows:" }, { "code": null, "e": 8096, "s": 7913, "text": "This method creates the s3 partition structure. The partition consists of root directory name followed by year, month,day,hour. In this way we can have a time based partitioned data." }, { "code": null, "e": 8280, "s": 8096, "text": "This method uploads the files to the specified s3 bucket. It uses the TransferConfig class to handle the multipart upload. We specify the configurations for TransferConfig as follows:" }, { "code": null, "e": 8554, "s": 8280, "text": "config = TransferConfig(multipart_threshold=cfg.MULTIPART_THRESHOLD, multipart_chunksize=cfg.MULTIPART_CHUNKSIZE, max_concurrency=cfg.MAX_CONCURRENCY, use_threads=cfg.USER_THREADS )" }, { "code": null, "e": 8845, "s": 8554, "text": "the multipart_threshold parameter determines the minimum size of file that should be after which the file will be uploaded via multipart. AWS recommends all files greater than 100MB be uploaded via multipart, so I have set this parameter to 100MB. This can be changed in the config.py file." }, { "code": null, "e": 8960, "s": 8845, "text": "the multipart_chunksize parameter determines the size of each part during multipart upload. I have set it to 20MB." }, { "code": null, "e": 9117, "s": 8960, "text": "the max_concurrency parameter determines the maximum number of concurrent S3 API transfer operations that should be used to upload each part. Default is 10." }, { "code": null, "e": 9433, "s": 9117, "text": "lastly the use_threads parameter determines whether transfer operations use threads to implement concurrency. Thread use can be disabled by setting the use_threads attribute to False. If thread use is disabled, transfer concurrency does not occur. Accordingly, the value of the max_concurrency attribute is ignored." }, { "code": null, "e": 9498, "s": 9433, "text": "We pass this config object to our s3.upload_fileobj as parameter" }, { "code": null, "e": 9608, "s": 9498, "text": "self.s3.upload_fileobj(source_file, self.s3_bucket_name, s3_target_file, Config=config)" }, { "code": null, "e": 9807, "s": 9608, "text": "The TransferConfig class automatically checks whether to upload the file as a single part or via multipart. It automatically handles the failed uploads and takes care of retries in case of failures." }, { "code": null, "e": 10170, "s": 9807, "text": "This method initiates the calls to establish ssh and sftp connections. Changes FTP directory path to specified path where the files reside. Gets list of all the files in the FTP specified path and starts upload to s3. Files Successfully uploaded to S3 gets moved into the processed directory on FTP server. Once all files are uploaded closes all the connections." }, { "code": null, "e": 10229, "s": 10170, "text": "This mehtod is used to close the ssh and sftp connections." }, { "code": null, "e": 10524, "s": 10229, "text": "As mentioned earlier, the same implementation can be used in a managed environment such as AWS Glue. If user has files arriving on the FTP server at a certain time period (hour, day, month etc) he can schedule the job to run at a specific time to ingest all the files from the FTP server to s3." }, { "code": null, "e": 10637, "s": 10524, "text": "We have to modify a few things in our code to be able to run this implementation as an AWS Glue Python shell job" }, { "code": null, "e": 10867, "s": 10637, "text": "In our imports section of python_glue_injestion_job.py file uncomment the following import. We are using easy install to install the paramiko module in the Glue Environment since it does not come with default Python installation." }, { "code": null, "e": 11111, "s": 10867, "text": "install_path = os.environ['GLUE_INSTALLATION']easy_install.main( [\"--install-dir\", install_path, \"https://files.pythonhosted.org/packages/ac/15/4351003352e11300b9f44 a13576bff52dcdc6e4a911129c07447bda0a358/paramiko-2.7.1.tar.gz\"] )reload(site)" }, { "code": null, "e": 11161, "s": 11111, "text": "in create_ssh_connection method comment following" }, { "code": null, "e": 11232, "s": 11161, "text": "#self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())" }, { "code": null, "e": 11260, "s": 11232, "text": "and uncomment the follwoing" }, { "code": null, "e": 11300, "s": 11260, "text": "self.ssh_client.load_system_host_keys()" }, { "code": null, "e": 11420, "s": 11300, "text": "what we are doing is instead of using an auto generated policy we are using the host keys of the environment we are in." }, { "code": null, "e": 11503, "s": 11420, "text": "After doing above steps we can run this code in as a Python shell job in AWS Glue." }, { "code": null, "e": 11866, "s": 11503, "text": "In this article, we looked at how can perform the data ingestion step of a Datalake pipeline. We learned how we can use the paramiko library to create a secure ssh SFTP connection with a FTP server and upload files from the server to our AWS S3 buckets. We also briefly looked at how we can use the given implementation in a managed environment such as AWS Glue." } ]
Batch Script - Moving Files
For moving files, Batch Script provides the MOVE command. MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination Following are the description of the options which can be presented to the DEL command. [drive:][path]filename1 Specifies the location and name of the file or files you want to move destination Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it. [drive:][path]dirname1 Specifies the directory you want to rename. dirname2 Specifies the new name of the directory. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /-Y Causes prompting to confirm you want to overwrite an existing destination file. Let’s look at some examples of renaming files. move c:\windows\temp\*.* c:\temp The above command will move the files of c:\windows\temp to the temp directory in root. move new.txt, test.txt c:\example The above command will move the files new.txt and test.txt into the c:\example folder. Print Add Notes Bookmark this page
[ { "code": null, "e": 2227, "s": 2169, "text": "For moving files, Batch Script provides the MOVE command." }, { "code": null, "e": 2286, "s": 2227, "text": "MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination\n" }, { "code": null, "e": 2374, "s": 2286, "text": "Following are the description of the options which can be presented to the DEL command." }, { "code": null, "e": 2398, "s": 2374, "text": "[drive:][path]filename1" }, { "code": null, "e": 2468, "s": 2398, "text": "Specifies the location and name of the file or files you want to move" }, { "code": null, "e": 2480, "s": 2468, "text": "destination" }, { "code": null, "e": 2723, "s": 2480, "text": "Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it." }, { "code": null, "e": 2746, "s": 2723, "text": "[drive:][path]dirname1" }, { "code": null, "e": 2790, "s": 2746, "text": "Specifies the directory you want to rename." }, { "code": null, "e": 2799, "s": 2790, "text": "dirname2" }, { "code": null, "e": 2840, "s": 2799, "text": "Specifies the new name of the directory." }, { "code": null, "e": 2843, "s": 2840, "text": "/Y" }, { "code": null, "e": 2927, "s": 2843, "text": "Suppresses prompting to confirm you want to overwrite an existing destination file." }, { "code": null, "e": 2931, "s": 2927, "text": "/-Y" }, { "code": null, "e": 3011, "s": 2931, "text": "Causes prompting to confirm you want to overwrite an existing destination file." }, { "code": null, "e": 3058, "s": 3011, "text": "Let’s look at some examples of renaming files." }, { "code": null, "e": 3092, "s": 3058, "text": "move c:\\windows\\temp\\*.* c:\\temp\n" }, { "code": null, "e": 3180, "s": 3092, "text": "The above command will move the files of c:\\windows\\temp to the temp directory in root." }, { "code": null, "e": 3215, "s": 3180, "text": "move new.txt, test.txt c:\\example\n" }, { "code": null, "e": 3302, "s": 3215, "text": "The above command will move the files new.txt and test.txt into the c:\\example folder." }, { "code": null, "e": 3309, "s": 3302, "text": " Print" }, { "code": null, "e": 3320, "s": 3309, "text": " Add Notes" } ]
Anonymous Array in Java - GeeksforGeeks
22 Apr, 2022 An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable. Properties of Anonymous Arrays: We can create an array without a name. Such types of nameless arrays are called anonymous arrays. The main purpose of an anonymous array is just for instant use (just for one-time usage). An anonymous array is passed as an argument of a method. Note: For Anonymous array creation, do not mention size in []. The number of values passing inside {} will become the size. Syntax: new <data type>[]{<list of values with comma separator>}; Examples: // anonymous int array new int[] { 1, 2, 3, 4}; // anonymous char array new char[] {'x', 'y', 'z'}; // anonymous String array new String[] {"Geeks", "for", "Geeks"}; // anonymous multidimensional array new int[][] { {10, 20}, {30, 40, 50} }; Java // Java program to illustrate the// concept of anonymous array class Test { public static void main(String[] args) { // anonymous array sum(new int[]{ 1, 2, 3 }); } public static void sum(int[] a) { int total = 0; // using for-each loop for (int i : a) total = total + i; System.out.println("The sum is: " + total); }} The sum is: 6 Explanation: In the above example, just to call the sum method, we required an array, but after implementing the sum method, we are not using the array anymore. Hence for this one-time requirement anonymous array is the best choice. Based on our requirement, we can later give the name to the anonymous array, and then it will no longer be anonymous. This article is contributed by Bishal Kumar Dubey. 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. nishkarshgandhi pramodask003 Java-Array-Programs Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23972, "s": 23944, "text": "\n22 Apr, 2022" }, { "code": null, "e": 24189, "s": 23972, "text": "An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable." }, { "code": null, "e": 24221, "s": 24189, "text": "Properties of Anonymous Arrays:" }, { "code": null, "e": 24319, "s": 24221, "text": "We can create an array without a name. Such types of nameless arrays are called anonymous arrays." }, { "code": null, "e": 24409, "s": 24319, "text": "The main purpose of an anonymous array is just for instant use (just for one-time usage)." }, { "code": null, "e": 24466, "s": 24409, "text": "An anonymous array is passed as an argument of a method." }, { "code": null, "e": 24590, "s": 24466, "text": "Note: For Anonymous array creation, do not mention size in []. The number of values passing inside {} will become the size." }, { "code": null, "e": 24599, "s": 24590, "text": "Syntax: " }, { "code": null, "e": 24657, "s": 24599, "text": "new <data type>[]{<list of values with comma separator>};" }, { "code": null, "e": 24667, "s": 24657, "text": "Examples:" }, { "code": null, "e": 24918, "s": 24667, "text": "// anonymous int array \nnew int[] { 1, 2, 3, 4}; \n\n// anonymous char array \nnew char[] {'x', 'y', 'z'}; \n\n// anonymous String array\nnew String[] {\"Geeks\", \"for\", \"Geeks\"}; \n\n// anonymous multidimensional array\nnew int[][] { {10, 20}, {30, 40, 50} };" }, { "code": null, "e": 24923, "s": 24918, "text": "Java" }, { "code": "// Java program to illustrate the// concept of anonymous array class Test { public static void main(String[] args) { // anonymous array sum(new int[]{ 1, 2, 3 }); } public static void sum(int[] a) { int total = 0; // using for-each loop for (int i : a) total = total + i; System.out.println(\"The sum is: \" + total); }}", "e": 25330, "s": 24923, "text": null }, { "code": null, "e": 25344, "s": 25330, "text": "The sum is: 6" }, { "code": null, "e": 25696, "s": 25344, "text": "Explanation: In the above example, just to call the sum method, we required an array, but after implementing the sum method, we are not using the array anymore. Hence for this one-time requirement anonymous array is the best choice. Based on our requirement, we can later give the name to the anonymous array, and then it will no longer be anonymous. " }, { "code": null, "e": 26123, "s": 25696, "text": "This article is contributed by Bishal Kumar Dubey. 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": 26139, "s": 26123, "text": "nishkarshgandhi" }, { "code": null, "e": 26152, "s": 26139, "text": "pramodask003" }, { "code": null, "e": 26172, "s": 26152, "text": "Java-Array-Programs" }, { "code": null, "e": 26184, "s": 26172, "text": "Java-Arrays" }, { "code": null, "e": 26189, "s": 26184, "text": "Java" }, { "code": null, "e": 26194, "s": 26189, "text": "Java" }, { "code": null, "e": 26292, "s": 26194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26307, "s": 26292, "text": "Stream In Java" }, { "code": null, "e": 26353, "s": 26307, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26374, "s": 26353, "text": "Constructors in Java" }, { "code": null, "e": 26393, "s": 26374, "text": "Exceptions in Java" }, { "code": null, "e": 26410, "s": 26393, "text": "Generics in Java" }, { "code": null, "e": 26440, "s": 26410, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26483, "s": 26440, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26512, "s": 26483, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26533, "s": 26512, "text": "Introduction to Java" } ]
Get distinct levels of array field in MongoDB?
To get distinct levels of array field, use $addToSet in MongoDB. Let us create a collection with documents − > db.demo122.insertOne({"ListOfValues":[100,10]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f20f1140daf4c2a3544b6") } > db.demo122.insertOne({"ListOfValues":[240,10]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f20f7140daf4c2a3544b7") } Display all documents from a collection with the help of find() method − > db.demo122.find(); This will produce the following output − { "_id" : ObjectId("5e2f20f1140daf4c2a3544b6"), "ListOfValues" : [ 100, 10 ] } { "_id" : ObjectId("5e2f20f7140daf4c2a3544b7"), "ListOfValues" : [ 240, 10 ] } Following is the query to get distinct levels of array field in MongoDB − > db.demo122.aggregate([ ... { ... "$group": { ... "_id": 0, ... "ListOfValues": { "$addToSet": "$ListOfValues" } ... } ... } ... ]) This will produce the following output − { "_id" : 0, "ListOfValues" : [ [ 240, 10 ], [ 100, 10 ] ] }
[ { "code": null, "e": 1171, "s": 1062, "text": "To get distinct levels of array field, use $addToSet in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1443, "s": 1171, "text": "> db.demo122.insertOne({\"ListOfValues\":[100,10]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2f20f1140daf4c2a3544b6\")\n}\n> db.demo122.insertOne({\"ListOfValues\":[240,10]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2f20f7140daf4c2a3544b7\")\n}" }, { "code": null, "e": 1516, "s": 1443, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1537, "s": 1516, "text": "> db.demo122.find();" }, { "code": null, "e": 1578, "s": 1537, "text": "This will produce the following output −" }, { "code": null, "e": 1736, "s": 1578, "text": "{ \"_id\" : ObjectId(\"5e2f20f1140daf4c2a3544b6\"), \"ListOfValues\" : [ 100, 10 ] }\n{ \"_id\" : ObjectId(\"5e2f20f7140daf4c2a3544b7\"), \"ListOfValues\" : [ 240, 10 ] }" }, { "code": null, "e": 1810, "s": 1736, "text": "Following is the query to get distinct levels of array field in MongoDB −" }, { "code": null, "e": 1979, "s": 1810, "text": "> db.demo122.aggregate([\n... {\n... \"$group\": {\n... \"_id\": 0,\n... \"ListOfValues\": { \"$addToSet\": \"$ListOfValues\" }\n... }\n... }\n... ])" }, { "code": null, "e": 2020, "s": 1979, "text": "This will produce the following output −" }, { "code": null, "e": 2081, "s": 2020, "text": "{ \"_id\" : 0, \"ListOfValues\" : [ [ 240, 10 ], [ 100, 10 ] ] }" } ]
Spring Batch - Configuration
While writing a Spring Batch application, we will configure the job, step, JobLauncher, JobRepository, Transaction Manager, readers, and writers using the XML tags provided in the Spring Batch namespace. Therefore, you need to include this namespace in your XML file as shown below. <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:batch = "http://www.springframework.org/schema/batch" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/bean http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> In the following sections, we will discuss the various tags, their attributes and examples, available in the Spring Batch namespace. This tag is used to define/configure the job of the SpringBatch. It contains a set of steps and it can be launched using the JobLauncher. This tag has 2 attributes as listed below − Id It is the Id of the job, it is mandatory to specify value to this attribute. restartable This is the attribute which is used to specify whether the job is restartable or not. This attribute is optional. Following is the XML configuration of the job of a SpringBatch. <job id = "jobid" restartable = "false" > . . . . . . . . . . . . . . . . . . . . . . . . // Step definitions </job> This tag is used to define/configure the steps of a SpringBatch job. It has the following three attributes − Id It is the Id of the job, it is mandatory to specify value to this attribute. next It is the shortcut to specify the next step. parent It is used to specify the name of the parent bean from which the configuration should inherit. Following is the XML configuration of the step of a SpringBatch. <job id = "jobid"> <step id = "step1" next = "step2"/> <step id = "step2" next = "step3"/> <step id = "step3"/> </job> This tag is used to define/configure a chunk of a tasklet. It has the following four attributes − reader It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemReader. writer It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemWriter. processor It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemProcessor. commit-interval It is used to specify the number of items to be processed before committing the transaction. Following is the XML configuration of the chunk of a SpringBatch. <batch:step id = "step1"> <batch:tasklet> <batch:chunk reader = "xmlItemReader" writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10"> </batch:chunk> </batch:tasklet> </batch:step> The JobRepository Bean is used to configure the JobRepository using a relational database. This bean is associated with the class of type org.springframework.batch.core.repository.JobRepository. dataSource It is used to specify the bean name which defines the datasource. transactionManager It is used specify the name of the bean which defines the transactionmanager. databaseType It specifies the type of the relational database used in the job repository. Following is the example configuration of the JobRepository. <bean id = "jobRepository" class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name = "dataSource" ref = "dataSource" /> <property name = "transactionManager" ref="transactionManager" /> <property name = "databaseType" value = "mysql" /> </bean> The JobLauncher bean is used to configure the JobLauncher. It is associated with the class org.springframework.batch.core.launch.support.SimpleJobLauncher (in our programs). This bean has one property named jobrepository, and it is used to specify the name of the bean which defines the jobrepository. Following is the example configuration of the jobLauncher. <bean id = "jobLauncher" class = "org.springframework.batch.core.launch.support.SimpleJobLauncher"> <property name = "jobRepository" ref = "jobRepository" /> </bean> The TransactionManager bean is used to configure the TransactionManager using a relational database. This bean is associated with the class of type org.springframework.transaction.platform.TransactionManager. <bean id = "transactionManager" class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager" /> The datasource bean is used to configure the Datasource. This bean is associated with the class of type org.springframework.jdbc.datasource.DriverManagerDataSource. driverClassName This specifies the class name of the driver used to connect with the database. url This specifies the URL of the database. username This specifies the username to connect with the database. password This specifies the password to connect with the database. Following is the example configuration of the datasource. <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> <property name = "url" value = "jdbc:mysql://localhost:3306/details" /> <property name = "username" value = "myuser" /> <property name = "password" value = "password" /> </bean> 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2211, "s": 1928, "text": "While writing a Spring Batch application, we will configure the job, step, JobLauncher, JobRepository, Transaction Manager, readers, and writers using the XML tags provided in the Spring Batch namespace. Therefore, you need to include this namespace in your XML file as shown below." }, { "code": null, "e": 2657, "s": 2211, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:batch = \"http://www.springframework.org/schema/batch\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/batch \n\n http://www.springframework.org/schema/batch/spring-batch-2.2.xsd \n http://www.springframework.org/schema/bean \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd\"> " }, { "code": null, "e": 2790, "s": 2657, "text": "In the following sections, we will discuss the various tags, their attributes and examples, available in the Spring Batch namespace." }, { "code": null, "e": 2928, "s": 2790, "text": "This tag is used to define/configure the job of the SpringBatch. It contains a set of steps and it can be launched using the JobLauncher." }, { "code": null, "e": 2972, "s": 2928, "text": "This tag has 2 attributes as listed below −" }, { "code": null, "e": 2975, "s": 2972, "text": "Id" }, { "code": null, "e": 3052, "s": 2975, "text": "It is the Id of the job, it is mandatory to specify value to this attribute." }, { "code": null, "e": 3064, "s": 3052, "text": "restartable" }, { "code": null, "e": 3178, "s": 3064, "text": "This is the attribute which is used to specify whether the job is restartable or not. This attribute is optional." }, { "code": null, "e": 3242, "s": 3178, "text": "Following is the XML configuration of the job of a SpringBatch." }, { "code": null, "e": 3375, "s": 3242, "text": "<job id = \"jobid\" restartable = \"false\" > \n . . . . . . . . \n . . . . . . . . \n . . . . . . . . // Step definitions \n</job>\n" }, { "code": null, "e": 3484, "s": 3375, "text": "This tag is used to define/configure the steps of a SpringBatch job. It has the following three attributes −" }, { "code": null, "e": 3487, "s": 3484, "text": "Id" }, { "code": null, "e": 3564, "s": 3487, "text": "It is the Id of the job, it is mandatory to specify value to this attribute." }, { "code": null, "e": 3569, "s": 3564, "text": "next" }, { "code": null, "e": 3614, "s": 3569, "text": "It is the shortcut to specify the next step." }, { "code": null, "e": 3621, "s": 3614, "text": "parent" }, { "code": null, "e": 3716, "s": 3621, "text": "It is used to specify the name of the parent bean from which the configuration should inherit." }, { "code": null, "e": 3781, "s": 3716, "text": "Following is the XML configuration of the step of a SpringBatch." }, { "code": null, "e": 3913, "s": 3781, "text": "<job id = \"jobid\"> \n <step id = \"step1\" next = \"step2\"/> \n <step id = \"step2\" next = \"step3\"/> \n <step id = \"step3\"/> \n</job>" }, { "code": null, "e": 4011, "s": 3913, "text": "This tag is used to define/configure a chunk of a tasklet. It has the following four attributes −" }, { "code": null, "e": 4018, "s": 4011, "text": "reader" }, { "code": null, "e": 4142, "s": 4018, "text": "It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemReader." }, { "code": null, "e": 4149, "s": 4142, "text": "writer" }, { "code": null, "e": 4273, "s": 4149, "text": "It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemWriter." }, { "code": null, "e": 4283, "s": 4273, "text": "processor" }, { "code": null, "e": 4410, "s": 4283, "text": "It represents the name of the item reader bean. It accepts the value of the type org.springframework.batch.item.ItemProcessor." }, { "code": null, "e": 4426, "s": 4410, "text": "commit-interval" }, { "code": null, "e": 4519, "s": 4426, "text": "It is used to specify the number of items to be processed before committing the transaction." }, { "code": null, "e": 4585, "s": 4519, "text": "Following is the XML configuration of the chunk of a SpringBatch." }, { "code": null, "e": 4824, "s": 4585, "text": "<batch:step id = \"step1\"> \n <batch:tasklet> \n <batch:chunk reader = \"xmlItemReader\" \n writer = \"mysqlItemWriter\" processor = \"itemProcessor\" commit-interval = \"10\"> \n </batch:chunk> \n </batch:tasklet> \n</batch:step> " }, { "code": null, "e": 5019, "s": 4824, "text": "The JobRepository Bean is used to configure the JobRepository using a relational database. This bean is associated with the class of type org.springframework.batch.core.repository.JobRepository." }, { "code": null, "e": 5030, "s": 5019, "text": "dataSource" }, { "code": null, "e": 5096, "s": 5030, "text": "It is used to specify the bean name which defines the datasource." }, { "code": null, "e": 5115, "s": 5096, "text": "transactionManager" }, { "code": null, "e": 5193, "s": 5115, "text": "It is used specify the name of the bean which defines the transactionmanager." }, { "code": null, "e": 5206, "s": 5193, "text": "databaseType" }, { "code": null, "e": 5283, "s": 5206, "text": "It specifies the type of the relational database used in the job repository." }, { "code": null, "e": 5344, "s": 5283, "text": "Following is the example configuration of the JobRepository." }, { "code": null, "e": 5652, "s": 5344, "text": "<bean id = \"jobRepository\" \n class = \"org.springframework.batch.core.repository.support.JobRepositoryFactoryBean\"> \n <property name = \"dataSource\" ref = \"dataSource\" /> \n <property name = \"transactionManager\" ref=\"transactionManager\" /> \n <property name = \"databaseType\" value = \"mysql\" /> \n</bean> " }, { "code": null, "e": 5954, "s": 5652, "text": "The JobLauncher bean is used to configure the JobLauncher. It is associated with the class org.springframework.batch.core.launch.support.SimpleJobLauncher (in our programs). This bean has one property named jobrepository, and it is used to specify the name of the bean which defines the jobrepository." }, { "code": null, "e": 6013, "s": 5954, "text": "Following is the example configuration of the jobLauncher." }, { "code": null, "e": 6188, "s": 6013, "text": "<bean id = \"jobLauncher\" \n class = \"org.springframework.batch.core.launch.support.SimpleJobLauncher\"> \n <property name = \"jobRepository\" ref = \"jobRepository\" /> \n</bean>" }, { "code": null, "e": 6397, "s": 6188, "text": "The TransactionManager bean is used to configure the TransactionManager using a relational database. This bean is associated with the class of type org.springframework.transaction.platform.TransactionManager." }, { "code": null, "e": 6522, "s": 6397, "text": "<bean id = \"transactionManager\"\n class = \"org.springframework.batch.support.transaction.ResourcelessTransactionManager\" />" }, { "code": null, "e": 6687, "s": 6522, "text": "The datasource bean is used to configure the Datasource. This bean is associated with the class of type org.springframework.jdbc.datasource.DriverManagerDataSource." }, { "code": null, "e": 6703, "s": 6687, "text": "driverClassName" }, { "code": null, "e": 6782, "s": 6703, "text": "This specifies the class name of the driver used to connect with the database." }, { "code": null, "e": 6786, "s": 6782, "text": "url" }, { "code": null, "e": 6826, "s": 6786, "text": "This specifies the URL of the database." }, { "code": null, "e": 6835, "s": 6826, "text": "username" }, { "code": null, "e": 6893, "s": 6835, "text": "This specifies the username to connect with the database." }, { "code": null, "e": 6902, "s": 6893, "text": "password" }, { "code": null, "e": 6960, "s": 6902, "text": "This specifies the password to connect with the database." }, { "code": null, "e": 7018, "s": 6960, "text": "Following is the example configuration of the datasource." }, { "code": null, "e": 7383, "s": 7018, "text": "<bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\"> \n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\" /> \n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/details\" /> \n <property name = \"username\" value = \"myuser\" /> \n <property name = \"password\" value = \"password\" /> \n</bean> " }, { "code": null, "e": 7417, "s": 7383, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 7431, "s": 7417, "text": " Karthikeya T" }, { "code": null, "e": 7464, "s": 7431, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 7479, "s": 7464, "text": " Chaand Sheikh" }, { "code": null, "e": 7514, "s": 7479, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7526, "s": 7514, "text": " Senol Atac" }, { "code": null, "e": 7561, "s": 7526, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7573, "s": 7561, "text": " Senol Atac" }, { "code": null, "e": 7608, "s": 7573, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7620, "s": 7608, "text": " Senol Atac" }, { "code": null, "e": 7653, "s": 7620, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7665, "s": 7653, "text": " Senol Atac" }, { "code": null, "e": 7672, "s": 7665, "text": " Print" }, { "code": null, "e": 7683, "s": 7672, "text": " Add Notes" } ]
What is Operator Precedence Parsing?
Operator Precedence Parsing is also a type of Bottom-Up Parsing that can be used to a class of Grammars known as Operator Grammar. A Grammar G is Operator Grammar if it has the following properties − Production should not contain ε on its right side. Production should not contain ε on its right side. There should not be two adjacent non-terminals at the right side of production. There should not be two adjacent non-terminals at the right side of production. Example1 − Verify whether the following Grammar is operator Grammar or not. E → E A E |(E)|id A → +| − | ∗ Solution No, it is not an operator Grammar as it does not satisfy property 2 of operator Grammar. As it contains two adjacent Non-terminals on R.H.S of production E → E A E. We can convert it into the operator Grammar by substituting the value of A in E → E A E. E → E + E |E − E |E * E |(E) | id. Operator Precedence Relations Three precedence relations exist between the pair of terminals. Depending upon these precedence Relations, we can decide which operations will be executed or parsed first. Association and Precedence Rules If operators have different precedence Since * has higher precedence than + Example− In a statement a + b * c ∴ + <. * In statement a * b + c ∴ ∗ . > + If operators have Equal precedence, then use Association rules. (a) Example minus; In statement a + b + c here + operators are having equal precedence. As '+' is left Associative in a + b + c ∴ (a + b) will be computed first, and then it will be added to c. i.e., (a + b) + c + .> + Similarly, '*' is left Associative in a * b * c (b) Example − In a statement a ↑ b ↑ c here, ↑ is the Right Associative operator ∴ It will become a ↑ (b ↑ c) ∴ (b ↑ c) will be computed first. ∴ ↑<. ↑ Identifier has more precedence then all operators and symbols. ∴ θ <. id $ <. id id . > θ id . > $ id . >) (<. id. $ has less precedence than all other operators and symbols. $ <. ( id . > $ $ <. + ). > $ $ <.* Example2 − Construct the Precedence Relation table for the Grammar. E → E + E | E ∗ E/id Solution Operator-Precedence Relations Advantages of Operator Precedence Parsing It is accessible to execute. Disadvantages of Operator Precedence Parsing Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements. Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements. Operator Precedence Parsing applies to only a small class of Grammars. Operator Precedence Parsing applies to only a small class of Grammars.
[ { "code": null, "e": 1193, "s": 1062, "text": "Operator Precedence Parsing is also a type of Bottom-Up Parsing that can be used to a class of Grammars known as Operator Grammar." }, { "code": null, "e": 1262, "s": 1193, "text": "A Grammar G is Operator Grammar if it has the following properties −" }, { "code": null, "e": 1313, "s": 1262, "text": "Production should not contain ε on its right side." }, { "code": null, "e": 1364, "s": 1313, "text": "Production should not contain ε on its right side." }, { "code": null, "e": 1444, "s": 1364, "text": "There should not be two adjacent non-terminals at the right side of production." }, { "code": null, "e": 1524, "s": 1444, "text": "There should not be two adjacent non-terminals at the right side of production." }, { "code": null, "e": 1600, "s": 1524, "text": "Example1 − Verify whether the following Grammar is operator Grammar or not." }, { "code": null, "e": 1618, "s": 1600, "text": "E → E A E |(E)|id" }, { "code": null, "e": 1631, "s": 1618, "text": "A → +| − | ∗" }, { "code": null, "e": 1640, "s": 1631, "text": "Solution" }, { "code": null, "e": 1729, "s": 1640, "text": "No, it is not an operator Grammar as it does not satisfy property 2 of operator Grammar." }, { "code": null, "e": 1805, "s": 1729, "text": "As it contains two adjacent Non-terminals on R.H.S of production E → E A E." }, { "code": null, "e": 1894, "s": 1805, "text": "We can convert it into the operator Grammar by substituting the value of A in E → E A E." }, { "code": null, "e": 1929, "s": 1894, "text": "E → E + E |E − E |E * E |(E) | id." }, { "code": null, "e": 1959, "s": 1929, "text": "Operator Precedence Relations" }, { "code": null, "e": 2023, "s": 1959, "text": "Three precedence relations exist between the pair of terminals." }, { "code": null, "e": 2131, "s": 2023, "text": "Depending upon these precedence Relations, we can decide which operations will be executed or parsed first." }, { "code": null, "e": 2164, "s": 2131, "text": "Association and Precedence Rules" }, { "code": null, "e": 2203, "s": 2164, "text": "If operators have different precedence" }, { "code": null, "e": 2240, "s": 2203, "text": "Since * has higher precedence than +" }, { "code": null, "e": 2249, "s": 2240, "text": "Example−" }, { "code": null, "e": 2274, "s": 2249, "text": "In a statement a + b * c" }, { "code": null, "e": 2283, "s": 2274, "text": "∴ + <. *" }, { "code": null, "e": 2306, "s": 2283, "text": "In statement a * b + c" }, { "code": null, "e": 2316, "s": 2306, "text": "∴ ∗ . > +" }, { "code": null, "e": 2380, "s": 2316, "text": "If operators have Equal precedence, then use Association rules." }, { "code": null, "e": 2468, "s": 2380, "text": "(a) Example minus; In statement a + b + c here + operators are having equal precedence." }, { "code": null, "e": 2508, "s": 2468, "text": "As '+' is left Associative in a + b + c" }, { "code": null, "e": 2574, "s": 2508, "text": "∴ (a + b) will be computed first, and then it will be added to c." }, { "code": null, "e": 2592, "s": 2574, "text": "i.e., (a + b) + c" }, { "code": null, "e": 2599, "s": 2592, "text": "+ .> +" }, { "code": null, "e": 2647, "s": 2599, "text": "Similarly, '*' is left Associative in a * b * c" }, { "code": null, "e": 2728, "s": 2647, "text": "(b) Example − In a statement a ↑ b ↑ c here, ↑ is the Right Associative operator" }, { "code": null, "e": 2757, "s": 2728, "text": "∴ It will become a ↑ (b ↑ c)" }, { "code": null, "e": 2791, "s": 2757, "text": "∴ (b ↑ c) will be computed first." }, { "code": null, "e": 2799, "s": 2791, "text": "∴ ↑<. ↑" }, { "code": null, "e": 2862, "s": 2799, "text": "Identifier has more precedence then all operators and symbols." }, { "code": null, "e": 2935, "s": 2862, "text": "∴ θ <. id $ <. id\nid . > θ id . > $\nid . >)\n(<. id." }, { "code": null, "e": 2995, "s": 2935, "text": "$ has less precedence than all other operators and symbols." }, { "code": null, "e": 3049, "s": 2995, "text": "$ <. ( id . > $\n$ <. + ). > $\n$ <.*" }, { "code": null, "e": 3117, "s": 3049, "text": "Example2 − Construct the Precedence Relation table for the Grammar." }, { "code": null, "e": 3138, "s": 3117, "text": "E → E + E | E ∗ E/id" }, { "code": null, "e": 3147, "s": 3138, "text": "Solution" }, { "code": null, "e": 3177, "s": 3147, "text": "Operator-Precedence Relations" }, { "code": null, "e": 3219, "s": 3177, "text": "Advantages of Operator Precedence Parsing" }, { "code": null, "e": 3248, "s": 3219, "text": "It is accessible to execute." }, { "code": null, "e": 3293, "s": 3248, "text": "Disadvantages of Operator Precedence Parsing" }, { "code": null, "e": 3412, "s": 3293, "text": "Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements." }, { "code": null, "e": 3531, "s": 3412, "text": "Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements." }, { "code": null, "e": 3602, "s": 3531, "text": "Operator Precedence Parsing applies to only a small class of Grammars." }, { "code": null, "e": 3673, "s": 3602, "text": "Operator Precedence Parsing applies to only a small class of Grammars." } ]
OpenCV - Scharr Operator
Scharr is also used to detect the second derivatives of an image in horizontal and vertical directions. You can perform scharr operation on an image using the method scharr(). Following is the syntax of this method − Scharr(src, dst, ddepth, dx, dy) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. dst − An object of the class Mat representing the destination (output) image. ddepth − An integer variable representing the depth of the image (-1) ddepth − An integer variable representing the depth of the image (-1) dx − An integer variable representing the x-derivative. (0 or 1) dx − An integer variable representing the x-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) dy − An integer variable representing the y-derivative. (0 or 1) The following program demonstrates how to apply scharr to a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ScharrTest { public static void main( String[] args ) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap16/sobel_input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Applying Box Filter effect on the Image Imgproc.Scharr(src, dst, Imgproc.CV_SCHARR, 0, 1); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap16/scharr_output.jpg", dst); System.out.println("Image processed"); } } Assume that following is the input image scharr_input.jpg specified in the above program. On executing it, you will get the following output − Image Processed If you open the specified path you can observe the output image as follows − On passing different values to the last to parameters (dx and dy) (among 0 and 1) you will get different outputs − // Applying scharr on the Image Imgproc.Scharr(src, dst, -1, 1, 1); Following is a table listing various values for the variables dx and dy of the method scharr() and their respective outputs. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3221, "s": 3004, "text": "Scharr is also used to detect the second derivatives of an image in horizontal and vertical directions. You can perform scharr operation on an image using the method scharr(). Following is the syntax of this method −" }, { "code": null, "e": 3255, "s": 3221, "text": "Scharr(src, dst, ddepth, dx, dy)\n" }, { "code": null, "e": 3302, "s": 3255, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3374, "s": 3302, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3446, "s": 3374, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3524, "s": 3446, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3602, "s": 3524, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3672, "s": 3602, "text": "ddepth − An integer variable representing the depth of the image (-1)" }, { "code": null, "e": 3742, "s": 3672, "text": "ddepth − An integer variable representing the depth of the image (-1)" }, { "code": null, "e": 3807, "s": 3742, "text": "dx − An integer variable representing the x-derivative. (0 or 1)" }, { "code": null, "e": 3872, "s": 3807, "text": "dx − An integer variable representing the x-derivative. (0 or 1)" }, { "code": null, "e": 3937, "s": 3872, "text": "dy − An integer variable representing the y-derivative. (0 or 1)" }, { "code": null, "e": 4002, "s": 3937, "text": "dy − An integer variable representing the y-derivative. (0 or 1)" }, { "code": null, "e": 4075, "s": 4002, "text": "The following program demonstrates how to apply scharr to a given image." }, { "code": null, "e": 4889, "s": 4075, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class ScharrTest {\n\n public static void main( String[] args ) {\n\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap16/sobel_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Applying Box Filter effect on the Image\n Imgproc.Scharr(src, dst, Imgproc.CV_SCHARR, 0, 1);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap16/scharr_output.jpg\", dst);\n\n System.out.println(\"Image processed\");\n }\n}" }, { "code": null, "e": 4979, "s": 4889, "text": "Assume that following is the input image scharr_input.jpg specified in the above program." }, { "code": null, "e": 5032, "s": 4979, "text": "On executing it, you will get the following output −" }, { "code": null, "e": 5049, "s": 5032, "text": "Image Processed\n" }, { "code": null, "e": 5126, "s": 5049, "text": "If you open the specified path you can observe the output image as follows −" }, { "code": null, "e": 5241, "s": 5126, "text": "On passing different values to the last to parameters (dx and dy) (among 0 and 1) you will get different outputs −" }, { "code": null, "e": 5310, "s": 5241, "text": "// Applying scharr on the Image\nImgproc.Scharr(src, dst, -1, 1, 1);\n" }, { "code": null, "e": 5435, "s": 5310, "text": "Following is a table listing various values for the variables dx and dy of the method scharr() and their respective outputs." }, { "code": null, "e": 5468, "s": 5435, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5485, "s": 5468, "text": " Abhilash Nelson" }, { "code": null, "e": 5518, "s": 5485, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5535, "s": 5518, "text": " Abhilash Nelson" }, { "code": null, "e": 5568, "s": 5535, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5582, "s": 5568, "text": " Spotle Learn" }, { "code": null, "e": 5614, "s": 5582, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5631, "s": 5614, "text": " Srikanth Guskra" }, { "code": null, "e": 5664, "s": 5631, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5679, "s": 5664, "text": " Haithem Gasmi" }, { "code": null, "e": 5714, "s": 5679, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5732, "s": 5714, "text": " Gianluca Mottola" }, { "code": null, "e": 5739, "s": 5732, "text": " Print" }, { "code": null, "e": 5750, "s": 5739, "text": " Add Notes" } ]
Bootstrap 4 Fluid Layout - GeeksforGeeks
24 Dec, 2021 Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. This is the most popular HTML, CSS, and JavaScript framework for developing responsive websites. It solves many issues which we had once, one of which is the cross-browser compatibility issue. The following class is used for fluid layout. It sets a width of 100% at all breakpoints. Syntax: .container-fluid, Bootstrap Fluid layout: In Bootstrap you can utilize the class “.container-fluid” to make fluid formats to use the 100% width of the viewport across all gadgets. The class “.container-fluid” essentially applies the “width:100%” rather than various widths for various viewport sizes. In any case, the design will be responsive and you can utilize the framework classes obviously. Example: This example will make a fluid design that covers 100% of the width of the screen using Bootstrap 4. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Bootstrap 4 Fluid Layout</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head><body> <nav class="navbar navbar-expand-md navbar-dark bg-success mb-3"> <div class="container-fluid"> <a href="#" class="navbar-brand mr-3">GeeksforGeeks</a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <div class="navbar-nav"> <a href="#" class="nav-item nav-link active"></a> <a href="#" class="nav-item nav-link">Courses</a> <a href="#" class="nav-item nav-link">DSA</a> <a href="#" class="nav-item nav-link">Articles</a> <a href="#" class="nav-item nav-link">Jobs</a> <a href="#" class="nav-item nav-link">Student</a> <a href="#" class="nav-item nav-link">Tutorials</a> </div> </div> </div> </nav> <div class="container-fluid"> <div class="jumbotron"> <h1>Get Hired With GeeksforGeeks and <strong>Win Exciting Rewards!</strong> </h1> <p class="lead"> Imagine a situation of visiting a game parlor or adventure park, having ultimate fun there, and coming back home without paying a single penny there and in fact, receiving some exciting rewards or cash benefits from them. </p> <p><a href="#" target="_blank" class="btn btn-success btn-lg"> Register here </a> </p> </div> <div class="row"> <div class="col-md-4"> <h2>Basic Concepts For Data Science</h2> <p> Data Scientist is one of the most lucrative career options that offers immense job satisfaction,insanely high salary, global recognition, and amazing growth opportunities. </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> <div class="col-md-4"> <h2>Stock Market APIs For Developers</h2> <p> Stock Market is all about the exchange of stocks (also pronounced as Shares) between various buyers and sellers. Since stocks of variable prices are prone </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> <div class="col-md-4"> <h2>Is Quick Sort Algorithm Adaptive or not</h2> <p> Pre-Requisites: Quick Sort Algorithm Adaptiveness in the Quick Sort Algorithm refers to the decision that if we are given an array that is already sorted </p> <p><a href="#" class="btn btn-success"> Read More »</a> </p> </div> </div> </div></body></html> Output: surindertarika1234 Bootstrap-4 Bootstrap-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25620, "s": 25592, "text": "\n24 Dec, 2021" }, { "code": null, "e": 25920, "s": 25620, "text": "Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. This is the most popular HTML, CSS, and JavaScript framework for developing responsive websites. It solves many issues which we had once, one of which is the cross-browser compatibility issue." }, { "code": null, "e": 26010, "s": 25920, "text": "The following class is used for fluid layout. It sets a width of 100% at all breakpoints." }, { "code": null, "e": 26018, "s": 26010, "text": "Syntax:" }, { "code": null, "e": 26037, "s": 26018, "text": ".container-fluid, " }, { "code": null, "e": 26417, "s": 26037, "text": "Bootstrap Fluid layout: In Bootstrap you can utilize the class “.container-fluid” to make fluid formats to use the 100% width of the viewport across all gadgets. The class “.container-fluid” essentially applies the “width:100%” rather than various widths for various viewport sizes. In any case, the design will be responsive and you can utilize the framework classes obviously. " }, { "code": null, "e": 26527, "s": 26417, "text": "Example: This example will make a fluid design that covers 100% of the width of the screen using Bootstrap 4." }, { "code": null, "e": 26532, "s": 26527, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>Bootstrap 4 Fluid Layout</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"> <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script></head><body> <nav class=\"navbar navbar-expand-md navbar-dark bg-success mb-3\"> <div class=\"container-fluid\"> <a href=\"#\" class=\"navbar-brand mr-3\">GeeksforGeeks</a> <button type=\"button\" class=\"navbar-toggler\" data-toggle=\"collapse\" data-target=\"#navbarCollapse\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"collapse navbar-collapse\" id=\"navbarCollapse\"> <div class=\"navbar-nav\"> <a href=\"#\" class=\"nav-item nav-link active\"></a> <a href=\"#\" class=\"nav-item nav-link\">Courses</a> <a href=\"#\" class=\"nav-item nav-link\">DSA</a> <a href=\"#\" class=\"nav-item nav-link\">Articles</a> <a href=\"#\" class=\"nav-item nav-link\">Jobs</a> <a href=\"#\" class=\"nav-item nav-link\">Student</a> <a href=\"#\" class=\"nav-item nav-link\">Tutorials</a> </div> </div> </div> </nav> <div class=\"container-fluid\"> <div class=\"jumbotron\"> <h1>Get Hired With GeeksforGeeks and <strong>Win Exciting Rewards!</strong> </h1> <p class=\"lead\"> Imagine a situation of visiting a game parlor or adventure park, having ultimate fun there, and coming back home without paying a single penny there and in fact, receiving some exciting rewards or cash benefits from them. </p> <p><a href=\"#\" target=\"_blank\" class=\"btn btn-success btn-lg\"> Register here </a> </p> </div> <div class=\"row\"> <div class=\"col-md-4\"> <h2>Basic Concepts For Data Science</h2> <p> Data Scientist is one of the most lucrative career options that offers immense job satisfaction,insanely high salary, global recognition, and amazing growth opportunities. </p> <p><a href=\"#\" class=\"btn btn-success\"> Read More »</a> </p> </div> <div class=\"col-md-4\"> <h2>Stock Market APIs For Developers</h2> <p> Stock Market is all about the exchange of stocks (also pronounced as Shares) between various buyers and sellers. Since stocks of variable prices are prone </p> <p><a href=\"#\" class=\"btn btn-success\"> Read More »</a> </p> </div> <div class=\"col-md-4\"> <h2>Is Quick Sort Algorithm Adaptive or not</h2> <p> Pre-Requisites: Quick Sort Algorithm Adaptiveness in the Quick Sort Algorithm refers to the decision that if we are given an array that is already sorted </p> <p><a href=\"#\" class=\"btn btn-success\"> Read More »</a> </p> </div> </div> </div></body></html>", "e": 30318, "s": 26532, "text": null }, { "code": null, "e": 30327, "s": 30318, "text": " Output:" }, { "code": null, "e": 30348, "s": 30329, "text": "surindertarika1234" }, { "code": null, "e": 30360, "s": 30348, "text": "Bootstrap-4" }, { "code": null, "e": 30380, "s": 30360, "text": "Bootstrap-Questions" }, { "code": null, "e": 30387, "s": 30380, "text": "Picked" }, { "code": null, "e": 30397, "s": 30387, "text": "Bootstrap" }, { "code": null, "e": 30414, "s": 30397, "text": "Web Technologies" }, { "code": null, "e": 30512, "s": 30414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30553, "s": 30512, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30616, "s": 30553, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 30649, "s": 30616, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 30675, "s": 30649, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 30724, "s": 30675, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 30766, "s": 30724, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30799, "s": 30766, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30842, "s": 30799, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30904, "s": 30842, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Check existence of an element in Java ArrayList
The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present. A program that demonstrates this is given as follows Live Demo import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z")); } } The output of the above program is as follows The element C is available in ArrayList? true The element Z is available in ArrayList? false Now let us understand the above program. The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “Z” are available in the ArrayList and the result is displayed. A code snippet which demonstrates this is as follows List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));
[ { "code": null, "e": 1370, "s": 1062, "text": "The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present." }, { "code": null, "e": 1423, "s": 1370, "text": "A program that demonstrates this is given as follows" }, { "code": null, "e": 1434, "s": 1423, "text": " Live Demo" }, { "code": null, "e": 1888, "s": 1434, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n List aList = new ArrayList();\n aList.add(\"A\");\n aList.add(\"B\");\n aList.add(\"C\");\n aList.add(\"D\");\n aList.add(\"E\");\n System.out.println(\"The element C is available in ArrayList? \" + aList.contains(\"C\"));\n System.out.println(\"The element Z is available in ArrayList? \" + aList.contains(\"Z\"));\n }\n}" }, { "code": null, "e": 1934, "s": 1888, "text": "The output of the above program is as follows" }, { "code": null, "e": 2027, "s": 1934, "text": "The element C is available in ArrayList? true\nThe element Z is available in ArrayList? false" }, { "code": null, "e": 2068, "s": 2027, "text": "Now let us understand the above program." }, { "code": null, "e": 2333, "s": 2068, "text": "The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “Z” are available in the ArrayList and the result is displayed. A code snippet which demonstrates this is as follows" }, { "code": null, "e": 2617, "s": 2333, "text": "List aList = new ArrayList();\naList.add(\"A\");\naList.add(\"B\");\naList.add(\"C\");\naList.add(\"D\");\naList.add(\"E\");\nSystem.out.println(\"The element C is available in ArrayList? \" + aList.contains(\"C\"));\nSystem.out.println(\"The element Z is available in ArrayList? \" + aList.contains(\"Z\"));" } ]
How to convert a string into upper case using JavaScript?
To convert a string into upper case, use the JavaScript toUpperCase() method. This method returns the calling string value converted to uppercase. You can try to run the following code to convert a string into the upper case − Live Demo <html> <head> <title>JavaScript String toUpperCase() Method</title> </head> <body> <script> var str = "demo text"; document.write(str.toUpperCase( )); </script> </body> </html>
[ { "code": null, "e": 1209, "s": 1062, "text": "To convert a string into upper case, use the JavaScript toUpperCase() method. This method returns the calling string value converted to uppercase." }, { "code": null, "e": 1289, "s": 1209, "text": "You can try to run the following code to convert a string into the upper case −" }, { "code": null, "e": 1299, "s": 1289, "text": "Live Demo" }, { "code": null, "e": 1525, "s": 1299, "text": "<html>\n <head>\n <title>JavaScript String toUpperCase() Method</title>\n </head>\n\n <body>\n <script>\n var str = \"demo text\";\n document.write(str.toUpperCase( ));\n </script>\n </body>\n</html>" } ]
Linux Admin - Shell Scripting
Like flavors of GNU Linux, shells come in many varieties and vary in compatibility. The default shell in CentOS is known as the Bash or Bourne Again Shell. The Bash shell is a modern day, modified version of Bourne Shell developed by Stephen Bourne. Bash was the direct replacement to the original Thompson Shell on the Unix operating system developed at Bell Labs by Ken Thompson and Dennis Ritchie (Stephen Bourne was also employed by Bell Labs) Everyone has a favorite shell and each has its strengths and difficulties. But for the most part, Bash is going to be the default shell across all Linux distributions and most commonly available. With experience, everyone will want to explore and use a shell that is best for them. However at the same time, everyone will also want to master Bash shell. Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish. Developing skills to use any Linux shell at an expert level is extremely important to a CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is a command line operating system. A shell is simply a user interface that allows an administrator (or user) to issue commands to the operating system. If a Linux system administrator were an airlines pilot, using the shell would be similar to taking the plane off auto-pilot and grabbing the manual controls for more maneuverable flight. A Linux shell, like Bash, is known in Computer Science terms as a Command Line Interpreter. Microsoft Windows also has two command line interpreters called DOS (not to be confused with the original DOS operating system) and PowerShell. Most modern shells like Bash provide constructs allowing more complex shell scripts to automate both common and complex tasks. Constructs include − Script flow control (ifthen and else) Logical comparison operations (greater than, less than, equality) Loops Variables Parameters defining operation (similar to switches with commands) Often when thinking about performing a task administrators ask themselves: Should I use a shell script or a scripting language such as Perl, Ruby or Python? There is no set rule here. There are only typical differences between shells versus scripting languages. Shell allows the use of Linux commands such as sed, grep, tee, cat and all other command-line based utilities on the Linux operating system. In fact, pretty much any command line Linux utility can be scripted in your shell. A great example of using a shell would be a quick script to check a list of hosts for DNS resolution. Our simple Bash Script to check DNS names − #!/bin/bash for name in $(cat $1); do host $name.$2 | grep "has address" done exit small wordlist to test DNS resolution on − dns www test dev mail rdp remote Output against google.com domain − [rdc@centos ~]$ ./dns-check.sh dns-names.txt google.com -doing dns dns.google.com has address 172.217.6.46 -doing www www.google.com has address 172.217.6.36 -doing test -doing dev -doing mail googlemail.l.google.com has address 172.217.6.37 -doing rdp -doing remote [rdc@centos ~]$ Leveraging simple Linux commands in our shell, we were able to make a simple 5-line script to audit DNS names from a word list. This would have taken some considerable time in Perl, Python, or Ruby even when using a nicely implemented DNS Library. A scripting language will give more control outside the shell. The above Bash script used a wrapper around the Linux host command. What if we wanted to do more and make our own application like host to interact outside the shell? This is where we would use a scripting language. Also, with a highly maintained scripting language we know our actions will work across different systems for the most part. Python 3.5, for example, will work on any other system running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH script on both Linux and HP-UX. Sometimes the lines between a scripting language and a powerful shell can be blurred. It is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing so is really quite commonplace. Also, affluent shell-script developers have made a simple, but otherwise functional, web-server daemon in Bash. With experience in scripting languages and automating tasks in shells, a CentOS administrator will be able to quickly determine where to start when needing to solve a problem. It is quite common to start a project with a shell script. Then progress to a scripting (or compiled) language as a project gets more complex. Also, it is ok to use both a scripting language and shell script for different parts of a project. An example could be a Perl script to scrape a website. Then, use a shell script to parse and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data into MySQL database using a web GUI. With some theory behind shells, let's get started with the basic building blocks to automate tasks from a Bash shell in CentOS. Processing stdout to another command − [rdc@centos ~]$ cat ~/output.txt | wc -l 6039 [rdc@centos ~]$ Above, we have passed cat'sstoud to wc for processing with the pipe character. wc then processed the output from cat, printing the line count of output.txt to the terminal. Think of the pipe character as a "pipe" passing output from one command, to be processed by the next command. Following are the key concepts to remember when dealing with command redirection − We introduced this in chapter one without really talking much about redirection or assigning redirection. When opening a terminal in Linux, your shell is seen as the default target for − standard input < 0 standard output > 1 standard error 2 Let's see how this works − [rdc@centos ~]$ lsof -ap $BASHPID -d 0,1,2 COMMAND PID USER **FD** TYPE DEVICE SIZE/OFF NODE NAME bash 13684 rdc **0u** CHR 136,0 0t0 3 /dev/pts/0 bash 13684 rdc **1u** CHR 136,0 0t0 3 /dev/pts/0 bash 13684 rdc **2u** CHR 136,0 0t0 3 /dev/pts/0 [rdc@centos ~]$ /dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open terminal application like a real terminal with the keyboard and display plugged in through a serial interface. However, like a hypervisor abstracts hardware to an operating system /dev/pts abstracts our terminal to applications. From the above lsof command, we can see under the FD column that all three file-descriptors are set to our virtual terminal (0,1,2). We can now send commands, see command output, as well as any errors associated with the command. Following are examples for STDIN and STDOUT − [root@centosLocal centos]# echo "I am coming from Standard output or STDOUT." > output.txt && cat output.txt I am coming from Standard output or STDOUT. [root@centosLocal centos]# It is also possible to send both stdout and stderr to separate files − bash-3.2# find / -name passwd 1> good.txt 2> err.txt bash-3.2# cat good.txt /etc/pam.d/passwd /etc/passwd bash-3.2# cat err.txt find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory bash-3.2# When searching the entire file system, two errors were encountered. Each were sent to a separate file for later perusal, while the results returned were placed into a separate text file. Sending stderr to a text file can be useful when doing things that output a lot of data to the terminal like compiling applications. This will allow for perusal of errors that could get lost from terminal scrollback history. One note when passing STDOUT to a text file are the differences between >> and >. The double ">>" will append to a file, while the singular form will clobber the file and write new contents (so all previous data will be lost). [root@centosLocal centos]# cat < stdin.txt Hello, I am being read form Standard input, STDIN. [root@centosLocal centos]# In the above command, the text file stdin.txt was redirected to the cat command which echoed its content to STDOUT. The pipe character will take the output from the first command, passing it as an input into the next command, allowing the secondary command to perform operations on the output. Now, let's "pipe" the stdout of cat to another command − [root@centosLocal centos]# cat output.txt | wc -l 2 [root@centosLocal centos]# Above, wc performs calculations on output from cat which was passed from the pipe. The pipe command is particularly useful when filtering the output from grep or egrep − [root@centosLocal centos]# egrep "^[0-9]{4}$" /usr/dicts/nums | wc -l 9000 [root@centosLocal centos]# In the above command, we passed every 4 digit number to wc from a text file containing all numbers from 65535 passed through an egrep filter. Output can be redirected using the & character. If we want to direct the output both STDOUT and STDERR, into the same file, it can be accomplished as follows − [root@centosLocal centos]# find / -name passwd > out.txt 2>&1 [root@centosLocal centos]# cat out.txt find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory /etc/passwd [root@centosLocal centos]# Redirecting using the & character works like this: first, the output is redirected into out.txt. Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in this case out.txt. Redirection is extremely useful and comes in handy while solving problems that surgace when manipulating large text-files, compiling source code, redirecting the output in shell scripts, and issuing complex Linux commands. While powerful, redirection can get complicated for newer CentOS Administrators. Practice, research, and occasional question to a Linux forum (such as Stack Overflow Linux) will help solve advanced solutions. Now that we have a good idea of how the Bash shell works, let's learn some basic constructs, commonly used, to write scripts. In this section we will explore − Variables Loops Conditionals Loop control Reading and writing to files Basic math operations BASH can be a little tricky compared to a dedicated scripting language. Some of the biggest hang-ups in BASH scripts are from incorrectly escaping or not escaping script operations being passed to the shell. If you have looked over a script a few times and it is not working as expected, don't fret. This is common even with those who use BASH to create complex scripts daily. A quick search of Google or signing up at an expert Linux forum to ask a question will lead to a quick resolution. There is a very likely chance someone has come across the exact issue and it has already been solved. BASH scripting is a great method of quickly creating powerful scripts for everything from automating administration tasks to creating useful tools. Becoming an expert level BASH script developer takes time and practice. Hence, use BASH scripts whenever possible, it is a great tool to have in your CentOS Administration toolbox. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2705, "s": 2257, "text": "Like flavors of GNU Linux, shells come in many varieties and vary in compatibility. The default shell in CentOS is known as the Bash or Bourne Again Shell. The Bash shell is a modern day, modified version of Bourne Shell developed by Stephen Bourne. Bash was the direct replacement to the original Thompson Shell on the Unix operating system developed at Bell Labs by Ken Thompson and Dennis Ritchie (Stephen Bourne was also employed by Bell Labs)" }, { "code": null, "e": 3059, "s": 2705, "text": "Everyone has a favorite shell and each has its strengths and difficulties. But for the most part, Bash is going to be the default shell across all Linux distributions and most commonly available. With experience, everyone will want to explore and use a shell that is best for them. However at the same time, everyone will also want to master Bash shell." }, { "code": null, "e": 3118, "s": 3059, "text": "Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish." }, { "code": null, "e": 3631, "s": 3118, "text": "Developing skills to use any Linux shell at an expert level is extremely important to a CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is a command line operating system. A shell is simply a user interface that allows an administrator (or user) to issue commands to the operating system. If a Linux system administrator were an airlines pilot, using the shell would be similar to taking the plane off auto-pilot and grabbing the manual controls for more maneuverable flight." }, { "code": null, "e": 3867, "s": 3631, "text": "A Linux shell, like Bash, is known in Computer Science terms as a Command Line Interpreter. Microsoft Windows also has two command line interpreters called DOS (not to be confused with the original DOS operating system) and PowerShell." }, { "code": null, "e": 3994, "s": 3867, "text": "Most modern shells like Bash provide constructs allowing more complex shell scripts to automate both common and complex tasks." }, { "code": null, "e": 4015, "s": 3994, "text": "Constructs include −" }, { "code": null, "e": 4053, "s": 4015, "text": "Script flow control (ifthen and else)" }, { "code": null, "e": 4119, "s": 4053, "text": "Logical comparison operations (greater than, less than, equality)" }, { "code": null, "e": 4125, "s": 4119, "text": "Loops" }, { "code": null, "e": 4135, "s": 4125, "text": "Variables" }, { "code": null, "e": 4201, "s": 4135, "text": "Parameters defining operation (similar to switches with commands)" }, { "code": null, "e": 4358, "s": 4201, "text": "Often when thinking about performing a task administrators ask themselves: Should I use a shell script or a scripting language such as Perl, Ruby or Python?" }, { "code": null, "e": 4463, "s": 4358, "text": "There is no set rule here. There are only typical differences between shells versus scripting languages." }, { "code": null, "e": 4687, "s": 4463, "text": "Shell allows the use of Linux commands such as sed, grep, tee, cat and all other command-line based utilities on the Linux operating system. In fact, pretty much any command line Linux utility can be scripted in your shell." }, { "code": null, "e": 4789, "s": 4687, "text": "A great example of using a shell would be a quick script to check a list of hosts for DNS resolution." }, { "code": null, "e": 4833, "s": 4789, "text": "Our simple Bash Script to check DNS names −" }, { "code": null, "e": 4932, "s": 4833, "text": "#!/bin/bash \nfor name in $(cat $1);\n do \n host $name.$2 | grep \"has address\" \n done \nexit" }, { "code": null, "e": 4975, "s": 4932, "text": "small wordlist to test DNS resolution on −" }, { "code": null, "e": 5015, "s": 4975, "text": "dns \nwww \ntest \ndev \nmail \nrdp \nremote\n" }, { "code": null, "e": 5050, "s": 5015, "text": "Output against google.com domain −" }, { "code": null, "e": 5336, "s": 5050, "text": "[rdc@centos ~]$ ./dns-check.sh dns-names.txt google.com\n-doing dns\ndns.google.com has address 172.217.6.46\n-doing www\nwww.google.com has address 172.217.6.36\n-doing test\n-doing dev\n-doing mail\ngooglemail.l.google.com has address 172.217.6.37\n-doing rdp\n-doing remote\n\n[rdc@centos ~]$\n" }, { "code": null, "e": 5584, "s": 5336, "text": "Leveraging simple Linux commands in our shell, we were able to make a simple 5-line script to audit DNS names from a word list. This would have taken some considerable time in Perl, Python, or Ruby even when using a nicely implemented DNS Library." }, { "code": null, "e": 5863, "s": 5584, "text": "A scripting language will give more control outside the shell. The above Bash script used a wrapper around the Linux host command. What if we wanted to do more and make our own application like host to interact outside the shell? This is where we would use a scripting language." }, { "code": null, "e": 6163, "s": 5863, "text": "Also, with a highly maintained scripting language we know our actions will work across different systems for the most part. Python 3.5, for example, will work on any other system running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH script on both Linux and HP-UX." }, { "code": null, "e": 6487, "s": 6163, "text": "Sometimes the lines between a scripting language and a powerful shell can be blurred. It is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing so is really quite commonplace. Also, affluent shell-script developers have made a simple, but otherwise functional, web-server daemon in Bash." }, { "code": null, "e": 6806, "s": 6487, "text": "With experience in scripting languages and automating tasks in shells, a CentOS administrator will be able to quickly determine where to start when needing to solve a problem. It is quite common to start a project with a shell script. Then progress to a scripting (or compiled) language as a project gets more complex." }, { "code": null, "e": 7123, "s": 6806, "text": "Also, it is ok to use both a scripting language and shell script for different parts of a project. An example could be a Perl script to scrape a website. Then, use a shell script to parse and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data into MySQL database using a web GUI." }, { "code": null, "e": 7251, "s": 7123, "text": "With some theory behind shells, let's get started with the basic building blocks to automate tasks from a Bash shell in CentOS." }, { "code": null, "e": 7290, "s": 7251, "text": "Processing stdout to another command −" }, { "code": null, "e": 7355, "s": 7290, "text": "[rdc@centos ~]$ cat ~/output.txt | wc -l \n6039 \n[rdc@centos ~]$\n" }, { "code": null, "e": 7638, "s": 7355, "text": "Above, we have passed cat'sstoud to wc for processing with the pipe character. wc then processed the output from cat, printing the line count of output.txt to the terminal. Think of the pipe character as a \"pipe\" passing output from one command, to be processed by the next command." }, { "code": null, "e": 7721, "s": 7638, "text": "Following are the key concepts to remember when dealing with command redirection −" }, { "code": null, "e": 7908, "s": 7721, "text": "We introduced this in chapter one without really talking much about redirection or assigning redirection. When opening a terminal in Linux, your shell is seen as the default target for −" }, { "code": null, "e": 7927, "s": 7908, "text": "standard input < 0" }, { "code": null, "e": 7947, "s": 7927, "text": "standard output > 1" }, { "code": null, "e": 7964, "s": 7947, "text": "standard error 2" }, { "code": null, "e": 7991, "s": 7964, "text": "Let's see how this works −" }, { "code": null, "e": 8361, "s": 7991, "text": "[rdc@centos ~]$ lsof -ap $BASHPID -d 0,1,2 \n COMMAND PID USER **FD** TYPE DEVICE SIZE/OFF NODE NAME \n bash 13684 rdc **0u** CHR 136,0 0t0 3 /dev/pts/0 \n bash 13684 rdc **1u** CHR 136,0 0t0 3 /dev/pts/0 \n bash 13684 rdc **2u** CHR 136,0 0t0 3 /dev/pts/0\n \n[rdc@centos ~]$ \n" }, { "code": null, "e": 8675, "s": 8361, "text": "/dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open terminal application like a real terminal with the keyboard and display plugged in through a serial interface. However, like a hypervisor abstracts hardware to an operating system /dev/pts abstracts our terminal to applications." }, { "code": null, "e": 8905, "s": 8675, "text": "From the above lsof command, we can see under the FD column that all three file-descriptors are set to our virtual terminal (0,1,2). We can now send commands, see command output, as well as any errors associated with the command." }, { "code": null, "e": 8951, "s": 8905, "text": "Following are examples for STDIN and STDOUT −" }, { "code": null, "e": 9133, "s": 8951, "text": "[root@centosLocal centos]# echo \"I am coming from Standard output or STDOUT.\" >\noutput.txt && cat output.txt\nI am coming from Standard output or STDOUT. \n[root@centosLocal centos]#\n" }, { "code": null, "e": 9204, "s": 9133, "text": "It is also possible to send both stdout and stderr to separate files −" }, { "code": null, "e": 9410, "s": 9204, "text": "bash-3.2# find / -name passwd 1> good.txt 2> err.txt\nbash-3.2# cat good.txt\n/etc/pam.d/passwd\n/etc/passwd\nbash-3.2# cat err.txt \nfind: /dev/fd/3: Not a directory\nfind: /dev/fd/4: Not a directory\nbash-3.2#\n" }, { "code": null, "e": 9597, "s": 9410, "text": "When searching the entire file system, two errors were encountered. Each were sent to a separate file for later perusal, while the results returned were placed into a separate text file." }, { "code": null, "e": 9822, "s": 9597, "text": "Sending stderr to a text file can be useful when doing things that output a lot of data to the terminal like compiling applications. This will allow for perusal of errors that could get lost from terminal scrollback history." }, { "code": null, "e": 10049, "s": 9822, "text": "One note when passing STDOUT to a text file are the differences between >> and >. The double \">>\" will append to a file, while the singular form will clobber the file and write new contents (so all previous data will be lost)." }, { "code": null, "e": 10172, "s": 10049, "text": "[root@centosLocal centos]# cat < stdin.txt\nHello,\nI am being read form Standard input, STDIN.\n\n[root@centosLocal centos]#\n" }, { "code": null, "e": 10288, "s": 10172, "text": "In the above command, the text file stdin.txt was redirected to the cat command which echoed its content to STDOUT." }, { "code": null, "e": 10466, "s": 10288, "text": "The pipe character will take the output from the first command, passing it as an input into the next command, allowing the secondary command to perform operations on the output." }, { "code": null, "e": 10523, "s": 10466, "text": "Now, let's \"pipe\" the stdout of cat to another command −" }, { "code": null, "e": 10603, "s": 10523, "text": "[root@centosLocal centos]# cat output.txt | wc -l\n2\n[root@centosLocal centos]#\n" }, { "code": null, "e": 10773, "s": 10603, "text": "Above, wc performs calculations on output from cat which was passed from the pipe. The pipe command is particularly useful when filtering the output from grep or egrep −" }, { "code": null, "e": 10879, "s": 10773, "text": "[root@centosLocal centos]# egrep \"^[0-9]{4}$\" /usr/dicts/nums | wc -l \n9000 \n[root@centosLocal centos]#\n" }, { "code": null, "e": 11021, "s": 10879, "text": "In the above command, we passed every 4 digit number to wc from a text file containing all numbers from 65535 passed through an egrep filter." }, { "code": null, "e": 11181, "s": 11021, "text": "Output can be redirected using the & character. If we want to direct the output both STDOUT and STDERR, into the same file, it can be accomplished as follows −" }, { "code": null, "e": 11393, "s": 11181, "text": "[root@centosLocal centos]# find / -name passwd > out.txt 2>&1\n[root@centosLocal centos]# cat out.txt \nfind: /dev/fd/3: Not a directory \nfind: /dev/fd/4: Not a directory \n/etc/passwd\n\n[root@centosLocal centos]#\n" }, { "code": null, "e": 11598, "s": 11393, "text": "Redirecting using the & character works like this: first, the output is redirected into out.txt. Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in this case out.txt." }, { "code": null, "e": 11821, "s": 11598, "text": "Redirection is extremely useful and comes in handy while solving problems that surgace when manipulating large text-files, compiling source code, redirecting the output in shell scripts, and issuing complex Linux commands." }, { "code": null, "e": 12030, "s": 11821, "text": "While powerful, redirection can get complicated for newer CentOS Administrators. Practice, research, and occasional question to a Linux forum (such as Stack Overflow Linux) will help solve advanced solutions." }, { "code": null, "e": 12190, "s": 12030, "text": "Now that we have a good idea of how the Bash shell works, let's learn some basic constructs, commonly used, to write scripts. In this section we will explore −" }, { "code": null, "e": 12200, "s": 12190, "text": "Variables" }, { "code": null, "e": 12206, "s": 12200, "text": "Loops" }, { "code": null, "e": 12219, "s": 12206, "text": "Conditionals" }, { "code": null, "e": 12232, "s": 12219, "text": "Loop control" }, { "code": null, "e": 12261, "s": 12232, "text": "Reading and writing to files" }, { "code": null, "e": 12283, "s": 12261, "text": "Basic math operations" }, { "code": null, "e": 12660, "s": 12283, "text": "BASH can be a little tricky compared to a dedicated scripting language. Some of the biggest hang-ups in BASH scripts are from incorrectly escaping or not escaping script operations being passed to the shell. If you have looked over a script a few times and it is not working as expected, don't fret. This is common even with those who use BASH to create complex scripts daily." }, { "code": null, "e": 12877, "s": 12660, "text": "A quick search of Google or signing up at an expert Linux forum to ask a question will lead to a quick resolution. There is a very likely chance someone has come across the exact issue and it has already been solved." }, { "code": null, "e": 13206, "s": 12877, "text": "BASH scripting is a great method of quickly creating powerful scripts for everything from automating administration tasks to creating useful tools. Becoming an expert level BASH script developer takes time and practice. Hence, use BASH scripts whenever possible, it is a great tool to have in your CentOS Administration toolbox." }, { "code": null, "e": 13241, "s": 13206, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 13257, "s": 13241, "text": " Mamta Tripathi" }, { "code": null, "e": 13290, "s": 13257, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 13304, "s": 13290, "text": " Lets Kode It" }, { "code": null, "e": 13339, "s": 13304, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13356, "s": 13339, "text": " Abhilash Nelson" }, { "code": null, "e": 13391, "s": 13356, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13408, "s": 13391, "text": " Frahaan Hussain" }, { "code": null, "e": 13443, "s": 13408, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13471, "s": 13443, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13504, "s": 13471, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 13544, "s": 13504, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 13551, "s": 13544, "text": " Print" }, { "code": null, "e": 13562, "s": 13551, "text": " Add Notes" } ]
Tryit Editor v3.7 - Show Java
public class GetFileInfo { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable: " + myObj.canRead()); System.out.println("File size in bytes: " + myObj.length()); } else { System.out.println("The file does not exist.");
[]
Python vs Excel — Compound Annual Growth Rate (CAGR) | by Wilson Wong | Towards Data Science
One of my greatest frustrations with Microsoft Excel (or Google Sheets) is the lack of an inbuilt function to calculate the compound annual growth rate or CAGR (XIRR is the closest but it’s not the same). This means that in every case where I needed to conduct a quick Excel CAGR analysis, I would need to write the Excel formula for CAGR. Every. Single. Time. If you don’t know already, the Excel formula for CAGR is as follows: where the End Value is the latest value of the given time period, the Start Value is the first value of the given time period, and the Number of Years is the number of years over which you would want to calculate the annual growth rate. In an Excel sheet it may look something like this: It’s a rather simple formula that can be easily be relied upon... except when the table grows longer with more years! Datasets tend to grow, and this presents a problem for an analyst who has to ensure formulas are all correct at all times! (I’ve been there. I had to fix a much more complicated formula for a much bigger dataset, correcting a mistake that has gone unnoticed for an entire year because the formula was buried beneath the sea of data!) This frustration is a reason why I’ve moved from spreadsheet to programming (specifically Python with the Pandas library) for data analysis. I’m still relatively new to Python but already I’m experiencing its tremendous versatility and efficiency over Excel (like not having to wait a few hours for an Excel sheet to fill all missing values). Here you’ll see why it’s much better and more efficient to program the CAGR function and apply it to a dataframe converted from a spreadsheet. Let’s start by defining the CAGR function in Python: def cagr(start_value, end_value, num_periods): return (end_value / start_value) ** (1 / (num_periods - 1)) - 1 And that’s it! Two lines of code to have your very own CAGR function. You will notice here that there is a slight difference with the Excel function. In this function, there is a minus 1 after num_periods. This allows me to correctly calculate the CAGR by specifying the total number of time periods as an argument rather than the number of compounding periods (which is always minus 1 of the total). I do this because I have, in the past, made repeated mistakes of incorrectly specifying the number of compounding periods on Excel. Now that you have your CAGR function, you can either save it into a separate Python file (from which you can import into any other Python file) or just code it into the file where you will be loading the Excel table into a dataframe and apply it there. To apply your CAGR function, first import the Pandas library: import pandas as pd Pandas is an open-source, easy to use Python library that can convert any csv or Excel file into a dataframe for data analysis. It’s a must-have for any data analyst programming in Python. Next, load the Excel into a Pandas dataframe: ExcelFile = 'ExcelTable.xlsx' #name of my Excel filedf = pd.read_excel(ExcelFile, index_col='Year') Notice that I’ve added a parameter index_col to assign the ‘Year’ column as the index, leaving ‘Yearly Income (RM)’ as the only column in the dataframe. Do a print function on your dataframe to see if the Excel table was successfully converted into a dataframe: print(df) You now have a dataframe to which you can apply the CAGR function. The keys to the CAGR function in Python, and why it is much easier to use in Python, are the variables below: start_value = float(df.iloc[0])end_value = float(df.iloc[-1])num_periods = len(df) These variables will extract the arguments you need for your CAGR function, and in this case, the output returns: 36000.00102000.009 The great thing about these variables is that the code does not have to change even as your dataset grows. Using the .iloc method together with list indexing ensures that the function will always use the first row as the start value and the last row as the end value, and the len function will always count correctly the total number of time periods. Even if you add an extra year(s), the code works the same. Say for example, you add a row to the dataframe: df.loc[2019] =[84000] Running a print function on the same variables will return a different output in accordance with the new data: 36000.0084000.0010 If you want to specify a time period, say 5 years between 2012 and 2016, for the CAGR calculation, you can also use the .loc method to easily do so: start_value = float(df.loc[2012])end_value = float(df.loc[2016])num_periods = len(df.loc[2012:2016]) Now let’s try to apply the CAGR function to this sliced dataset by using the variables as input arguments: result = cagr(start_value, end_value, num_periods)print(result)0.12801507993497308 But wait! The output shows the result in a float type with too many decimals. Though I personally prefer this kind of output, it is generally not friendly to many eyes. We will need string formatting to present the output in percentages: print("{:.2%}".format(result))12.80% Much more human-friendly. And that’s all you need to perform CAGR analysis in Python!
[ { "code": null, "e": 511, "s": 171, "text": "One of my greatest frustrations with Microsoft Excel (or Google Sheets) is the lack of an inbuilt function to calculate the compound annual growth rate or CAGR (XIRR is the closest but it’s not the same). This means that in every case where I needed to conduct a quick Excel CAGR analysis, I would need to write the Excel formula for CAGR." }, { "code": null, "e": 532, "s": 511, "text": "Every. Single. Time." }, { "code": null, "e": 601, "s": 532, "text": "If you don’t know already, the Excel formula for CAGR is as follows:" }, { "code": null, "e": 838, "s": 601, "text": "where the End Value is the latest value of the given time period, the Start Value is the first value of the given time period, and the Number of Years is the number of years over which you would want to calculate the annual growth rate." }, { "code": null, "e": 889, "s": 838, "text": "In an Excel sheet it may look something like this:" }, { "code": null, "e": 1007, "s": 889, "text": "It’s a rather simple formula that can be easily be relied upon... except when the table grows longer with more years!" }, { "code": null, "e": 1341, "s": 1007, "text": "Datasets tend to grow, and this presents a problem for an analyst who has to ensure formulas are all correct at all times! (I’ve been there. I had to fix a much more complicated formula for a much bigger dataset, correcting a mistake that has gone unnoticed for an entire year because the formula was buried beneath the sea of data!)" }, { "code": null, "e": 1684, "s": 1341, "text": "This frustration is a reason why I’ve moved from spreadsheet to programming (specifically Python with the Pandas library) for data analysis. I’m still relatively new to Python but already I’m experiencing its tremendous versatility and efficiency over Excel (like not having to wait a few hours for an Excel sheet to fill all missing values)." }, { "code": null, "e": 1827, "s": 1684, "text": "Here you’ll see why it’s much better and more efficient to program the CAGR function and apply it to a dataframe converted from a spreadsheet." }, { "code": null, "e": 1880, "s": 1827, "text": "Let’s start by defining the CAGR function in Python:" }, { "code": null, "e": 1994, "s": 1880, "text": "def cagr(start_value, end_value, num_periods): return (end_value / start_value) ** (1 / (num_periods - 1)) - 1" }, { "code": null, "e": 2527, "s": 1994, "text": "And that’s it! Two lines of code to have your very own CAGR function. You will notice here that there is a slight difference with the Excel function. In this function, there is a minus 1 after num_periods. This allows me to correctly calculate the CAGR by specifying the total number of time periods as an argument rather than the number of compounding periods (which is always minus 1 of the total). I do this because I have, in the past, made repeated mistakes of incorrectly specifying the number of compounding periods on Excel." }, { "code": null, "e": 2780, "s": 2527, "text": "Now that you have your CAGR function, you can either save it into a separate Python file (from which you can import into any other Python file) or just code it into the file where you will be loading the Excel table into a dataframe and apply it there." }, { "code": null, "e": 2842, "s": 2780, "text": "To apply your CAGR function, first import the Pandas library:" }, { "code": null, "e": 2862, "s": 2842, "text": "import pandas as pd" }, { "code": null, "e": 3051, "s": 2862, "text": "Pandas is an open-source, easy to use Python library that can convert any csv or Excel file into a dataframe for data analysis. It’s a must-have for any data analyst programming in Python." }, { "code": null, "e": 3097, "s": 3051, "text": "Next, load the Excel into a Pandas dataframe:" }, { "code": null, "e": 3197, "s": 3097, "text": "ExcelFile = 'ExcelTable.xlsx' #name of my Excel filedf = pd.read_excel(ExcelFile, index_col='Year')" }, { "code": null, "e": 3350, "s": 3197, "text": "Notice that I’ve added a parameter index_col to assign the ‘Year’ column as the index, leaving ‘Yearly Income (RM)’ as the only column in the dataframe." }, { "code": null, "e": 3459, "s": 3350, "text": "Do a print function on your dataframe to see if the Excel table was successfully converted into a dataframe:" }, { "code": null, "e": 3469, "s": 3459, "text": "print(df)" }, { "code": null, "e": 3536, "s": 3469, "text": "You now have a dataframe to which you can apply the CAGR function." }, { "code": null, "e": 3646, "s": 3536, "text": "The keys to the CAGR function in Python, and why it is much easier to use in Python, are the variables below:" }, { "code": null, "e": 3729, "s": 3646, "text": "start_value = float(df.iloc[0])end_value = float(df.iloc[-1])num_periods = len(df)" }, { "code": null, "e": 3843, "s": 3729, "text": "These variables will extract the arguments you need for your CAGR function, and in this case, the output returns:" }, { "code": null, "e": 3862, "s": 3843, "text": "36000.00102000.009" }, { "code": null, "e": 4213, "s": 3862, "text": "The great thing about these variables is that the code does not have to change even as your dataset grows. Using the .iloc method together with list indexing ensures that the function will always use the first row as the start value and the last row as the end value, and the len function will always count correctly the total number of time periods." }, { "code": null, "e": 4321, "s": 4213, "text": "Even if you add an extra year(s), the code works the same. Say for example, you add a row to the dataframe:" }, { "code": null, "e": 4343, "s": 4321, "text": "df.loc[2019] =[84000]" }, { "code": null, "e": 4454, "s": 4343, "text": "Running a print function on the same variables will return a different output in accordance with the new data:" }, { "code": null, "e": 4474, "s": 4454, "text": "36000.0084000.0010 " }, { "code": null, "e": 4623, "s": 4474, "text": "If you want to specify a time period, say 5 years between 2012 and 2016, for the CAGR calculation, you can also use the .loc method to easily do so:" }, { "code": null, "e": 4724, "s": 4623, "text": "start_value = float(df.loc[2012])end_value = float(df.loc[2016])num_periods = len(df.loc[2012:2016])" }, { "code": null, "e": 4831, "s": 4724, "text": "Now let’s try to apply the CAGR function to this sliced dataset by using the variables as input arguments:" }, { "code": null, "e": 4914, "s": 4831, "text": "result = cagr(start_value, end_value, num_periods)print(result)0.12801507993497308" }, { "code": null, "e": 5152, "s": 4914, "text": "But wait! The output shows the result in a float type with too many decimals. Though I personally prefer this kind of output, it is generally not friendly to many eyes. We will need string formatting to present the output in percentages:" }, { "code": null, "e": 5189, "s": 5152, "text": "print(\"{:.2%}\".format(result))12.80%" }, { "code": null, "e": 5215, "s": 5189, "text": "Much more human-friendly." } ]
Ubuntu - Secure Shell
The Secure Shell (SSH) in Linux is used to log into the machine in an encrypted and safe manner. This helps in providing a secure channel to streamline all requests to the Ubuntu server. SSH uses cryptographic keys to log into the server. On Windows, the most common tool to perform a secure shell to a Linux server is putty. In this chapter, we will learn how to use putty to Secure Shell into a server. Step 1 − Download putty from the http://www.putty.org/ site. Step 2 − Before connecting to use putty, we need to know the IP address of our Ubuntu box. To do this, type ifconfig in the command shell of the Ubuntu server. From the above screenshot, we know that the IP address of the server is 192.168.0.20 Step 3 − Next step is installing SSH on the server. In order to SSH to a server, you need to make sure it is installed. Run the following command in the Ubuntu server command prompt session. sudo apt-get install openssh-server Step 4 − Launch PuTTY. Enter the IP address of the Ubuntu server and click the Open button. Step 5 − The next screen requests to accept the encrypted key sent from the server. Step 6 − Finally, enter the username and password to log into the server. We have successfully established a secure shell to the server. 8 Lectures 31 mins Musab Zayadneh 14 Lectures 1.5 hours Satish 26 Lectures 1.5 hours YouAccel Print Add Notes Bookmark this page
[ { "code": null, "e": 2372, "s": 2133, "text": "The Secure Shell (SSH) in Linux is used to log into the machine in an encrypted and safe manner. This helps in providing a secure channel to streamline all requests to the Ubuntu server. SSH uses cryptographic keys to log into the server." }, { "code": null, "e": 2538, "s": 2372, "text": "On Windows, the most common tool to perform a secure shell to a Linux server is putty. In this chapter, we will learn how to use putty to Secure Shell into a server." }, { "code": null, "e": 2599, "s": 2538, "text": "Step 1 − Download putty from the http://www.putty.org/ site." }, { "code": null, "e": 2759, "s": 2599, "text": "Step 2 − Before connecting to use putty, we need to know the IP address of our Ubuntu box. To do this, type ifconfig in the command shell of the Ubuntu server." }, { "code": null, "e": 2844, "s": 2759, "text": "From the above screenshot, we know that the IP address of the server is 192.168.0.20" }, { "code": null, "e": 3035, "s": 2844, "text": "Step 3 − Next step is installing SSH on the server. In order to SSH to a server, you need to make sure it is installed. Run the following command in the Ubuntu server command prompt session." }, { "code": null, "e": 3072, "s": 3035, "text": "sudo apt-get install openssh-server\n" }, { "code": null, "e": 3164, "s": 3072, "text": "Step 4 − Launch PuTTY. Enter the IP address of the Ubuntu server and click the Open button." }, { "code": null, "e": 3248, "s": 3164, "text": "Step 5 − The next screen requests to accept the encrypted key sent from the server." }, { "code": null, "e": 3385, "s": 3248, "text": "Step 6 − Finally, enter the username and password to log into the server. We have successfully established a secure shell to the server." }, { "code": null, "e": 3416, "s": 3385, "text": "\n 8 Lectures \n 31 mins\n" }, { "code": null, "e": 3432, "s": 3416, "text": " Musab Zayadneh" }, { "code": null, "e": 3467, "s": 3432, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3475, "s": 3467, "text": " Satish" }, { "code": null, "e": 3510, "s": 3475, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3520, "s": 3510, "text": " YouAccel" }, { "code": null, "e": 3527, "s": 3520, "text": " Print" }, { "code": null, "e": 3538, "s": 3527, "text": " Add Notes" } ]
DoubleStream sum() method in Java
The sum() method of the DoubleStream class in Java returns the sum of elements in this stream. The syntax is as follows double sum() To use the DoubleStream class in Java, import the following package import java.util.stream.DoubleStream; Create DoubleStream and add some elements DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8); Now, sum the elements of the stream double sum = doubleStream.sum(); The following is an example to implement DoubleStream sum() method in Java Live Demo import java.util.*; import java.util.stream.DoubleStream; public class Demo { public static void main(String[] args) { DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8); double sum = doubleStream.sum(); System.out.println("The sum of all the elements of the stream = "+sum); } } The sum of all the elements of the stream = 442.2
[ { "code": null, "e": 1157, "s": 1062, "text": "The sum() method of the DoubleStream class in Java returns the sum of elements in this stream." }, { "code": null, "e": 1182, "s": 1157, "text": "The syntax is as follows" }, { "code": null, "e": 1195, "s": 1182, "text": "double sum()" }, { "code": null, "e": 1263, "s": 1195, "text": "To use the DoubleStream class in Java, import the following package" }, { "code": null, "e": 1301, "s": 1263, "text": "import java.util.stream.DoubleStream;" }, { "code": null, "e": 1343, "s": 1301, "text": "Create DoubleStream and add some elements" }, { "code": null, "e": 1430, "s": 1343, "text": "DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8);" }, { "code": null, "e": 1466, "s": 1430, "text": "Now, sum the elements of the stream" }, { "code": null, "e": 1500, "s": 1466, "text": "double sum = doubleStream.sum();\n" }, { "code": null, "e": 1575, "s": 1500, "text": "The following is an example to implement DoubleStream sum() method in Java" }, { "code": null, "e": 1586, "s": 1575, "text": " Live Demo" }, { "code": null, "e": 1925, "s": 1586, "text": "import java.util.*;\nimport java.util.stream.DoubleStream;\npublic class Demo {\n public static void main(String[] args) {\n DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8);\n double sum = doubleStream.sum();\n System.out.println(\"The sum of all the elements of the stream = \"+sum);\n }\n}" }, { "code": null, "e": 1975, "s": 1925, "text": "The sum of all the elements of the stream = 442.2" } ]
Partnership - Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Partnership. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - With an amount of Rs. 25000 started business by ajay. After 3 month, vijay joined the business by investing amount of Rs. 30000. If profit of the firm is 19000 at the end of the year then what should be the share of Ajay in profit? A - Rs. 9423 B - Rs. 10250 C - Rs. 12500 D - Rs. 10000 Ajay : Vijay = (25000*12: 30000*9) = 300000: 270000 = 10: 9 Share of Ajay = Rs. (19000* 10/19) = Rs. 10000 Q 2 - Ajay , Bijender and chaman started a business and invested Rs. 20000 each partner .After the period of 4 month, some changes are made in investment just like Ajay withdraw Rs. 5000, Bijender and chaman both add 6000 each in the invested capital. An amount of Rs. 69900 recorded as a profit in the firm. What should be the share of Bijender in profit? A - Rs. 56000 B - Rs. 21200 C - Rs. 9000 D - Rs. 20000 Ajay : Bijender: chaman = (20000*5+15000*7) : (20000*5+ 16000*7) :(20000*5+26000*7) = 205000: 212000 : 262000 = 205 : 212: 282 Share of B in profit = Rs. (69900* 212/699) = Rs. 21200 Q 3 - The proportion of partners capital in a business are 1/3 of A , 1/4 of B and 1/5 of C. After the period of 4 month 1/2 part of his investment withdraw by A .if the total profit of Rs. 8470 earned by the firm then what should be the share of A? A - Rs. 2520 B - Rs. 2800 C - Rs. 3150 D - Rs. 4120 In the starting time ratio of capitals = 1/3 : 1/4 : 1/5 = 20: 15: 12 Suppose A, B and C invest Rs. 20x , Rs. 15x and 12x respectively. A: B:C = (20*4+ 10x*8) : (15*12) : (12x * 12) = 160x : 180x : 144x = 40: 45: 36 Share of A = Rs. ( 8470* 40/121) = Rs. 2800 Q 4 - 12:11 was the investment ratio of A and B who started a business and the ratio of profit were 4:1 . The period ofA investment was 11 month and what was the period of B investment? A - 3 month B - 5 month C - 2 month D - 7 month Rs. 12x and Rs. 11 x is the investment in a business. If for the y month money invested by B .then, A: B = (12x*11) : (11x*y) = (132x : 11xy) = (12: y) ∴ 12/y = 4/1 = 4y = 12 ⇒ y = 3 So, we can say B invested his share for the period of 3 months in the business. Q 5 - In a partnership firm A and B invested. For the period of 8 month. A invested Rs 16000 and rest of the capital by B for the rest of the time. Find out the money contributed by B if he claims 2/7 part of the profit ? A - Rs. 1190 B - Rs. 10500 C - Rs. 13600 D - Rs. 12800 Let total profit of the firm = 1 Share of B in profit = (1-2/7 ) = 5/7 Ratio of profit = 5: 2 Contribution of B = x then (16000*8)/ 4x = 5/2 ⇒20x = 256000 ⇒ x= 12800. Hence, b contributed rs. 12800. Q 6 - What should be the ratio of profit between A, B and C after the period of 3 years. If A invest 25 lakhs at starting of the business and Rs. 10 lakhs also add after one year and B invest 35 lakhs in the starting and Rs. 10 lakhs withdraw after 2 year and C invested 30 lakhs only from starting. A - 10:10:9 B - 20:19:18 C - 20:20:19 D - none of these Investment of A = Rs. (25*1+ 35*2) = Rs. 95 Investment of B = Rs. (35*2+25*1) = Rs. 95 Investment of C = Rs. (30*3) = Rs. 90 ∴ A:B:C = 95:95: 90 = 19: 19: 18 Q 7 - The ratio of investment in a firm by A and B is 3:2 . if A received Rs. 8550 share as a profit after doing charity5% out of the total profit. What should be the total profit? A - Rs. 15760 B - Rs. 15000 C - Rs. 8600 D - Rs. 2000 If X is the total profit of a firm at the end of the year . Amount of charity which is paid = 5% of rs. x = (5/100*x) = x/20 , balance =(x-x/20) = rs. 19x/20 Share of A = rs. (19x/20* 3/5) = Rs. 57x/100 ∴ 57x/100= 8550 ⇒ x = (8550*100)/57 = 15000. Hence, the total profit of the firm = Rs. 15000. Q 8 - In a partnership business, Mr X invests Rs 2400 for 4 years, Mr Y invests Rs 2800 for 8 years and Mr Z invests Rs 2000 for 10 years. They earn Rs 1170. Find the share of profit for each partners. A - 215, 450, 555 B - 215, 500, 455 C - 215, 505, 450 D - 216, 504, 450 Rs 2400 investment in 4 years earns as much as Rs 2400*4 = Rs 9600 in 1 year Similary, Rs 2800*8 = Rs 22400 in 1 year And Rs 2000*10 = Rs 20000 in 1 year. Ratio for profit to be shared = 9600 : 22400 : 20000 = 12 : 28 : 25 Sum of ratios = 12 + 28 + 25 = 65 Hence, X's share = 12/65 * 1170 = Rs 216 Y's share = 28/65 * 1170 = Rs 504 Z's share = 25/65 * 1170 = Rs 450 Q 9 - Kabir starts a business with Re 4,50,000/- Nisha joins him after a certain period of time who invests Re 3,00,000/-. At the end of year, they divide profir in the ratio 9:4. When did Nisha join Kabir? A - After 3 months B - After 5 months C - After 6 months D - After 4 months Suppose Nisha is with Kabir for x months. So, 4,50,000*12/3,00,000*x = 9/4 Or, x = 8 months Hence Nisha joined Kabir after (12 - 8) months = 4 months. Q 10 - Hariprasad and Madhusudan started a business investing amounts in the ratio of 2:3 respectively. If Hariprasad had invested an additional amount of Re 10000, the ratio of investment would have been 3:2. What was the amount invested by Hariprasad? A - Re 18000 B - Re 12000 C - Re 8000 D - None of these Let the initial investment be of Hariprasad and Madhusudan be 2x and 3x respectively. As per question, 2x + 10000 = 3/2 3x Or, 4x + 20000 = 9x Or, 5x = 20000 Or, x = 4000 Hariprasad?s initial investment = 2x = 2*4000 = Re 8000 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4217, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Partnership. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4456, "s": 4217, "text": "Q 1 - With an amount of Rs. 25000 started business by ajay. After 3 month, vijay joined the business by investing amount of Rs. 30000. If profit of the firm is 19000 at the end of the year then what should be the share of Ajay in profit?" }, { "code": null, "e": 4469, "s": 4456, "text": "A - Rs. 9423" }, { "code": null, "e": 4483, "s": 4469, "text": "B - Rs. 10250" }, { "code": null, "e": 4497, "s": 4483, "text": "C - Rs. 12500" }, { "code": null, "e": 4511, "s": 4497, "text": "D - Rs. 10000" }, { "code": null, "e": 4618, "s": 4511, "text": "Ajay : Vijay = (25000*12: 30000*9) = 300000: 270000 = 10: 9\nShare of Ajay = Rs. (19000* 10/19) = Rs. 10000" }, { "code": null, "e": 4977, "s": 4618, "text": "Q 2 - Ajay , Bijender and chaman started a business and invested Rs. 20000 each partner .After the period of 4 month, some changes are made in investment just like Ajay withdraw Rs. 5000, Bijender and chaman both add 6000 each in the invested capital. An amount of Rs. 69900 recorded as a profit in the firm. What should be the share of Bijender in profit?" }, { "code": null, "e": 4991, "s": 4977, "text": "A - Rs. 56000" }, { "code": null, "e": 5005, "s": 4991, "text": "B - Rs. 21200" }, { "code": null, "e": 5018, "s": 5005, "text": "C - Rs. 9000" }, { "code": null, "e": 5032, "s": 5018, "text": "D - Rs. 20000" }, { "code": null, "e": 5218, "s": 5032, "text": "Ajay : Bijender: chaman = (20000*5+15000*7) : (20000*5+ 16000*7) :(20000*5+26000*7)\n= 205000: 212000 : 262000 = 205 : 212: 282\nShare of B in profit = Rs. (69900* 212/699) = Rs. 21200" }, { "code": null, "e": 5470, "s": 5218, "text": "Q 3 - The proportion of partners capital in a business are 1/3 of A , 1/4 of B and 1/5 of C. After the period of 4 month 1/2 part of his investment withdraw by A .if the total profit of Rs. 8470 earned by the firm then what should be the share of A?" }, { "code": null, "e": 5483, "s": 5470, "text": "A - Rs. 2520" }, { "code": null, "e": 5496, "s": 5483, "text": "B - Rs. 2800" }, { "code": null, "e": 5509, "s": 5496, "text": "C - Rs. 3150" }, { "code": null, "e": 5522, "s": 5509, "text": "D - Rs. 4120" }, { "code": null, "e": 5786, "s": 5522, "text": "In the starting time ratio of capitals = 1/3 : 1/4 : 1/5 = 20: 15: 12\nSuppose A, B and C invest Rs. 20x , Rs. 15x and 12x respectively.\nA: B:C = (20*4+ 10x*8) : (15*12) : (12x * 12) = 160x : 180x : 144x = 40: 45: 36\nShare of A = Rs. ( 8470* 40/121) = Rs. 2800" }, { "code": null, "e": 5973, "s": 5786, "text": "Q 4 - 12:11 was the investment ratio of A and B who started a business and the ratio of profit were 4:1 . The period ofA investment was 11 month and what was the period of B investment?" }, { "code": null, "e": 5985, "s": 5973, "text": "A - 3 month" }, { "code": null, "e": 5997, "s": 5985, "text": "B - 5 month" }, { "code": null, "e": 6009, "s": 5997, "text": "C - 2 month" }, { "code": null, "e": 6021, "s": 6009, "text": "D - 7 month" }, { "code": null, "e": 6286, "s": 6021, "text": "Rs. 12x and Rs. 11 x is the investment in a business. If for the y month money invested by B .then,\nA: B = (12x*11) : (11x*y) = (132x : 11xy) = (12: y)\n∴ 12/y = 4/1 = 4y = 12 ⇒ y = 3\nSo, we can say B invested his share for the period of 3 months in the business." }, { "code": null, "e": 6511, "s": 6286, "text": "Q 5 - In a partnership firm A and B invested. For the period of 8 month. A invested Rs 16000 and rest of the capital by B for the rest of the time. Find out the money contributed by B if he claims 2/7 part of the profit ?" }, { "code": null, "e": 6524, "s": 6511, "text": "A - Rs. 1190" }, { "code": null, "e": 6538, "s": 6524, "text": "B - Rs. 10500" }, { "code": null, "e": 6552, "s": 6538, "text": "C - Rs. 13600" }, { "code": null, "e": 6566, "s": 6552, "text": "D - Rs. 12800" }, { "code": null, "e": 6766, "s": 6566, "text": "Let total profit of the firm = 1\nShare of B in profit = (1-2/7 ) = 5/7\nRatio of profit = 5: 2\nContribution of B = x then (16000*8)/ 4x = 5/2 ⇒20x = 256000 ⇒ x= 12800.\nHence, b contributed rs. 12800." }, { "code": null, "e": 7076, "s": 6766, "text": "Q 6 - What should be the ratio of profit between A, B and C after the period of 3 years. If A invest 25 lakhs at starting of the business and Rs. 10 lakhs also add after one year and B invest 35 lakhs in the starting and Rs. 10 lakhs withdraw after 2 year and C invested 30 lakhs only from starting." }, { "code": null, "e": 7088, "s": 7076, "text": "A - 10:10:9" }, { "code": null, "e": 7101, "s": 7088, "text": "B - 20:19:18" }, { "code": null, "e": 7114, "s": 7101, "text": "C - 20:20:19" }, { "code": null, "e": 7132, "s": 7114, "text": "D - none of these" }, { "code": null, "e": 7292, "s": 7132, "text": "Investment of A = Rs. (25*1+ 35*2) = Rs. 95\nInvestment of B = Rs. (35*2+25*1) = Rs. 95\nInvestment of C = Rs. (30*3) = Rs. 90\n∴ A:B:C = 95:95: 90 = 19: 19: 18" }, { "code": null, "e": 7477, "s": 7292, "text": "Q 7 - The ratio of investment in a firm by A and B is 3:2 . if A received Rs. 8550 share as a profit after doing charity5% out of the total profit. What should be the total profit?" }, { "code": null, "e": 7491, "s": 7477, "text": "A - Rs. 15760" }, { "code": null, "e": 7505, "s": 7491, "text": "B - Rs. 15000" }, { "code": null, "e": 7518, "s": 7505, "text": "C - Rs. 8600" }, { "code": null, "e": 7531, "s": 7518, "text": "D - Rs. 2000" }, { "code": null, "e": 7830, "s": 7531, "text": "If X is the total profit of a firm at the end of the year .\nAmount of charity which is paid = 5% of rs. x = (5/100*x) = x/20 , balance =(x-x/20) = rs. 19x/20\nShare of A = rs. (19x/20* 3/5) = Rs. 57x/100\n∴ 57x/100= 8550 ⇒ x = (8550*100)/57 = 15000.\nHence, the total profit of the firm = Rs. 15000." }, { "code": null, "e": 8032, "s": 7830, "text": "Q 8 - In a partnership business, Mr X invests Rs 2400 for 4 years, Mr Y invests Rs 2800 for 8 years and Mr Z invests Rs 2000 for 10 years. They earn Rs 1170. Find the share of profit for each partners." }, { "code": null, "e": 8050, "s": 8032, "text": "A - 215, 450, 555" }, { "code": null, "e": 8068, "s": 8050, "text": "B - 215, 500, 455" }, { "code": null, "e": 8086, "s": 8068, "text": "C - 215, 505, 450" }, { "code": null, "e": 8104, "s": 8086, "text": "D - 216, 504, 450" }, { "code": null, "e": 8472, "s": 8104, "text": "Rs 2400 investment in 4 years earns as much as Rs 2400*4 = Rs 9600 in 1 year\nSimilary, Rs 2800*8 = Rs 22400 in 1 year\nAnd Rs 2000*10 = Rs 20000 in 1 year.\n\nRatio for profit to be shared = 9600 : 22400 : 20000\n= 12 : 28 : 25\nSum of ratios = 12 + 28 + 25 = 65\nHence,\nX's share = 12/65 * 1170 = Rs 216\nY's share = 28/65 * 1170 = Rs 504\nZ's share = 25/65 * 1170 = Rs 450\n" }, { "code": null, "e": 8680, "s": 8472, "text": "Q 9 - Kabir starts a business with Re 4,50,000/- Nisha joins him after a certain period of time who invests Re 3,00,000/-. At the end of year, they divide profir in the ratio 9:4. When did Nisha join Kabir?" }, { "code": null, "e": 8699, "s": 8680, "text": "A - After 3 months" }, { "code": null, "e": 8718, "s": 8699, "text": "B - After 5 months" }, { "code": null, "e": 8737, "s": 8718, "text": "C - After 6 months" }, { "code": null, "e": 8756, "s": 8737, "text": "D - After 4 months" }, { "code": null, "e": 8908, "s": 8756, "text": "Suppose Nisha is with Kabir for x months.\nSo, 4,50,000*12/3,00,000*x = 9/4\nOr, x = 8 months\nHence Nisha joined Kabir after (12 - 8) months = 4 months." }, { "code": null, "e": 9162, "s": 8908, "text": "Q 10 - Hariprasad and Madhusudan started a business investing amounts in the ratio of 2:3 respectively. If Hariprasad had invested an additional amount of Re 10000, the ratio of investment would have been 3:2. What was the amount invested by Hariprasad?" }, { "code": null, "e": 9175, "s": 9162, "text": "A - Re 18000" }, { "code": null, "e": 9188, "s": 9175, "text": "B - Re 12000" }, { "code": null, "e": 9200, "s": 9188, "text": "C - Re 8000" }, { "code": null, "e": 9218, "s": 9200, "text": "D - None of these" }, { "code": null, "e": 9449, "s": 9218, "text": "Let the initial investment be of Hariprasad and Madhusudan be 2x and 3x respectively.\nAs per question,\n2x + 10000 = 3/2\n3x\nOr, 4x + 20000 = 9x\nOr, 5x = 20000\nOr, x = 4000\nHariprasad?s initial investment = 2x = 2*4000 = Re 8000" }, { "code": null, "e": 9485, "s": 9449, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 9503, "s": 9485, "text": " Programming Line" }, { "code": null, "e": 9510, "s": 9503, "text": " Print" }, { "code": null, "e": 9521, "s": 9510, "text": " Add Notes" } ]
SORT command in Linux/Unix with examples - GeeksforGeeks
11 Feb, 2022 SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically. SORT command sorts the contents of a text file, line by line. sort is a standard command-line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by number, by month, and can also remove duplicates. The sort command can also sort by items not at the beginning of the line, ignore case sensitivity, and return whether a file is sorted or not. Sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as the sort key. Blank space is the default field separator. The sort command follows these features as stated below: Lines starting with a number will appear before lines starting with a letter.Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet.Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase. Lines starting with a number will appear before lines starting with a letter. Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet. Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase. Examples Suppose you create a data file with name file.txt: Command : $ cat > file.txt abhishek chitransh satish rajan naveen divyam harsh Sorting a file: Now use the sort command Syntax : $ sort filename.txt Command: $ sort file.txt Output : abhishek chitransh divyam harsh naveen rajan satish Note: This command does not actually change the input file, i.e. file.txt. Sort function with mix file i.e. uppercase and lower case: When we have a mix file with both uppercase and lowercase letters then first the upper case letters would be sorted following with the lower case letters. Example: Create a file mix.txt Command : $ cat > mix.txt abc apple BALL Abc bat Now use the sort command Command : $ sort mix.txt Output : Abc BALL abc apple bat Options with sort function: 1. -o Option: Unix also provides us with special facilities like if you want to write the output to a new file, output.txt, redirects the output like this or you can also use the built-in sort option -o, which allows you to specify an output file. Using the -o option is functionally the same as redirecting the output to a file. Note: Neither one has an advantage over the other. Example: The input file is the same as mentioned above. Syntax: $ sort inputfile.txt > filename.txt $ sort -o filename.txt inputfile.txt Command: $ sort file.txt > output.txt $ sort -o output.txt file.txt $ cat output.txt Output : abhishek chitransh divyam harsh naveen rajan satish 2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above. Syntax : $ sort -r inputfile.txt Command : $ sort -r file.txt Output : satish rajan naveen harsh divyam chitransh abhishek 3. -n Option: To sort a file numerically used –n option. -n option is also predefined in Unix as the above options are. This option is used to sort the file with numeric data present inside. Example : Let us consider a file with numbers: Command : $ cat > file1.txt 50 39 15 89 200 Syntax: $ sort -n filename.txt Command : $ sort -n file1.txt Output : 15 39 50 89 200 4. -nr option: To sort a file with numeric data in reverse order we can use the combination of two options as stated below. Example: The numeric file is the same as above. Syntax : $ sort -nr filename.txt Command : $ sort -nr file1.txt Output : 200 89 50 39 15 5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column. Example : Let us create a table with 2 columns $ cat > employee.txt manager 5000 clerk 4000 employee 6000 peon 4500 director 9000 guard 3000 Syntax : $ sort -k filename.txt Command : $ sort -k 2n employee.txt guard 3000 clerk 4000 peon 4500 manager 5000 employee 6000 director 9000 6. -c option: This option is used to check if the file given is already sorted or not & checks if a file is already sorted pass the -c option to sort. This will write to standard output if there are lines that are out of order. The sort tool can be used to understand if this file is sorted and which lines are out of order Example : Suppose a file exists with a list of cars called cars.txt. Audi Cadillac BMW Dodge Syntax : $ sort -c filename.txt Command : $ sort -c cars.txt Output : sort: cars.txt:3: disorder: BMW Note : If there is no output then the file is considered to be already sorted 7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a sorted list to standard output and remove duplicates. This option is helpful as the duplicates being removed give us a redundant file. Example: Suppose a file exists with a list of cars called cars.txt. Audi BMW Cadillac BMW Dodge Syntax : $ sort -u filename.txt Command : $ sort -u cars.txt $ cat cars.txt Output : Audi BMW Cadillac Dodge 8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list to standard output ordered by month name. Example: Suppose the following file exists and is saved as months.txt $ cat > months.txt February January March August September Syntax : $ sort -M filename.txt Using The -M option with sort allows us to order this file. Command : $ sort -M months.txt $ cat months.txt Output : January February March August September Application and uses of sort command: It can sort any type of file be it table file text file numeric file and so on.Sorting can be directly implemented from one file to another without the present work being hampered.Sorting of table files on the basis of columns has been made way simpler and easier.So many options are available for sorting in all possible ways.The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided.Original data is always safe and not hampered. It can sort any type of file be it table file text file numeric file and so on. Sorting can be directly implemented from one file to another without the present work being hampered. Sorting of table files on the basis of columns has been made way simpler and easier. So many options are available for sorting in all possible ways. The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided. Original data is always safe and not hampered. TechFukrey roopal jangid mahajanrohanraj9 linux-command Linux-text-processing-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization tee command in Linux with examples echo command in Linux with Examples Compiling with g++
[ { "code": null, "e": 23958, "s": 23930, "text": "\n11 Feb, 2022" }, { "code": null, "e": 24186, "s": 23958, "text": "SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically. " }, { "code": null, "e": 24248, "s": 24186, "text": "SORT command sorts the contents of a text file, line by line." }, { "code": null, "e": 24398, "s": 24248, "text": "sort is a standard command-line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order." }, { "code": null, "e": 24581, "s": 24398, "text": "The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by number, by month, and can also remove duplicates." }, { "code": null, "e": 24806, "s": 24581, "text": "The sort command can also sort by items not at the beginning of the line, ignore case sensitivity, and return whether a file is sorted or not. Sorting is done based on one or more sort keys extracted from each line of input." }, { "code": null, "e": 24905, "s": 24806, "text": "By default, the entire input is taken as the sort key. Blank space is the default field separator." }, { "code": null, "e": 24964, "s": 24905, "text": "The sort command follows these features as stated below: " }, { "code": null, "e": 25298, "s": 24964, "text": "Lines starting with a number will appear before lines starting with a letter.Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet.Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase." }, { "code": null, "e": 25376, "s": 25298, "text": "Lines starting with a number will appear before lines starting with a letter." }, { "code": null, "e": 25526, "s": 25376, "text": "Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet." }, { "code": null, "e": 25634, "s": 25526, "text": "Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase." }, { "code": null, "e": 25643, "s": 25634, "text": "Examples" }, { "code": null, "e": 25695, "s": 25643, "text": "Suppose you create a data file with name file.txt: " }, { "code": null, "e": 25775, "s": 25695, "text": "Command : \n$ cat > file.txt\nabhishek\nchitransh\nsatish\nrajan\nnaveen\ndivyam\nharsh" }, { "code": null, "e": 25817, "s": 25775, "text": "Sorting a file: Now use the sort command " }, { "code": null, "e": 25827, "s": 25817, "text": "Syntax : " }, { "code": null, "e": 25847, "s": 25827, "text": "$ sort filename.txt" }, { "code": null, "e": 25935, "s": 25847, "text": "Command:\n$ sort file.txt\n\nOutput :\nabhishek\nchitransh\ndivyam\nharsh\nnaveen \nrajan\nsatish" }, { "code": null, "e": 26011, "s": 25935, "text": "Note: This command does not actually change the input file, i.e. file.txt. " }, { "code": null, "e": 26225, "s": 26011, "text": "Sort function with mix file i.e. uppercase and lower case: When we have a mix file with both uppercase and lowercase letters then first the upper case letters would be sorted following with the lower case letters." }, { "code": null, "e": 26235, "s": 26225, "text": "Example: " }, { "code": null, "e": 26258, "s": 26235, "text": "Create a file mix.txt " }, { "code": null, "e": 26307, "s": 26258, "text": "Command :\n$ cat > mix.txt\nabc\napple\nBALL\nAbc\nbat" }, { "code": null, "e": 26333, "s": 26307, "text": "Now use the sort command " }, { "code": null, "e": 26979, "s": 26333, "text": "Command :\n$ sort mix.txt\nOutput :\nAbc \nBALL \nabc \napple \nbat" }, { "code": null, "e": 27007, "s": 26979, "text": "Options with sort function:" }, { "code": null, "e": 27256, "s": 27007, "text": "1. -o Option: Unix also provides us with special facilities like if you want to write the output to a new file, output.txt, redirects the output like this or you can also use the built-in sort option -o, which allows you to specify an output file. " }, { "code": null, "e": 27339, "s": 27256, "text": "Using the -o option is functionally the same as redirecting the output to a file. " }, { "code": null, "e": 27391, "s": 27339, "text": "Note: Neither one has an advantage over the other. " }, { "code": null, "e": 27448, "s": 27391, "text": "Example: The input file is the same as mentioned above. " }, { "code": null, "e": 27456, "s": 27448, "text": "Syntax:" }, { "code": null, "e": 27529, "s": 27456, "text": "$ sort inputfile.txt > filename.txt\n$ sort -o filename.txt inputfile.txt" }, { "code": null, "e": 27678, "s": 27529, "text": "Command:\n$ sort file.txt > output.txt \n$ sort -o output.txt file.txt\n$ cat output.txt\n\nOutput :\nabhishek\nchitransh\ndivyam\nharsh\nnaveen \nrajan\nsatish" }, { "code": null, "e": 27898, "s": 27678, "text": "2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. " }, { "code": null, "e": 27955, "s": 27898, "text": "Example: The input file is the same as mentioned above. " }, { "code": null, "e": 27965, "s": 27955, "text": "Syntax : " }, { "code": null, "e": 27989, "s": 27965, "text": "$ sort -r inputfile.txt" }, { "code": null, "e": 28080, "s": 27989, "text": "Command :\n$ sort -r file.txt\nOutput :\nsatish\nrajan\nnaveen \nharsh\ndivyam\nchitransh\nabhishek" }, { "code": null, "e": 28272, "s": 28080, "text": "3. -n Option: To sort a file numerically used –n option. -n option is also predefined in Unix as the above options are. This option is used to sort the file with numeric data present inside. " }, { "code": null, "e": 28283, "s": 28272, "text": "Example : " }, { "code": null, "e": 28321, "s": 28283, "text": "Let us consider a file with numbers: " }, { "code": null, "e": 28365, "s": 28321, "text": "Command :\n$ cat > file1.txt\n50\n39\n15\n89\n200" }, { "code": null, "e": 28373, "s": 28365, "text": "Syntax:" }, { "code": null, "e": 28396, "s": 28373, "text": "$ sort -n filename.txt" }, { "code": null, "e": 28451, "s": 28396, "text": "Command :\n$ sort -n file1.txt\nOutput :\n15\n39\n50\n89\n200" }, { "code": null, "e": 28576, "s": 28451, "text": "4. -nr option: To sort a file with numeric data in reverse order we can use the combination of two options as stated below. " }, { "code": null, "e": 28625, "s": 28576, "text": "Example: The numeric file is the same as above. " }, { "code": null, "e": 28635, "s": 28625, "text": "Syntax : " }, { "code": null, "e": 28659, "s": 28635, "text": "$ sort -nr filename.txt" }, { "code": null, "e": 28715, "s": 28659, "text": "Command :\n$ sort -nr file1.txt\nOutput :\n200\n89\n50\n39\n15" }, { "code": null, "e": 28829, "s": 28715, "text": "5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. " }, { "code": null, "e": 28931, "s": 28829, "text": "Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column. " }, { "code": null, "e": 28942, "s": 28931, "text": "Example : " }, { "code": null, "e": 28980, "s": 28942, "text": "Let us create a table with 2 columns " }, { "code": null, "e": 29087, "s": 28980, "text": "$ cat > employee.txt\nmanager 5000\nclerk 4000\nemployee 6000\npeon 4500\ndirector 9000\nguard 3000" }, { "code": null, "e": 29096, "s": 29087, "text": "Syntax :" }, { "code": null, "e": 29119, "s": 29096, "text": "$ sort -k filename.txt" }, { "code": null, "e": 29239, "s": 29119, "text": "Command :\n$ sort -k 2n employee.txt\nguard 3000\nclerk 4000\npeon 4500\nmanager 5000\nemployee 6000\ndirector 9000" }, { "code": null, "e": 29564, "s": 29239, "text": "6. -c option: This option is used to check if the file given is already sorted or not & checks if a file is already sorted pass the -c option to sort. This will write to standard output if there are lines that are out of order. The sort tool can be used to understand if this file is sorted and which lines are out of order " }, { "code": null, "e": 29575, "s": 29564, "text": "Example : " }, { "code": null, "e": 29635, "s": 29575, "text": "Suppose a file exists with a list of cars called cars.txt. " }, { "code": null, "e": 29659, "s": 29635, "text": "Audi\nCadillac\nBMW\nDodge" }, { "code": null, "e": 29668, "s": 29659, "text": "Syntax :" }, { "code": null, "e": 29691, "s": 29668, "text": "$ sort -c filename.txt" }, { "code": null, "e": 29841, "s": 29691, "text": "Command :\n$ sort -c cars.txt\nOutput :\nsort: cars.txt:3: disorder: BMW\n Note : If there is no output then the file is considered to be already sorted " }, { "code": null, "e": 30067, "s": 29841, "text": "7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a sorted list to standard output and remove duplicates. This option is helpful as the duplicates being removed give us a redundant file. " }, { "code": null, "e": 30136, "s": 30067, "text": "Example: Suppose a file exists with a list of cars called cars.txt. " }, { "code": null, "e": 30164, "s": 30136, "text": "Audi\nBMW\nCadillac\nBMW\nDodge" }, { "code": null, "e": 30173, "s": 30164, "text": "Syntax :" }, { "code": null, "e": 30196, "s": 30173, "text": "$ sort -u filename.txt" }, { "code": null, "e": 30273, "s": 30196, "text": "Command :\n$ sort -u cars.txt\n$ cat cars.txt\nOutput :\nAudi\nBMW\nCadillac\nDodge" }, { "code": null, "e": 30405, "s": 30273, "text": "8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list to standard output ordered by month name. " }, { "code": null, "e": 30415, "s": 30405, "text": "Example: " }, { "code": null, "e": 30477, "s": 30415, "text": "Suppose the following file exists and is saved as months.txt " }, { "code": null, "e": 30496, "s": 30477, "text": "$ cat > months.txt" }, { "code": null, "e": 30551, "s": 30496, "text": "February \nJanuary \nMarch \nAugust \nSeptember \n\nSyntax :" }, { "code": null, "e": 30574, "s": 30551, "text": "$ sort -M filename.txt" }, { "code": null, "e": 30634, "s": 30574, "text": "Using The -M option with sort allows us to order this file." }, { "code": null, "e": 30731, "s": 30634, "text": "Command :\n$ sort -M months.txt\n$ cat months.txt\nOutput :\nJanuary\nFebruary\nMarch\nAugust\nSeptember" }, { "code": null, "e": 30769, "s": 30731, "text": "Application and uses of sort command:" }, { "code": null, "e": 31269, "s": 30769, "text": "It can sort any type of file be it table file text file numeric file and so on.Sorting can be directly implemented from one file to another without the present work being hampered.Sorting of table files on the basis of columns has been made way simpler and easier.So many options are available for sorting in all possible ways.The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided.Original data is always safe and not hampered." }, { "code": null, "e": 31349, "s": 31269, "text": "It can sort any type of file be it table file text file numeric file and so on." }, { "code": null, "e": 31451, "s": 31349, "text": "Sorting can be directly implemented from one file to another without the present work being hampered." }, { "code": null, "e": 31536, "s": 31451, "text": "Sorting of table files on the basis of columns has been made way simpler and easier." }, { "code": null, "e": 31600, "s": 31536, "text": "So many options are available for sorting in all possible ways." }, { "code": null, "e": 31727, "s": 31600, "text": "The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided." }, { "code": null, "e": 31774, "s": 31727, "text": "Original data is always safe and not hampered." }, { "code": null, "e": 31785, "s": 31774, "text": "TechFukrey" }, { "code": null, "e": 31799, "s": 31785, "text": "roopal jangid" }, { "code": null, "e": 31816, "s": 31799, "text": "mahajanrohanraj9" }, { "code": null, "e": 31830, "s": 31816, "text": "linux-command" }, { "code": null, "e": 31861, "s": 31830, "text": "Linux-text-processing-commands" }, { "code": null, "e": 31872, "s": 31861, "text": "Linux-Unix" }, { "code": null, "e": 31970, "s": 31872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32005, "s": 31970, "text": "tar command in Linux with examples" }, { "code": null, "e": 32043, "s": 32005, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 32081, "s": 32043, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 32116, "s": 32081, "text": "Cat command in Linux with examples" }, { "code": null, "e": 32152, "s": 32116, "text": "Tail command in Linux with examples" }, { "code": null, "e": 32189, "s": 32152, "text": "touch command in Linux with Examples" }, { "code": null, "e": 32233, "s": 32189, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 32268, "s": 32233, "text": "tee command in Linux with examples" }, { "code": null, "e": 32304, "s": 32268, "text": "echo command in Linux with Examples" } ]
C++ Program to Check Whether a Directed Graph Contains a Eulerian Path
The Euler path is a path; by which we can visit every edge exactly once. We can use the same vertices for multiple times. One graph which contains Euler Circuit is also considered in this case, as it also has the Euler path. To check whether a directed graph has Euler path or not, we have to check these conditions - There must be one single vertex an where (in-degree + 1 = out_degree) There must be one single vertex bn where (in-degree = out_degree + 1) Rest all vertices have (in-degree = out_degree) if any of these cases fails, the graph has no Euler path. Vertex b has (in-degree 1, out-degree 2), vertex c has (in-degree 2, out-degree 1). And for the rest of the vertices a, d has (in-degree 2, out-degree 2), e has (in-degree 1, out-degree 1). Adjacency matrix of the graph. Euler Path Found. Input The start node u and the visited node to mark which node is visited. Output Traverse all connected vertices. Begin mark u as visited for all vertex v, if it is adjacent with u, do if v is not visited, then traverse(v, visited) done End Input : The graph. Output: True if the graph is connected. Begin define visited array for all vertices u in the graph, do make all nodes unvisited traverse(u, visited) if any unvisited node is still remaining, then return false done return true End Input The given Graph. Output True when one Euler circuit is found. Begin an := 0 bn := 0 if isConnected() is false, then return false define list for inward and outward edge count for each node for all vertex i in the graph, do sum := 0 for all vertex j which are connected with i, do inward edges for vertex i increased increase sum done number of outward of vertex i is sum done if inward list and outward list are same, then return true for all vertex i in the vertex set V, do if inward[i] ≠ outward[i], then if inward[i] + 1 = outward[i], then an := an + 1 else if inward[i] = outward[i] + 1, then bn := bn + 1 done if an and bn both are 1, then return true otherwise return false End #include<iostream> #include<vector> #define NODE 5 using namespace std; int graph[NODE][NODE] = {{0, 0, 1, 1, 0}, {1, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 0, 0}}; void traverse(int u, bool visited[]) { visited[u] = true; //mark v as visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { if(!visited[v]) traverse(v, visited); } } } bool isConnected() { bool *vis = new bool[NODE]; //for all vertex u as start point, check whether all nodes are visible or not for(int u; u < NODE; u++) { for(int i = 0; i<NODE; i++) vis[i] = false; //initialize as no node is visited traverse(u, vis); for(int i = 0; i<NODE; i++) { if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected return false; } } return true; } bool hasEulerPath() { int an = 0, bn = 0; if(isConnected() == false){ //when graph is not connected return false; } vector<int> inward(NODE, 0), outward(NODE, 0); for(int i = 0; i<NODE; i++) { int sum = 0; for(int j = 0; j<NODE; j++) { if(graph[i][j]) { inward[j]++; //increase inward edge for destination vertex sum++; //how many outward edge } } outward[i] = sum; } //check the condition for Euler paths if(inward == outward) //when number inward edges and outward edges for each node is same return true; //Euler Circuit, it has Euler path for(int i = 0; i<NODE; i++) { if(inward[i] != outward[i]) { if((inward[i] + 1 == outward[i])) { an++; } else if((inward[i] == outward[i] + 1)) { bn++; } } } if(an == 1 && bn == 1) { //if there is only an, and bn, then this has euler path return true; } return false; } int main() { if(hasEulerPath()) cout << "Euler Path Found."; else cout << "There is no Euler Circuit."; } Euler Path Found.
[ { "code": null, "e": 1287, "s": 1062, "text": "The Euler path is a path; by which we can visit every edge exactly once. We can use the same vertices for multiple times. One graph which contains Euler Circuit is also considered in this case, as it also has the Euler path." }, { "code": null, "e": 1380, "s": 1287, "text": "To check whether a directed graph has Euler path or not, we have to check these conditions -" }, { "code": null, "e": 1450, "s": 1380, "text": "There must be one single vertex an where (in-degree + 1 = out_degree)" }, { "code": null, "e": 1520, "s": 1450, "text": "There must be one single vertex bn where (in-degree = out_degree + 1)" }, { "code": null, "e": 1626, "s": 1520, "text": "Rest all vertices have (in-degree = out_degree) if any of these cases fails, the graph has no Euler path." }, { "code": null, "e": 1816, "s": 1626, "text": "Vertex b has (in-degree 1, out-degree 2), vertex c has (in-degree 2, out-degree 1). And for the rest of the vertices a, d has (in-degree 2, out-degree 2), e has (in-degree 1, out-degree 1)." }, { "code": null, "e": 1847, "s": 1816, "text": "Adjacency matrix of the graph." }, { "code": null, "e": 1865, "s": 1847, "text": "Euler Path Found." }, { "code": null, "e": 1940, "s": 1865, "text": "Input The start node u and the visited node to mark which node is visited." }, { "code": null, "e": 1980, "s": 1940, "text": "Output Traverse all connected vertices." }, { "code": null, "e": 2128, "s": 1980, "text": "Begin\n mark u as visited\n for all vertex v, if it is adjacent with u, do\n if v is not visited, then\n traverse(v, visited)\n done\nEnd" }, { "code": null, "e": 2147, "s": 2128, "text": "Input : The graph." }, { "code": null, "e": 2187, "s": 2147, "text": "Output: True if the graph is connected." }, { "code": null, "e": 2419, "s": 2187, "text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd" }, { "code": null, "e": 2442, "s": 2419, "text": "Input The given Graph." }, { "code": null, "e": 2487, "s": 2442, "text": "Output True when one Euler circuit is found." }, { "code": null, "e": 3265, "s": 2487, "text": "Begin\n an := 0\n bn := 0\n if isConnected() is false, then\n return false\n define list for inward and outward edge count for each node\n for all vertex i in the graph, do\n sum := 0\n for all vertex j which are connected with i, do\n inward edges for vertex i increased\n increase sum\n done\n number of outward of vertex i is sum\n done\n if inward list and outward list are same, then\n return true\n for all vertex i in the vertex set V, do\n if inward[i] ≠ outward[i], then\n if inward[i] + 1 = outward[i], then\n an := an + 1\n else if inward[i] = outward[i] + 1, then\n bn := bn + 1\n done\n if an and bn both are 1, then\n return true\n otherwise return false\nEnd" }, { "code": null, "e": 5261, "s": 3265, "text": "#include<iostream>\n#include<vector>\n#define NODE 5\nusing namespace std;\nint graph[NODE][NODE] = {{0, 0, 1, 1, 0},\n {1, 0, 1, 0, 0},\n {0, 0, 0, 1, 0},\n {0, 1, 0, 0, 1},\n {1, 0, 0, 0, 0}};\nvoid traverse(int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) {\n if(!visited[v])\n traverse(v, visited);\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i<NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nbool hasEulerPath() {\n int an = 0, bn = 0;\n if(isConnected() == false){ //when graph is not connected\n return false;\n }\n vector<int> inward(NODE, 0), outward(NODE, 0);\n for(int i = 0; i<NODE; i++) {\n int sum = 0;\n for(int j = 0; j<NODE; j++) {\n if(graph[i][j]) {\n inward[j]++; //increase inward edge for destination vertex\n sum++; //how many outward edge\n }\n }\n outward[i] = sum;\n }\n //check the condition for Euler paths\n if(inward == outward) //when number inward edges and outward edges for each node is same\n return true; //Euler Circuit, it has Euler path\n for(int i = 0; i<NODE; i++) {\n if(inward[i] != outward[i]) {\n if((inward[i] + 1 == outward[i])) {\n an++;\n } else if((inward[i] == outward[i] + 1)) {\n bn++;\n }\n }\n }\n if(an == 1 && bn == 1) { //if there is only an, and bn, then this has euler path\n return true;\n }\n return false;\n}\nint main() {\n if(hasEulerPath())\n cout << \"Euler Path Found.\";\n else\n cout << \"There is no Euler Circuit.\";\n}" }, { "code": null, "e": 5279, "s": 5261, "text": "Euler Path Found." } ]
error_reporting() function in PHP
The error_reporting() function specifies which errors are reported. It sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. It returns the old error reporting level or the current error reporting level if no level parameter is given. error_reporting(level) level − It specifies the error report level for the current script. Value number and constant name are accepted. level − It specifies the error report level for the current script. Value number and constant name are accepted. The error_reporting() function returns the old error reporting level or the current error reporting level if no level parameter is given. The following is an example − Live Demo <?php // Turn off error reporting error_reporting(0); // Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); ?> Let us see another example to report all errors − <?php error_reporting(E_ALL); ?>
[ { "code": null, "e": 1400, "s": 1062, "text": "The error_reporting() function specifies which errors are reported. It sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. It returns the old error reporting level or the current error reporting level if no level parameter is given." }, { "code": null, "e": 1423, "s": 1400, "text": "error_reporting(level)" }, { "code": null, "e": 1536, "s": 1423, "text": "level − It specifies the error report level for the current script. Value number and constant name are accepted." }, { "code": null, "e": 1649, "s": 1536, "text": "level − It specifies the error report level for the current script. Value number and constant name are accepted." }, { "code": null, "e": 1787, "s": 1649, "text": "The error_reporting() function returns the old error reporting level or the current error reporting level if no level parameter is given." }, { "code": null, "e": 1817, "s": 1787, "text": "The following is an example −" }, { "code": null, "e": 1828, "s": 1817, "text": " Live Demo" }, { "code": null, "e": 1971, "s": 1828, "text": "<?php\n // Turn off error reporting\n error_reporting(0);\n\n // Report runtime errors\n error_reporting(E_ERROR | E_WARNING | E_PARSE);\n?>" }, { "code": null, "e": 2021, "s": 1971, "text": "Let us see another example to report all errors −" }, { "code": null, "e": 2057, "s": 2021, "text": "<?php\n error_reporting(E_ALL);\n?>" } ]
Time series analysis for predictive maintenance of turbofan engines | by Koen Peters | Towards Data Science
<disclaimer: I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.> Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. This will be the third analysis on FD001, where all engines run on the same operating condition and develop the same fault. Initially we assumed the Remaining Useful Life (RUL) of the engines to decline linearly. In my last post we re-examined this assumption by clipping any values above 125. Clipping the RUL improved the baseline linear regression by 31% (from an RMSE of 31.95 to an RMSE of 21.90). We then switched to a Support Vector Regression and squeezed out another 6% improvement for a total RMSE of 20.54. Today, we’ll focus on time series analysis to forecast when the engines are due for maintenance. But, before getting into the time series part, we first have to recap a few processing steps. Let’s get started! First, we’ll import some libraries and read the data. Looks good. Next, the linear declining RUL is computed (clipping is added later) and uninformative columns are dropped. Nice, with that out of the way let’s discuss our approach. Time series analysis and forecasting for this data set can be done with one of three general approaches: Predicting sensor values and setting ‘alarm’ thresholds. The component is deteriorated to a state in which breakdown is imminent when a sensor is predicted to cross this threshold. There are a few caveats using this approach for the current dataset.(a) Every sensor has to be modelled individually, therefore we cannot make use of interactions between sensors.(b) it requires a lot of domain knowledge for setting the appropriate thresholds and (c) it doesn’t directly inform us about our target feature, the Remaining Useful Life (RUL).Vector Autoregression (VAR) type models. These types of models can handle multivariate timeseries, however the model initially creates lags of both our X and Y variables. Normally in timeseries the past values of Y play a large role in determining future values of Y. But since we assume our values for Y to be constant or linearly declining in the training set, incorporating these self-defined targets in the model and using them for prediction would highly influence model results and overemphasize the effect of Yt-1 on Yt. You could write some custom code to set the coefficients for the weights of the lagged Y variables to 0, but in my opinion, there is an easier method.Distributed lag models. Basically, a regression model where you have full control over how many lags you add for each variable. Predicting sensor values and setting ‘alarm’ thresholds. The component is deteriorated to a state in which breakdown is imminent when a sensor is predicted to cross this threshold. There are a few caveats using this approach for the current dataset.(a) Every sensor has to be modelled individually, therefore we cannot make use of interactions between sensors.(b) it requires a lot of domain knowledge for setting the appropriate thresholds and (c) it doesn’t directly inform us about our target feature, the Remaining Useful Life (RUL). Vector Autoregression (VAR) type models. These types of models can handle multivariate timeseries, however the model initially creates lags of both our X and Y variables. Normally in timeseries the past values of Y play a large role in determining future values of Y. But since we assume our values for Y to be constant or linearly declining in the training set, incorporating these self-defined targets in the model and using them for prediction would highly influence model results and overemphasize the effect of Yt-1 on Yt. You could write some custom code to set the coefficients for the weights of the lagged Y variables to 0, but in my opinion, there is an easier method. Distributed lag models. Basically, a regression model where you have full control over how many lags you add for each variable. In creating a distributed lag model, we can use many of the tools and tests from both time series and regression analyses. However, we’ll start small and add complexity as needed. In its basic form the model we’re going to implement looks as follows: Yt = a + B1*Xt + B2*Xt-1 + ... + Bn*Xt-n Where a is the intercept and B1 to Bn are the coefficients. Xt-1 and Xt-n are the lagged variables of Xt, with a lag of one till n respectively and Yt is the target variable at the current time t.Note: to be in line with previous posts we’re predicting RUL at Yt, if you want to predict the RUL of the next time_cycle (Yt+1) you can simply shift the target by one, as explained below. We can use Pandas shift function to add lagged variables. You can see the lagged columns contain data from the previous time stamps. Row 2 for example, has the data of time 0 and 1 appended. This is how we can get data from multiple time instances represented in one row, which is a convenient representation for use by our model. Now let’s apply this principle to our dataset. We drop the rows where NaN values were introduced as a result of adding lagged variables and fit a new regression model. # returns# train set RMSE:39.367692351135005, Variance:0.6709929595362338# test set RMSE:31.423109839706022, Variance:0.42820706786532714 Great! Adding a lag of one already gives a small improvement upon our baseline model, which had a RMSE of 31.95. The above example showcases the basics of what we’re trying to achieve. Correction: In the above example I forgot to drop the index_names. The results do not improve compared to baseline when these are dropped. Thanks Xuanang Liu for pointing this out! Fortunately this has little impact on the overall flow, adding more lags will start to improve results (as you can read further down below) Let’s wrap this functionality in two functions for later use, one to add lags from 1 till n, and one to add specific lags. There are a few assumptions to consider when applying time series analysis and regression, let’s look at those now. Stationarity implies the statistical properties of the time series, such as mean and variance do not change over time, in addition the covariance (spread of the time series) should not be dependent on time (see Figure 1 below). It is important that these statistical properties stay constant because a lot of statistical models rely on these properties for their predictions. Hence, if the mean, variance or covariance changes with time the model would not be able to accurately predict the next value [1]. Fortunately, there are tests to check for stationarity in your data, and there are also methods to make time series stationary if the tests are not passed. To test for stationarity, we’re going to use the Augmented Dickey-Fuller test, you can check [1–5] for more information. For now, the adf-test-statistic and p-value are the most important. The more negative the test statistic, the more stationary the signal. When the p-value is below 0.05, it can be assumed the time-series is stationary. Let’s perform this test on a column of a single engine. # returns# single unit, single column test results# adf: -2.276666927948019 # pvalue: 0.17960380425358546# Significant: False The test statistic is negative but not significant. We can difference the data once in an attempt to remove the trend and test again [6]. # returns# single unit, single column test results after differencing# adf: -14.824168539718967 # pvalue: 1.9431018596392618e-27# Significant: True Much better, the p-value is now < 0.05 allowing us to assume stationarity. Note: It’s important to take into account how you implement your test, for example testing stationarity of one sensor column has the time series of all 100 engines. All engines together form a stationary signal, but signals of individual engines are not stationary! (see Figure 2) Since we don’t know beforehand how many times the timeseries of each sensor of each engine needs to be differenced before becoming stationary, it’s best to create some functions which handle these steps for us. We’ll use the p-value as the decisive factor to assume stationarity. We apply these functions to make our data stationary. Let’s fit a new linear regression to get an idea of the effect of stationary data on model performance. # returns# train set RMSE:51.63375613791181, Variance:0.4340864011385228 Training RMSE has become quite a bit worse as a result of making the data stationary. This can be explained by the data no longer having a trend, making it difficult to fit a regression line. Performance will improve again when adding lagged variables, as this will inform the model of the relation between the changes in sensor values over time. Next, we can start our search to determine how many lags to add for optimal model results. The Akaike Information Criterion (AIC) is a metric which reflects model quality and is often used in time series analysis. It takes both over- and underfitting into account. When training multiple similar models, the AIC-scores can be compared for model selection [7]. A lower score is generally better, but there is usually a trade-off between complexity and model quality improvement. Let’s train some models with 0 to n lags and calculate the AIC to determine the highest quality model. We’re looking for a tipping point in the AIC’s indicating diminishing returns of model improvement by adding more lags. However, based on the table of metrics it does not become clear how many lags to add as the metrics seem to keep improving steadily. Let’s try plotting the AIC for any visual ques. Based on the graph, quality improvement seems to stagnate after 14 lags. To me this indicates the trade-off between model complexity and quality is reached at this point, as adding more lags (complexity) no longer substantially improves model quality. One problem with adding multiple lags of the same variable is the possibility of introducing multicollinearity, let’s check that next. Multicollinearity occurs when independent variables in a multiple regression model are highly correlated [8]. Due to the nature of time series, where the value of a previous timepoint is inherently related to the next value in time, the chances of introducing multicollinearity when you add lagged variables is substantial. Multicollinearity influences the models’ coefficients and stability, increasing the chance of incorrect results on new data. Let’s test the multicollinearity of our model by calculating the Variance Inflation Factor (VIF), as a rule of thumb vif-values below 5 are considered safe [9]. Our model seems to suffer greatly from multicollinearity with vif-values far bigger than 5. When searching for ways to reduce multicollinearity I found the method used by statsmodels for calculating multicollinearity may be heavily influenced by scaling [10]. This would be quite an easy fix, so let’s implement a scaling transformation and hope we don’t have to look further to solve our problems. Much better! We now have all components to train, predict and evaluate to find the best model. We first repeat our procedure for identifying the number of lags to add. The point shifted a little bit after adding scaling, model quality improvement now stagnates at 9 lags instead of 14. Let’s put our pipeline together and train our model with 9 lags to see how it performs. We’ll also incorporate the clipped RUL from here on. # returns# train set RMSE:20.80233928213837, Variance:0.7523208224684113# test set RMSE:21.14895857012398, Variance:0.7409888687595052 A RMSE of 21.14 isn’t bad, but I think we can squeeze out a little bit more. Currently our model uses consecutive lagged variables. However, adjacent lags do not necessarily have to hold distinctive information. For example, the change in sensor values at lag 6, 7 and 8 could be minimal and therefore not really informative to the model. Changes in sensor values become more apparent when increasing the timesteps in between lags. For example, sensor values at lag 5, 10 and 20 might differ enough to be informative. Note, by adding higher lagged variables you also throw away more rows of data, so there’s a trade-off to take into account. When the engines deteriorate and get closer to breakdown there are clear trends in the sensors which are distinguishable between single timesteps. So personally, I choose to keep the first few lags consecutive before increasing the timesteps between lags. Let’s try a few variations and see which scores best. # Results of different lags and test RMSE# RMSE = 21.76, lags = [1,2,3,4,5]# RMSE = 21.14, lags = [1,2,3,4,5,6,7,8,9]# RMSE = 21.06, lags = [1,2,3,4,5,10,20,30]# RMSE = 20.85, lags = [1,2,3,4,5,10,20] There are of course many more possibilities, but with minimal testing and taking into account the stagnating improvement from adding more continuous lags, lags [1,2,3,4,5,10,20] performed best with a RMSE of 20.85. These results come pretty close to our SVR from last time (RMSE = 20.54). In the end, I feel the distributed lag model is a valuable addition to the possible methods for solving this use-case. It gives great flexibility and control during model development while also being easy to explain and interpret by the business. For the complete notebook you can check out my github page here. I would like to thank Wisse Smit and Maikel Grobbe for their inputs and reviewing my article. Next time we’ll delve into survival analysis. Are you able to find a combination of specific lags (not fully continuous) which performs better? Let me know in the comments below! References:[1] https://medium.com/open-machine-learning-course/open-machine-learning-course-topic-9-time-series-analysis-in-python-a270cb05e0b3[2] https://en.wikipedia.org/wiki/Augmented_Dickey%E2%80%93Fuller_test[3] https://www.statsmodels.org/stable/generated/statsmodels.tsa.stattools.adfuller.html[4] https://www.quora.com/What-is-unit-root-in-a-time-series[5] https://www.machinelearningplus.com/time-series/time-series-analysis-python/[6] https://www.quora.com/What-is-the-purpose-of-differencing-in-time-series-models[7] https://en.wikipedia.org/wiki/Akaike_information_criterion[8] https://en.wikipedia.org/wiki/Multicollinearity[9] https://www.statisticshowto.com/variance-inflation-factor/[10] https://stats.stackexchange.com/questions/332428/regression-model-constant-causes-multicollinearity-warning-but-not-in-standardi
[ { "code": null, "e": 414, "s": 171, "text": "<disclaimer: I aim to showcase the effect of different methods and choices made during model development. These effects are often shown using the test set, something which is considered (very) bad practice but helps for educational purposes.>" }, { "code": null, "e": 620, "s": 414, "text": "Welcome to another installment of the ‘Exploring NASA’s turbofan dataset’ series. This will be the third analysis on FD001, where all engines run on the same operating condition and develop the same fault." }, { "code": null, "e": 1014, "s": 620, "text": "Initially we assumed the Remaining Useful Life (RUL) of the engines to decline linearly. In my last post we re-examined this assumption by clipping any values above 125. Clipping the RUL improved the baseline linear regression by 31% (from an RMSE of 31.95 to an RMSE of 21.90). We then switched to a Support Vector Regression and squeezed out another 6% improvement for a total RMSE of 20.54." }, { "code": null, "e": 1224, "s": 1014, "text": "Today, we’ll focus on time series analysis to forecast when the engines are due for maintenance. But, before getting into the time series part, we first have to recap a few processing steps. Let’s get started!" }, { "code": null, "e": 1278, "s": 1224, "text": "First, we’ll import some libraries and read the data." }, { "code": null, "e": 1398, "s": 1278, "text": "Looks good. Next, the linear declining RUL is computed (clipping is added later) and uninformative columns are dropped." }, { "code": null, "e": 1457, "s": 1398, "text": "Nice, with that out of the way let’s discuss our approach." }, { "code": null, "e": 1562, "s": 1457, "text": "Time series analysis and forecasting for this data set can be done with one of three general approaches:" }, { "code": null, "e": 2905, "s": 1562, "text": "Predicting sensor values and setting ‘alarm’ thresholds. The component is deteriorated to a state in which breakdown is imminent when a sensor is predicted to cross this threshold. There are a few caveats using this approach for the current dataset.(a) Every sensor has to be modelled individually, therefore we cannot make use of interactions between sensors.(b) it requires a lot of domain knowledge for setting the appropriate thresholds and (c) it doesn’t directly inform us about our target feature, the Remaining Useful Life (RUL).Vector Autoregression (VAR) type models. These types of models can handle multivariate timeseries, however the model initially creates lags of both our X and Y variables. Normally in timeseries the past values of Y play a large role in determining future values of Y. But since we assume our values for Y to be constant or linearly declining in the training set, incorporating these self-defined targets in the model and using them for prediction would highly influence model results and overemphasize the effect of Yt-1 on Yt. You could write some custom code to set the coefficients for the weights of the lagged Y variables to 0, but in my opinion, there is an easier method.Distributed lag models. Basically, a regression model where you have full control over how many lags you add for each variable." }, { "code": null, "e": 3443, "s": 2905, "text": "Predicting sensor values and setting ‘alarm’ thresholds. The component is deteriorated to a state in which breakdown is imminent when a sensor is predicted to cross this threshold. There are a few caveats using this approach for the current dataset.(a) Every sensor has to be modelled individually, therefore we cannot make use of interactions between sensors.(b) it requires a lot of domain knowledge for setting the appropriate thresholds and (c) it doesn’t directly inform us about our target feature, the Remaining Useful Life (RUL)." }, { "code": null, "e": 4122, "s": 3443, "text": "Vector Autoregression (VAR) type models. These types of models can handle multivariate timeseries, however the model initially creates lags of both our X and Y variables. Normally in timeseries the past values of Y play a large role in determining future values of Y. But since we assume our values for Y to be constant or linearly declining in the training set, incorporating these self-defined targets in the model and using them for prediction would highly influence model results and overemphasize the effect of Yt-1 on Yt. You could write some custom code to set the coefficients for the weights of the lagged Y variables to 0, but in my opinion, there is an easier method." }, { "code": null, "e": 4250, "s": 4122, "text": "Distributed lag models. Basically, a regression model where you have full control over how many lags you add for each variable." }, { "code": null, "e": 4430, "s": 4250, "text": "In creating a distributed lag model, we can use many of the tools and tests from both time series and regression analyses. However, we’ll start small and add complexity as needed." }, { "code": null, "e": 4501, "s": 4430, "text": "In its basic form the model we’re going to implement looks as follows:" }, { "code": null, "e": 4542, "s": 4501, "text": "Yt = a + B1*Xt + B2*Xt-1 + ... + Bn*Xt-n" }, { "code": null, "e": 4927, "s": 4542, "text": "Where a is the intercept and B1 to Bn are the coefficients. Xt-1 and Xt-n are the lagged variables of Xt, with a lag of one till n respectively and Yt is the target variable at the current time t.Note: to be in line with previous posts we’re predicting RUL at Yt, if you want to predict the RUL of the next time_cycle (Yt+1) you can simply shift the target by one, as explained below." }, { "code": null, "e": 4985, "s": 4927, "text": "We can use Pandas shift function to add lagged variables." }, { "code": null, "e": 5258, "s": 4985, "text": "You can see the lagged columns contain data from the previous time stamps. Row 2 for example, has the data of time 0 and 1 appended. This is how we can get data from multiple time instances represented in one row, which is a convenient representation for use by our model." }, { "code": null, "e": 5426, "s": 5258, "text": "Now let’s apply this principle to our dataset. We drop the rows where NaN values were introduced as a result of adding lagged variables and fit a new regression model." }, { "code": null, "e": 5564, "s": 5426, "text": "# returns# train set RMSE:39.367692351135005, Variance:0.6709929595362338# test set RMSE:31.423109839706022, Variance:0.42820706786532714" }, { "code": null, "e": 5749, "s": 5564, "text": "Great! Adding a lag of one already gives a small improvement upon our baseline model, which had a RMSE of 31.95. The above example showcases the basics of what we’re trying to achieve." }, { "code": null, "e": 6070, "s": 5749, "text": "Correction: In the above example I forgot to drop the index_names. The results do not improve compared to baseline when these are dropped. Thanks Xuanang Liu for pointing this out! Fortunately this has little impact on the overall flow, adding more lags will start to improve results (as you can read further down below)" }, { "code": null, "e": 6193, "s": 6070, "text": "Let’s wrap this functionality in two functions for later use, one to add lags from 1 till n, and one to add specific lags." }, { "code": null, "e": 6309, "s": 6193, "text": "There are a few assumptions to consider when applying time series analysis and regression, let’s look at those now." }, { "code": null, "e": 6537, "s": 6309, "text": "Stationarity implies the statistical properties of the time series, such as mean and variance do not change over time, in addition the covariance (spread of the time series) should not be dependent on time (see Figure 1 below)." }, { "code": null, "e": 6816, "s": 6537, "text": "It is important that these statistical properties stay constant because a lot of statistical models rely on these properties for their predictions. Hence, if the mean, variance or covariance changes with time the model would not be able to accurately predict the next value [1]." }, { "code": null, "e": 6972, "s": 6816, "text": "Fortunately, there are tests to check for stationarity in your data, and there are also methods to make time series stationary if the tests are not passed." }, { "code": null, "e": 7368, "s": 6972, "text": "To test for stationarity, we’re going to use the Augmented Dickey-Fuller test, you can check [1–5] for more information. For now, the adf-test-statistic and p-value are the most important. The more negative the test statistic, the more stationary the signal. When the p-value is below 0.05, it can be assumed the time-series is stationary. Let’s perform this test on a column of a single engine." }, { "code": null, "e": 7494, "s": 7368, "text": "# returns# single unit, single column test results# adf: -2.276666927948019 # pvalue: 0.17960380425358546# Significant: False" }, { "code": null, "e": 7632, "s": 7494, "text": "The test statistic is negative but not significant. We can difference the data once in an attempt to remove the trend and test again [6]." }, { "code": null, "e": 7780, "s": 7632, "text": "# returns# single unit, single column test results after differencing# adf: -14.824168539718967 # pvalue: 1.9431018596392618e-27# Significant: True" }, { "code": null, "e": 7855, "s": 7780, "text": "Much better, the p-value is now < 0.05 allowing us to assume stationarity." }, { "code": null, "e": 8136, "s": 7855, "text": "Note: It’s important to take into account how you implement your test, for example testing stationarity of one sensor column has the time series of all 100 engines. All engines together form a stationary signal, but signals of individual engines are not stationary! (see Figure 2)" }, { "code": null, "e": 8416, "s": 8136, "text": "Since we don’t know beforehand how many times the timeseries of each sensor of each engine needs to be differenced before becoming stationary, it’s best to create some functions which handle these steps for us. We’ll use the p-value as the decisive factor to assume stationarity." }, { "code": null, "e": 8470, "s": 8416, "text": "We apply these functions to make our data stationary." }, { "code": null, "e": 8574, "s": 8470, "text": "Let’s fit a new linear regression to get an idea of the effect of stationary data on model performance." }, { "code": null, "e": 8647, "s": 8574, "text": "# returns# train set RMSE:51.63375613791181, Variance:0.4340864011385228" }, { "code": null, "e": 8994, "s": 8647, "text": "Training RMSE has become quite a bit worse as a result of making the data stationary. This can be explained by the data no longer having a trend, making it difficult to fit a regression line. Performance will improve again when adding lagged variables, as this will inform the model of the relation between the changes in sensor values over time." }, { "code": null, "e": 9085, "s": 8994, "text": "Next, we can start our search to determine how many lags to add for optimal model results." }, { "code": null, "e": 9575, "s": 9085, "text": "The Akaike Information Criterion (AIC) is a metric which reflects model quality and is often used in time series analysis. It takes both over- and underfitting into account. When training multiple similar models, the AIC-scores can be compared for model selection [7]. A lower score is generally better, but there is usually a trade-off between complexity and model quality improvement. Let’s train some models with 0 to n lags and calculate the AIC to determine the highest quality model." }, { "code": null, "e": 9876, "s": 9575, "text": "We’re looking for a tipping point in the AIC’s indicating diminishing returns of model improvement by adding more lags. However, based on the table of metrics it does not become clear how many lags to add as the metrics seem to keep improving steadily. Let’s try plotting the AIC for any visual ques." }, { "code": null, "e": 10128, "s": 9876, "text": "Based on the graph, quality improvement seems to stagnate after 14 lags. To me this indicates the trade-off between model complexity and quality is reached at this point, as adding more lags (complexity) no longer substantially improves model quality." }, { "code": null, "e": 10263, "s": 10128, "text": "One problem with adding multiple lags of the same variable is the possibility of introducing multicollinearity, let’s check that next." }, { "code": null, "e": 10873, "s": 10263, "text": "Multicollinearity occurs when independent variables in a multiple regression model are highly correlated [8]. Due to the nature of time series, where the value of a previous timepoint is inherently related to the next value in time, the chances of introducing multicollinearity when you add lagged variables is substantial. Multicollinearity influences the models’ coefficients and stability, increasing the chance of incorrect results on new data. Let’s test the multicollinearity of our model by calculating the Variance Inflation Factor (VIF), as a rule of thumb vif-values below 5 are considered safe [9]." }, { "code": null, "e": 11272, "s": 10873, "text": "Our model seems to suffer greatly from multicollinearity with vif-values far bigger than 5. When searching for ways to reduce multicollinearity I found the method used by statsmodels for calculating multicollinearity may be heavily influenced by scaling [10]. This would be quite an easy fix, so let’s implement a scaling transformation and hope we don’t have to look further to solve our problems." }, { "code": null, "e": 11367, "s": 11272, "text": "Much better! We now have all components to train, predict and evaluate to find the best model." }, { "code": null, "e": 11440, "s": 11367, "text": "We first repeat our procedure for identifying the number of lags to add." }, { "code": null, "e": 11558, "s": 11440, "text": "The point shifted a little bit after adding scaling, model quality improvement now stagnates at 9 lags instead of 14." }, { "code": null, "e": 11699, "s": 11558, "text": "Let’s put our pipeline together and train our model with 9 lags to see how it performs. We’ll also incorporate the clipped RUL from here on." }, { "code": null, "e": 11834, "s": 11699, "text": "# returns# train set RMSE:20.80233928213837, Variance:0.7523208224684113# test set RMSE:21.14895857012398, Variance:0.7409888687595052" }, { "code": null, "e": 12476, "s": 11834, "text": "A RMSE of 21.14 isn’t bad, but I think we can squeeze out a little bit more. Currently our model uses consecutive lagged variables. However, adjacent lags do not necessarily have to hold distinctive information. For example, the change in sensor values at lag 6, 7 and 8 could be minimal and therefore not really informative to the model. Changes in sensor values become more apparent when increasing the timesteps in between lags. For example, sensor values at lag 5, 10 and 20 might differ enough to be informative. Note, by adding higher lagged variables you also throw away more rows of data, so there’s a trade-off to take into account." }, { "code": null, "e": 12786, "s": 12476, "text": "When the engines deteriorate and get closer to breakdown there are clear trends in the sensors which are distinguishable between single timesteps. So personally, I choose to keep the first few lags consecutive before increasing the timesteps between lags. Let’s try a few variations and see which scores best." }, { "code": null, "e": 12987, "s": 12786, "text": "# Results of different lags and test RMSE# RMSE = 21.76, lags = [1,2,3,4,5]# RMSE = 21.14, lags = [1,2,3,4,5,6,7,8,9]# RMSE = 21.06, lags = [1,2,3,4,5,10,20,30]# RMSE = 20.85, lags = [1,2,3,4,5,10,20]" }, { "code": null, "e": 13276, "s": 12987, "text": "There are of course many more possibilities, but with minimal testing and taking into account the stagnating improvement from adding more continuous lags, lags [1,2,3,4,5,10,20] performed best with a RMSE of 20.85. These results come pretty close to our SVR from last time (RMSE = 20.54)." }, { "code": null, "e": 13588, "s": 13276, "text": "In the end, I feel the distributed lag model is a valuable addition to the possible methods for solving this use-case. It gives great flexibility and control during model development while also being easy to explain and interpret by the business. For the complete notebook you can check out my github page here." }, { "code": null, "e": 13861, "s": 13588, "text": "I would like to thank Wisse Smit and Maikel Grobbe for their inputs and reviewing my article. Next time we’ll delve into survival analysis. Are you able to find a combination of specific lags (not fully continuous) which performs better? Let me know in the comments below!" } ]
New to Data Visualization? Start with New York City | by Thomas Hikaru Clark | Towards Data Science
Like many others, I have been working from home for several weeks due to the coronavirus. Inspired in part by Terence Shin’s great article on data science projects to try during quarantine, I decided to use some of my free time on improving my data science skills. I am a high school computer science teacher, and adding data science skills to the portfolio of content that I can teach my students is important to me, given the rising prominence of data science in today’s world. One thing I’ve learned is that if you are trying to teach yourself data visualization, New York City is a great place to start, and I will explain why in this article. Along the way, I will provide some examples of bite-size NYC-themed projects you can try to become more familiar with how to process and visualize data in Python. New York City provides a wealth of public data at a high level of granularity (in some cases down to the individual building). You can pretty easily find information about assessed property value, income brackets by zip code, locations of public facilities, and more. Additionally, there are excellent custom downloaders available to get just the data you need. The NYC Open Data website is a great starting point to search publicly available datasets and download files. NYC Open Data Portal: https://opendata.cityofnewyork.us/ The New York City government has released a dataset called PLUTO which contains tax-related information about every lot in the city. Using this massive dataset, you can all manner of information about any given plot in the city, such as the number of square feet of building space, the number of floors, the assessed property value for tax purposes, the name of the owner, and more. Additionally, the MapPLUTO dataset merges this data with geographic data, providing polygons for each lot in the city. A great tool for accessing this data is Chris Whong’s custom PLUTO downloader, which lets you select exactly which areas of the city you would like to download, along with which columns of the PLUTO data you want. Chris Whong’s NYC PLUTO custom data downloader: https://chriswhong.github.io/plutoplus/ The New York City Capital Planning Platform is another excellent custom downloaded where you view all public facilities, such as parks, schools, hospitals, youth centers, parking lots, and more. Once you have refined your selection, you can download the data as a CSV file. New York City Capital Planning Platform: https://capitalplanning.nyc.gov/map/facilities#10/40.7128/-74.0807 As an iconic global city that is simultaneously a business Mecca, a tourist hot-spot, and a backdrop for countless films and shows, New York has instant brand-name recognition. Most people probably have some basic familiarity with aspects of New York’s geography, such as Central Park, the five boroughs, some of New York’s many neighborhoods (like the Upper East Side, Harlem, etc.). This recognizability may help you make sense of your data as you are pre-processing it, or give you a sanity check on your results once you hit run. But even if you have no familiarity with the city, there is a good chance that others viewing your work will be familiar. This makes projects involving New York City data great for a personal portfolio, blog, or other medium that you wish to share with others as a demonstration of your skills. New York is both very dense and very diverse. These factors help make visualizations relating to New York City more interesting; very meaningful and data-rich visualizations can be made at the level of a single neighborhood. Its diversity gives many dimensions along which to analyze and visualize data, especially in visual or map form, including the following examples: The relationship between socioeconomic status and geography The relationship between race/ethnicity and geography The relationship between language and geography This project’s objective is to visualize each lot’s distance to the nearest library. Using a very similar process, however, you could also visualize distance to many different features of interest, such as subway stations, parks, schools, or hospitals. A choropleth map provides an excellent way to visualize this large amount of geographic data at a glance. Using this approach, it becomes easy to identify potential “reading deserts” or “green space deserts” in the city. I used the MapPLUTO dataset to load information about all lots in Manhattan, including their latitude and longitude. I also used the New York City Capital Planning Platform to download data on all libraries in Manhattan, including their names and latitude/longitude. I then loaded this data into my Python program as a Pandas DataFrame. My first attempt to calculate the nearest library for each lot was a naive brute-force approach, as seen in the snippet below. This turned out to be much too slow, owing to the large amount of redundant computation. df['dist'] = df['coord'].apply(lambda x: min([geopy.distance.distance(x, y).km for y in libs['coord']])) My big break was in remembering a lecture from college in which the professor mentioned something called a K-D tree. This is a data structure that is optimized for quickly finding the nearest neighbor of a given point. An implementation of this is contained in the sklearn.neighbors library. Since we are dealing with (latitude, longitude) coordinate pairs, we should use a BallTree with a “haversine” distance metric. Using this library to calculate the nearest library sped up the runtime by several orders of magnitude. Use choropleth maps wisely. They can be great for certain situations, but misleading in others. For example, a county-level choropleth map of 2016 presidential election results in the United States would give the impression that the overwhelming majority of the country voted red, yet this is misleading because more densely populated areas tended to vote blue.Algorithmic efficiency matters. Especially when working with large datasets, pay attention to whether you are performing many redundant computations. Do some research to see if tools exist to complete parts of your task more optimally so that you are not re-inventing the wheel. Use choropleth maps wisely. They can be great for certain situations, but misleading in others. For example, a county-level choropleth map of 2016 presidential election results in the United States would give the impression that the overwhelming majority of the country voted red, yet this is misleading because more densely populated areas tended to vote blue. Algorithmic efficiency matters. Especially when working with large datasets, pay attention to whether you are performing many redundant computations. Do some research to see if tools exist to complete parts of your task more optimally so that you are not re-inventing the wheel. Access data files and code at https://github.com/thomashikaru/nycvisualization. This project’s objective is to visualize the population density of different neighborhoods in New York City. With slight variations, the same approach can be used to visualize distribution of ethnicity, income, or other characteristics. In addition to dividing the city up into individual lots or zip codes, it is also possible to break the city up into Neighborhood Tabulation Areas. These correspond to the familiar neighborhoods of New York, such as the Upper West Side, Chinatown, or Park Slope. It was relatively easy to find a data file with each neighborhood’s population, as well as using the NYC Open Data tool to download a GeoJSON file with the polygons for neighborhood boundaries. Coloring the map by total population might be misleading because the neighborhoods vary quite widely in size. Instead, we can color by the map by population density. This requires calculating the area of each neighborhood, which is not directly contained in the data. Using the area library, we can compute each GeoJSON polygon’s area, then use these values to calculate density (population divided by area). Use choropleth maps wisely (again). The sizes of each neighborhood vary widely and are somewhat arbitrary. It is more meaningful to visualize the density of each neighborhood than the absolute population.Combining data from different sources. The population data for each neighborhood was stored in one CSV file (which I read into a Pandas DataFrame), while the polygons for each neighborhood were stored in the GeoJSON file. I went through the GeoJSON file and made a dictionary mapping each neighborhood code to its area, then used the Pandas.Series.map() function to match up neighborhoods in the DataFrame with the corresponding area in order to calculate density values. Use choropleth maps wisely (again). The sizes of each neighborhood vary widely and are somewhat arbitrary. It is more meaningful to visualize the density of each neighborhood than the absolute population. Combining data from different sources. The population data for each neighborhood was stored in one CSV file (which I read into a Pandas DataFrame), while the polygons for each neighborhood were stored in the GeoJSON file. I went through the GeoJSON file and made a dictionary mapping each neighborhood code to its area, then used the Pandas.Series.map() function to match up neighborhoods in the DataFrame with the corresponding area in order to calculate density values. Access data files and code at https://github.com/thomashikaru/nycvisualization. If you are new to data science or data visualization, consider choosing New York City as a starting point to spend less time hunting for data and more time acquiring new skills. Take advantage of the wealth of available data and the excellent custom downloaders that exist. Try one of the projects mentioned above to get familiar with useful data science tools such as Pandas and Plotly, as well as common data formats such as GeoJSON and CSV. I hope you learned something new. Best of luck in your learning journey! [1] T. Shin, 14 Data Science Projects to do During Your 14 Day Quarantine (2020), Medium. [2] N. Piepenbreier, Visualizing COVID-19 Data Beautifully in Python (in 5 Minutes or Less) (2020), Medium. [3] E. Grimaldi, How to create interactive map plots with Plotly (2020), Medium. [4] T. Shin, How To Visualize the Coronavirus Pandemic with Choropleth Maps (2020), Medium.
[ { "code": null, "e": 983, "s": 172, "text": "Like many others, I have been working from home for several weeks due to the coronavirus. Inspired in part by Terence Shin’s great article on data science projects to try during quarantine, I decided to use some of my free time on improving my data science skills. I am a high school computer science teacher, and adding data science skills to the portfolio of content that I can teach my students is important to me, given the rising prominence of data science in today’s world. One thing I’ve learned is that if you are trying to teach yourself data visualization, New York City is a great place to start, and I will explain why in this article. Along the way, I will provide some examples of bite-size NYC-themed projects you can try to become more familiar with how to process and visualize data in Python." }, { "code": null, "e": 1345, "s": 983, "text": "New York City provides a wealth of public data at a high level of granularity (in some cases down to the individual building). You can pretty easily find information about assessed property value, income brackets by zip code, locations of public facilities, and more. Additionally, there are excellent custom downloaders available to get just the data you need." }, { "code": null, "e": 1455, "s": 1345, "text": "The NYC Open Data website is a great starting point to search publicly available datasets and download files." }, { "code": null, "e": 1512, "s": 1455, "text": "NYC Open Data Portal: https://opendata.cityofnewyork.us/" }, { "code": null, "e": 2228, "s": 1512, "text": "The New York City government has released a dataset called PLUTO which contains tax-related information about every lot in the city. Using this massive dataset, you can all manner of information about any given plot in the city, such as the number of square feet of building space, the number of floors, the assessed property value for tax purposes, the name of the owner, and more. Additionally, the MapPLUTO dataset merges this data with geographic data, providing polygons for each lot in the city. A great tool for accessing this data is Chris Whong’s custom PLUTO downloader, which lets you select exactly which areas of the city you would like to download, along with which columns of the PLUTO data you want." }, { "code": null, "e": 2316, "s": 2228, "text": "Chris Whong’s NYC PLUTO custom data downloader: https://chriswhong.github.io/plutoplus/" }, { "code": null, "e": 2590, "s": 2316, "text": "The New York City Capital Planning Platform is another excellent custom downloaded where you view all public facilities, such as parks, schools, hospitals, youth centers, parking lots, and more. Once you have refined your selection, you can download the data as a CSV file." }, { "code": null, "e": 2698, "s": 2590, "text": "New York City Capital Planning Platform: https://capitalplanning.nyc.gov/map/facilities#10/40.7128/-74.0807" }, { "code": null, "e": 3083, "s": 2698, "text": "As an iconic global city that is simultaneously a business Mecca, a tourist hot-spot, and a backdrop for countless films and shows, New York has instant brand-name recognition. Most people probably have some basic familiarity with aspects of New York’s geography, such as Central Park, the five boroughs, some of New York’s many neighborhoods (like the Upper East Side, Harlem, etc.)." }, { "code": null, "e": 3527, "s": 3083, "text": "This recognizability may help you make sense of your data as you are pre-processing it, or give you a sanity check on your results once you hit run. But even if you have no familiarity with the city, there is a good chance that others viewing your work will be familiar. This makes projects involving New York City data great for a personal portfolio, blog, or other medium that you wish to share with others as a demonstration of your skills." }, { "code": null, "e": 3899, "s": 3527, "text": "New York is both very dense and very diverse. These factors help make visualizations relating to New York City more interesting; very meaningful and data-rich visualizations can be made at the level of a single neighborhood. Its diversity gives many dimensions along which to analyze and visualize data, especially in visual or map form, including the following examples:" }, { "code": null, "e": 3959, "s": 3899, "text": "The relationship between socioeconomic status and geography" }, { "code": null, "e": 4013, "s": 3959, "text": "The relationship between race/ethnicity and geography" }, { "code": null, "e": 4061, "s": 4013, "text": "The relationship between language and geography" }, { "code": null, "e": 4535, "s": 4061, "text": "This project’s objective is to visualize each lot’s distance to the nearest library. Using a very similar process, however, you could also visualize distance to many different features of interest, such as subway stations, parks, schools, or hospitals. A choropleth map provides an excellent way to visualize this large amount of geographic data at a glance. Using this approach, it becomes easy to identify potential “reading deserts” or “green space deserts” in the city." }, { "code": null, "e": 4872, "s": 4535, "text": "I used the MapPLUTO dataset to load information about all lots in Manhattan, including their latitude and longitude. I also used the New York City Capital Planning Platform to download data on all libraries in Manhattan, including their names and latitude/longitude. I then loaded this data into my Python program as a Pandas DataFrame." }, { "code": null, "e": 5088, "s": 4872, "text": "My first attempt to calculate the nearest library for each lot was a naive brute-force approach, as seen in the snippet below. This turned out to be much too slow, owing to the large amount of redundant computation." }, { "code": null, "e": 5193, "s": 5088, "text": "df['dist'] = df['coord'].apply(lambda x: min([geopy.distance.distance(x, y).km for y in libs['coord']]))" }, { "code": null, "e": 5716, "s": 5193, "text": "My big break was in remembering a lecture from college in which the professor mentioned something called a K-D tree. This is a data structure that is optimized for quickly finding the nearest neighbor of a given point. An implementation of this is contained in the sklearn.neighbors library. Since we are dealing with (latitude, longitude) coordinate pairs, we should use a BallTree with a “haversine” distance metric. Using this library to calculate the nearest library sped up the runtime by several orders of magnitude." }, { "code": null, "e": 6356, "s": 5716, "text": "Use choropleth maps wisely. They can be great for certain situations, but misleading in others. For example, a county-level choropleth map of 2016 presidential election results in the United States would give the impression that the overwhelming majority of the country voted red, yet this is misleading because more densely populated areas tended to vote blue.Algorithmic efficiency matters. Especially when working with large datasets, pay attention to whether you are performing many redundant computations. Do some research to see if tools exist to complete parts of your task more optimally so that you are not re-inventing the wheel." }, { "code": null, "e": 6718, "s": 6356, "text": "Use choropleth maps wisely. They can be great for certain situations, but misleading in others. For example, a county-level choropleth map of 2016 presidential election results in the United States would give the impression that the overwhelming majority of the country voted red, yet this is misleading because more densely populated areas tended to vote blue." }, { "code": null, "e": 6997, "s": 6718, "text": "Algorithmic efficiency matters. Especially when working with large datasets, pay attention to whether you are performing many redundant computations. Do some research to see if tools exist to complete parts of your task more optimally so that you are not re-inventing the wheel." }, { "code": null, "e": 7077, "s": 6997, "text": "Access data files and code at https://github.com/thomashikaru/nycvisualization." }, { "code": null, "e": 7314, "s": 7077, "text": "This project’s objective is to visualize the population density of different neighborhoods in New York City. With slight variations, the same approach can be used to visualize distribution of ethnicity, income, or other characteristics." }, { "code": null, "e": 7771, "s": 7314, "text": "In addition to dividing the city up into individual lots or zip codes, it is also possible to break the city up into Neighborhood Tabulation Areas. These correspond to the familiar neighborhoods of New York, such as the Upper West Side, Chinatown, or Park Slope. It was relatively easy to find a data file with each neighborhood’s population, as well as using the NYC Open Data tool to download a GeoJSON file with the polygons for neighborhood boundaries." }, { "code": null, "e": 8180, "s": 7771, "text": "Coloring the map by total population might be misleading because the neighborhoods vary quite widely in size. Instead, we can color by the map by population density. This requires calculating the area of each neighborhood, which is not directly contained in the data. Using the area library, we can compute each GeoJSON polygon’s area, then use these values to calculate density (population divided by area)." }, { "code": null, "e": 8856, "s": 8180, "text": "Use choropleth maps wisely (again). The sizes of each neighborhood vary widely and are somewhat arbitrary. It is more meaningful to visualize the density of each neighborhood than the absolute population.Combining data from different sources. The population data for each neighborhood was stored in one CSV file (which I read into a Pandas DataFrame), while the polygons for each neighborhood were stored in the GeoJSON file. I went through the GeoJSON file and made a dictionary mapping each neighborhood code to its area, then used the Pandas.Series.map() function to match up neighborhoods in the DataFrame with the corresponding area in order to calculate density values." }, { "code": null, "e": 9061, "s": 8856, "text": "Use choropleth maps wisely (again). The sizes of each neighborhood vary widely and are somewhat arbitrary. It is more meaningful to visualize the density of each neighborhood than the absolute population." }, { "code": null, "e": 9533, "s": 9061, "text": "Combining data from different sources. The population data for each neighborhood was stored in one CSV file (which I read into a Pandas DataFrame), while the polygons for each neighborhood were stored in the GeoJSON file. I went through the GeoJSON file and made a dictionary mapping each neighborhood code to its area, then used the Pandas.Series.map() function to match up neighborhoods in the DataFrame with the corresponding area in order to calculate density values." }, { "code": null, "e": 9613, "s": 9533, "text": "Access data files and code at https://github.com/thomashikaru/nycvisualization." }, { "code": null, "e": 9887, "s": 9613, "text": "If you are new to data science or data visualization, consider choosing New York City as a starting point to spend less time hunting for data and more time acquiring new skills. Take advantage of the wealth of available data and the excellent custom downloaders that exist." }, { "code": null, "e": 10057, "s": 9887, "text": "Try one of the projects mentioned above to get familiar with useful data science tools such as Pandas and Plotly, as well as common data formats such as GeoJSON and CSV." }, { "code": null, "e": 10130, "s": 10057, "text": "I hope you learned something new. Best of luck in your learning journey!" }, { "code": null, "e": 10220, "s": 10130, "text": "[1] T. Shin, 14 Data Science Projects to do During Your 14 Day Quarantine (2020), Medium." }, { "code": null, "e": 10328, "s": 10220, "text": "[2] N. Piepenbreier, Visualizing COVID-19 Data Beautifully in Python (in 5 Minutes or Less) (2020), Medium." }, { "code": null, "e": 10409, "s": 10328, "text": "[3] E. Grimaldi, How to create interactive map plots with Plotly (2020), Medium." } ]
Make the button size small with Bootstrap
To make a small button, use the .btn-sm Bootstrap class. You can try to run the following code to make small size of button − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <button type = "button" class = "btn btn-default btn-sm"> Small button </button> </body> </html>
[ { "code": null, "e": 1119, "s": 1062, "text": "To make a small button, use the .btn-sm Bootstrap class." }, { "code": null, "e": 1188, "s": 1119, "text": "You can try to run the following code to make small size of button −" }, { "code": null, "e": 1198, "s": 1188, "text": "Live Demo" }, { "code": null, "e": 1807, "s": 1198, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <button type = \"button\" class = \"btn btn-default btn-sm\">\n Small button\n </button>\n </body>\n</html>" } ]
showq - Unix, Linux Command
showq [generic Postfix daemon options] The showq(8) daemon can also be run in stand-alone mode by the superuser. This mode of operation is used to emulate the ‘mailq’ command while the Postfix mail system is down. The text below provides only a parameter summary. See postconf(5) for more details including examples. /var/spool/postfix, queue directories pickup(8), local mail pickup service cleanup(8), canonicalize and enqueue mail qmgr(8), queue manager postconf(5), configuration parameters master(8), process manager syslogd(8), system logging Wietse Venema IBM T.J. Watson Research P.O. Box 704 Yorktown Heights, NY 10598, USA Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10617, "s": 10577, "text": "showq [generic Postfix daemon options]\n" }, { "code": null, "e": 10794, "s": 10617, "text": "\nThe showq(8) daemon can also be run in stand-alone mode\nby the superuser. This mode of operation is used to emulate\nthe ‘mailq’ command while the Postfix mail system is down.\n" }, { "code": null, "e": 10905, "s": 10800, "text": "\nThe text below provides only a parameter summary. See\npostconf(5) for more details including examples.\n" }, { "code": null, "e": 10944, "s": 10905, "text": "/var/spool/postfix, queue directories\n" }, { "code": null, "e": 11139, "s": 10944, "text": "pickup(8), local mail pickup service\ncleanup(8), canonicalize and enqueue mail\nqmgr(8), queue manager\npostconf(5), configuration parameters\nmaster(8), process manager\nsyslogd(8), system logging\n" }, { "code": null, "e": 11226, "s": 11141, "text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n" }, { "code": null, "e": 11243, "s": 11226, "text": "\nAdvertisements\n" }, { "code": null, "e": 11278, "s": 11243, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11306, "s": 11278, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11340, "s": 11306, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11357, "s": 11340, "text": " Frahaan Hussain" }, { "code": null, "e": 11390, "s": 11357, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11401, "s": 11390, "text": " Pradeep D" }, { "code": null, "e": 11436, "s": 11401, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11452, "s": 11436, "text": " Musab Zayadneh" }, { "code": null, "e": 11485, "s": 11452, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11497, "s": 11485, "text": " GUHARAJANM" }, { "code": null, "e": 11529, "s": 11497, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11537, "s": 11529, "text": " Uplatz" }, { "code": null, "e": 11544, "s": 11537, "text": " Print" }, { "code": null, "e": 11555, "s": 11544, "text": " Add Notes" } ]
NumPy Array Manipulation. A practical guide to modify the shape... | by Soner Yıldırım | Towards Data Science
Everything about data science starts with data and it comes in various formats. Numbers, images, texts, x-rays, sound and video recordings are just some examples of data sources. Whatever the format data comes in, it needs to be converted to an array of numbers to be analyzed. Complex computer vision models cannot see or process an image like a human being. An image is converted to an array of numbers before analyzed. Hence, it is crucial to effectively store and modify arrays of numbers in data science.NumPy (Numerical Python) is a scientific computing package that offers very functional ways to create and operate on arrays of numbers. In this post, I will cover the ways to manipulate the shape of an array in NumPy using the following operations: Reshape Expand_dims Ravel and Flatten If you would like to read about the basics of NumPy, you can visit the following post: towardsdatascience.com Let’s start with importing NumPy: import numpy as np Tip: NumPy arrays are much more efficient than lists in terms of storage and processing. Numpy provides flexible tools to change the dimension of an array. Before changing the dimension, it is better to remember what dimension of an array means and how arrays with different dimension look like: a = np.random.randint(10, size=5)aarray([9, 7, 3, 7, 5])a.ndim1a.shape(5,0) We can also create multidimensional arrays with numpy: # 2-dimensionalb = np.zeros((3,4))barray([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])b.ndim2# 3-dimensionalc = np.ones((2,2,2))carray([[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]]])c.ndim3 There are different ways to change the dimension of an array. Reshape function is commonly used to modify the shape and thus the dimension of an array. We just need to pass the new shape as an argument to reshape function: Tip: I use different ways when creating arrays for examples so that you will also get familiar with creating arrays. np.arange(6)array([0, 1, 2, 3, 4, 5])np.arange(6).reshape(2,3)array([[0, 1, 2], [3, 4, 5]]) Reshape (2,3) returns a new array with 2 rows and 3 columns which is 2-dimensional. So the array that we apply reshape(2,3) must be 6 elements. Let’s also create a 3-dimensional array using reshape: np.arange(8).reshape(2,2,2)array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) One very useful feature of reshape function is that if you do not know the number of elements in the original array, you can specify one of the dimensions as “-1”. Since we almost always work with very large arrays, it is also convenient to type (-1,1) instead of (100000,1). Tip: When reshaping arrays, the new shape needs to be compatible with the original shape. np.arange(6).reshape(-1,2)array([[0, 1], [2, 3], [4, 5]])np.arange(6).reshape(-1,3)array([[0, 1, 2], [3, 4, 5]]) It is also possible to increase the dimension without changing the sequence of elements. We can achieve it by reshape(-1,1) or (1,-1): np.random.normal(0,1,3)array([-0.14788456, 0.01909406, 0.88659889])np.random.normal(0,1,3).reshape(-1,1)array([[-0.14588167], [ 0.06871804], [ 2.32699261]])np.random.normal(0,1,3).reshape(1,-1)array([[ 1.46812451, 0.48818206, -0.80228877]]) As the name suggests, expand_dims expands the shape of an array. a = np.array([1,2,3])np.expand_dims(a, axis=0)array([[1, 2, 3]])np.expand_dims(a, axis=1)array([[1], [2], [3]]) axis parameter allows to choose through which axis the expansion is done. expand_dims with axis=1 is equivalent to reshape(-1,1). np.expand_dims(a, axis=1)array([[1], [2], [3]])np.expand_dims(a, axis=1)array([[1], [2], [3]]) Ravel returns a flattened array. If you are familiar with convolutional neural netwoks (CNN), pooled feature maps are flattened before feeding to fully connected layer. This operation is converting a 2-D array to a 1-D array. a = np.random.randint(10, size=(2,3))aarray([[6, 8, 2], [5, 1, 8]])np.ravel(a)array([6, 8, 2, 5, 1, 8]) Second row is concatenated at the end of first row. Ravel function also allows to column-wise concatenation using order parameter: np.ravel(a, order='F')array([6, 5, 8, 1, 2, 8]) Flatten also performs the same operation: array([[3, 5, 2], [6, 7, 8]])a.flatten()array([3, 5, 2, 6, 7, 8]) The difference between ravel and flatten: Ravel: Returns a view of the original array when possible. Flatten: Always returns a copy of the original array. Therefore, the changes you make on an array return by flatten will never be made on the original array. However, if you modify the returned array by ravel, you may also change the original array. Let’s go over an example to make it clear: array([[3, 5, 2], [6, 7, 8]])a.flatten()[0] = 10aarray([[3, 5, 2], [6, 7, 8]])np.ravel(a)[0] = 10aarray([[10, 5, 2], [ 6, 7, 8]]) As you can see, the changes we make on ravel also changed the original array. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 816, "s": 171, "text": "Everything about data science starts with data and it comes in various formats. Numbers, images, texts, x-rays, sound and video recordings are just some examples of data sources. Whatever the format data comes in, it needs to be converted to an array of numbers to be analyzed. Complex computer vision models cannot see or process an image like a human being. An image is converted to an array of numbers before analyzed. Hence, it is crucial to effectively store and modify arrays of numbers in data science.NumPy (Numerical Python) is a scientific computing package that offers very functional ways to create and operate on arrays of numbers." }, { "code": null, "e": 929, "s": 816, "text": "In this post, I will cover the ways to manipulate the shape of an array in NumPy using the following operations:" }, { "code": null, "e": 937, "s": 929, "text": "Reshape" }, { "code": null, "e": 949, "s": 937, "text": "Expand_dims" }, { "code": null, "e": 967, "s": 949, "text": "Ravel and Flatten" }, { "code": null, "e": 1054, "s": 967, "text": "If you would like to read about the basics of NumPy, you can visit the following post:" }, { "code": null, "e": 1077, "s": 1054, "text": "towardsdatascience.com" }, { "code": null, "e": 1111, "s": 1077, "text": "Let’s start with importing NumPy:" }, { "code": null, "e": 1130, "s": 1111, "text": "import numpy as np" }, { "code": null, "e": 1219, "s": 1130, "text": "Tip: NumPy arrays are much more efficient than lists in terms of storage and processing." }, { "code": null, "e": 1426, "s": 1219, "text": "Numpy provides flexible tools to change the dimension of an array. Before changing the dimension, it is better to remember what dimension of an array means and how arrays with different dimension look like:" }, { "code": null, "e": 1502, "s": 1426, "text": "a = np.random.randint(10, size=5)aarray([9, 7, 3, 7, 5])a.ndim1a.shape(5,0)" }, { "code": null, "e": 1557, "s": 1502, "text": "We can also create multidimensional arrays with numpy:" }, { "code": null, "e": 1832, "s": 1557, "text": "# 2-dimensionalb = np.zeros((3,4))barray([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])b.ndim2# 3-dimensionalc = np.ones((2,2,2))carray([[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]]])c.ndim3" }, { "code": null, "e": 2055, "s": 1832, "text": "There are different ways to change the dimension of an array. Reshape function is commonly used to modify the shape and thus the dimension of an array. We just need to pass the new shape as an argument to reshape function:" }, { "code": null, "e": 2172, "s": 2055, "text": "Tip: I use different ways when creating arrays for examples so that you will also get familiar with creating arrays." }, { "code": null, "e": 2278, "s": 2172, "text": "np.arange(6)array([0, 1, 2, 3, 4, 5])np.arange(6).reshape(2,3)array([[0, 1, 2], [3, 4, 5]])" }, { "code": null, "e": 2422, "s": 2278, "text": "Reshape (2,3) returns a new array with 2 rows and 3 columns which is 2-dimensional. So the array that we apply reshape(2,3) must be 6 elements." }, { "code": null, "e": 2477, "s": 2422, "text": "Let’s also create a 3-dimensional array using reshape:" }, { "code": null, "e": 2597, "s": 2477, "text": "np.arange(8).reshape(2,2,2)array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])" }, { "code": null, "e": 2761, "s": 2597, "text": "One very useful feature of reshape function is that if you do not know the number of elements in the original array, you can specify one of the dimensions as “-1”." }, { "code": null, "e": 2873, "s": 2761, "text": "Since we almost always work with very large arrays, it is also convenient to type (-1,1) instead of (100000,1)." }, { "code": null, "e": 2963, "s": 2873, "text": "Tip: When reshaping arrays, the new shape needs to be compatible with the original shape." }, { "code": null, "e": 3118, "s": 2963, "text": "np.arange(6).reshape(-1,2)array([[0, 1], [2, 3], [4, 5]])np.arange(6).reshape(-1,3)array([[0, 1, 2], [3, 4, 5]])" }, { "code": null, "e": 3253, "s": 3118, "text": "It is also possible to increase the dimension without changing the sequence of elements. We can achieve it by reshape(-1,1) or (1,-1):" }, { "code": null, "e": 3525, "s": 3253, "text": "np.random.normal(0,1,3)array([-0.14788456, 0.01909406, 0.88659889])np.random.normal(0,1,3).reshape(-1,1)array([[-0.14588167], [ 0.06871804], [ 2.32699261]])np.random.normal(0,1,3).reshape(1,-1)array([[ 1.46812451, 0.48818206, -0.80228877]])" }, { "code": null, "e": 3590, "s": 3525, "text": "As the name suggests, expand_dims expands the shape of an array." }, { "code": null, "e": 3730, "s": 3590, "text": "a = np.array([1,2,3])np.expand_dims(a, axis=0)array([[1, 2, 3]])np.expand_dims(a, axis=1)array([[1], [2], [3]])" }, { "code": null, "e": 3804, "s": 3730, "text": "axis parameter allows to choose through which axis the expansion is done." }, { "code": null, "e": 3860, "s": 3804, "text": "expand_dims with axis=1 is equivalent to reshape(-1,1)." }, { "code": null, "e": 4011, "s": 3860, "text": "np.expand_dims(a, axis=1)array([[1], [2], [3]])np.expand_dims(a, axis=1)array([[1], [2], [3]])" }, { "code": null, "e": 4237, "s": 4011, "text": "Ravel returns a flattened array. If you are familiar with convolutional neural netwoks (CNN), pooled feature maps are flattened before feeding to fully connected layer. This operation is converting a 2-D array to a 1-D array." }, { "code": null, "e": 4355, "s": 4237, "text": "a = np.random.randint(10, size=(2,3))aarray([[6, 8, 2], [5, 1, 8]])np.ravel(a)array([6, 8, 2, 5, 1, 8])" }, { "code": null, "e": 4486, "s": 4355, "text": "Second row is concatenated at the end of first row. Ravel function also allows to column-wise concatenation using order parameter:" }, { "code": null, "e": 4534, "s": 4486, "text": "np.ravel(a, order='F')array([6, 5, 8, 1, 2, 8])" }, { "code": null, "e": 4576, "s": 4534, "text": "Flatten also performs the same operation:" }, { "code": null, "e": 4656, "s": 4576, "text": "array([[3, 5, 2], [6, 7, 8]])a.flatten()array([3, 5, 2, 6, 7, 8])" }, { "code": null, "e": 4698, "s": 4656, "text": "The difference between ravel and flatten:" }, { "code": null, "e": 4757, "s": 4698, "text": "Ravel: Returns a view of the original array when possible." }, { "code": null, "e": 4811, "s": 4757, "text": "Flatten: Always returns a copy of the original array." }, { "code": null, "e": 5050, "s": 4811, "text": "Therefore, the changes you make on an array return by flatten will never be made on the original array. However, if you modify the returned array by ravel, you may also change the original array. Let’s go over an example to make it clear:" }, { "code": null, "e": 5226, "s": 5050, "text": "array([[3, 5, 2], [6, 7, 8]])a.flatten()[0] = 10aarray([[3, 5, 2], [6, 7, 8]])np.ravel(a)[0] = 10aarray([[10, 5, 2], [ 6, 7, 8]])" }, { "code": null, "e": 5304, "s": 5226, "text": "As you can see, the changes we make on ravel also changed the original array." } ]
Spring Security - Form Login, Remember Me and Logout
Introduction and Overview Getting Started (Practical Guide) Spring Security comes with a ton of built-in features and tools for our convenience. In this example, we are going to discuss three of those interesting and useful features − Form-login Remember Me Logout Form-based login is one form of Username/password authentication that Spring Security provides support for. This is provided through an Html form. Whenever a user requests a protected resource, Spring Security checks for the authentication of the request. If the request is not authenticated/authorized, the user will be redirected to the login page. The login page must be somehow rendered by the application. Spring Security provides that login form by default. Moreover, any other configuration, if needed, must be explicitly provided as given below − protected void configure(HttpSecurity http) throws Exception { http // ... .formLogin( form -> form .loginPage("/login") .permitAll() ); } This code requires a login.html file to be present in the templates folder which would be returned on hitting the /login. This HTML file should contain a login form. Furthermore, the request should be a post request to /login. The parameter names should be “username” and “password” for username and password respectively. In addition to this, a CSRF Token also needs to be included with the form. The above code snippet will be clearer once we are done with code exercise. This type of authentication requires a remember-me cookie to be sent to the browser. This cookie stores user information/authentication principal and it is stored in the browser. So, the website can remember the identity of the user next time when the session is started. Spring Security has the necessary implementations in place for this operation. One uses hashing to preserve the security of cookie-based tokens while the other uses a database or other persistent storage mechanism to store the generated tokens. The default URL /logout logs the user out by− Invalidating the HTTP Session Cleaning up any RememberMe authentication that was configured Clearing the SecurityContextHolder Redirect to /login?logout WebSecurityConfigurerAdapter automatically applies logout capabilities to the Spring Boot application. Getting Started (Practical Guide) As usual, we shall start by going to start.spring.io. Here we choose a maven project. We name the project “formlogin” and choose the desired Java version. I am choosing Java 8 for this example. We also go on to add the following dependencies − Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let’s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. Let’s take a look at our pom.xml file. It should look something similar to this − <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId> com.spring.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Let’s create a package in our folder /src/main/java under the default package. We shall be naming it as config as we would place all our configuration classes here. So, the name should look something similar to this – com.tutorial.spring.security.formlogin.config. package com.tutorial.spring.security.formlogin.config; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.spring.security.formlogin.AuthFilter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean protected UserDetailsService userDetailsService() { UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); UserDetails user = User.withUsername("abby") .password(passwordEncoder().encode("12345")) .authorities("read") .build(); userDetailsManager.createUser(user); return userDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().anyRequest() .authenticated() .and() .formLogin() .and() .rememberMe() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .deleteCookies("remember-me"); } } Inside of our config package, we have created the WebSecurityConfig class. This class extends the WebSecurityConfigurerAdapter of Spring Security. We shall be using this class for our security configurations, so let’s annotate it with an @Configuration annotation. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. Let’s take a look at our configuration class. First, we shall create a bean of our UserDetailsService class by using the userDetailsService() method. We shall be using this bean for managing our users for this application. Here, to keep things simple, we shall use an InMemoryUserDetailsManager instance to create a user. This user, along with our given username and password, will contain a simple “read” authority. Now, let’s look at our PasswordEncoder. We shall be using a BCryptPasswordEncoder instance for this example. Hence, while creating the user, we used the passwordEncoder to encode our plaintext password like this .password(passwordEncoder().encode("12345")) After the above steps, we move on to our next configuration. Here, we override the configure method of WebSecurityConfigurerAdapter class. This method takes HttpSecurity as a parameter. We shall be configuring this to use our form login and logout, as well as a remember-me function. Http Security Configuration We can observe that all these functionalities are available in Spring Security. Let’s study the below section in detail − http.csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() .formLogin() .and() .rememberMe() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .deleteCookies("remember-me"); There are a few points to note here − We have disabled csrf or Cross-Site Request Forgery protection As this is a simple application only for demonstration purposes, we can safely disable this for now. Then we add configuration which requires all requests to be authenticated. As we shall see later, we will have a single “/” endpoint for the index page of this application, for simplicity. After that, we shall be using the formLogin() functionality of Spring Security as mentioned above. This generates a simple login page. Then, we use the rememberMe() functionality of Spring Security. This will perform two things. Firstly, it will add a “Remember Me” checkbox to our default login form that we generated using formLogin(). And, secondly, ticking the checkbox generates the remember-me cookie. The cookie stores the identity of the user and the browser stores it. Spring Security detects the cookie in future sessions to automate the login. As a result, the user can access the application again without logging in again. And lastly, we have the logout() functionality. For this too, a default functionality has been provided by Spring security. Here it performs two important functions − Invalidates the Http session, and unbinds objects bound to the session. It clears the remember-me cookie. Removes the authentication from Spring’s Security context. We also, provided a logoutSuccessUrl(), so that the application comes back to the login page after logout. This completes our application configuration. We shall now create a dummy index page now for the user to view when he logs in. It will also contain a logout button. In our /src/main/resources/templates, we add a index.html file.Then add some Html content to it. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>Hello, world!</h1> <a href="logout">logout</a> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> This content is from Bootstrap 4 getting started template. We also add <a href="logout">logout</a> to our file, so as the user can log out of the application using this link. The Resource Controller We have created the protected resource, we now add the controller to serve this resource. package com.tutorial.spring.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping("/") public String home() { return "index"; } } As we can see, it is a very simple controller. It only has a get endpoint which serves our index.html file when the start our application. Let’s run the application as a Spring Boot Application. We can go to http://localhost:8080 on our browser when the application starts. It should ask us for username and password. Additionally, we shall also be able to see the remember-me checkbox. Now, if we provide the user information as we had configured in our WebSecurity config file, we shall be able to log in. Also, if we tick the remember-me checkbox, we shall be able to see the remember-me cookie in our browser’s developer tools section. As we can see the cookie is sent along with our login request. Also, included in the web page is a link for log out. On clicking the link, we shall be logged out of our application and sent back to our login page. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 1861, "s": 1835, "text": "Introduction and Overview" }, { "code": null, "e": 1895, "s": 1861, "text": "Getting Started (Practical Guide)" }, { "code": null, "e": 2070, "s": 1895, "text": "Spring Security comes with a ton of built-in features and tools for our convenience. In this example, we are going to discuss three of those interesting and useful features −" }, { "code": null, "e": 2081, "s": 2070, "text": "Form-login" }, { "code": null, "e": 2093, "s": 2081, "text": "Remember Me" }, { "code": null, "e": 2100, "s": 2093, "text": "Logout" }, { "code": null, "e": 2247, "s": 2100, "text": "Form-based login is one form of Username/password authentication that Spring Security provides support for. This is provided through an Html form." }, { "code": null, "e": 2564, "s": 2247, "text": "Whenever a user requests a protected resource, Spring Security checks for the authentication of the request. If the request is not authenticated/authorized, the user will be redirected to the login page. The login page must be somehow rendered by the application. Spring Security provides that login form by default." }, { "code": null, "e": 2655, "s": 2564, "text": "Moreover, any other configuration, if needed, must be explicitly provided as given below −" }, { "code": null, "e": 2826, "s": 2655, "text": "protected void configure(HttpSecurity http) throws Exception {\nhttp \n // ... \n .formLogin(\n form -> form .loginPage(\"/login\") \n .permitAll() \n ); \n}" }, { "code": null, "e": 3224, "s": 2826, "text": "This code requires a login.html file to be present in the templates folder which would be returned on hitting the /login. This HTML file should contain a login form. Furthermore, the request should be a post request to /login. The parameter names should be “username” and “password” for username and password respectively. In addition to this, a CSRF Token also needs to be included with the form." }, { "code": null, "e": 3300, "s": 3224, "text": "The above code snippet will be clearer once we are done with code exercise." }, { "code": null, "e": 3817, "s": 3300, "text": "This type of authentication requires a remember-me cookie to be sent to the browser. This cookie stores user information/authentication principal and it is stored in the browser. So, the website can remember the identity of the user next time when the session is started. Spring Security has the necessary implementations in place for this operation. One uses hashing to preserve the security of cookie-based tokens while the other uses a database or other persistent storage mechanism to store the generated tokens." }, { "code": null, "e": 3863, "s": 3817, "text": "The default URL /logout logs the user out by−" }, { "code": null, "e": 3893, "s": 3863, "text": "Invalidating the HTTP Session" }, { "code": null, "e": 3955, "s": 3893, "text": "Cleaning up any RememberMe authentication that was configured" }, { "code": null, "e": 3990, "s": 3955, "text": "Clearing the SecurityContextHolder" }, { "code": null, "e": 4016, "s": 3990, "text": "Redirect to /login?logout" }, { "code": null, "e": 4119, "s": 4016, "text": "WebSecurityConfigurerAdapter automatically applies logout capabilities to the Spring Boot application." }, { "code": null, "e": 4397, "s": 4119, "text": "Getting Started (Practical Guide) As usual, we shall start by going to start.spring.io. Here we choose a maven project. We name the project “formlogin” and choose the desired Java version. I am choosing Java 8 for this example. We also go on to add the following dependencies −" }, { "code": null, "e": 4408, "s": 4397, "text": "Spring Web" }, { "code": null, "e": 4424, "s": 4408, "text": "Spring Security" }, { "code": null, "e": 4434, "s": 4424, "text": "Thymeleaf" }, { "code": null, "e": 4455, "s": 4434, "text": "Spring Boot DevTools" }, { "code": null, "e": 4779, "s": 4455, "text": "Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link." }, { "code": null, "e": 5066, "s": 4779, "text": "Let’s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications." }, { "code": null, "e": 5148, "s": 5066, "text": "Let’s take a look at our pom.xml file. It should look something similar to this −" }, { "code": null, "e": 7357, "s": 5148, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion> \n <parent> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-parent</artifactId> \n <version>2.3.1.RELEASE</version> \n <relativePath /> \n <!-- lookup parent from repository --> \n </parent> \n <groupId> com.spring.security</groupId> \n <artifactId>formlogin</artifactId> \n <version>0.0.1-SNAPSHOT</version> \n <name>formlogin</name> \n <description>Demo project for Spring Boot</description> \n \n <properties> \n <java.version>1.8</java.version> \n </properties> \n \n <dependencies> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-security</artifactId>\n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-web</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-thymeleaf</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-devtools</artifactId> \n </dependency> \n <dependency> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-starter-test</artifactId> \n <scope>test</scope> \n <exclusions> \n <exclusion> \n <groupId>org.junit.vintage</groupId>\n <artifactId>junit-vintage-engine</artifactId> \n </exclusion> \n </exclusions> \n </dependency> \n <dependency> \n <groupId>org.springframework.security</groupId> \n <artifactId>spring-security-test</artifactId> \n <scope>test</scope> \n </dependency> \n </dependencies> \n\n <build> \n <plugins> \n <plugin> \n <groupId>org.springframework.boot</groupId> \n <artifactId>spring-boot-maven-plugin</artifactId> \n </plugin> \n </plugins> \n </build>\n</project>" }, { "code": null, "e": 7622, "s": 7357, "text": "Let’s create a package in our folder /src/main/java under the default package. We shall be naming it as config as we would place all our configuration classes here. So, the name should look something similar to this – com.tutorial.spring.security.formlogin.config." }, { "code": null, "e": 9773, "s": 7622, "text": "package com.tutorial.spring.security.formlogin.config; \n\nimport java.util.List; \nimport org.springframework.beans.factory.annotation.Autowired; \nimport org.springframework.context.annotation.Bean; \nimport org.springframework.context.annotation.Configuration; \nimport org.springframework.security.config.annotation.web.builders.HttpSecurity; \nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; \nimport org.springframework.security.core.userdetails.User; \nimport org.springframework.security.core.userdetails.UserDetails; \nimport org.springframework.security.core.userdetails.UserDetailsService; \nimport org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; \nimport org.springframework.security.crypto.password.NoOpPasswordEncoder; \nimport org.springframework.security.crypto.password.PasswordEncoder; \nimport org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.UserDetailsManager;\nimport org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; \nimport org.springframework.security.web.util.matcher.AntPathRequestMatcher; \n\nimport com.spring.security.formlogin.AuthFilter;\n \n@Configuration \npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter { \n \n @Bean \n protected UserDetailsService userDetailsService() {\n UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(); \n UserDetails user = User.withUsername(\"abby\") \n .password(passwordEncoder().encode(\"12345\")) \n .authorities(\"read\") .build(); \n userDetailsManager.createUser(user); \n return userDetailsManager; \n \n }\n @Bean \n public PasswordEncoder passwordEncoder() { \n return new BCryptPasswordEncoder(); }; \n @Override \n protected void configure(HttpSecurity http) throws Exception { \n http.csrf().disable() .authorizeRequests().anyRequest()\n .authenticated() .and() \n .formLogin() \n .and() \n .rememberMe() \n .and() .logout() .logoutUrl(\"/logout\") \n .logoutSuccessUrl(\"/login\") .deleteCookies(\"remember-me\"); \n } \n}" }, { "code": null, "e": 10192, "s": 9773, "text": "Inside of our config package, we have created the WebSecurityConfig class. This class extends the WebSecurityConfigurerAdapter of Spring Security. We shall be using this class for our security configurations, so let’s annotate it with an @Configuration annotation. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring." }, { "code": null, "e": 10238, "s": 10192, "text": "Let’s take a look at our configuration class." }, { "code": null, "e": 10609, "s": 10238, "text": "First, we shall create a bean of our UserDetailsService class by using the userDetailsService() method. We shall be using this bean for managing our users for this application. Here, to keep things simple, we shall use an InMemoryUserDetailsManager instance to create a user. This user, along with our given username and password, will contain a simple “read” authority." }, { "code": null, "e": 10821, "s": 10609, "text": "Now, let’s look at our PasswordEncoder. We shall be using a BCryptPasswordEncoder instance for this example. Hence, while creating the user, we used the passwordEncoder to encode our plaintext password like this" }, { "code": null, "e": 10867, "s": 10821, "text": ".password(passwordEncoder().encode(\"12345\"))\n" }, { "code": null, "e": 11151, "s": 10867, "text": "After the above steps, we move on to our next configuration. Here, we override the configure method of WebSecurityConfigurerAdapter class. This method takes HttpSecurity as a parameter. We shall be configuring this to use our form login and logout, as well as a remember-me function." }, { "code": null, "e": 11179, "s": 11151, "text": "Http Security Configuration" }, { "code": null, "e": 11301, "s": 11179, "text": "We can observe that all these functionalities are available in Spring Security. Let’s study the below section in detail −" }, { "code": null, "e": 11551, "s": 11301, "text": "http.csrf().disable() \n .authorizeRequests().anyRequest().authenticated() \n .and() \n .formLogin() \n .and() \n .rememberMe() \n .and() \n .logout()\n .logoutUrl(\"/logout\") .logoutSuccessUrl(\"/login\") .deleteCookies(\"remember-me\");" }, { "code": null, "e": 11589, "s": 11551, "text": "There are a few points to note here −" }, { "code": null, "e": 11753, "s": 11589, "text": "We have disabled csrf or Cross-Site Request Forgery protection As this is a simple application only for demonstration purposes, we can safely disable this for now." }, { "code": null, "e": 11942, "s": 11753, "text": "Then we add configuration which requires all requests to be authenticated. As we shall see later, we will have a single “/” endpoint for the index page of this application, for simplicity." }, { "code": null, "e": 12077, "s": 11942, "text": "After that, we shall be using the formLogin() functionality of Spring Security as mentioned above. This generates a simple login page." }, { "code": null, "e": 12171, "s": 12077, "text": "Then, we use the rememberMe() functionality of Spring Security. This will perform two things." }, { "code": null, "e": 12280, "s": 12171, "text": "Firstly, it will add a “Remember Me” checkbox to our default login form that we generated using formLogin()." }, { "code": null, "e": 12497, "s": 12280, "text": "And, secondly, ticking the checkbox generates the remember-me cookie. The cookie stores the identity of the user and the browser stores it. Spring Security detects the cookie in future sessions to automate the login." }, { "code": null, "e": 12578, "s": 12497, "text": "As a result, the user can access the application again without logging in again." }, { "code": null, "e": 12745, "s": 12578, "text": "And lastly, we have the logout() functionality. For this too, a default functionality has been provided by Spring security. Here it performs two important functions −" }, { "code": null, "e": 12817, "s": 12745, "text": "Invalidates the Http session, and unbinds objects bound to the session." }, { "code": null, "e": 12851, "s": 12817, "text": "It clears the remember-me cookie." }, { "code": null, "e": 12910, "s": 12851, "text": "Removes the authentication from Spring’s Security context." }, { "code": null, "e": 13063, "s": 12910, "text": "We also, provided a logoutSuccessUrl(), so that the application comes back to the login page after logout. This completes our application configuration." }, { "code": null, "e": 13182, "s": 13063, "text": "We shall now create a dummy index page now for the user to view when he logs in. It will also contain a logout button." }, { "code": null, "e": 13279, "s": 13182, "text": "In our /src/main/resources/templates, we add a index.html file.Then add some Html content to it." }, { "code": null, "e": 14581, "s": 13279, "text": "<!doctype html> \n<html lang=\"en\"> \n <head> \n <!-- Required meta tags -->\n <meta charset=\"utf-8\"> \n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> \n <!-- Bootstrap CSS --> \n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> \n <title>Hello, world!</title> \n </head> \n <body> \n <h1>Hello, world!</h1> <a href=\"logout\">logout</a> \n <!-- Optional JavaScript --> \n <!-- jQuery first, then Popper.js, then Bootstrap JS --> \n <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"></script> \n <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> \n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"\n integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"></script> \n </body> \n</html>" }, { "code": null, "e": 14640, "s": 14581, "text": "This content is from Bootstrap 4 getting started template." }, { "code": null, "e": 14652, "s": 14640, "text": "We also add" }, { "code": null, "e": 14681, "s": 14652, "text": "<a href=\"logout\">logout</a>\n" }, { "code": null, "e": 14757, "s": 14681, "text": "to our file, so as the user can log out of the application using this link." }, { "code": null, "e": 14781, "s": 14757, "text": "The Resource Controller" }, { "code": null, "e": 14871, "s": 14781, "text": "We have created the protected resource, we now add the controller to serve this resource." }, { "code": null, "e": 15149, "s": 14871, "text": "package com.tutorial.spring.security.formlogin.controllers; \nimport org.springframework.stereotype.Controller; \nimport org.springframework.web.bind.annotation.GetMapping; \n@Controller public class AuthController { \n @GetMapping(\"/\") public String home() { return \"index\"; }\n}" }, { "code": null, "e": 15288, "s": 15149, "text": "As we can see, it is a very simple controller. It only has a get endpoint which serves our index.html file when the start our application." }, { "code": null, "e": 15536, "s": 15288, "text": "Let’s run the application as a Spring Boot Application. We can go to http://localhost:8080 on our browser when the application starts. It should ask us for username and password. Additionally, we shall also be able to see the remember-me checkbox." }, { "code": null, "e": 15789, "s": 15536, "text": "Now, if we provide the user information as we had configured in our WebSecurity config file, we shall be able to log in. Also, if we tick the remember-me checkbox, we shall be able to see the remember-me cookie in our browser’s developer tools section." }, { "code": null, "e": 15852, "s": 15789, "text": "As we can see the cookie is sent along with our login request." }, { "code": null, "e": 16003, "s": 15852, "text": "Also, included in the web page is a link for log out. On clicking the link, we shall be logged out of our application and sent back to our login page." }, { "code": null, "e": 16037, "s": 16003, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 16051, "s": 16037, "text": " Karthikeya T" }, { "code": null, "e": 16084, "s": 16051, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 16099, "s": 16084, "text": " Chaand Sheikh" }, { "code": null, "e": 16134, "s": 16099, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 16146, "s": 16134, "text": " Senol Atac" }, { "code": null, "e": 16181, "s": 16146, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 16193, "s": 16181, "text": " Senol Atac" }, { "code": null, "e": 16228, "s": 16193, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 16240, "s": 16228, "text": " Senol Atac" }, { "code": null, "e": 16273, "s": 16240, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 16285, "s": 16273, "text": " Senol Atac" }, { "code": null, "e": 16292, "s": 16285, "text": " Print" }, { "code": null, "e": 16303, "s": 16292, "text": " Add Notes" } ]
Left Shift and Right Shift Operators in C/C++
In the left shift operator, the left operands value is moved left by the number of bits specified by the right operand. Here is an example of left shift operator in C language, Live Demo #include <stdio.h> int main() { int y = 28; // 11100 int i = 0; for(i;i<=3;++i) printf("Left shift by %d: %d\n", i, y<<i); return 0; } Here is the output Left shift by 0: 28 Left shift by 1: 56 Left shift by 2: 112 Left shift by 3: 224 In the right shift operator, the left operands value is moved right by the number of bits specified by the right operand. Here is an example of right shift operator in C language, Live Demo #include <stdio.h> int main() { int x = 10; // 1010 int i = 0; for(i;i<2;i++) printf("Right shift by %d: %d\n", i, x>>i); return 0; } Here is the output Right shift by 0: 10 Right shift by 1: 5
[ { "code": null, "e": 1182, "s": 1062, "text": "In the left shift operator, the left operands value is moved left by the number of bits specified by the right operand." }, { "code": null, "e": 1239, "s": 1182, "text": "Here is an example of left shift operator in C language," }, { "code": null, "e": 1250, "s": 1239, "text": " Live Demo" }, { "code": null, "e": 1403, "s": 1250, "text": "#include <stdio.h>\n\nint main() {\n int y = 28; // 11100\n int i = 0;\n\n for(i;i<=3;++i)\n printf(\"Left shift by %d: %d\\n\", i, y<<i);\n\n return 0;\n}" }, { "code": null, "e": 1422, "s": 1403, "text": "Here is the output" }, { "code": null, "e": 1504, "s": 1422, "text": "Left shift by 0: 28\nLeft shift by 1: 56\nLeft shift by 2: 112\nLeft shift by 3: 224" }, { "code": null, "e": 1626, "s": 1504, "text": "In the right shift operator, the left operands value is moved right by the number of bits specified by the right operand." }, { "code": null, "e": 1684, "s": 1626, "text": "Here is an example of right shift operator in C language," }, { "code": null, "e": 1695, "s": 1684, "text": " Live Demo" }, { "code": null, "e": 1847, "s": 1695, "text": "#include <stdio.h>\n\nint main() {\n int x = 10; // 1010\n int i = 0;\n\n for(i;i<2;i++)\n printf(\"Right shift by %d: %d\\n\", i, x>>i);\n\n return 0;\n}" }, { "code": null, "e": 1866, "s": 1847, "text": "Here is the output" }, { "code": null, "e": 1907, "s": 1866, "text": "Right shift by 0: 10\nRight shift by 1: 5" } ]
Widest Path Problem | Practical application of Dijkstra's Algorithm - GeeksforGeeks
01 Sep, 2021 It is highly recommended to read Dijkstra’s algorithm using the Priority Queue first.Widest Path Problem is a problem of finding a path between two vertices of the graph maximizing the weight of the minimum-weight edge in the path. See the below image to get the idea of the problem: Practical Application Example: This problem is a famous variant of Dijkstra’s algorithm. In the practical application, this problem can be seen as a graph with routers as its vertices and edges represent bandwidth between two vertices. Now if we want to find the maximum bandwidth path between two places in the internet connection, then this problem can be solved by this algorithm.How to solve this problem? We are going to solve this problem by using the priority queue ((|E|+|V|)log|V|) implementation of the Dijkstra’s algorithm with a slight change.We solve this problem by just replacing the condition of relaxation in Dijkstra’s algorithm by: max(min(widest_dist[u], weight(u, v)), widest_dist[v]) where u is the source vertex for v. v is the current vertex we are checking the condition.This algorithm runs for both directed and undirected graph.See the series of images below to get the idea about the problem and the algorithm:The values over the edges represents weights of directed edges. We will start from source vertex and then travel all the vertex connected to it and add in priority queue according to relaxation condition. Now (2, 1) will pop up and 2 will be the current source vertex. Now (3, 1) will pop from the queue. But as 3 does not have any connected vertex through directed edge nothing will happen. So (4, 2) will pop next. Finally the algorithm stops, as there is no more elements in priority queue. The path with the maximum value of widest distance is 1-4-3 which has the maximum bottle-neck value of 2. So we end up getting widest distance of 2 to reach the target vertex 3.Below is the implementation of the above approach: CPP Python3 // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the required pathvoid printpath(vector<int>& parent, int vertex, int target){ if (vertex == 0) { return; } printpath(parent, parent[vertex], target); cout << vertex << (vertex == target ? "\n" : "--");} // Function to return the maximum weight// in the widest path of the given graphint widest_path_problem(vector<vector<pair<int, int> > >& Graph, int src, int target){ // To keep track of widest distance vector<int> widest(Graph.size(), INT_MIN); // To get the path at the end of the algorithm vector<int> parent(Graph.size(), 0); // Use of Minimum Priority Queue to keep track minimum // widest distance vertex so far in the algorithm priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > container; container.push(make_pair(0, src)); widest[src] = INT_MAX; while (container.empty() == false) { pair<int, int> temp = container.top(); int current_src = temp.second; container.pop(); for (auto vertex : Graph[current_src]) { // Finding the widest distance to the vertex // using current_source vertex's widest distance // and its widest distance so far int distance = max(widest[vertex.second], min(widest[current_src], vertex.first)); // Relaxation of edge and adding into Priority Queue if (distance > widest[vertex.second]) { // Updating bottle-neck distance widest[vertex.second] = distance; // To keep track of parent parent[vertex.second] = current_src; // Adding the relaxed edge in the priority queue container.push(make_pair(distance, vertex.second)); } } } printpath(parent, target, target); return widest[target];} // Driver codeint main(){ // Graph representation vector<vector<pair<int, int> > > graph; int no_vertices = 4; graph.assign(no_vertices + 1, vector<pair<int, int> >()); // Adding edges to graph // Resulting graph // 1--2 // | | // 4--3 // Note that order in pair is (distance, vertex) graph[1].push_back(make_pair(1, 2)); graph[1].push_back(make_pair(2, 4)); graph[2].push_back(make_pair(3, 3)); graph[4].push_back(make_pair(5, 3)); cout << widest_path_problem(graph, 1, 3); return 0;} # Python3 implementation of the approach # Function to print required pathdef printpath(parent, vertex, target): # global parent if (vertex == 0): return printpath(parent, parent[vertex], target) print(vertex ,end="\n" if (vertex == target) else "--") # Function to return the maximum weight# in the widest path of the given graphdef widest_path_problem(Graph, src, target): # To keep track of widest distance widest = [-10**9]*(len(Graph)) # To get the path at the end of the algorithm parent = [0]*len(Graph) # Use of Minimum Priority Queue to keep track minimum # widest distance vertex so far in the algorithm container = [] container.append((0, src)) widest[src] = 10**9 container = sorted(container) while (len(container)>0): temp = container[-1] current_src = temp[1] del container[-1] for vertex in Graph[current_src]: # Finding the widest distance to the vertex # using current_source vertex's widest distance # and its widest distance so far distance = max(widest[vertex[1]], min(widest[current_src], vertex[0])) # Relaxation of edge and adding into Priority Queue if (distance > widest[vertex[1]]): # Updating bottle-neck distance widest[vertex[1]] = distance # To keep track of parent parent[vertex[1]] = current_src # Adding the relaxed edge in the priority queue container.append((distance, vertex[1])) container = sorted(container) printpath(parent, target, target) return widest[target] # Driver codeif __name__ == '__main__': # Graph representation graph = [[] for i in range(5)] no_vertices = 4 # Adding edges to graph # Resulting graph #1--2 #| | #4--3 # Note that order in pair is (distance, vertex) graph[1].append((1, 2)) graph[1].append((2, 4)) graph[2].append((3, 3)) graph[4].append((5, 3)) print(widest_path_problem(graph, 1, 3)) # This code is contributed by mohit kumar 29 1--4--3 2 Time Complexity: O(E * logV), Where E is the total number of edges and V is the total number of vertices in the graph.Auxiliary Space: O(V). mohit kumar 29 khushboogoyal499 pankajsharmagfg surindertarika1234 Dijkstra Algorithms Data Structures Graph Data Structures Graph Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Quadratic Probing in Hashing DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) How to Start Learning DSA? Abstract Data Types Implementing a Linked List in Java using Class
[ { "code": null, "e": 26051, "s": 26023, "text": "\n01 Sep, 2021" }, { "code": null, "e": 26336, "s": 26051, "text": "It is highly recommended to read Dijkstra’s algorithm using the Priority Queue first.Widest Path Problem is a problem of finding a path between two vertices of the graph maximizing the weight of the minimum-weight edge in the path. See the below image to get the idea of the problem: " }, { "code": null, "e": 26988, "s": 26336, "text": "Practical Application Example: This problem is a famous variant of Dijkstra’s algorithm. In the practical application, this problem can be seen as a graph with routers as its vertices and edges represent bandwidth between two vertices. Now if we want to find the maximum bandwidth path between two places in the internet connection, then this problem can be solved by this algorithm.How to solve this problem? We are going to solve this problem by using the priority queue ((|E|+|V|)log|V|) implementation of the Dijkstra’s algorithm with a slight change.We solve this problem by just replacing the condition of relaxation in Dijkstra’s algorithm by: " }, { "code": null, "e": 27043, "s": 26988, "text": "max(min(widest_dist[u], weight(u, v)), widest_dist[v])" }, { "code": null, "e": 27341, "s": 27043, "text": "where u is the source vertex for v. v is the current vertex we are checking the condition.This algorithm runs for both directed and undirected graph.See the series of images below to get the idea about the problem and the algorithm:The values over the edges represents weights of directed edges. " }, { "code": null, "e": 27484, "s": 27341, "text": "We will start from source vertex and then travel all the vertex connected to it and add in priority queue according to relaxation condition. " }, { "code": null, "e": 27551, "s": 27486, "text": "Now (2, 1) will pop up and 2 will be the current source vertex. " }, { "code": null, "e": 27700, "s": 27551, "text": "Now (3, 1) will pop from the queue. But as 3 does not have any connected vertex through directed edge nothing will happen. So (4, 2) will pop next. " }, { "code": null, "e": 27779, "s": 27700, "text": "Finally the algorithm stops, as there is no more elements in priority queue. " }, { "code": null, "e": 28008, "s": 27779, "text": "The path with the maximum value of widest distance is 1-4-3 which has the maximum bottle-neck value of 2. So we end up getting widest distance of 2 to reach the target vertex 3.Below is the implementation of the above approach: " }, { "code": null, "e": 28012, "s": 28008, "text": "CPP" }, { "code": null, "e": 28020, "s": 28012, "text": "Python3" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the required pathvoid printpath(vector<int>& parent, int vertex, int target){ if (vertex == 0) { return; } printpath(parent, parent[vertex], target); cout << vertex << (vertex == target ? \"\\n\" : \"--\");} // Function to return the maximum weight// in the widest path of the given graphint widest_path_problem(vector<vector<pair<int, int> > >& Graph, int src, int target){ // To keep track of widest distance vector<int> widest(Graph.size(), INT_MIN); // To get the path at the end of the algorithm vector<int> parent(Graph.size(), 0); // Use of Minimum Priority Queue to keep track minimum // widest distance vertex so far in the algorithm priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > container; container.push(make_pair(0, src)); widest[src] = INT_MAX; while (container.empty() == false) { pair<int, int> temp = container.top(); int current_src = temp.second; container.pop(); for (auto vertex : Graph[current_src]) { // Finding the widest distance to the vertex // using current_source vertex's widest distance // and its widest distance so far int distance = max(widest[vertex.second], min(widest[current_src], vertex.first)); // Relaxation of edge and adding into Priority Queue if (distance > widest[vertex.second]) { // Updating bottle-neck distance widest[vertex.second] = distance; // To keep track of parent parent[vertex.second] = current_src; // Adding the relaxed edge in the priority queue container.push(make_pair(distance, vertex.second)); } } } printpath(parent, target, target); return widest[target];} // Driver codeint main(){ // Graph representation vector<vector<pair<int, int> > > graph; int no_vertices = 4; graph.assign(no_vertices + 1, vector<pair<int, int> >()); // Adding edges to graph // Resulting graph // 1--2 // | | // 4--3 // Note that order in pair is (distance, vertex) graph[1].push_back(make_pair(1, 2)); graph[1].push_back(make_pair(2, 4)); graph[2].push_back(make_pair(3, 3)); graph[4].push_back(make_pair(5, 3)); cout << widest_path_problem(graph, 1, 3); return 0;}", "e": 30577, "s": 28020, "text": null }, { "code": "# Python3 implementation of the approach # Function to print required pathdef printpath(parent, vertex, target): # global parent if (vertex == 0): return printpath(parent, parent[vertex], target) print(vertex ,end=\"\\n\" if (vertex == target) else \"--\") # Function to return the maximum weight# in the widest path of the given graphdef widest_path_problem(Graph, src, target): # To keep track of widest distance widest = [-10**9]*(len(Graph)) # To get the path at the end of the algorithm parent = [0]*len(Graph) # Use of Minimum Priority Queue to keep track minimum # widest distance vertex so far in the algorithm container = [] container.append((0, src)) widest[src] = 10**9 container = sorted(container) while (len(container)>0): temp = container[-1] current_src = temp[1] del container[-1] for vertex in Graph[current_src]: # Finding the widest distance to the vertex # using current_source vertex's widest distance # and its widest distance so far distance = max(widest[vertex[1]], min(widest[current_src], vertex[0])) # Relaxation of edge and adding into Priority Queue if (distance > widest[vertex[1]]): # Updating bottle-neck distance widest[vertex[1]] = distance # To keep track of parent parent[vertex[1]] = current_src # Adding the relaxed edge in the priority queue container.append((distance, vertex[1])) container = sorted(container) printpath(parent, target, target) return widest[target] # Driver codeif __name__ == '__main__': # Graph representation graph = [[] for i in range(5)] no_vertices = 4 # Adding edges to graph # Resulting graph #1--2 #| | #4--3 # Note that order in pair is (distance, vertex) graph[1].append((1, 2)) graph[1].append((2, 4)) graph[2].append((3, 3)) graph[4].append((5, 3)) print(widest_path_problem(graph, 1, 3)) # This code is contributed by mohit kumar 29", "e": 32725, "s": 30577, "text": null }, { "code": null, "e": 32735, "s": 32725, "text": "1--4--3\n2" }, { "code": null, "e": 32880, "s": 32737, "text": "Time Complexity: O(E * logV), Where E is the total number of edges and V is the total number of vertices in the graph.Auxiliary Space: O(V). " }, { "code": null, "e": 32895, "s": 32880, "text": "mohit kumar 29" }, { "code": null, "e": 32912, "s": 32895, "text": "khushboogoyal499" }, { "code": null, "e": 32928, "s": 32912, "text": "pankajsharmagfg" }, { "code": null, "e": 32947, "s": 32928, "text": "surindertarika1234" }, { "code": null, "e": 32956, "s": 32947, "text": "Dijkstra" }, { "code": null, "e": 32967, "s": 32956, "text": "Algorithms" }, { "code": null, "e": 32983, "s": 32967, "text": "Data Structures" }, { "code": null, "e": 32989, "s": 32983, "text": "Graph" }, { "code": null, "e": 33005, "s": 32989, "text": "Data Structures" }, { "code": null, "e": 33011, "s": 33005, "text": "Graph" }, { "code": null, "e": 33022, "s": 33011, "text": "Algorithms" }, { "code": null, "e": 33120, "s": 33022, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33145, "s": 33120, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33172, "s": 33145, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33206, "s": 33172, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33273, "s": 33206, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33302, "s": 33273, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 33327, "s": 33302, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33383, "s": 33327, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 33410, "s": 33383, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33430, "s": 33410, "text": "Abstract Data Types" } ]
Call a method Asynchronously in C#
Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using asynchronous approach, the applications continues with other tasks as well. An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding messages if the processing takes more time than expected. Let us see what is discussed above. private void OnRequestDownload(object sender, RoutedEventArgs e) { var req = HttpWebRequest.Create(_requestedUri); var res = req.GetResponse(); } To solve the above issue, use the async and await keywords. private async void OnRequestDownload(object sender, RoutedEventArgs e) { var req= HttpWebRequest.Create(_requestedUri); var res = await req.GetResponseAsync(); }
[ { "code": null, "e": 1405, "s": 1062, "text": "Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using asynchronous approach, the applications continues with other tasks as well." }, { "code": null, "e": 1717, "s": 1405, "text": "An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding messages if the processing takes more time than expected." }, { "code": null, "e": 1753, "s": 1717, "text": "Let us see what is discussed above." }, { "code": null, "e": 1905, "s": 1753, "text": "private void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req = HttpWebRequest.Create(_requestedUri);\n var res = req.GetResponse();\n}" }, { "code": null, "e": 1965, "s": 1905, "text": "To solve the above issue, use the async and await keywords." }, { "code": null, "e": 2133, "s": 1965, "text": "private async void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req= HttpWebRequest.Create(_requestedUri);\n var res = await req.GetResponseAsync();\n}" } ]
How to find the number of non-empty values in an R data frame column?
To find the number of non-empty values, we can find the negation of the sum of empty values which is actually the total number of non-empty values. For example, if we have a data frame df that contains a column x which has some empty values then to find the total number of non-empty values we can find the opposite/negation of total empty values. This can be done with the help of sum function and negation operator as shown in the below examples. Consider the below data frame − Live Demo > x<-sample(c(1,2,""),20,replace=TRUE) > df1<-data.frame(x) > df1 x 1 1 2 2 3 4 5 6 7 8 2 9 10 11 2 12 2 13 2 14 2 15 2 16 17 18 19 20 1 Finding total number of non-empty values in column x of df1 − > sum(df1$x!="") [1] 9 Live Demo > y<-sample(c(5,""),20,replace=TRUE) > df2<-data.frame(y) > df2 y 1 5 2 3 5 4 5 5 6 5 7 8 5 9 5 10 5 11 5 12 13 14 5 15 16 17 18 19 20 Finding total number of non-empty values in column y of df2 − > sum(df2$y!="") [1] 9 Live Demo > z<-sample(c(5,3,2,""),20,replace=TRUE) > df3<-data.frame(z) > df3 z 1 5 2 3 3 4 3 5 6 7 8 3 9 2 10 2 11 2 12 13 2 14 2 15 16 3 17 18 2 19 20 3 Finding total number of non-empty values in column z of df3 − > sum(df3$z!="") [1] 12
[ { "code": null, "e": 1511, "s": 1062, "text": "To find the number of non-empty values, we can find the negation of the sum of empty values which is actually the total number of non-empty values. For example, if we have a data frame df that contains a column x which has some empty values then to find the total number of non-empty values we can find the opposite/negation of total empty values. This can be done with the help of sum function and negation operator as shown in the below examples." }, { "code": null, "e": 1543, "s": 1511, "text": "Consider the below data frame −" }, { "code": null, "e": 1553, "s": 1543, "text": "Live Demo" }, { "code": null, "e": 1619, "s": 1553, "text": "> x<-sample(c(1,2,\"\"),20,replace=TRUE)\n> df1<-data.frame(x)\n> df1" }, { "code": null, "e": 1708, "s": 1619, "text": " x\n1 1\n2 2\n3 \n4 \n5 \n6 \n7 \n8 2\n9 \n10\n11 2\n12 2\n13 2\n14 2\n15 2\n16\n17\n18\n19\n20 1" }, { "code": null, "e": 1770, "s": 1708, "text": "Finding total number of non-empty values in column x of df1 −" }, { "code": null, "e": 1787, "s": 1770, "text": "> sum(df1$x!=\"\")" }, { "code": null, "e": 1793, "s": 1787, "text": "[1] 9" }, { "code": null, "e": 1803, "s": 1793, "text": "Live Demo" }, { "code": null, "e": 1867, "s": 1803, "text": "> y<-sample(c(5,\"\"),20,replace=TRUE)\n> df2<-data.frame(y)\n> df2" }, { "code": null, "e": 1953, "s": 1867, "text": " y\n1 5\n2 \n3 5\n4 \n5 5\n6 5\n7 \n8 5\n9 5\n10 5\n11 5\n12\n13\n14 5\n15\n16\n17\n18\n19\n20" }, { "code": null, "e": 2015, "s": 1953, "text": "Finding total number of non-empty values in column y of df2 −" }, { "code": null, "e": 2032, "s": 2015, "text": "> sum(df2$y!=\"\")" }, { "code": null, "e": 2038, "s": 2032, "text": "[1] 9" }, { "code": null, "e": 2048, "s": 2038, "text": "Live Demo" }, { "code": null, "e": 2116, "s": 2048, "text": "> z<-sample(c(5,3,2,\"\"),20,replace=TRUE)\n> df3<-data.frame(z)\n> df3" }, { "code": null, "e": 2209, "s": 2116, "text": " z\n1 5\n2 3\n3 \n4 3\n5 \n6 \n7 \n8 3\n9 2\n10 2\n11 2\n12\n13 2\n14 2\n15\n16 3\n17\n18 2\n19\n20 3" }, { "code": null, "e": 2271, "s": 2209, "text": "Finding total number of non-empty values in column z of df3 −" }, { "code": null, "e": 2288, "s": 2271, "text": "> sum(df3$z!=\"\")" }, { "code": null, "e": 2295, "s": 2288, "text": "[1] 12" } ]
Binary Insertion Sort - GeeksforGeeks
14 Jan, 2022 We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion sort, it takes O(n) comparisons (at nth iteration) in the worst case. We can reduce it to O(log n) by using binary search. C++ C Java Python3 C# PHP Javascript // C program for implementation of// binary insertion sort#include <iostream>using namespace std; // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); cout <<"Sorted array: \n"; for (i = 0; i < n; i++) cout <<" "<< a[i]; return 0;} // this code is contribution by shivanisinghss2110 // C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]); return 0;} // Java Program implementing// binary insertion sort import java.util.Arrays;class GFG{ public static void main(String[] args) { final int[] arr = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; new GFG().sort(arr); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); } // Driver Code public void sort(int array[]) { for (int i = 1; i < array.length; i++) { int x = array[i]; // Find location to insert // using binary search int j = Math.abs( Arrays.binarySearch(array, 0, i, x) + 1); // Shifting array to one // location right System.arraycopy(array, j, array, j + 1, i - j); // Placing element at its // correct location array[j] = x; } }} // Code contributed by Mohit Gupta_OMG # Python Program implementation# of binary insertion sort def binary_search(arr, val, start, end): # we need to distinugish whether we # should insert before or after the # left boundary. imagine [0] is the last # step of the binary search and we need # to decide where to insert -1 if start == end: if arr[start] > val: return start else: return start+1 # this occurs if we are moving # beyond left's boundary meaning # the left boundary is the least # position to find a number greater than val if start > end: return start mid = (start+end)//2 if arr[mid] < val: return binary_search(arr, val, mid+1, end) elif arr[mid] > val: return binary_search(arr, val, start, mid-1) else: return mid def insertion_sort(arr): for i in range(1, len(arr)): val = arr[i] j = binary_search(arr, val, 0, i-1) arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] return arr print("Sorted array:")print(insertion_sort([37, 23, 0, 31, 22, 17, 12, 72, 31, 46, 100, 88, 54])) # Code contributed by Mohit Gupta_OMG // C# Program implementing// binary insertion sortusing System; class GFG { public static void Main() { int[] arr = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; sort(arr); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); } // Driver Code public static void sort(int[] array) { for (int i = 1; i < array.Length; i++) { int x = array[i]; // Find location to insert using // binary search int j = Math.Abs( Array.BinarySearch(array, 0, i, x) + 1); // Shifting array to one location right System.Array.Copy(array, j, array, j + 1, i - j); // Placing element at its correct // location array[j] = x; } }} // This code is contributed by nitin mittal. <?php// PHP program for implementation of// binary insertion sort // A binary search based function to find// the position where item should be// inserted in a[low..high]function binarySearch($a, $item, $low, $high){ if ($high <= $low) return ($item > $a[$low]) ? ($low + 1) : $low; $mid = (int)(($low + $high) / 2); if($item == $a[$mid]) return $mid + 1; if($item > $a[$mid]) return binarySearch($a, $item, $mid + 1, $high); return binarySearch($a, $item, $low, $mid - 1);} // Function to sort an array a of size 'n'function insertionSort(&$a, $n){ $i; $loc; $j; $k; $selected; for ($i = 1; $i < $n; ++$i) { $j = $i - 1; $selected = $a[$i]; // find location where selected // item should be inserted $loc = binarySearch($a, $selected, 0, $j); // Move all elements after location // to create space while ($j >= $loc) { $a[$j + 1] = $a[$j]; $j--; } $a[$j + 1] = $selected; }} // Driver Code$a = array(37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54); $n = sizeof($a); insertionSort($a, $n); echo "Sorted array:\n";for ($i = 0; $i < $n; $i++) echo "$a[$i] "; // This code is contributed by// Adesh Singh?> <script>// Javascript Program implementing// binary insertion sort function binarySearch(a, item, low, high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; mid = Math.floor((low + high) / 2); if(item == a[mid]) return mid + 1; if(item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} function sort(array){ for (let i = 1; i < array.length; i++) { let j = i - 1; let x = array[i]; // Find location to insert // using binary search let loc = Math.abs( binarySearch(array, x, 0, j)); // Shifting array to one // location right while (j >= loc) { array[j + 1] = array[j]; j--; } // Placing element at its // correct location array[j+1] = x; }} // Driver Codelet arr=[ 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54];sort(arr); for (let i = 0; i < arr.length; i++) document.write(arr[i] + " "); // This code is contributed by unknown2108</script>// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]); r// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]); // C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]); // C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]);// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]);// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]) Sorted array: 0 12 17 23 31 37 46 54 72 88 100 Time Complexity: The algorithm as a whole still has a running worst-case running time of O(n2) because of the series of swaps required for each insertion. Another approach: Following is an iterative implementation of the above recursive code C++ C Java Python3 C# Javascript #include <iostream>using namespace std; // iterative implementationint binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); cout <<"Sorted array: \n"; for (i = 0; i < n; i++) cout <<" "<< a[i]; return 0;} // This code is contributed by shivanisinghss2110. #include <stdio.h> // iterative implementationint binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf("Sorted array: \n"); for (i = 0; i < n; i++) printf("%d ", a[i]); return 0;}// contributed by tmeid import java.io.*; class GFG { // iterative implementationstatic int binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'static void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codepublic static void main (String[] args){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = a.length, i; insertionSort(a, n); System.out.println("Sorted array:"); for (i = 0; i < n; i++) System.out.print(a[i] +" "); }} // This code is contributed by shivanisinghss2110. # iterative implementationdef binarySearch(a, item, low, high): while (low <= high): mid = low + (high - low) // 2 if (item == a[mid]): return mid + 1 elif (item > a[mid]): low = mid + 1 else: high = mid - 1 return low # Function to sort an array a[] of size 'n'def insertionSort(a, n): for i in range (n): j = i - 1 selected = a[i] # find location where selected should be inseretd loc = binarySearch(a, selected, 0, j) # Move all elements after location to create space while (j >= loc): a[j + 1] = a[j] j-=1 a[j + 1] = selected # Driver Codea = [37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]n = len(a)insertionSort(a, n)print("Sorted array: ")for i in range (n): print(a[i], end=" ") # This code is contributed by shivanisinghss2110 using System; class GFG { // iterative implementationstatic int binarySearch(int []a, int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'static void insertionSort(int []a, int n){ int i, loc, j, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codepublic static void Main (String[] args){ int []a = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = a.Length, i; insertionSort(a, n); Console.WriteLine("Sorted array:"); for (i = 0; i < n; i++) Console.Write(a[i] +" "); }} // This code is contributed by shivanisinghss2110 <script>// iterative implementationfunction binarySearch( a, item, low, high){ while (low <= high) { var mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'function insertionSort(a, n){ var i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Code var a = [ 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 ]; var n = a.length, i; insertionSort(a, n); document.write("Sorted array:" + "<br>"); for (i = 0; i < n; i++) document.write(a[i] +" "); // This code is contributed by shivanisinghss2110</script> Sorted array: 0 12 17 23 31 37 46 54 72 88 100 This article is contributed by Amit Auddy. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal SayanMaiti Shubhaw Kumar AdeshSingh1 nawfelgiuma rishabhtiwari759 SURAJ SURYAWANSHI unknown2108 tmeid kirushikesh sagartomar9927 shivanisinghss2110 sweetyty amartyaghoshgfg Algorithms-InsertionSort Binary Search Sorting Quiz Sorting Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Python Program for Bubble Sort
[ { "code": null, "e": 24999, "s": 24971, "text": "\n14 Jan, 2022" }, { "code": null, "e": 25345, "s": 24999, "text": "We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion sort, it takes O(n) comparisons (at nth iteration) in the worst case. We can reduce it to O(log n) by using binary search." }, { "code": null, "e": 25349, "s": 25345, "text": "C++" }, { "code": null, "e": 25351, "s": 25349, "text": "C" }, { "code": null, "e": 25356, "s": 25351, "text": "Java" }, { "code": null, "e": 25364, "s": 25356, "text": "Python3" }, { "code": null, "e": 25367, "s": 25364, "text": "C#" }, { "code": null, "e": 25371, "s": 25367, "text": "PHP" }, { "code": null, "e": 25382, "s": 25371, "text": "Javascript" }, { "code": "// C program for implementation of// binary insertion sort#include <iostream>using namespace std; // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); cout <<\"Sorted array: \\n\"; for (i = 0; i < n; i++) cout <<\" \"<< a[i]; return 0;} // this code is contribution by shivanisinghss2110", "e": 26773, "s": 25382, "text": null }, { "code": "// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]); return 0;}", "e": 28096, "s": 26773, "text": null }, { "code": "// Java Program implementing// binary insertion sort import java.util.Arrays;class GFG{ public static void main(String[] args) { final int[] arr = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; new GFG().sort(arr); for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + \" \"); } // Driver Code public void sort(int array[]) { for (int i = 1; i < array.length; i++) { int x = array[i]; // Find location to insert // using binary search int j = Math.abs( Arrays.binarySearch(array, 0, i, x) + 1); // Shifting array to one // location right System.arraycopy(array, j, array, j + 1, i - j); // Placing element at its // correct location array[j] = x; } }} // Code contributed by Mohit Gupta_OMG", "e": 29095, "s": 28096, "text": null }, { "code": "# Python Program implementation# of binary insertion sort def binary_search(arr, val, start, end): # we need to distinugish whether we # should insert before or after the # left boundary. imagine [0] is the last # step of the binary search and we need # to decide where to insert -1 if start == end: if arr[start] > val: return start else: return start+1 # this occurs if we are moving # beyond left's boundary meaning # the left boundary is the least # position to find a number greater than val if start > end: return start mid = (start+end)//2 if arr[mid] < val: return binary_search(arr, val, mid+1, end) elif arr[mid] > val: return binary_search(arr, val, start, mid-1) else: return mid def insertion_sort(arr): for i in range(1, len(arr)): val = arr[i] j = binary_search(arr, val, 0, i-1) arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] return arr print(\"Sorted array:\")print(insertion_sort([37, 23, 0, 31, 22, 17, 12, 72, 31, 46, 100, 88, 54])) # Code contributed by Mohit Gupta_OMG", "e": 30228, "s": 29095, "text": null }, { "code": "// C# Program implementing// binary insertion sortusing System; class GFG { public static void Main() { int[] arr = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; sort(arr); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + \" \"); } // Driver Code public static void sort(int[] array) { for (int i = 1; i < array.Length; i++) { int x = array[i]; // Find location to insert using // binary search int j = Math.Abs( Array.BinarySearch(array, 0, i, x) + 1); // Shifting array to one location right System.Array.Copy(array, j, array, j + 1, i - j); // Placing element at its correct // location array[j] = x; } }} // This code is contributed by nitin mittal.", "e": 31203, "s": 30228, "text": null }, { "code": "<?php// PHP program for implementation of// binary insertion sort // A binary search based function to find// the position where item should be// inserted in a[low..high]function binarySearch($a, $item, $low, $high){ if ($high <= $low) return ($item > $a[$low]) ? ($low + 1) : $low; $mid = (int)(($low + $high) / 2); if($item == $a[$mid]) return $mid + 1; if($item > $a[$mid]) return binarySearch($a, $item, $mid + 1, $high); return binarySearch($a, $item, $low, $mid - 1);} // Function to sort an array a of size 'n'function insertionSort(&$a, $n){ $i; $loc; $j; $k; $selected; for ($i = 1; $i < $n; ++$i) { $j = $i - 1; $selected = $a[$i]; // find location where selected // item should be inserted $loc = binarySearch($a, $selected, 0, $j); // Move all elements after location // to create space while ($j >= $loc) { $a[$j + 1] = $a[$j]; $j--; } $a[$j + 1] = $selected; }} // Driver Code$a = array(37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54); $n = sizeof($a); insertionSort($a, $n); echo \"Sorted array:\\n\";for ($i = 0; $i < $n; $i++) echo \"$a[$i] \"; // This code is contributed by// Adesh Singh?>", "e": 32566, "s": 31203, "text": null }, { "code": "<script>// Javascript Program implementing// binary insertion sort function binarySearch(a, item, low, high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; mid = Math.floor((low + high) / 2); if(item == a[mid]) return mid + 1; if(item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} function sort(array){ for (let i = 1; i < array.length; i++) { let j = i - 1; let x = array[i]; // Find location to insert // using binary search let loc = Math.abs( binarySearch(array, x, 0, j)); // Shifting array to one // location right while (j >= loc) { array[j + 1] = array[j]; j--; } // Placing element at its // correct location array[j+1] = x; }} // Driver Codelet arr=[ 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54];sort(arr); for (let i = 0; i < arr.length; i++) document.write(arr[i] + \" \"); // This code is contributed by unknown2108</script>// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]); r// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]); // C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]); // C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]);// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]);// C program for implementation of// binary insertion sort#include <stdio.h> // A binary search based function// to find the position// where item should be inserted// in a[low..high]int binarySearch(int a[], int item, int low, int high){ if (high <= low) return (item > a[low]) ? (low + 1) : low; int mid = (low + high) / 2; if (item == a[mid]) return mid + 1; if (item > a[mid]) return binarySearch(a, item, mid + 1, high); return binarySearch(a, item, low, mid - 1);} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i])", "e": 41737, "s": 32566, "text": null }, { "code": null, "e": 41786, "s": 41737, "text": "Sorted array: \n0 12 17 23 31 37 46 54 72 88 100 " }, { "code": null, "e": 41942, "s": 41786, "text": "Time Complexity: The algorithm as a whole still has a running worst-case running time of O(n2) because of the series of swaps required for each insertion. " }, { "code": null, "e": 42029, "s": 41942, "text": "Another approach: Following is an iterative implementation of the above recursive code" }, { "code": null, "e": 42033, "s": 42029, "text": "C++" }, { "code": null, "e": 42035, "s": 42033, "text": "C" }, { "code": null, "e": 42040, "s": 42035, "text": "Java" }, { "code": null, "e": 42048, "s": 42040, "text": "Python3" }, { "code": null, "e": 42051, "s": 42048, "text": "C#" }, { "code": null, "e": 42062, "s": 42051, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // iterative implementationint binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); cout <<\"Sorted array: \\n\"; for (i = 0; i < n; i++) cout <<\" \"<< a[i]; return 0;} // This code is contributed by shivanisinghss2110.", "e": 43193, "s": 42062, "text": null }, { "code": "#include <stdio.h> // iterative implementationint binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codeint main(){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = sizeof(a) / sizeof(a[0]), i; insertionSort(a, n); printf(\"Sorted array: \\n\"); for (i = 0; i < n; i++) printf(\"%d \", a[i]); return 0;}// contributed by tmeid", "e": 44278, "s": 43193, "text": null }, { "code": "import java.io.*; class GFG { // iterative implementationstatic int binarySearch(int a[], int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'static void insertionSort(int a[], int n){ int i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codepublic static void main (String[] args){ int a[] = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = a.length, i; insertionSort(a, n); System.out.println(\"Sorted array:\"); for (i = 0; i < n; i++) System.out.print(a[i] +\" \"); }} // This code is contributed by shivanisinghss2110.", "e": 45434, "s": 44278, "text": null }, { "code": "# iterative implementationdef binarySearch(a, item, low, high): while (low <= high): mid = low + (high - low) // 2 if (item == a[mid]): return mid + 1 elif (item > a[mid]): low = mid + 1 else: high = mid - 1 return low # Function to sort an array a[] of size 'n'def insertionSort(a, n): for i in range (n): j = i - 1 selected = a[i] # find location where selected should be inseretd loc = binarySearch(a, selected, 0, j) # Move all elements after location to create space while (j >= loc): a[j + 1] = a[j] j-=1 a[j + 1] = selected # Driver Codea = [37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]n = len(a)insertionSort(a, n)print(\"Sorted array: \")for i in range (n): print(a[i], end=\" \") # This code is contributed by shivanisinghss2110", "e": 46334, "s": 45434, "text": null }, { "code": "using System; class GFG { // iterative implementationstatic int binarySearch(int []a, int item, int low, int high){ while (low <= high) { int mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'static void insertionSort(int []a, int n){ int i, loc, j, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Codepublic static void Main (String[] args){ int []a = { 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; int n = a.Length, i; insertionSort(a, n); Console.WriteLine(\"Sorted array:\"); for (i = 0; i < n; i++) Console.Write(a[i] +\" \"); }} // This code is contributed by shivanisinghss2110", "e": 47471, "s": 46334, "text": null }, { "code": "<script>// iterative implementationfunction binarySearch( a, item, low, high){ while (low <= high) { var mid = low + (high - low) / 2; if (item == a[mid]) return mid + 1; else if (item > a[mid]) low = mid + 1; else high = mid - 1; } return low;} // Function to sort an array a[] of size 'n'function insertionSort(a, n){ var i, loc, j, k, selected; for (i = 1; i < n; ++i) { j = i - 1; selected = a[i]; // find location where selected should be inseretd loc = binarySearch(a, selected, 0, j); // Move all elements after location to create space while (j >= loc) { a[j + 1] = a[j]; j--; } a[j + 1] = selected; }} // Driver Code var a = [ 37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 ]; var n = a.length, i; insertionSort(a, n); document.write(\"Sorted array:\" + \"<br>\"); for (i = 0; i < n; i++) document.write(a[i] +\" \"); // This code is contributed by shivanisinghss2110</script>", "e": 48536, "s": 47471, "text": null }, { "code": null, "e": 48585, "s": 48536, "text": "Sorted array: \n0 12 17 23 31 37 46 54 72 88 100 " }, { "code": null, "e": 48752, "s": 48585, "text": "This article is contributed by Amit Auddy. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 48765, "s": 48752, "text": "nitin mittal" }, { "code": null, "e": 48776, "s": 48765, "text": "SayanMaiti" }, { "code": null, "e": 48790, "s": 48776, "text": "Shubhaw Kumar" }, { "code": null, "e": 48802, "s": 48790, "text": "AdeshSingh1" }, { "code": null, "e": 48814, "s": 48802, "text": "nawfelgiuma" }, { "code": null, "e": 48831, "s": 48814, "text": "rishabhtiwari759" }, { "code": null, "e": 48849, "s": 48831, "text": "SURAJ SURYAWANSHI" }, { "code": null, "e": 48861, "s": 48849, "text": "unknown2108" }, { "code": null, "e": 48867, "s": 48861, "text": "tmeid" }, { "code": null, "e": 48879, "s": 48867, "text": "kirushikesh" }, { "code": null, "e": 48894, "s": 48879, "text": "sagartomar9927" }, { "code": null, "e": 48913, "s": 48894, "text": "shivanisinghss2110" }, { "code": null, "e": 48922, "s": 48913, "text": "sweetyty" }, { "code": null, "e": 48938, "s": 48922, "text": "amartyaghoshgfg" }, { "code": null, "e": 48963, "s": 48938, "text": "Algorithms-InsertionSort" }, { "code": null, "e": 48977, "s": 48963, "text": "Binary Search" }, { "code": null, "e": 48990, "s": 48977, "text": "Sorting Quiz" }, { "code": null, "e": 48998, "s": 48990, "text": "Sorting" }, { "code": null, "e": 49006, "s": 48998, "text": "Sorting" }, { "code": null, "e": 49020, "s": 49006, "text": "Binary Search" }, { "code": null, "e": 49118, "s": 49020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49141, "s": 49118, "text": "std::sort() in C++ STL" }, { "code": null, "e": 49185, "s": 49141, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 49196, "s": 49185, "text": "Radix Sort" }, { "code": null, "e": 49220, "s": 49196, "text": "Merge two sorted arrays" }, { "code": null, "e": 49251, "s": 49220, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 49307, "s": 49251, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 49338, "s": 49307, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 49382, "s": 49338, "text": "k largest(or smallest) elements in an array" } ]
How to draw a rectangle in OpenCV using C++?
To draw a rectangle, we need four points. Look at the following figure. In the figure, there are four points x1, x2, y1 and y2. These four points are forming the four coordinates. To draw a rectangle using OpenCV, we have to define these points and show the rectangle we need a matrix. We have to declare other relevant values like the color of the line and line width. The basic syntax of this method is as follows − rectangle(whiteMatrix, starting, ending, line_Color, thickness); The following program represents how to draw a rectangle in OpenCV. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; int main() { Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));// Declaring a white matrix// Point starting(40, 40);//Declaring the starting coordinate// Point ending(160, 100);//Declaring the ending coordinate Scalar line_Color(0, 0, 0);//Color of the rectangle// int thickness = 2;//thickens of the line// namedWindow("whiteMatrix");//Declaring a window to show the rectangle// rectangle(whiteMatrix, starting, ending, line_Color, thickness);//Drawing the rectangle// imshow("WhiteMatrix", whiteMatrix);//Showing the rectangle// waitKey(0);//Waiting for Keystroke return 0; }
[ { "code": null, "e": 1134, "s": 1062, "text": "To draw a rectangle, we need four points. Look at the following figure." }, { "code": null, "e": 1432, "s": 1134, "text": "In the figure, there are four points x1, x2, y1 and y2. These four points are forming the four coordinates. To draw a rectangle using OpenCV, we have to define these points and show the rectangle we need a matrix. We have to declare other relevant values like the color of the line and line width." }, { "code": null, "e": 1480, "s": 1432, "text": "The basic syntax of this method is as follows −" }, { "code": null, "e": 1545, "s": 1480, "text": "rectangle(whiteMatrix, starting, ending, line_Color, thickness);" }, { "code": null, "e": 1613, "s": 1545, "text": "The following program represents how to draw a rectangle in OpenCV." }, { "code": null, "e": 2365, "s": 1613, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace cv;\nusing namespace std;\nint main() {\n Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));// Declaring a white matrix//\n Point starting(40, 40);//Declaring the starting coordinate//\n Point ending(160, 100);//Declaring the ending coordinate\n Scalar line_Color(0, 0, 0);//Color of the rectangle//\n int thickness = 2;//thickens of the line//\n namedWindow(\"whiteMatrix\");//Declaring a window to show the rectangle//\n rectangle(whiteMatrix, starting, ending, line_Color, thickness);//Drawing the rectangle//\n imshow(\"WhiteMatrix\", whiteMatrix);//Showing the rectangle//\n waitKey(0);//Waiting for Keystroke\n return 0;\n}" } ]
How to compare two JavaScript array objects using jQuery/JavaScript ? - GeeksforGeeks
29 Jun, 2021 Given two JavaScript array/array objects and the task is to compare the equality of both array objects. Approach 1: Use jQuery not() method to check for each element of array1, if it is not present in array2 or for each element of array2, if this is not present in array1, then it return false in both cases. Also check the length of both arrays. Example: This example uses jQuery not() method to compare the equality of both array. html <!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [1, 3, 5, 8]; var arr2 = [1, 3, 5, 7]; up.innerHTML = "Click on the button to check " + "equality of arrays.<br>Array1 - " + arr1 + "<br>Array2 - " + arr2; function GFG_Fun() { down.innerHTML = $(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: First, use sort() function to sort both arrays in ascending order. Then start matching the element one by one and if there is any mismatch found then it returns false otherwise it returns true. Example:This example uses approach as discussed above. html <!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [1, 3, 7, 5]; var arr2 = [1, 3, 5, 7]; up.innerHTML = "Click on the button to check " + "equality of arrays.<br>Array1 - " + arr1 + "<br>Array2 - " + arr2; function compare(ar1, ar2) { ar1.sort(); ar2.sort(); if(ar1.length != ar2.length) return false; for(var i = 0; i < ar1.length; i++) { if (ar1[i] != ar2[i]) return false; } return true; } function GFG_Fun() { down.innerHTML = compare(arr1, arr2); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 3: Create two array objects and store it into arr1 and arr2 variables. Use JSON.stringify() function to convert object into JSON string. Now compare both JSON string using comparison operator (==) to check both array objects are equal or not. Note: This method works only when both array objects sorted into the same fashion.Example: html <!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h2> Click on the button to check equality of arrays </h2> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [ {id: "1", name: "GeeksforGeeks"}, {id: "2", name: "GFG"} ]; var arr2 = [ {id: "1", name: "GeeksforGeeks"}, {id: "2", name: "GFG"} ]; up.innerHTML = "<h3>Array1:</h3> " + JSON.stringify(arr1) + "<h3>Array2:</h3> " + JSON.stringify(arr2); function compare(ar1, ar2) { if(JSON.stringify(arr1) == JSON.stringify(arr2)){ return true; } else return false; } function GFG_Fun() { down.innerHTML = compare(arr1, arr2); } </script> </body> </html> Output: Before Click on the Button: After Click on the Button: abhishek0719kadiyan javascript-array javascript-object JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26744, "s": 26716, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26862, "s": 26744, "text": "Given two JavaScript array/array objects and the task is to compare the equality of both array objects. Approach 1: " }, { "code": null, "e": 27055, "s": 26862, "text": "Use jQuery not() method to check for each element of array1, if it is not present in array2 or for each element of array2, if this is not present in array1, then it return false in both cases." }, { "code": null, "e": 27093, "s": 27055, "text": "Also check the length of both arrays." }, { "code": null, "e": 27180, "s": 27093, "text": "Example: This example uses jQuery not() method to compare the equality of both array. " }, { "code": null, "e": 27185, "s": 27180, "text": "html" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [1, 3, 5, 8]; var arr2 = [1, 3, 5, 7]; up.innerHTML = \"Click on the button to check \" + \"equality of arrays.<br>Array1 - \" + arr1 + \"<br>Array2 - \" + arr2; function GFG_Fun() { down.innerHTML = $(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0; } </script> </body> </html>", "e": 28342, "s": 27185, "text": null }, { "code": null, "e": 28352, "s": 28342, "text": "Output: " }, { "code": null, "e": 28385, "s": 28352, "text": "Before clicking on the button: " }, { "code": null, "e": 28417, "s": 28385, "text": "After clicking on the button: " }, { "code": null, "e": 28431, "s": 28417, "text": "Approach 2: " }, { "code": null, "e": 28498, "s": 28431, "text": "First, use sort() function to sort both arrays in ascending order." }, { "code": null, "e": 28625, "s": 28498, "text": "Then start matching the element one by one and if there is any mismatch found then it returns false otherwise it returns true." }, { "code": null, "e": 28682, "s": 28625, "text": "Example:This example uses approach as discussed above. " }, { "code": null, "e": 28687, "s": 28682, "text": "html" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [1, 3, 7, 5]; var arr2 = [1, 3, 5, 7]; up.innerHTML = \"Click on the button to check \" + \"equality of arrays.<br>Array1 - \" + arr1 + \"<br>Array2 - \" + arr2; function compare(ar1, ar2) { ar1.sort(); ar2.sort(); if(ar1.length != ar2.length) return false; for(var i = 0; i < ar1.length; i++) { if (ar1[i] != ar2[i]) return false; } return true; } function GFG_Fun() { down.innerHTML = compare(arr1, arr2); } </script> </body> </html>", "e": 30111, "s": 28687, "text": null }, { "code": null, "e": 30121, "s": 30111, "text": "Output: " }, { "code": null, "e": 30154, "s": 30121, "text": "Before clicking on the button: " }, { "code": null, "e": 30186, "s": 30154, "text": "After clicking on the button: " }, { "code": null, "e": 30200, "s": 30186, "text": "Approach 3: " }, { "code": null, "e": 30268, "s": 30200, "text": "Create two array objects and store it into arr1 and arr2 variables." }, { "code": null, "e": 30334, "s": 30268, "text": "Use JSON.stringify() function to convert object into JSON string." }, { "code": null, "e": 30440, "s": 30334, "text": "Now compare both JSON string using comparison operator (==) to check both array objects are equal or not." }, { "code": null, "e": 30533, "s": 30440, "text": "Note: This method works only when both array objects sorted into the same fashion.Example: " }, { "code": null, "e": 30538, "s": 30533, "text": "html" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to compare two JavaScript array objects using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h2> Click on the button to check equality of arrays </h2> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr1 = [ {id: \"1\", name: \"GeeksforGeeks\"}, {id: \"2\", name: \"GFG\"} ]; var arr2 = [ {id: \"1\", name: \"GeeksforGeeks\"}, {id: \"2\", name: \"GFG\"} ]; up.innerHTML = \"<h3>Array1:</h3> \" + JSON.stringify(arr1) + \"<h3>Array2:</h3> \" + JSON.stringify(arr2); function compare(ar1, ar2) { if(JSON.stringify(arr1) == JSON.stringify(arr2)){ return true; } else return false; } function GFG_Fun() { down.innerHTML = compare(arr1, arr2); } </script> </body> </html>", "e": 32082, "s": 30538, "text": null }, { "code": null, "e": 32092, "s": 32082, "text": "Output: " }, { "code": null, "e": 32122, "s": 32092, "text": "Before Click on the Button: " }, { "code": null, "e": 32151, "s": 32122, "text": "After Click on the Button: " }, { "code": null, "e": 32173, "s": 32153, "text": "abhishek0719kadiyan" }, { "code": null, "e": 32190, "s": 32173, "text": "javascript-array" }, { "code": null, "e": 32208, "s": 32190, "text": "javascript-object" }, { "code": null, "e": 32219, "s": 32208, "text": "JavaScript" }, { "code": null, "e": 32226, "s": 32219, "text": "JQuery" }, { "code": null, "e": 32243, "s": 32226, "text": "Web Technologies" }, { "code": null, "e": 32270, "s": 32243, "text": "Web technologies Questions" }, { "code": null, "e": 32368, "s": 32270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32408, "s": 32368, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32453, "s": 32408, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32514, "s": 32453, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32586, "s": 32514, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32638, "s": 32586, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 32684, "s": 32638, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 32713, "s": 32684, "text": "Form validation using jQuery" }, { "code": null, "e": 32776, "s": 32713, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 32853, "s": 32776, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Find the maximum number of composite summands of a number - GeeksforGeeks
21 Jul, 2021 Given an integer N(1<=N<=10^9). The task is to represent N as a sum of the maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. There can be multiple queries Examples: Input : 12 Output : 3 Explanation : 12 can be written has 4 + 4 + 4 or 6 + 6 or 8 + 4 But, 4 + 4 + 4 has maximum number of summands. Input : 7 Output : -1 Approach : Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in a splitting of big numbers. Let’s write for small numbers (1<=M<=N) dpN be the number of composite summands in splitting of N.Let’s find an answer for all numbers from 1 to 15. Several observations: Only 4, 6, 9 occurs in optimal splittings.It is not beneficial to use 6 or 9 more than once because 6 + 6 = 4 + 4 + 4, 9 + 9 = 6 + 6 + 6.12, 13, 14, 15 have valid splittings. Only 4, 6, 9 occurs in optimal splittings. It is not beneficial to use 6 or 9 more than once because 6 + 6 = 4 + 4 + 4, 9 + 9 = 6 + 6 + 6. 12, 13, 14, 15 have valid splittings. Let’s prove that all numbers that are greater than 15 will have 4 in optimal splitting. Let’s guess that it is incorrect. If the minimal number in splitting is neither 4 nor 6 nor 9 then this number will have some non-trivial splitting by induction.If this number either 6 or 9 and we will decrease query by this number then we will sooner or later get some small number (which is less or equal than 15). There is no splitting of small numbers or it contains 4 in splitting (and it contradicts with minimality of the first number) or it contains 6 and 9. So we have contradiction in all cases.We can subtract 4 from any big query and our solution is correct.If our query n is small number let’s print dpn. Else let’s find minimal number k such that n – 4·k is a small number. Then print k + dpn – 4·k. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; const int maxn = 16; // Function to generate the dp arrayvector<int> precompute(){ vector<int> dp(maxn, -1); dp[0] = 0; for (int i = 1; i < maxn; ++i) { // combination of three integers for (auto j : vector<int>{ 4, 6, 9 }) { // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = max(dp[i], dp[i - j] + 1); } } } return dp;} // Function to find the maximum number of summandsint Maximum_Summands(vector<int> dp, int n){ // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t]; }} // Driver codeint main(){ int n = 12; // Generate dp array vector<int> dp = precompute(); cout << Maximum_Summands(dp, n) << endl; return 0;} // Java implementation of the above approachclass GFG{ static int maxn = 16; // Function to generate the dp arraystatic int[] precompute(){int dp[] = new int[maxn], arr[]={ 4, 6, 9 }; // initializefor(int i = 0; i < maxn; i++)dp[i] = -1; dp[0] = 0; for (int i = 1; i < maxn; ++i){ // combination of three integers for (int k = 0; k < 3; k++) { int j = arr[k]; // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.max(dp[i], dp[i - j] + 1); } }} return dp;} // Function to find the maximum number of summandsstatic int Maximum_Summands(int[] dp, int n){// If n is a smaller number, less than 16// return dp[n]if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t];}} // Driver codepublic static void main(String args[]){ int n = 12; // Generate dp array int[] dp = precompute(); System.out.println(Maximum_Summands(dp, n));}} // This code is contributed by Arnab Kundu # Python 3 implementation of the above approachglobal maxnmaxn = 16 # Function to generate the dp arraydef precompute(): dp = [-1 for i in range(maxn)] dp[0] = 0 v = [4, 6, 9] for i in range(1, maxn, 1): # combination of three integers for k in range(3): j = v[k] # take the maximum number of summands if (i >= j and dp[i - j] != -1): dp[i] = max(dp[i], dp[i - j] + 1) return dp # Function to find the maximum number of summandsdef Maximum_Summands(dp, n): # If n is a smaller number, # less than 16, return dp[n] if (n < maxn): return dp[n] else: # Else, find a minimal number t # as explained in solution t = int((n - maxn) / 4)+ 1 return t + dp[n - 4 * t] # Driver codeif __name__ == '__main__': n = 12 # Generate dp array dp = precompute() print(Maximum_Summands(dp, n)) # This code is contributed by# Surendra_Gangwar // C# implementation of the above approachusing System;using System.Collections; class GFG{ static int maxn = 16;static int[] dp = new int[maxn + 1]; // Function to generate the dp arraystatic void precompute(){ for(int i = 0; i <= maxn; i++) dp[i] = -1; dp[0] = 0; int[] vec = { 4, 6, 9 }; for (int i = 1; i < maxn; ++i) { // combination of three integers foreach (int j in vec) { // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.Max(dp[i], dp[i - j] + 1); } } } } // Function to find the maximum number of summandsstatic int Maximum_Summands(int n){ // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t]; }} // Driver codestatic void Main(){ int n = 12; // Generate dp array precompute(); Console.WriteLine(Maximum_Summands(n));}} // This code is contributed by chandan_jnu <?php// PHP implementation of the above approach$maxn = 16; // Function to generate the dp arrayfunction precompute(){ $dp = array_fill(0, $GLOBALS['maxn'], -1); $dp[0] = 0; $v = array(4, 6, 9); for ($i = 1; $i < $GLOBALS['maxn']; ++$i) { // combination of three integers for ($k = 0; $k<3 ;$k++) { $j = $v[$k]; // take the maximum number of summands if ($i >= $j && $dp[$i - $j] != -1) { $dp[$i] = max($dp[$i], $dp[$i - $j] + 1); } } } return $dp;} // Function to find the maximum// number of summandsfunction Maximum_Summands($dp, $n){ // If n is a smaller number, // less than 16 return dp[n] if ($n < $GLOBALS['maxn']) return $dp[$n]; else { // Else, find a minimal number t // as explained in solution $t = ($n - $GLOBALS['maxn']) / 4 + 1; return $t + $dp[$n - 4 * $t]; }} // Driver code$n = 12; // Generate dp array$dp = precompute(); echo Maximum_Summands($dp, $n); // This code is contributed by Ryuga?> <script> // JavaScript implementation of the above approach let maxn = 16; // Function to generate the dp array function precompute() { let dp = new Array(maxn); let arr = [ 4, 6, 9 ]; // initialize for(let i = 0; i < maxn; i++) dp[i] = -1; dp[0] = 0; for (let i = 1; i < maxn; ++i) { // combination of three integers for (let k = 0; k < 3; k++) { let j = arr[k]; // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.max(dp[i], dp[i - j] + 1); } } } return dp; } // Function to find the maximum number of summands function Maximum_Summands(dp, n) { // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution let t = parseInt((n - maxn) / 4, 10) + 1; return t + dp[n - 4 * t]; } } let n = 12; // Generate dp array let dp = precompute(); document.write(Maximum_Summands(dp, n)); </script> 3 Chandan_Kumar andrew1234 SURENDRA_GANGWAR ankthon nidhi_biet hritikbhatnagar2182 suresh07 anikakapoor sagartomar9927 number-theory Competitive Programming Dynamic Programming Mathematical number-theory Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Pairs with same Manhattan and Euclidean distance Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm Multistage Graph (Shortest Path) Runtime Errors 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 25046, "s": 25018, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25274, "s": 25046, "text": "Given an integer N(1<=N<=10^9). The task is to represent N as a sum of the maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. There can be multiple queries" }, { "code": null, "e": 25285, "s": 25274, "text": "Examples: " }, { "code": null, "e": 25441, "s": 25285, "text": "Input : 12\nOutput : 3\nExplanation : 12 can be written has 4 + 4 + 4 or 6 + 6 or 8 + 4\nBut, 4 + 4 + 4 has maximum number of summands.\n\nInput : 7\nOutput : -1" }, { "code": null, "e": 25758, "s": 25441, "text": "Approach : Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in a splitting of big numbers. Let’s write for small numbers (1<=M<=N) dpN be the number of composite summands in splitting of N.Let’s find an answer for all numbers from 1 to 15. Several observations: " }, { "code": null, "e": 25933, "s": 25758, "text": "Only 4, 6, 9 occurs in optimal splittings.It is not beneficial to use 6 or 9 more than once because 6 + 6 = 4 + 4 + 4, 9 + 9 = 6 + 6 + 6.12, 13, 14, 15 have valid splittings." }, { "code": null, "e": 25976, "s": 25933, "text": "Only 4, 6, 9 occurs in optimal splittings." }, { "code": null, "e": 26072, "s": 25976, "text": "It is not beneficial to use 6 or 9 more than once because 6 + 6 = 4 + 4 + 4, 9 + 9 = 6 + 6 + 6." }, { "code": null, "e": 26110, "s": 26072, "text": "12, 13, 14, 15 have valid splittings." }, { "code": null, "e": 26912, "s": 26110, "text": "Let’s prove that all numbers that are greater than 15 will have 4 in optimal splitting. Let’s guess that it is incorrect. If the minimal number in splitting is neither 4 nor 6 nor 9 then this number will have some non-trivial splitting by induction.If this number either 6 or 9 and we will decrease query by this number then we will sooner or later get some small number (which is less or equal than 15). There is no splitting of small numbers or it contains 4 in splitting (and it contradicts with minimality of the first number) or it contains 6 and 9. So we have contradiction in all cases.We can subtract 4 from any big query and our solution is correct.If our query n is small number let’s print dpn. Else let’s find minimal number k such that n – 4·k is a small number. Then print k + dpn – 4·k." }, { "code": null, "e": 26965, "s": 26912, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26969, "s": 26965, "text": "C++" }, { "code": null, "e": 26974, "s": 26969, "text": "Java" }, { "code": null, "e": 26982, "s": 26974, "text": "Python3" }, { "code": null, "e": 26985, "s": 26982, "text": "C#" }, { "code": null, "e": 26989, "s": 26985, "text": "PHP" }, { "code": null, "e": 27000, "s": 26989, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; const int maxn = 16; // Function to generate the dp arrayvector<int> precompute(){ vector<int> dp(maxn, -1); dp[0] = 0; for (int i = 1; i < maxn; ++i) { // combination of three integers for (auto j : vector<int>{ 4, 6, 9 }) { // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = max(dp[i], dp[i - j] + 1); } } } return dp;} // Function to find the maximum number of summandsint Maximum_Summands(vector<int> dp, int n){ // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t]; }} // Driver codeint main(){ int n = 12; // Generate dp array vector<int> dp = precompute(); cout << Maximum_Summands(dp, n) << endl; return 0;}", "e": 28046, "s": 27000, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ static int maxn = 16; // Function to generate the dp arraystatic int[] precompute(){int dp[] = new int[maxn], arr[]={ 4, 6, 9 }; // initializefor(int i = 0; i < maxn; i++)dp[i] = -1; dp[0] = 0; for (int i = 1; i < maxn; ++i){ // combination of three integers for (int k = 0; k < 3; k++) { int j = arr[k]; // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.max(dp[i], dp[i - j] + 1); } }} return dp;} // Function to find the maximum number of summandsstatic int Maximum_Summands(int[] dp, int n){// If n is a smaller number, less than 16// return dp[n]if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t];}} // Driver codepublic static void main(String args[]){ int n = 12; // Generate dp array int[] dp = precompute(); System.out.println(Maximum_Summands(dp, n));}} // This code is contributed by Arnab Kundu", "e": 29130, "s": 28046, "text": null }, { "code": "# Python 3 implementation of the above approachglobal maxnmaxn = 16 # Function to generate the dp arraydef precompute(): dp = [-1 for i in range(maxn)] dp[0] = 0 v = [4, 6, 9] for i in range(1, maxn, 1): # combination of three integers for k in range(3): j = v[k] # take the maximum number of summands if (i >= j and dp[i - j] != -1): dp[i] = max(dp[i], dp[i - j] + 1) return dp # Function to find the maximum number of summandsdef Maximum_Summands(dp, n): # If n is a smaller number, # less than 16, return dp[n] if (n < maxn): return dp[n] else: # Else, find a minimal number t # as explained in solution t = int((n - maxn) / 4)+ 1 return t + dp[n - 4 * t] # Driver codeif __name__ == '__main__': n = 12 # Generate dp array dp = precompute() print(Maximum_Summands(dp, n)) # This code is contributed by# Surendra_Gangwar", "e": 30135, "s": 29130, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections; class GFG{ static int maxn = 16;static int[] dp = new int[maxn + 1]; // Function to generate the dp arraystatic void precompute(){ for(int i = 0; i <= maxn; i++) dp[i] = -1; dp[0] = 0; int[] vec = { 4, 6, 9 }; for (int i = 1; i < maxn; ++i) { // combination of three integers foreach (int j in vec) { // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.Max(dp[i], dp[i - j] + 1); } } } } // Function to find the maximum number of summandsstatic int Maximum_Summands(int n){ // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution int t = (n - maxn) / 4 + 1; return t + dp[n - 4 * t]; }} // Driver codestatic void Main(){ int n = 12; // Generate dp array precompute(); Console.WriteLine(Maximum_Summands(n));}} // This code is contributed by chandan_jnu", "e": 31283, "s": 30135, "text": null }, { "code": "<?php// PHP implementation of the above approach$maxn = 16; // Function to generate the dp arrayfunction precompute(){ $dp = array_fill(0, $GLOBALS['maxn'], -1); $dp[0] = 0; $v = array(4, 6, 9); for ($i = 1; $i < $GLOBALS['maxn']; ++$i) { // combination of three integers for ($k = 0; $k<3 ;$k++) { $j = $v[$k]; // take the maximum number of summands if ($i >= $j && $dp[$i - $j] != -1) { $dp[$i] = max($dp[$i], $dp[$i - $j] + 1); } } } return $dp;} // Function to find the maximum// number of summandsfunction Maximum_Summands($dp, $n){ // If n is a smaller number, // less than 16 return dp[n] if ($n < $GLOBALS['maxn']) return $dp[$n]; else { // Else, find a minimal number t // as explained in solution $t = ($n - $GLOBALS['maxn']) / 4 + 1; return $t + $dp[$n - 4 * $t]; }} // Driver code$n = 12; // Generate dp array$dp = precompute(); echo Maximum_Summands($dp, $n); // This code is contributed by Ryuga?>", "e": 32410, "s": 31283, "text": null }, { "code": "<script> // JavaScript implementation of the above approach let maxn = 16; // Function to generate the dp array function precompute() { let dp = new Array(maxn); let arr = [ 4, 6, 9 ]; // initialize for(let i = 0; i < maxn; i++) dp[i] = -1; dp[0] = 0; for (let i = 1; i < maxn; ++i) { // combination of three integers for (let k = 0; k < 3; k++) { let j = arr[k]; // take the maximum number of summands if (i >= j && dp[i - j] != -1) { dp[i] = Math.max(dp[i], dp[i - j] + 1); } } } return dp; } // Function to find the maximum number of summands function Maximum_Summands(dp, n) { // If n is a smaller number, less than 16 // return dp[n] if (n < maxn) return dp[n]; else { // Else, find a minimal number t // as explained in solution let t = parseInt((n - maxn) / 4, 10) + 1; return t + dp[n - 4 * t]; } } let n = 12; // Generate dp array let dp = precompute(); document.write(Maximum_Summands(dp, n)); </script>", "e": 33698, "s": 32410, "text": null }, { "code": null, "e": 33700, "s": 33698, "text": "3" }, { "code": null, "e": 33716, "s": 33702, "text": "Chandan_Kumar" }, { "code": null, "e": 33727, "s": 33716, "text": "andrew1234" }, { "code": null, "e": 33744, "s": 33727, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33752, "s": 33744, "text": "ankthon" }, { "code": null, "e": 33763, "s": 33752, "text": "nidhi_biet" }, { "code": null, "e": 33783, "s": 33763, "text": "hritikbhatnagar2182" }, { "code": null, "e": 33792, "s": 33783, "text": "suresh07" }, { "code": null, "e": 33804, "s": 33792, "text": "anikakapoor" }, { "code": null, "e": 33819, "s": 33804, "text": "sagartomar9927" }, { "code": null, "e": 33833, "s": 33819, "text": "number-theory" }, { "code": null, "e": 33857, "s": 33833, "text": "Competitive Programming" }, { "code": null, "e": 33877, "s": 33857, "text": "Dynamic Programming" }, { "code": null, "e": 33890, "s": 33877, "text": "Mathematical" }, { "code": null, "e": 33904, "s": 33890, "text": "number-theory" }, { "code": null, "e": 33924, "s": 33904, "text": "Dynamic Programming" }, { "code": null, "e": 33937, "s": 33924, "text": "Mathematical" }, { "code": null, "e": 34035, "s": 33937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34044, "s": 34035, "text": "Comments" }, { "code": null, "e": 34057, "s": 34044, "text": "Old Comments" }, { "code": null, "e": 34106, "s": 34057, "text": "Pairs with same Manhattan and Euclidean distance" }, { "code": null, "e": 34152, "s": 34106, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 34210, "s": 34152, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 34243, "s": 34210, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 34258, "s": 34243, "text": "Runtime Errors" }, { "code": null, "e": 34287, "s": 34258, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 34317, "s": 34287, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34349, "s": 34317, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 34383, "s": 34349, "text": "Longest Common Subsequence | DP-4" } ]
Collapsing Table Borders in CSS
The CSS border-collapse property is used to specify whether <table>elements have shared or separate borders. It can take two values: separate and collapse. The syntax of CSS border-collapse property is as follows − Selector { border-collapse: /*value*/ } The following examples illustrate CSS border-collapse − Live Demo <!DOCTYPE html> <html> <head> <style> #cdemo { border-collapse: collapse; } #sdemo { border-collapse: separate; } table { display: inline-table; margin: 30px; } th,td { border: 3px ridge orange; } td { border-color: red; } caption { box-shadow: 0px -5px 4px 3px green; } </style> </head> <body> <h2>Employee Records</h2> <table id="sdemo"> <caption> Employee Details (Separate Border) </caption> <tr> <th>Employee</th> <th>Department</th> </tr> <tr> <td>Tim</td> <td>Operations</td> </tr> <tr> <td>Nathan</td> <td>Finance</td> </tr> <tr> <td>John </td> <td>Marketing</td> </tr> </table> <table id="cdemo"> <caption> Employee Details (Collapse Border) </caption> <tr> <th>Employee</th> <th>Department</th> </tr> <tr> <td>Tim</td> <td>Operations</td> </tr> <tr> <td>Nathan</td> <td>Finance</td> </tr> <tr> <td>John </td> <td>Marketing</td> </tr> </table> </body> </html> This gives the following output − Live Demo <!DOCTYPE html> <html> <head> <style> table { border-collapse: separate; empty-cells: hide; display: inline-table; margin: 30px; } table+table { border-collapse: collapse; empty-cells: hide; } td { border: 3px ridge lightblue; } caption { box-shadow: 0px -5px 4px 3px grey; } </style> </head> <body> <h2>Demo Tables</h2> <table> <caption>Demo caption</caption> <tr> <td>demo</td> <td>demo</td> </tr> <tr> <td>demo</td> <td>demo</td> </tr> <tr> <td>demo</td> <td>demo</td> <td></td> </tr> </table> <table> <caption>Demo caption</caption> <tr> <td>demo</td> <td>demo</td> </tr> <tr> <td>demo</td> <td>demo</td> </tr> <tr> <td>demo</td> <td>demo</td> <td></td> </tr> </table> </body> </html> This gives the following output −
[ { "code": null, "e": 1218, "s": 1062, "text": "The CSS border-collapse property is used to specify whether <table>elements have shared or separate borders. It can take two values: separate and collapse." }, { "code": null, "e": 1277, "s": 1218, "text": "The syntax of CSS border-collapse property is as follows −" }, { "code": null, "e": 1320, "s": 1277, "text": "Selector {\n border-collapse: /*value*/\n}" }, { "code": null, "e": 1376, "s": 1320, "text": "The following examples illustrate CSS border-collapse −" }, { "code": null, "e": 1387, "s": 1376, "text": " Live Demo" }, { "code": null, "e": 2277, "s": 1387, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n#cdemo {\n border-collapse: collapse;\n}\n#sdemo {\n border-collapse: separate;\n}\ntable {\n display: inline-table;\n margin: 30px;\n}\nth,td {\n border: 3px ridge orange;\n}\ntd {\n border-color: red;\n}\ncaption {\n box-shadow: 0px -5px 4px 3px green;\n}\n</style>\n</head>\n<body>\n<h2>Employee Records</h2>\n<table id=\"sdemo\">\n<caption> Employee Details (Separate Border) </caption>\n<tr>\n<th>Employee</th>\n<th>Department</th>\n</tr>\n<tr>\n<td>Tim</td>\n<td>Operations</td>\n</tr>\n<tr>\n<td>Nathan</td>\n<td>Finance</td>\n</tr>\n<tr>\n<td>John </td>\n<td>Marketing</td>\n</tr>\n</table>\n<table id=\"cdemo\">\n<caption> Employee Details (Collapse Border) </caption>\n<tr>\n<th>Employee</th>\n<th>Department</th>\n</tr>\n<tr>\n<td>Tim</td>\n<td>Operations</td>\n</tr>\n<tr>\n<td>Nathan</td>\n<td>Finance</td>\n</tr>\n<tr>\n<td>John </td>\n<td>Marketing</td>\n</tr>\n</table>\n</body>\n</html>" }, { "code": null, "e": 2311, "s": 2277, "text": "This gives the following output −" }, { "code": null, "e": 2322, "s": 2311, "text": " Live Demo" }, { "code": null, "e": 3035, "s": 2322, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n border-collapse: separate;\n empty-cells: hide;\n display: inline-table;\n margin: 30px;\n}\ntable+table {\n border-collapse: collapse;\n empty-cells: hide;\n}\ntd {\n border: 3px ridge lightblue;\n}\ncaption {\n box-shadow: 0px -5px 4px 3px grey;\n}\n</style>\n</head>\n<body>\n<h2>Demo Tables</h2>\n<table>\n<caption>Demo caption</caption>\n<tr>\n<td>demo</td>\n<td>demo</td>\n</tr>\n<tr>\n<td>demo</td>\n<td>demo</td>\n</tr>\n<tr>\n<td>demo</td>\n<td>demo</td>\n<td></td>\n</tr>\n</table>\n<table>\n<caption>Demo caption</caption>\n<tr>\n<td>demo</td>\n<td>demo</td>\n</tr>\n<tr>\n<td>demo</td>\n<td>demo</td>\n</tr>\n<tr>\n<td>demo</td>\n<td>demo</td>\n<td></td>\n</tr>\n</table>\n</body>\n</html>" }, { "code": null, "e": 3069, "s": 3035, "text": "This gives the following output −" } ]
Difference between 3-address instruction and 0-address instruction - GeeksforGeeks
16 May, 2020 Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One address field is used for destination and two address fields for source. Example: X = (A + B) x (C + D) Solution: ADD R1, A, B R1 <- M[A] + M[B] ADD R2, C, D R2 <- M[C] + M[D] MUL X, R1, R2 M[X] <- R1 x R2 2. Zero-Address Instructions :Zero-address instruction is a format of machine instruction. It has one opcode and no address fields. Example: X = (A + B) x (C + D) Solution: LOAD A AC <- M[A] PUSH A TOS <- A PUSH B TOS <- B ADD TOS <- (A + B) PUSH C TOS <- C PUSH D TOS <- D ADD TOS <- (C + D) MUL TOS <- (C + D) x (A + B) POP X M[X] <- TOS Difference between Three-Address Instruction and Zero-Address Instruction : Computer Organization & Architecture Difference Between GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor I2C Communication Protocol Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 26049, "s": 26021, "text": "\n16 May, 2020" }, { "code": null, "e": 26297, "s": 26049, "text": "Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One address field is used for destination and two address fields for source." }, { "code": null, "e": 26306, "s": 26297, "text": "Example:" }, { "code": null, "e": 26329, "s": 26306, "text": "X = (A + B) x (C + D) " }, { "code": null, "e": 26339, "s": 26329, "text": "Solution:" }, { "code": null, "e": 26446, "s": 26339, "text": "ADD R1, A, B R1 <- M[A] + M[B]\nADD R2, C, D R2 <- M[C] + M[D]\nMUL X, R1, R2 M[X] <- R1 x R2 " }, { "code": null, "e": 26578, "s": 26446, "text": "2. Zero-Address Instructions :Zero-address instruction is a format of machine instruction. It has one opcode and no address fields." }, { "code": null, "e": 26587, "s": 26578, "text": "Example:" }, { "code": null, "e": 26610, "s": 26587, "text": "X = (A + B) x (C + D) " }, { "code": null, "e": 26620, "s": 26610, "text": "Solution:" }, { "code": null, "e": 26843, "s": 26620, "text": "LOAD A AC <- M[A]\nPUSH A TOS <- A\nPUSH B TOS <- B\nADD TOS <- (A + B)\nPUSH C TOS <- C\nPUSH D TOS <- D\nADD TOS <- (C + D)\nMUL TOS <- (C + D) x (A + B)\nPOP X M[X] <- TOS " }, { "code": null, "e": 26919, "s": 26843, "text": "Difference between Three-Address Instruction and Zero-Address Instruction :" }, { "code": null, "e": 26956, "s": 26919, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26975, "s": 26956, "text": "Difference Between" }, { "code": null, "e": 26983, "s": 26975, "text": "GATE CS" }, { "code": null, "e": 27081, "s": 26983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27143, "s": 27081, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 27234, "s": 27143, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 27270, "s": 27234, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 27305, "s": 27270, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 27332, "s": 27305, "text": "I2C Communication Protocol" }, { "code": null, "e": 27363, "s": 27332, "text": "Difference between BFS and DFS" }, { "code": null, "e": 27403, "s": 27363, "text": "Class method vs Static method in Python" }, { "code": null, "e": 27435, "s": 27403, "text": "Differences between TCP and UDP" }, { "code": null, "e": 27496, "s": 27435, "text": "Difference between var, let and const keywords in JavaScript" } ]
Angular PrimeNG tag Component - GeeksforGeeks
08 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the tag component in Angular PrimeNG. tag component: It is used to make a tag in order to categorize the content. Properties: value: It specifies the value to display inside the tag. It is of string data type, the default value is null. severity: It specifies the severity type of the tag. It is of string data type, the default value is null. rounded: It specifies whether the corners of the tag are rounded or not. It is of the boolean data type, the default value is false. icon: It sets the icon of the tag to display next to the value. It is of string data type, the default value is null. style: It specifies the inline style of the component. It is of object data type, the default value is null. styleClass: It specifies the style class of the component. It is of string data type, the default value is null. Styling: p-tag: It is a tag element. p-tag-rounded: It is used to make the rounded shaped elements. p-tag-icon: It is a tag icon. p-tag-value: It is a value of the tag. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: After complete installation, it will look like the following: Example 1: This is the basic example that shows how to use the tag component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNg Tag Component</h5><p-tag styleClass="p-mr-2" value="Tag1" icon="pi pi-check"></p-tag><p-tag styleClass="p-mr-2" value="Tag2" icon="pi pi-bars" severity="success"></p-tag><p-tag styleClass="p-mr-2" value="Tag3" icon="pi pi-info" severity="info"></p-tag><p-tag styleClass="p-mr-2" value="Tag4" icon="pi pi-times" severity="danger"></p-tag><p-tag styleClass="p-mr-2" value="Tag5" icon="pi pi-thumbs-up" severity="warning"></p-tag> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { TagModule } from 'primeng/tag'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TagModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} Output: Example 2: In this example, we will use the rounded property in the tag component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNg Tag Component</h5><p-tag styleClass="p-mr-2" value="Check" rounded='true' icon="pi pi-check" severity="success"></p-tag><p-tag styleClass="p-mr-2" value="Info" rounded='true' icon="pi pi-info"></p-tag><p-tag styleClass="p-mr-2" value="Bars" rounded='true' icon="pi pi-bars" severity="danger"></p-tag><p-tag styleClass="p-mr-2" value="Thumbs Up" rounded='true' icon="pi pi-thumbs-up" severity="warning"></p-tag><p-tag styleClass="p-mr-2" value="Cross" rounded='true' icon="pi pi-times" severity="info"></p-tag> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { TagModule } from 'primeng/tag'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TagModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} Output: Reference: https://primefaces.org/primeng/showcase/#/tag Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26743, "s": 26464, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the tag component in Angular PrimeNG." }, { "code": null, "e": 26819, "s": 26743, "text": "tag component: It is used to make a tag in order to categorize the content." }, { "code": null, "e": 26831, "s": 26819, "text": "Properties:" }, { "code": null, "e": 26942, "s": 26831, "text": "value: It specifies the value to display inside the tag. It is of string data type, the default value is null." }, { "code": null, "e": 27049, "s": 26942, "text": "severity: It specifies the severity type of the tag. It is of string data type, the default value is null." }, { "code": null, "e": 27182, "s": 27049, "text": "rounded: It specifies whether the corners of the tag are rounded or not. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27300, "s": 27182, "text": "icon: It sets the icon of the tag to display next to the value. It is of string data type, the default value is null." }, { "code": null, "e": 27409, "s": 27300, "text": "style: It specifies the inline style of the component. It is of object data type, the default value is null." }, { "code": null, "e": 27522, "s": 27409, "text": "styleClass: It specifies the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27531, "s": 27522, "text": "Styling:" }, { "code": null, "e": 27559, "s": 27531, "text": "p-tag: It is a tag element." }, { "code": null, "e": 27622, "s": 27559, "text": "p-tag-rounded: It is used to make the rounded shaped elements." }, { "code": null, "e": 27652, "s": 27622, "text": "p-tag-icon: It is a tag icon." }, { "code": null, "e": 27691, "s": 27652, "text": "p-tag-value: It is a value of the tag." }, { "code": null, "e": 27745, "s": 27693, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27812, "s": 27745, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 27827, "s": 27812, "text": "ng new appname" }, { "code": null, "e": 27924, "s": 27827, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 27935, "s": 27924, "text": "cd appname" }, { "code": null, "e": 27984, "s": 27935, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28041, "s": 27984, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28122, "s": 28041, "text": "Project Structure: After complete installation, it will look like the following:" }, { "code": null, "e": 28202, "s": 28124, "text": "Example 1: This is the basic example that shows how to use the tag component." }, { "code": null, "e": 28221, "s": 28202, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNg Tag Component</h5><p-tag styleClass=\"p-mr-2\" value=\"Tag1\" icon=\"pi pi-check\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Tag2\" icon=\"pi pi-bars\" severity=\"success\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Tag3\" icon=\"pi pi-info\" severity=\"info\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Tag4\" icon=\"pi pi-times\" severity=\"danger\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Tag5\" icon=\"pi pi-thumbs-up\" severity=\"warning\"></p-tag>", "e": 28718, "s": 28221, "text": null }, { "code": null, "e": 28732, "s": 28718, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { TagModule } from 'primeng/tag'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TagModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 29189, "s": 28732, "text": null }, { "code": null, "e": 29206, "s": 29189, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 29351, "s": 29206, "text": null }, { "code": null, "e": 29359, "s": 29351, "text": "Output:" }, { "code": null, "e": 29442, "s": 29359, "text": "Example 2: In this example, we will use the rounded property in the tag component." }, { "code": null, "e": 29461, "s": 29442, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNg Tag Component</h5><p-tag styleClass=\"p-mr-2\" value=\"Check\" rounded='true' icon=\"pi pi-check\" severity=\"success\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Info\" rounded='true' icon=\"pi pi-info\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Bars\" rounded='true' icon=\"pi pi-bars\" severity=\"danger\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Thumbs Up\" rounded='true' icon=\"pi pi-thumbs-up\" severity=\"warning\"></p-tag><p-tag styleClass=\"p-mr-2\" value=\"Cross\" rounded='true' icon=\"pi pi-times\" severity=\"info\"></p-tag>", "e": 30040, "s": 29461, "text": null }, { "code": null, "e": 30054, "s": 30040, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { TagModule } from 'primeng/tag'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, TagModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 30511, "s": 30054, "text": null }, { "code": null, "e": 30528, "s": 30511, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 30673, "s": 30528, "text": null }, { "code": null, "e": 30681, "s": 30673, "text": "Output:" }, { "code": null, "e": 30738, "s": 30681, "text": "Reference: https://primefaces.org/primeng/showcase/#/tag" }, { "code": null, "e": 30754, "s": 30738, "text": "Angular-PrimeNG" }, { "code": null, "e": 30764, "s": 30754, "text": "AngularJS" }, { "code": null, "e": 30781, "s": 30764, "text": "Web Technologies" }, { "code": null, "e": 30879, "s": 30781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30914, "s": 30879, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30949, "s": 30914, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 30984, "s": 30949, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31008, "s": 30984, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31061, "s": 31008, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31101, "s": 31061, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31134, "s": 31101, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31179, "s": 31134, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31222, "s": 31179, "text": "How to fetch data from an API in ReactJS ?" } ]
Google BigQuery SQL Dates and Times Cheat Sheet | by Rebecca Vickery | Towards Data Science
I have just started working on a time series forecasting project this morning. The first step in this project, as with most data science tasks, was to gather the data first. This meant a relatively simple SQL query in Google BigQuery. Once again I found myself googling how to extract the year from a timestamp, and scrolling through the documentation to find the correct function and realised that I needed to write this down somewhere. I am writing this into a blog post so that I have something to refer back to, and hopefully this may also help others. Please note all expressions are based on Standard SQL. List of all date parts that can be used in the expressions listed below: DAYOFWEEK (returns 1-7 Sunday is 1)DAYDAYOFYEAR (0-365)WEEK (week of year 0-53, week begins on Sunday)WEEK(<chosen weekday>) (week of year begins on your chosen day e.g. SUNDAY)ISOWEEK (ISO 8601 week number, week begins on Monday)MONTHQUARTER (1-4)YEAR (ISO 8601 year number) EXTRACT(part FROM date_expression)Example: EXTRACT(YEAR FROM 2019-04-01)Output: 2019 DATE(year, month, day)Example: DATE(2019, 04, 01)Output: 2019-04-01 DATE_ADD(date_expression, INTERVAL INT64_expr date_part)Example: DATE_ADD('2019-04-01', INTERVAL 1 DAY)Output: 2019-04-02DATE_SUB(date_expression, INTERVAL INT64_expr date_part)Example: DATE_SUB('2019-04-01', INTERVAL 1 DAY)Output: 2019-03-31Example use case - dynamic dates:where my_date between DATE_SUB(current_date, INTERVAL 7 DAY) and DATE_SUB(current_date, INTERVAL 1 DAY) DATE_DIFF(date_expression, date_expression, date_part)Example: DATE_DIFF(2019-02-02, 2019-02-01, DAY)Output: 1 DATE_TRUNC(date_expression, date_part)Example: DATE_TRUNC(2019-04-12, WEEK)Output: 2019-04-07 MICROSECONDMILLISECONDSECONDMINUTEHOUR DATETIME(year, month, day, hour, minute, second)DATETIME(date_expression, time_expression)DATETIME(timestamp_expression [, timezone])Example: DATETIME(2019, 04, 01, 11, 55, 00)Output: 2019-04-01 11:55:00 DATETIME_ADD(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_ADD('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:56:00DATETIME_SUB(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_SUB('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:54:00 DATETIME_DIFF(datetime_expression, datetime_expression, part)Example: DATETIME_DIFF('2019-04-01 11:56:00', '2019-04-01 11:55:00', MINUTE)Output: 1 DATETIME_TRUNC(datetime_expression, part)Example: DATETIME_TRUNC('2019-04-01 11:55:00', HOUR)Output: 2019-04-01 11:00:00 This is not by any means an exhaustive guide to date and time expressions in BigQuery. It is only meant as a quick reference to those I use most often. For a more comprehensive guide please see the Google BigQuery documentation.
[ { "code": null, "e": 784, "s": 172, "text": "I have just started working on a time series forecasting project this morning. The first step in this project, as with most data science tasks, was to gather the data first. This meant a relatively simple SQL query in Google BigQuery. Once again I found myself googling how to extract the year from a timestamp, and scrolling through the documentation to find the correct function and realised that I needed to write this down somewhere. I am writing this into a blog post so that I have something to refer back to, and hopefully this may also help others. Please note all expressions are based on Standard SQL." }, { "code": null, "e": 857, "s": 784, "text": "List of all date parts that can be used in the expressions listed below:" }, { "code": null, "e": 1134, "s": 857, "text": "DAYOFWEEK (returns 1-7 Sunday is 1)DAYDAYOFYEAR (0-365)WEEK (week of year 0-53, week begins on Sunday)WEEK(<chosen weekday>) (week of year begins on your chosen day e.g. SUNDAY)ISOWEEK (ISO 8601 week number, week begins on Monday)MONTHQUARTER (1-4)YEAR (ISO 8601 year number) " }, { "code": null, "e": 1219, "s": 1134, "text": "EXTRACT(part FROM date_expression)Example: EXTRACT(YEAR FROM 2019-04-01)Output: 2019" }, { "code": null, "e": 1287, "s": 1219, "text": "DATE(year, month, day)Example: DATE(2019, 04, 01)Output: 2019-04-01" }, { "code": null, "e": 1666, "s": 1287, "text": "DATE_ADD(date_expression, INTERVAL INT64_expr date_part)Example: DATE_ADD('2019-04-01', INTERVAL 1 DAY)Output: 2019-04-02DATE_SUB(date_expression, INTERVAL INT64_expr date_part)Example: DATE_SUB('2019-04-01', INTERVAL 1 DAY)Output: 2019-03-31Example use case - dynamic dates:where my_date between DATE_SUB(current_date, INTERVAL 7 DAY) and DATE_SUB(current_date, INTERVAL 1 DAY)" }, { "code": null, "e": 1777, "s": 1666, "text": "DATE_DIFF(date_expression, date_expression, date_part)Example: DATE_DIFF(2019-02-02, 2019-02-01, DAY)Output: 1" }, { "code": null, "e": 1871, "s": 1777, "text": "DATE_TRUNC(date_expression, date_part)Example: DATE_TRUNC(2019-04-12, WEEK)Output: 2019-04-07" }, { "code": null, "e": 1910, "s": 1871, "text": "MICROSECONDMILLISECONDSECONDMINUTEHOUR" }, { "code": null, "e": 2114, "s": 1910, "text": "DATETIME(year, month, day, hour, minute, second)DATETIME(date_expression, time_expression)DATETIME(timestamp_expression [, timezone])Example: DATETIME(2019, 04, 01, 11, 55, 00)Output: 2019-04-01 11:55:00" }, { "code": null, "e": 2413, "s": 2114, "text": "DATETIME_ADD(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_ADD('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:56:00DATETIME_SUB(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_SUB('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:54:00" }, { "code": null, "e": 2560, "s": 2413, "text": "DATETIME_DIFF(datetime_expression, datetime_expression, part)Example: DATETIME_DIFF('2019-04-01 11:56:00', '2019-04-01 11:55:00', MINUTE)Output: 1" }, { "code": null, "e": 2681, "s": 2560, "text": "DATETIME_TRUNC(datetime_expression, part)Example: DATETIME_TRUNC('2019-04-01 11:55:00', HOUR)Output: 2019-04-01 11:00:00" } ]
CharArrayWriter append() method in Java with Examples - GeeksforGeeks
05 Jun, 2020 The append() method of CharArrayWriter class in Java is of three types: The append(char) method of CharArrayWriter class in Java is used to append the specified character to the writer. This append() method appends one character at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(char c) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS The append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = "GEEKS"; CharSequence csq2 = "FOR"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKSFORGEEKS The append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq, int start, int end) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: csq – It represents the character sequence whose subsequence is to be appended.start – It represents the starting index for the subsequence.end – It represents the index of character following the end for the subsequence.Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = "GEEKSFORGEEKS"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS The append(char) method of CharArrayWriter class in Java is used to append the specified character to the writer. This append() method appends one character at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(char c) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS public CharArrayWriter append(char c) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: Java // Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }} GEEKS The append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = "GEEKS"; CharSequence csq2 = "FOR"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKSFORGEEKS The append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: Java // Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = "GEEKS"; CharSequence csq2 = "FOR"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }} GEEKSFORGEEKS The append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq, int start, int end) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: csq – It represents the character sequence whose subsequence is to be appended.start – It represents the starting index for the subsequence.end – It represents the index of character following the end for the subsequence.Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = "GEEKSFORGEEKS"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS The append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq, int start, int end) Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: csq – It represents the character sequence whose subsequence is to be appended. start – It represents the starting index for the subsequence. end – It represents the index of character following the end for the subsequence. Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: Java // Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = "GEEKSFORGEEKS"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }} GEEKS References: 1. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(char) 2. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(java.lang.CharSequence) 3. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(java.lang.CharSequence, int, int) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java HashMap get() Method in Java Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n05 Jun, 2020" }, { "code": null, "e": 24020, "s": 23948, "text": "The append() method of CharArrayWriter class in Java is of three types:" }, { "code": null, "e": 28925, "s": 24020, "text": "The append(char) method of CharArrayWriter class in Java is used to append the specified character to the writer. This append() method appends one character at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(char c)\n\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS\nThe append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq)\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = \"GEEKS\"; CharSequence csq2 = \"FOR\"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKSFORGEEKS\nThe append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq, \n int start, \n int end)\n\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: csq – It represents the character sequence whose subsequence is to be appended.start – It represents the starting index for the subsequence.end – It represents the index of character following the end for the subsequence.Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = \"GEEKSFORGEEKS\"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS\n" }, { "code": null, "e": 30312, "s": 28925, "text": "The append(char) method of CharArrayWriter class in Java is used to append the specified character to the writer. This append() method appends one character at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(char c)\n\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS\n" }, { "code": null, "e": 30352, "s": 30312, "text": "public CharArrayWriter append(char c)\n\n" }, { "code": null, "e": 30852, "s": 30352, "text": "Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter c that represents the 16-bit character that is to be appended.Return value: This method returns CharArrayWriter after appending the character into it.Exceptions: This method does not throw any exception.Below program illustrates append(char) method in CharArrayWriter class in IO package:Program: " }, { "code": null, "e": 30857, "s": 30852, "text": "Java" }, { "code": "// Java program to illustrate// CharArrayWriter append(char) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Append the character charArrayWriter.append('G'); charArrayWriter.append('E'); charArrayWriter.append('E'); charArrayWriter.append('K'); charArrayWriter.append('S'); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}", "e": 31453, "s": 30857, "text": null }, { "code": null, "e": 31460, "s": 31453, "text": "GEEKS\n" }, { "code": null, "e": 33092, "s": 31460, "text": "The append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq)\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = \"GEEKS\"; CharSequence csq2 = \"FOR\"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKSFORGEEKS\n" }, { "code": null, "e": 33349, "s": 33092, "text": "The append(CharSequence) method of CharArrayWriter class in Java is used to append the specified character sequence to the writer. This append() method appends a character sequence at a time to the CharArrayWriter and returns this CharArrayWriter.Syntax: " }, { "code": null, "e": 33398, "s": 33349, "text": "public CharArrayWriter append(CharSequence csq)\n" }, { "code": null, "e": 34018, "s": 33398, "text": "Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts one parameter csq that represents the character sequence that is to be appended. If the character sequence is null then the 4 characters ‘null’ is appended to the CharArrayWriter.Return value: This method returns CharArrayWriter after appending the character sequence into it.Exceptions: This method does not throw any exception.Below program illustrates append(CharSequence) method in CharArrayWriter class in IO package:Program: " }, { "code": null, "e": 34023, "s": 34018, "text": "Java" }, { "code": "// Java program to illustrate// CharArrayWriter append(CharSequence) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq1 = \"GEEKS\"; CharSequence csq2 = \"FOR\"; // Append character sequences // to the charArrayWriter charArrayWriter.append(csq1); charArrayWriter.append(csq2); charArrayWriter.append(csq1); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}", "e": 34703, "s": 34023, "text": null }, { "code": null, "e": 34718, "s": 34703, "text": "GEEKSFORGEEKS\n" }, { "code": null, "e": 36606, "s": 34718, "text": "The append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: public CharArrayWriter append(CharSequence csq, \n int start, \n int end)\n\nSpecified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: csq – It represents the character sequence whose subsequence is to be appended.start – It represents the starting index for the subsequence.end – It represents the index of character following the end for the subsequence.Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: JavaJava// Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = \"GEEKSFORGEEKS\"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}Output:GEEKS\n" }, { "code": null, "e": 36891, "s": 36606, "text": "The append(CharSequence, int, int) method of CharArrayWriter class in Java is used to append the subsequence of a specified character sequence to the writer. This append() method appends a portion of character sequence to the CharArrayWriter and returns this CharArrayWriter.Syntax: " }, { "code": null, "e": 37023, "s": 36891, "text": "public CharArrayWriter append(CharSequence csq, \n int start, \n int end)\n\n" }, { "code": null, "e": 37230, "s": 37023, "text": "Specified By: This method is specified by the append() method of Appendable interface.Overrides: This method overrides the append() method of Writer class.Parameters: This method accepts three parameters: " }, { "code": null, "e": 37310, "s": 37230, "text": "csq – It represents the character sequence whose subsequence is to be appended." }, { "code": null, "e": 37372, "s": 37310, "text": "start – It represents the starting index for the subsequence." }, { "code": null, "e": 37454, "s": 37372, "text": "end – It represents the index of character following the end for the subsequence." }, { "code": null, "e": 37875, "s": 37454, "text": "Return value: This method returns CharArrayWriter after appending the subsequence of the given character sequence into it.Exceptions: This method throws IndexOutOfBoundsException if the start or the end are negative or start is greater than end or end is greater than the length of given character sequence.Below program illustrates append(CharSequence, int, int) method in CharArrayWriter class in IO package:Program: " }, { "code": null, "e": 37880, "s": 37875, "text": "Java" }, { "code": "// Java program to illustrate// CharArrayWriter// append(CharSequence, int, int) method import java.io.*; public class GFG { public static void main(String[] args) { // Create charArrayWriter CharArrayWriter charArrayWriter = new CharArrayWriter(); // Create character sequence CharSequence csq = \"GEEKSFORGEEKS\"; // Append subsequence of character // sequence to the charArrayWriter charArrayWriter.append(csq, 8, 13); // print the charArrayWriter System.out.println( charArrayWriter.toString()); }}", "e": 38485, "s": 37880, "text": null }, { "code": null, "e": 38492, "s": 38485, "text": "GEEKS\n" }, { "code": null, "e": 38815, "s": 38492, "text": "References: 1. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(char) 2. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(java.lang.CharSequence) 3. https://docs.oracle.com/javase/10/docs/api/java/io/CharArrayWriter.html#append(java.lang.CharSequence, int, int) " }, { "code": null, "e": 38830, "s": 38815, "text": "Java-Functions" }, { "code": null, "e": 38846, "s": 38830, "text": "Java-IO package" }, { "code": null, "e": 38851, "s": 38846, "text": "Java" }, { "code": null, "e": 38856, "s": 38851, "text": "Java" }, { "code": null, "e": 38954, "s": 38856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38969, "s": 38954, "text": "Stream In Java" }, { "code": null, "e": 38990, "s": 38969, "text": "Constructors in Java" }, { "code": null, "e": 39036, "s": 38990, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 39055, "s": 39036, "text": "Exceptions in Java" }, { "code": null, "e": 39085, "s": 39055, "text": "Functional Interfaces in Java" }, { "code": null, "e": 39102, "s": 39085, "text": "Generics in Java" }, { "code": null, "e": 39145, "s": 39102, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 39166, "s": 39145, "text": "Introduction to Java" }, { "code": null, "e": 39195, "s": 39166, "text": "HashMap get() Method in Java" } ]
How To Make Your Graph Look Astonishingly Beautiful Quickly | by Bruce Ironhardt | Towards Data Science
So, you just finished retrieving, processing, and analyzing your data. You grab your data and you decide to graph it so you can show others your findings. You click ‘graph’ and...... Ya looks kinda boring. What we want is something a little more fun and dynamic. Something like... this: Yes! Now that looks awesome! So let’s see how we can do quickly get this animation going. Okay here’s what you’ll need to get started: Data for a bar graph (duh!) Adobe Illustrator (Don’t worry we don’t need it for anything complicated) Adobe After Effects So, let’s just do a few things to make our graph look better. We can start by making the text a bit larger and let’s change the graph style while we’re at it. Now for the style, I don’t want the y-axis and instead, I just want the total numeric value at the top of each bar in our graph. We can do it in excel pretty easily, Select the graphClick on the ‘brush icon’Under ‘Style’ we can find the graph style we’re looking for. For me, it was the second one but it may be different for you. Select the graph Click on the ‘brush icon’ Under ‘Style’ we can find the graph style we’re looking for. For me, it was the second one but it may be different for you. Next just make the font size larger and change the font to whatever tickles your fancy. Remove any background lines (you can just select and delete them). And maybe make the bar wider. After I was done editing my graph looked like this. Don’t worry about the text being too light right now, later on, I’ll be adding a darker background color to make things pop more. Experiment, and play with the kind of design you want to have, feel free to be as creative as you want. Create a new project in Adobe Illustrator and set the size to 1920 by 1080. Then simply copy-paste the graph you just made from Excel into Illustrator. The image will copy in as a vector image meaning you can resize it without having to worry about quality loss. Resize your image until it fits the way you want it to on your canvas. See below for reference on how it’s been sized. If you open the ‘Layers’ panel (you can click f7 or Window -> Layers to open it up) you should see ‘Layer 1’. If we open it up, we should see a Layer called ‘<Clip Group>’ with all the bars that we need. Right now they’re all stuck together. 1. Select that ‘<Clip group>’ -> Right-click on the bar -> Select ‘Release Clipping Mask’. That will create a ‘Compound Path’ Layer. 2. Select this layer and again right-click on the bar and select ‘Release Compound Path’. Now we have all the bars separated. Create five new layers (one for each bar) and drag each bar layer into the new layer. Rename the new bar layers to make it easier to use in After Effects later. Create one more layer called ‘Values’ and just move all the numeric bar values into that layer. Make sure not to move any of the Year values, we just want the bar values there. Now we’re basically done. The last thing we’ll need to do is remove any sub-layers in Layer 1 that we don’t need. An easy way to do this is to click on the little ‘eye’ icon next to the layer. If something disappears from Illustrator then we want to keep that. If it looks like nothing disappeared then we can remove it. The point of this is to delete the white background so we can add on our own later in After Effects. If you want to keep the white background feel free to move on to the next step. Once that’s done rename ‘Layer 1’ to ‘Axis’ so it’s easier to identify in After Effects. Create a new After Effects project and set the size to 1920 by 1080. My duration was set to 5 seconds but you can set it 3 seconds if you want to. Next, we need to import the Illustrator file that we just created. We can do this by double-clicking the Project Panel and selecting our AI file. Make sure that Import Kind is set to Composition and Footage Dimension is set to Layer Size. We can then just click on the new composition that after-effects automatically created for us and start working on it. You should also see all our layers in the Composition Panel. Each layer has an anchor point. These anchor points are the points at which the effects we apply take place. We’ll need to move these anchor points to the bottom of each bar so that the animation starts from that point. To do this Select a specific bar object (example: bar 1)In the toolbar select the anchor tool.Then just move the anchor to the center bottom of the bar. Repeat this for each bar. You can see an example below for how I did it. Select a specific bar object (example: bar 1) In the toolbar select the anchor tool. Then just move the anchor to the center bottom of the bar. Repeat this for each bar. You can see an example below for how I did it. Once we have our anchors set at the correct position we can start animating. This part is really simple. In the Composition Panel: Bar Layer (ex: Bar 1) > Transform > Scale. Unlink the scale by clicking the chain icon on the scale option. This unlinks the width from the height.Click on the stopwatch icon next to the Scale option. This creates a keyframe for our animations.Set the height to 0%. On the Scale options, the height is the second value.Move the scrubber on the timeline to 7 Frames (or however long you want the animation to last) and adjust the height back to 100%. This will automatically create a new keyframe for us and animate our growing bar from 0% to 100% of its original height, over 7 frames. Unlink the scale by clicking the chain icon on the scale option. This unlinks the width from the height. Click on the stopwatch icon next to the Scale option. This creates a keyframe for our animations. Set the height to 0%. On the Scale options, the height is the second value. Move the scrubber on the timeline to 7 Frames (or however long you want the animation to last) and adjust the height back to 100%. This will automatically create a new keyframe for us and animate our growing bar from 0% to 100% of its original height, over 7 frames. The bounce animation makes it so that when our bar reaches the top it will overshoot and then go back down. This makes the animation look a lot smoother and more lively. To do this click on the stopwatch icon next to Scale while holding down the ALT key. A text area will open on the timeline. Copy-paste the following there. // Inertial Bounce - Created by Animoplex: www.animoplex.com// Original Version: http://www.graymachine.com/top-5-effects-expressions/// Modified expression for a smoother bounce effect and easier editing. Use this on any property with two keyframes to get a nice bounce effect that is based on velocity of the value change. Perfect for a scale from 0 to 100 or a speedy rotation that needs some extra life. Adjust amp, freq and decay values to tweak the effect. Amp is intensity, freq is bounces per second, and decay is the speed of decay, slow to fast.// Variation Aamp = 5.0; freq = 2.0; decay = 4.0;n = 0;if (numKeys > 0) { n = nearestKey(time).index; if (key(n).time > time) { n--; }}if (n == 0) { t = 0; }else { t = time - key(n).time; }if (n > 0 && t < 1) { v = velocityAtTime(key(n).time - thisComp.frameDuration/10); value + v*(amp/100)*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);}else { value; } Congratulations! The hard part is over, now we just need to do some copy-pasting and fix up a few things. You should now have something that looks like this: If you close the dropdown menu for the component we were just working on and select it again you can type the letter ‘U’ on your keyboard to just view properties you’ve changed. Do that and select the two keyframes we just made.Ctrl+C or Cmd+C to copy them.Select each of the other bar components and paste them to each one. Do that and select the two keyframes we just made. Ctrl+C or Cmd+C to copy them. Select each of the other bar components and paste them to each one. Having all the properties open for all the bars we just animated. We see that the animation for each bar takes place at the same time. To fix this we just need to shift the keyframe animation for each bar to start when the last one animation ended. ‘Bar 5’ for me was my first bar on the graph and ‘Bar 1’ was my last. So for me, I just need to shift them like shown below but you may need to shift them differently. The values being there at the beginning of the animation is pretty weird. Instead, a better look would be for them to appear near the end of the animation. Click on the ‘Values’ component > Transform > OpacityClick the stopwatch and set the keyframe to 0%We want to not start animating until near the end of the animation so position your time scrubber halfway between the start and end of the last bar animation. You can manually create a keyframe by selecting the diamond icon on the far right of the Opacity property.Move the scrubber to the end of the last bar animation and set the opacity to back to 100%. Now the values will appear near the end of the animation. Click on the ‘Values’ component > Transform > Opacity Click the stopwatch and set the keyframe to 0% We want to not start animating until near the end of the animation so position your time scrubber halfway between the start and end of the last bar animation. You can manually create a keyframe by selecting the diamond icon on the far right of the Opacity property. Move the scrubber to the end of the last bar animation and set the opacity to back to 100%. Now the values will appear near the end of the animation. Layer > New > Solid...Pick your favorite color.In the Composition Panel drag your background to the bottom to see your graph again. Layer > New > Solid... Pick your favorite color. In the Composition Panel drag your background to the bottom to see your graph again. Marvel at your beautiful creation. If you liked this consider reading some more cool stuff like How to Handle Missing Data in Python towardsdatascience.com Or How salmon can use a magical force to return home!
[ { "code": null, "e": 354, "s": 171, "text": "So, you just finished retrieving, processing, and analyzing your data. You grab your data and you decide to graph it so you can show others your findings. You click ‘graph’ and......" }, { "code": null, "e": 458, "s": 354, "text": "Ya looks kinda boring. What we want is something a little more fun and dynamic. Something like... this:" }, { "code": null, "e": 548, "s": 458, "text": "Yes! Now that looks awesome! So let’s see how we can do quickly get this animation going." }, { "code": null, "e": 593, "s": 548, "text": "Okay here’s what you’ll need to get started:" }, { "code": null, "e": 621, "s": 593, "text": "Data for a bar graph (duh!)" }, { "code": null, "e": 695, "s": 621, "text": "Adobe Illustrator (Don’t worry we don’t need it for anything complicated)" }, { "code": null, "e": 715, "s": 695, "text": "Adobe After Effects" }, { "code": null, "e": 874, "s": 715, "text": "So, let’s just do a few things to make our graph look better. We can start by making the text a bit larger and let’s change the graph style while we’re at it." }, { "code": null, "e": 1040, "s": 874, "text": "Now for the style, I don’t want the y-axis and instead, I just want the total numeric value at the top of each bar in our graph. We can do it in excel pretty easily," }, { "code": null, "e": 1205, "s": 1040, "text": "Select the graphClick on the ‘brush icon’Under ‘Style’ we can find the graph style we’re looking for. For me, it was the second one but it may be different for you." }, { "code": null, "e": 1222, "s": 1205, "text": "Select the graph" }, { "code": null, "e": 1248, "s": 1222, "text": "Click on the ‘brush icon’" }, { "code": null, "e": 1372, "s": 1248, "text": "Under ‘Style’ we can find the graph style we’re looking for. For me, it was the second one but it may be different for you." }, { "code": null, "e": 1609, "s": 1372, "text": "Next just make the font size larger and change the font to whatever tickles your fancy. Remove any background lines (you can just select and delete them). And maybe make the bar wider. After I was done editing my graph looked like this." }, { "code": null, "e": 1739, "s": 1609, "text": "Don’t worry about the text being too light right now, later on, I’ll be adding a darker background color to make things pop more." }, { "code": null, "e": 1843, "s": 1739, "text": "Experiment, and play with the kind of design you want to have, feel free to be as creative as you want." }, { "code": null, "e": 1995, "s": 1843, "text": "Create a new project in Adobe Illustrator and set the size to 1920 by 1080. Then simply copy-paste the graph you just made from Excel into Illustrator." }, { "code": null, "e": 2225, "s": 1995, "text": "The image will copy in as a vector image meaning you can resize it without having to worry about quality loss. Resize your image until it fits the way you want it to on your canvas. See below for reference on how it’s been sized." }, { "code": null, "e": 2429, "s": 2225, "text": "If you open the ‘Layers’ panel (you can click f7 or Window -> Layers to open it up) you should see ‘Layer 1’. If we open it up, we should see a Layer called ‘<Clip Group>’ with all the bars that we need." }, { "code": null, "e": 2467, "s": 2429, "text": "Right now they’re all stuck together." }, { "code": null, "e": 2600, "s": 2467, "text": "1. Select that ‘<Clip group>’ -> Right-click on the bar -> Select ‘Release Clipping Mask’. That will create a ‘Compound Path’ Layer." }, { "code": null, "e": 2726, "s": 2600, "text": "2. Select this layer and again right-click on the bar and select ‘Release Compound Path’. Now we have all the bars separated." }, { "code": null, "e": 2887, "s": 2726, "text": "Create five new layers (one for each bar) and drag each bar layer into the new layer. Rename the new bar layers to make it easier to use in After Effects later." }, { "code": null, "e": 3064, "s": 2887, "text": "Create one more layer called ‘Values’ and just move all the numeric bar values into that layer. Make sure not to move any of the Year values, we just want the bar values there." }, { "code": null, "e": 3178, "s": 3064, "text": "Now we’re basically done. The last thing we’ll need to do is remove any sub-layers in Layer 1 that we don’t need." }, { "code": null, "e": 3566, "s": 3178, "text": "An easy way to do this is to click on the little ‘eye’ icon next to the layer. If something disappears from Illustrator then we want to keep that. If it looks like nothing disappeared then we can remove it. The point of this is to delete the white background so we can add on our own later in After Effects. If you want to keep the white background feel free to move on to the next step." }, { "code": null, "e": 3655, "s": 3566, "text": "Once that’s done rename ‘Layer 1’ to ‘Axis’ so it’s easier to identify in After Effects." }, { "code": null, "e": 3948, "s": 3655, "text": "Create a new After Effects project and set the size to 1920 by 1080. My duration was set to 5 seconds but you can set it 3 seconds if you want to. Next, we need to import the Illustrator file that we just created. We can do this by double-clicking the Project Panel and selecting our AI file." }, { "code": null, "e": 4221, "s": 3948, "text": "Make sure that Import Kind is set to Composition and Footage Dimension is set to Layer Size. We can then just click on the new composition that after-effects automatically created for us and start working on it. You should also see all our layers in the Composition Panel." }, { "code": null, "e": 4441, "s": 4221, "text": "Each layer has an anchor point. These anchor points are the points at which the effects we apply take place. We’ll need to move these anchor points to the bottom of each bar so that the animation starts from that point." }, { "code": null, "e": 4452, "s": 4441, "text": "To do this" }, { "code": null, "e": 4667, "s": 4452, "text": "Select a specific bar object (example: bar 1)In the toolbar select the anchor tool.Then just move the anchor to the center bottom of the bar. Repeat this for each bar. You can see an example below for how I did it." }, { "code": null, "e": 4713, "s": 4667, "text": "Select a specific bar object (example: bar 1)" }, { "code": null, "e": 4752, "s": 4713, "text": "In the toolbar select the anchor tool." }, { "code": null, "e": 4884, "s": 4752, "text": "Then just move the anchor to the center bottom of the bar. Repeat this for each bar. You can see an example below for how I did it." }, { "code": null, "e": 4989, "s": 4884, "text": "Once we have our anchors set at the correct position we can start animating. This part is really simple." }, { "code": null, "e": 5058, "s": 4989, "text": "In the Composition Panel: Bar Layer (ex: Bar 1) > Transform > Scale." }, { "code": null, "e": 5601, "s": 5058, "text": "Unlink the scale by clicking the chain icon on the scale option. This unlinks the width from the height.Click on the stopwatch icon next to the Scale option. This creates a keyframe for our animations.Set the height to 0%. On the Scale options, the height is the second value.Move the scrubber on the timeline to 7 Frames (or however long you want the animation to last) and adjust the height back to 100%. This will automatically create a new keyframe for us and animate our growing bar from 0% to 100% of its original height, over 7 frames." }, { "code": null, "e": 5706, "s": 5601, "text": "Unlink the scale by clicking the chain icon on the scale option. This unlinks the width from the height." }, { "code": null, "e": 5804, "s": 5706, "text": "Click on the stopwatch icon next to the Scale option. This creates a keyframe for our animations." }, { "code": null, "e": 5880, "s": 5804, "text": "Set the height to 0%. On the Scale options, the height is the second value." }, { "code": null, "e": 6147, "s": 5880, "text": "Move the scrubber on the timeline to 7 Frames (or however long you want the animation to last) and adjust the height back to 100%. This will automatically create a new keyframe for us and animate our growing bar from 0% to 100% of its original height, over 7 frames." }, { "code": null, "e": 6317, "s": 6147, "text": "The bounce animation makes it so that when our bar reaches the top it will overshoot and then go back down. This makes the animation look a lot smoother and more lively." }, { "code": null, "e": 6473, "s": 6317, "text": "To do this click on the stopwatch icon next to Scale while holding down the ALT key. A text area will open on the timeline. Copy-paste the following there." }, { "code": null, "e": 7386, "s": 6473, "text": "// Inertial Bounce - Created by Animoplex: www.animoplex.com// Original Version: http://www.graymachine.com/top-5-effects-expressions/// Modified expression for a smoother bounce effect and easier editing. Use this on any property with two keyframes to get a nice bounce effect that is based on velocity of the value change. Perfect for a scale from 0 to 100 or a speedy rotation that needs some extra life. Adjust amp, freq and decay values to tweak the effect. Amp is intensity, freq is bounces per second, and decay is the speed of decay, slow to fast.// Variation Aamp = 5.0; freq = 2.0; decay = 4.0;n = 0;if (numKeys > 0) { n = nearestKey(time).index; if (key(n).time > time) { n--; }}if (n == 0) { t = 0; }else { t = time - key(n).time; }if (n > 0 && t < 1) { v = velocityAtTime(key(n).time - thisComp.frameDuration/10); value + v*(amp/100)*Math.sin(freq*t*2*Math.PI)/Math.exp(decay*t);}else { value; }" }, { "code": null, "e": 7544, "s": 7386, "text": "Congratulations! The hard part is over, now we just need to do some copy-pasting and fix up a few things. You should now have something that looks like this:" }, { "code": null, "e": 7722, "s": 7544, "text": "If you close the dropdown menu for the component we were just working on and select it again you can type the letter ‘U’ on your keyboard to just view properties you’ve changed." }, { "code": null, "e": 7869, "s": 7722, "text": "Do that and select the two keyframes we just made.Ctrl+C or Cmd+C to copy them.Select each of the other bar components and paste them to each one." }, { "code": null, "e": 7920, "s": 7869, "text": "Do that and select the two keyframes we just made." }, { "code": null, "e": 7950, "s": 7920, "text": "Ctrl+C or Cmd+C to copy them." }, { "code": null, "e": 8018, "s": 7950, "text": "Select each of the other bar components and paste them to each one." }, { "code": null, "e": 8267, "s": 8018, "text": "Having all the properties open for all the bars we just animated. We see that the animation for each bar takes place at the same time. To fix this we just need to shift the keyframe animation for each bar to start when the last one animation ended." }, { "code": null, "e": 8435, "s": 8267, "text": "‘Bar 5’ for me was my first bar on the graph and ‘Bar 1’ was my last. So for me, I just need to shift them like shown below but you may need to shift them differently." }, { "code": null, "e": 8591, "s": 8435, "text": "The values being there at the beginning of the animation is pretty weird. Instead, a better look would be for them to appear near the end of the animation." }, { "code": null, "e": 9105, "s": 8591, "text": "Click on the ‘Values’ component > Transform > OpacityClick the stopwatch and set the keyframe to 0%We want to not start animating until near the end of the animation so position your time scrubber halfway between the start and end of the last bar animation. You can manually create a keyframe by selecting the diamond icon on the far right of the Opacity property.Move the scrubber to the end of the last bar animation and set the opacity to back to 100%. Now the values will appear near the end of the animation." }, { "code": null, "e": 9159, "s": 9105, "text": "Click on the ‘Values’ component > Transform > Opacity" }, { "code": null, "e": 9206, "s": 9159, "text": "Click the stopwatch and set the keyframe to 0%" }, { "code": null, "e": 9472, "s": 9206, "text": "We want to not start animating until near the end of the animation so position your time scrubber halfway between the start and end of the last bar animation. You can manually create a keyframe by selecting the diamond icon on the far right of the Opacity property." }, { "code": null, "e": 9622, "s": 9472, "text": "Move the scrubber to the end of the last bar animation and set the opacity to back to 100%. Now the values will appear near the end of the animation." }, { "code": null, "e": 9754, "s": 9622, "text": "Layer > New > Solid...Pick your favorite color.In the Composition Panel drag your background to the bottom to see your graph again." }, { "code": null, "e": 9777, "s": 9754, "text": "Layer > New > Solid..." }, { "code": null, "e": 9803, "s": 9777, "text": "Pick your favorite color." }, { "code": null, "e": 9888, "s": 9803, "text": "In the Composition Panel drag your background to the bottom to see your graph again." }, { "code": null, "e": 9923, "s": 9888, "text": "Marvel at your beautiful creation." }, { "code": null, "e": 10021, "s": 9923, "text": "If you liked this consider reading some more cool stuff like How to Handle Missing Data in Python" }, { "code": null, "e": 10044, "s": 10021, "text": "towardsdatascience.com" } ]
10 Features Your Streamlit ML App Can’t Do Without — Implemented | by Dor Meir | Towards Data Science
Much has been written about Streamlit killer data apps, and it is no surprise to see Streamlit is the fastest growing platform in this field: However, developing an object segmentation app with the CRISP-DM phases in Streamlit made me realize many basic features are missing from the platform. These features are rarely mentioned in Streamlit articles, probably since they do “dirty work” in the background and are, simply put, not that glamorous. Even though they are not discussed, I’m confident that without those features your data app won’t cut it. In my case, some of the features were brought up as requirements by the app’s users, while others are built in the R-shiny platform, where I joined developing another AutoML app. Many basic app features are missing from Streamlit. Without them, your app won’t cut it. So why am I writing this article? Setting aside the missing features, Streamlit is an awesome platform (see here), maybe one of its kind for developing apps in Python with almost no experience in apps development. Thus, I did everything I can to scavage those missing features online, googling dozens of solutions and trying to implement them. Furthermore, when there was no good solution online, I developed features on my own. And if I’ve already spent the time on gathering those features — you shouldn’t. You’re welcome to sit back, relax, and enjoy the ride... I’ve already spent the time gathering those features—so you shouldn’t. You’re welcome to sit back, relax, and enjoy the ride... Before diving into the code, let me stress most of the features here are dependent on each other. Don’t worry — they’re mentioned in order of dependence, so each former feature is independent of the a latter one. In addition, it’s worth mentioning I’m a Data Scientist in my core, and not an app developer. Therefore, I might not use the proper jargon for concepts in the app development domain. Nevertheless, I excuse myself from being precise since I believe most of you come from a similar background to mine, meaning you‘re proficient in Python and in building Machine Learning models, yet you have little to no knowledge in developing apps. If, however, you ARE an experienced developer, I hereby apologize for desecrating your profession :) So, without further ado, here are the 10 features: Preserving work on refresh and lost connectionSaving work for later useFiles explorerLogin screenMulti-page AppRunning long parallel calculationsUsing models of different environmentsDynamically plotting training resultsEmbedding Jupyter and Serving a license file on new tabDeploying a trained model Preserving work on refresh and lost connection Saving work for later use Files explorer Login screen Multi-page App Running long parallel calculations Using models of different environments Dynamically plotting training results Embedding Jupyter and Serving a license file on new tab Deploying a trained model Problem: The Streamlit user loses her work on refresh or connection timeouts. Solution: Auto-save and auto-load the user’s session with a session file. One of the most important things in any app is a session management capability, i.e., the app must “remember” any setting the user have configured whenever the user switches pages, refreshes the web browser and, of course, saves the model and loads it later on. If you know how a ML model class looks like, a saved session is basically the same concept only on a broader context. A session will not only save the hyper parameters and trained model weights but also the entire dataset (or its file path), the predictions, the file paths of the training log, the plots, the scripts the user has written, and any other work the user has made in his session. This means that without keeping her session persistent, the user will lose all her work whenever she refreshes the browser or just temporarily loses connection to the app. Without keeping her session persistent the user will lose all her work whenever she refreshes the browser or just temporarily loses connection to the app. Even though this feature was constantly asked for in the Streamlit forum right from the early days of the platform, session management was introduced to the platform only two years after. Still and all, the official Streamlit solution has a major downside: it only preserves the user’s work when she switches between pages, whilst it doesn’t preserve a user’s work if a session ends expectedly. My solution does, and it’s using a session management solution of the user okld instead. First, the app’s script should have these lines: Second, this functionality only works when Streamlit is started in debug mode and writes the debug messages to a log file: streamlit run app.py --logger.level=debug log_file.log 2>&1 The log file should be stored in the folder configs[‘APP_BASE_DIR’] + ‘/logs/streamlit_logs/ as it is used in the was_session_shutdown() function. Third, this is how you auto-save a session: autosave_session(state) When should we auto-save and auto-load? I call the autosave function whenever the user changes a configuration or even just changes a page in the app — that way when a session reload occurs, the user can immediately continue his work without having to browse back to the page he was working on. The loading part should be one of the first commands to be called in the app’s script, since an app refresh re-runs the entire script from the beginning, and we want the user’s downtime to be minimal. When will a session NOT be auto-loaded? when a user has logged out (see Multi-pages section below), or when the Streamlit app restarted. Is it possible to add the auto-save feature to the official Streamlit session solution? it very well might, do tell me if you succeed on doing that! Problem: Streamlit has no option to save a user’s work for later use. Solution: Save, load & delete buttons Letting the user save and load his work has the same exact logic as in the section above, only this time save and load are triggered when the user is pressing action buttons. It goes without saying you’ll also have to present a table showing all saved models, as well as some kind of indication of whether a model was successfully saved/loaded/deleted. Problem: The Streamlit user can’t create, delete, or browse folders Solution: A recursive function for folder manipulation A files explorer is an absolute necessity for any CRISP-DM app as it is used for saving files and organizing them in directories in almost all of the work’s phases. For instance, you might decide to have a folder for each user’s trained models and a folder for the datasets of each specific project. Even though it’s a very basic requirement, if you google this issue you’ll probably find some not-so-functionating Streamlit users’ solutions. This solution enables the user to create, delete, and browse folders, and see the folders’ tree structure. Most importantly, it’ll work even if your Streamlit app is running on a remote server where the user has no direct access to the file system. Problem: Streamlit has no built-in user authentication screen Solution: If statement before main() which verifies the user and password Any professional app needs a “bouncer” guarding the entrance. Streamlit doesn’t have one, even though this was also asked for by Streamlit users a long time ago. Bear in mind that my implementation uses hard-coded user and password but adding LDAP or MongoDB authentication should be quite easy. Problem: Streamlit has no built-in multi-page capability Solution: Add radio menu in the sidebar linked to functions for each page Working with CRISP-DM requires moving back and forth between the different phases. This work process is best represented in the app in the form of ordered options of a menu, each option linked to a different function. The concept of a separate function for each phase also makes perfect sense when you code those phases. Problem: Streamlit can’t run two operations at once and stop them in the middle Solution: Run sub-processes and create a process control table in the sidebar Whether you’re brute forcing your way in feature engineering or training heavy deep learning models, you’ll need a way to run things in parallel and, in some cases, kill them prematurely. One way to add this functionality is to run each calculation as a a sub-process, while having a processes table that is both dynamically updating and has action buttons to kill each process separately or shut them all at once. Running independent sub-processes not only let’s you use parallel computing but also ensures that even if the Streamlit session is suddenly killed, the sub-processes will continue running without interruption on the server. So, whatever happens to the Streamlit session, the user can login again and see the results. Another approach to this solution would be to send these sub-processes to work on a cloud service instead of on your own machine - this will probably be of value to you if you need an extra computing power. Running a sub-process is rather easy with Popen: try: subprocess.Popen(command)except: st.write(f"Couldn't run: {command}") e = sys.exc_info() st.error(e)updated_processes_table(process_table_sidebar, state)# see updated_processes_table() implementation on the gist below It gets a bit tricker if the command you’re running asks the user for input, but it’s also manageble with PIPE: process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)try: process.communicate("\n".join(user_arguments), timeout=0.2)except: passupdated_processes_table(process_table_sidebar, state) And here’s how you can implement the processes control table: Problem: Streamlit has no option for using models on different environments Solution: Activate Conda environments when running sub-processes When working with heavy CV and NLP models you often need to install different coding environments for each model, since many-a-time they rely on specific Tensorflow or Pytorch versions which aren’t compatible with other installations. In that case, you’ll want to call each model command from its own environment, and you should also capture all of the environments outputs to a log (the variable output_to_log in the gist below). Of course, Conda is just one multi-env solution, one might also consider Pyenv or even use Docker images instead. Now that we know how to run sub-processes (see section above), it’s quite straightforward to run them on different conda environments: Problem: Streamlit can’t show training outputs during training Solution: Tail models logs and plot them on intervals Are you underfitting, overfitting or just-fitting? When dealing with deep learning models (as in the section above) it’s especially hard to know this without plotting the models’ metrics during training. It might also be useful to see the textual output of the commands you’re running, and to have an option to download it to a file. finally, it might be convenient to set the interval for refreshing the metrics plots, since they usually update on the finish of one training epoch and the duration of an epoch varies for different models and datasets. Problem: Streamlit has no free coding and can’t redirect to a file on a new tab Solution: Embed Jupyter as HTML iframe and add a Jupyter link to the file Embedding a Jupyter notebook/lab instance on a page of the app is one of the hardest challenges I faced. There are multiple theoretical ways and tools for doing that but from my experience, “stars need to align” for the configurations to work. In the end I succeeded embedding Jupyter to Streamlit only with a rather promiscuous security configuration. If that’s a concern for you, start with my configurations and try adding restrictions while still having everything work. Jupyter was tough implementing, but worth the effort. It’s a very powerful tool as it lets the knowledgeable user do basically anything he wants with the models already trained, and even add some phases which are not yet implemented like post-processing, explainability, etc. But from the exact same reason, it is also a dangerous tool which gives the user a terminal access to the server, i.e., a capability to destroy it with a command — so use with caution! First, you should create a jupyter configuration file, with: jupyter notebook --generate-config Next, edit the file so that it’ll have these configurations: c.NotebookApp.allow_origin = '*'c.NotebookApp.disable_check_xsrf = Truec.NotebookApp.ip = '*'c.NotebookApp.notebook_dir = <directory of datasets and outputs>c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8502c.NotebookApp.token = ''c.NotebookApp.tornado_settings = {'headers': { 'Content-Security-Policy': "frame-ancestors http://<Server-IP>:8501/ " }}c.NotebookApp.use_redirect_file = True The most important configuration is c.NotebookApp.tornado_settings, which tells Jupyter to trust your Streamlit app when presenting an iframe of Jupyter. Also note that you should set c.NotebookApp.port to a number that is not already occupied by the Streamlit port. The default Streamlit port number is 8501, and any new Streamlit session will be opened with the next free port, i.e. 8502, 8503, and so on. Starting Jupyter is straightforward, all you should do is add these lines to the beginning of your app: # in if __name__ == "__main__":command = rf"""jupyter lab --allow-root"""try: subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)except: st.error(f"Couldn't run {script_type}:") e = sys.exc_info() st.error(e) But embedding Jupyter to Streamlit is a different and longer story: If you wish the users of your app’s to be redirected to a new separate tab when opening the LICENCE file, you need, in other words, some web app to serve your LICNESE file. Lucky for you, Jupyter can do this exactly, as it’s built upon a Torando web server. with col9: linespace_generator(2) while not is_jupyter_up(): time.sleep(0) link = f"[license](http://{state.jupyter_ip}:{state.jupyter_port}/files/Licence.html)" st.markdown(link, unsafe_allow_html=True) Problem: Streamlit has no option for delivering a trained model Solution: Create a REST API flask web service Building a model is easy but serving the model so that people can use it directly and on a daily basis — that’s a totally different challenge. The solution I’m presenting here has nothing to do with Streamlit, nonetheless it’s an essential part of any CRISP-DM app and so I chose to include it in the article. My solution is using Flask, which is a rather straightforward platform that will probably be suffice for your POC needs. Still, when things get serious and you need to manage multiple sessions, security and more, you might want to switch to Django or Node.js. My Image segmentation API have several independent paths: www.AwsomeApp.com:8503 /models: Query trained models/configs: Set prediction arguments /base64: Convert image files formats to base64 strings/predict: Feed model with data and get predictions Here’s is the entire API implementation, along with instructions on how to use it (right after the gist): Query which algorithms are available for prediction: import requestsIP = "<IP address>"res = requests.get(f"http://{IP}:8503/models"); res.json() Query which trained weights are available for a specific model: params = {"algorithm":"FastFCN", "Model_path":"coco", "return_weights":"True"}res = requests.post(f"http://{IP}:8503/models", data=params); res.json() Query which classes a specific model was trained on: params = {"algorithm":"FastFCN", "Model_path":"coco", "return_classes":"True"}res = requests.post(f"http://{IP}:8503/models", data=params); res.json() First, create a json file containing the prediction configurations. Those configurations will be used for all subsequent predictions until a new configuration file is sent to the API. Example of configs.json file: {'algorithm': 'FastFCN', 'Model_path': 'coco', 'weight': 'FastFCN_coco1', 'IMAGE_MIN_DIM': '1024', 'IMAGE_MAX_DIM': '2048', 'DETECTION_MIN_CONFIDENCE': '0.7', 'mode': '2', 'class_show': 'None'} Second, Send the file and evaluate the current configurations: IP = "<IP>"files = {'file': open('configs.json', 'rb')}; json.load(files['file'])files = {'file': open('configs.json', 'rb')}res = requests.post(f"http://{IP}:8503/configs", files=files)res = requests.get(f"http://{IP}:8503/configs"); res.json() Optional: Preprocess a zip of images to a list of base64 strings, to be later fed into the model for prediction: files = {'file': open('image_to_predict.zip', 'rb')}; res = requests.post(f"http://{IP}:8503/base64", files=files); list_of_base64=res.json()params['images'] = list_of_base64 First, define a dictionary called params with an images key of which its value is a list of base64 strings representing the images for prediction: params = {'images':[<image0_base64>,<image1_base64>,<image2_base64>]} Set this config to True to get the results in the form of image files instead of base64 strings: params['create_images'] = True Second, make a prediction request, and evaluate results: IP = "<IP>"res = requests.post(f"http://{IP}:8503/predict", data=params)res = res.json()['Responses']predicted_image0 = res[0][1]json_result0 = res[0][0]print(f"Classes found: {json_result0['results']['class_name']}") print(f"Prediction scores: {json_result0['results']['scores']}")print(f"Bounding Boxes: {json_result0['results']['rois [y_min, x_min, y_max, x_max]']}") Developing an ML app with Streamlit is like taking a ride on the wildest roller-coaster of the amusement park: it’s super quick, extremely exciting, dizzying at times but certainly a lot of fun. Yet after a speedy implementation in Streamlit of your brilliant Machine Learning ideas, it’s almost inevitable your app will not really be usable. That’s a result of Streamlit lacking some basic features: Preserving work on refresh and lost connection, Saving work for later use, Files explorer, Login screen, Multi-page App, Running long parallel calculations, Using models of different environments, Dynamically plotting training results, Embedding Jupyter and Serving a license file on new tab, Deploying a trained model. You could try to implement those features yourself or even “roll the dice” on google, but why waste the time? All those features’ codes are above - so sit back, relax, and enjoy the ride :) Please feel free to share your feedbacks. Thank you, and good luck! 🍀
[ { "code": null, "e": 314, "s": 172, "text": "Much has been written about Streamlit killer data apps, and it is no surprise to see Streamlit is the fastest growing platform in this field:" }, { "code": null, "e": 905, "s": 314, "text": "However, developing an object segmentation app with the CRISP-DM phases in Streamlit made me realize many basic features are missing from the platform. These features are rarely mentioned in Streamlit articles, probably since they do “dirty work” in the background and are, simply put, not that glamorous. Even though they are not discussed, I’m confident that without those features your data app won’t cut it. In my case, some of the features were brought up as requirements by the app’s users, while others are built in the R-shiny platform, where I joined developing another AutoML app." }, { "code": null, "e": 994, "s": 905, "text": "Many basic app features are missing from Streamlit. Without them, your app won’t cut it." }, { "code": null, "e": 1560, "s": 994, "text": "So why am I writing this article? Setting aside the missing features, Streamlit is an awesome platform (see here), maybe one of its kind for developing apps in Python with almost no experience in apps development. Thus, I did everything I can to scavage those missing features online, googling dozens of solutions and trying to implement them. Furthermore, when there was no good solution online, I developed features on my own. And if I’ve already spent the time on gathering those features — you shouldn’t. You’re welcome to sit back, relax, and enjoy the ride..." }, { "code": null, "e": 1688, "s": 1560, "text": "I’ve already spent the time gathering those features—so you shouldn’t. You’re welcome to sit back, relax, and enjoy the ride..." }, { "code": null, "e": 2435, "s": 1688, "text": "Before diving into the code, let me stress most of the features here are dependent on each other. Don’t worry — they’re mentioned in order of dependence, so each former feature is independent of the a latter one. In addition, it’s worth mentioning I’m a Data Scientist in my core, and not an app developer. Therefore, I might not use the proper jargon for concepts in the app development domain. Nevertheless, I excuse myself from being precise since I believe most of you come from a similar background to mine, meaning you‘re proficient in Python and in building Machine Learning models, yet you have little to no knowledge in developing apps. If, however, you ARE an experienced developer, I hereby apologize for desecrating your profession :)" }, { "code": null, "e": 2486, "s": 2435, "text": "So, without further ado, here are the 10 features:" }, { "code": null, "e": 2787, "s": 2486, "text": "Preserving work on refresh and lost connectionSaving work for later useFiles explorerLogin screenMulti-page AppRunning long parallel calculationsUsing models of different environmentsDynamically plotting training resultsEmbedding Jupyter and Serving a license file on new tabDeploying a trained model" }, { "code": null, "e": 2834, "s": 2787, "text": "Preserving work on refresh and lost connection" }, { "code": null, "e": 2860, "s": 2834, "text": "Saving work for later use" }, { "code": null, "e": 2875, "s": 2860, "text": "Files explorer" }, { "code": null, "e": 2888, "s": 2875, "text": "Login screen" }, { "code": null, "e": 2903, "s": 2888, "text": "Multi-page App" }, { "code": null, "e": 2938, "s": 2903, "text": "Running long parallel calculations" }, { "code": null, "e": 2977, "s": 2938, "text": "Using models of different environments" }, { "code": null, "e": 3015, "s": 2977, "text": "Dynamically plotting training results" }, { "code": null, "e": 3071, "s": 3015, "text": "Embedding Jupyter and Serving a license file on new tab" }, { "code": null, "e": 3097, "s": 3071, "text": "Deploying a trained model" }, { "code": null, "e": 3175, "s": 3097, "text": "Problem: The Streamlit user loses her work on refresh or connection timeouts." }, { "code": null, "e": 3249, "s": 3175, "text": "Solution: Auto-save and auto-load the user’s session with a session file." }, { "code": null, "e": 4076, "s": 3249, "text": "One of the most important things in any app is a session management capability, i.e., the app must “remember” any setting the user have configured whenever the user switches pages, refreshes the web browser and, of course, saves the model and loads it later on. If you know how a ML model class looks like, a saved session is basically the same concept only on a broader context. A session will not only save the hyper parameters and trained model weights but also the entire dataset (or its file path), the predictions, the file paths of the training log, the plots, the scripts the user has written, and any other work the user has made in his session. This means that without keeping her session persistent, the user will lose all her work whenever she refreshes the browser or just temporarily loses connection to the app." }, { "code": null, "e": 4231, "s": 4076, "text": "Without keeping her session persistent the user will lose all her work whenever she refreshes the browser or just temporarily loses connection to the app." }, { "code": null, "e": 4715, "s": 4231, "text": "Even though this feature was constantly asked for in the Streamlit forum right from the early days of the platform, session management was introduced to the platform only two years after. Still and all, the official Streamlit solution has a major downside: it only preserves the user’s work when she switches between pages, whilst it doesn’t preserve a user’s work if a session ends expectedly. My solution does, and it’s using a session management solution of the user okld instead." }, { "code": null, "e": 4764, "s": 4715, "text": "First, the app’s script should have these lines:" }, { "code": null, "e": 4887, "s": 4764, "text": "Second, this functionality only works when Streamlit is started in debug mode and writes the debug messages to a log file:" }, { "code": null, "e": 4947, "s": 4887, "text": "streamlit run app.py --logger.level=debug log_file.log 2>&1" }, { "code": null, "e": 5094, "s": 4947, "text": "The log file should be stored in the folder configs[‘APP_BASE_DIR’] + ‘/logs/streamlit_logs/ as it is used in the was_session_shutdown() function." }, { "code": null, "e": 5138, "s": 5094, "text": "Third, this is how you auto-save a session:" }, { "code": null, "e": 5162, "s": 5138, "text": "autosave_session(state)" }, { "code": null, "e": 5658, "s": 5162, "text": "When should we auto-save and auto-load? I call the autosave function whenever the user changes a configuration or even just changes a page in the app — that way when a session reload occurs, the user can immediately continue his work without having to browse back to the page he was working on. The loading part should be one of the first commands to be called in the app’s script, since an app refresh re-runs the entire script from the beginning, and we want the user’s downtime to be minimal." }, { "code": null, "e": 5795, "s": 5658, "text": "When will a session NOT be auto-loaded? when a user has logged out (see Multi-pages section below), or when the Streamlit app restarted." }, { "code": null, "e": 5944, "s": 5795, "text": "Is it possible to add the auto-save feature to the official Streamlit session solution? it very well might, do tell me if you succeed on doing that!" }, { "code": null, "e": 6014, "s": 5944, "text": "Problem: Streamlit has no option to save a user’s work for later use." }, { "code": null, "e": 6052, "s": 6014, "text": "Solution: Save, load & delete buttons" }, { "code": null, "e": 6405, "s": 6052, "text": "Letting the user save and load his work has the same exact logic as in the section above, only this time save and load are triggered when the user is pressing action buttons. It goes without saying you’ll also have to present a table showing all saved models, as well as some kind of indication of whether a model was successfully saved/loaded/deleted." }, { "code": null, "e": 6473, "s": 6405, "text": "Problem: The Streamlit user can’t create, delete, or browse folders" }, { "code": null, "e": 6528, "s": 6473, "text": "Solution: A recursive function for folder manipulation" }, { "code": null, "e": 6971, "s": 6528, "text": "A files explorer is an absolute necessity for any CRISP-DM app as it is used for saving files and organizing them in directories in almost all of the work’s phases. For instance, you might decide to have a folder for each user’s trained models and a folder for the datasets of each specific project. Even though it’s a very basic requirement, if you google this issue you’ll probably find some not-so-functionating Streamlit users’ solutions." }, { "code": null, "e": 7220, "s": 6971, "text": "This solution enables the user to create, delete, and browse folders, and see the folders’ tree structure. Most importantly, it’ll work even if your Streamlit app is running on a remote server where the user has no direct access to the file system." }, { "code": null, "e": 7282, "s": 7220, "text": "Problem: Streamlit has no built-in user authentication screen" }, { "code": null, "e": 7356, "s": 7282, "text": "Solution: If statement before main() which verifies the user and password" }, { "code": null, "e": 7518, "s": 7356, "text": "Any professional app needs a “bouncer” guarding the entrance. Streamlit doesn’t have one, even though this was also asked for by Streamlit users a long time ago." }, { "code": null, "e": 7652, "s": 7518, "text": "Bear in mind that my implementation uses hard-coded user and password but adding LDAP or MongoDB authentication should be quite easy." }, { "code": null, "e": 7709, "s": 7652, "text": "Problem: Streamlit has no built-in multi-page capability" }, { "code": null, "e": 7783, "s": 7709, "text": "Solution: Add radio menu in the sidebar linked to functions for each page" }, { "code": null, "e": 8104, "s": 7783, "text": "Working with CRISP-DM requires moving back and forth between the different phases. This work process is best represented in the app in the form of ordered options of a menu, each option linked to a different function. The concept of a separate function for each phase also makes perfect sense when you code those phases." }, { "code": null, "e": 8184, "s": 8104, "text": "Problem: Streamlit can’t run two operations at once and stop them in the middle" }, { "code": null, "e": 8262, "s": 8184, "text": "Solution: Run sub-processes and create a process control table in the sidebar" }, { "code": null, "e": 9201, "s": 8262, "text": "Whether you’re brute forcing your way in feature engineering or training heavy deep learning models, you’ll need a way to run things in parallel and, in some cases, kill them prematurely. One way to add this functionality is to run each calculation as a a sub-process, while having a processes table that is both dynamically updating and has action buttons to kill each process separately or shut them all at once. Running independent sub-processes not only let’s you use parallel computing but also ensures that even if the Streamlit session is suddenly killed, the sub-processes will continue running without interruption on the server. So, whatever happens to the Streamlit session, the user can login again and see the results. Another approach to this solution would be to send these sub-processes to work on a cloud service instead of on your own machine - this will probably be of value to you if you need an extra computing power." }, { "code": null, "e": 9250, "s": 9201, "text": "Running a sub-process is rather easy with Popen:" }, { "code": null, "e": 9485, "s": 9250, "text": "try: subprocess.Popen(command)except: st.write(f\"Couldn't run: {command}\") e = sys.exc_info() st.error(e)updated_processes_table(process_table_sidebar, state)# see updated_processes_table() implementation on the gist below" }, { "code": null, "e": 9597, "s": 9485, "text": "It gets a bit tricker if the command you’re running asks the user for input, but it’s also manageble with PIPE:" }, { "code": null, "e": 9866, "s": 9597, "text": "process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)try: process.communicate(\"\\n\".join(user_arguments), timeout=0.2)except: passupdated_processes_table(process_table_sidebar, state)" }, { "code": null, "e": 9928, "s": 9866, "text": "And here’s how you can implement the processes control table:" }, { "code": null, "e": 10004, "s": 9928, "text": "Problem: Streamlit has no option for using models on different environments" }, { "code": null, "e": 10069, "s": 10004, "text": "Solution: Activate Conda environments when running sub-processes" }, { "code": null, "e": 10614, "s": 10069, "text": "When working with heavy CV and NLP models you often need to install different coding environments for each model, since many-a-time they rely on specific Tensorflow or Pytorch versions which aren’t compatible with other installations. In that case, you’ll want to call each model command from its own environment, and you should also capture all of the environments outputs to a log (the variable output_to_log in the gist below). Of course, Conda is just one multi-env solution, one might also consider Pyenv or even use Docker images instead." }, { "code": null, "e": 10749, "s": 10614, "text": "Now that we know how to run sub-processes (see section above), it’s quite straightforward to run them on different conda environments:" }, { "code": null, "e": 10812, "s": 10749, "text": "Problem: Streamlit can’t show training outputs during training" }, { "code": null, "e": 10866, "s": 10812, "text": "Solution: Tail models logs and plot them on intervals" }, { "code": null, "e": 11419, "s": 10866, "text": "Are you underfitting, overfitting or just-fitting? When dealing with deep learning models (as in the section above) it’s especially hard to know this without plotting the models’ metrics during training. It might also be useful to see the textual output of the commands you’re running, and to have an option to download it to a file. finally, it might be convenient to set the interval for refreshing the metrics plots, since they usually update on the finish of one training epoch and the duration of an epoch varies for different models and datasets." }, { "code": null, "e": 11499, "s": 11419, "text": "Problem: Streamlit has no free coding and can’t redirect to a file on a new tab" }, { "code": null, "e": 11573, "s": 11499, "text": "Solution: Embed Jupyter as HTML iframe and add a Jupyter link to the file" }, { "code": null, "e": 12048, "s": 11573, "text": "Embedding a Jupyter notebook/lab instance on a page of the app is one of the hardest challenges I faced. There are multiple theoretical ways and tools for doing that but from my experience, “stars need to align” for the configurations to work. In the end I succeeded embedding Jupyter to Streamlit only with a rather promiscuous security configuration. If that’s a concern for you, start with my configurations and try adding restrictions while still having everything work." }, { "code": null, "e": 12509, "s": 12048, "text": "Jupyter was tough implementing, but worth the effort. It’s a very powerful tool as it lets the knowledgeable user do basically anything he wants with the models already trained, and even add some phases which are not yet implemented like post-processing, explainability, etc. But from the exact same reason, it is also a dangerous tool which gives the user a terminal access to the server, i.e., a capability to destroy it with a command — so use with caution!" }, { "code": null, "e": 12570, "s": 12509, "text": "First, you should create a jupyter configuration file, with:" }, { "code": null, "e": 12605, "s": 12570, "text": "jupyter notebook --generate-config" }, { "code": null, "e": 12666, "s": 12605, "text": "Next, edit the file so that it’ll have these configurations:" }, { "code": null, "e": 13075, "s": 12666, "text": "c.NotebookApp.allow_origin = '*'c.NotebookApp.disable_check_xsrf = Truec.NotebookApp.ip = '*'c.NotebookApp.notebook_dir = <directory of datasets and outputs>c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8502c.NotebookApp.token = ''c.NotebookApp.tornado_settings = {'headers': { 'Content-Security-Policy': \"frame-ancestors http://<Server-IP>:8501/ \" }}c.NotebookApp.use_redirect_file = True" }, { "code": null, "e": 13483, "s": 13075, "text": "The most important configuration is c.NotebookApp.tornado_settings, which tells Jupyter to trust your Streamlit app when presenting an iframe of Jupyter. Also note that you should set c.NotebookApp.port to a number that is not already occupied by the Streamlit port. The default Streamlit port number is 8501, and any new Streamlit session will be opened with the next free port, i.e. 8502, 8503, and so on." }, { "code": null, "e": 13587, "s": 13483, "text": "Starting Jupyter is straightforward, all you should do is add these lines to the beginning of your app:" }, { "code": null, "e": 13818, "s": 13587, "text": "# in if __name__ == \"__main__\":command = rf\"\"\"jupyter lab --allow-root\"\"\"try: subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)except: st.error(f\"Couldn't run {script_type}:\") e = sys.exc_info() st.error(e)" }, { "code": null, "e": 13886, "s": 13818, "text": "But embedding Jupyter to Streamlit is a different and longer story:" }, { "code": null, "e": 14144, "s": 13886, "text": "If you wish the users of your app’s to be redirected to a new separate tab when opening the LICENCE file, you need, in other words, some web app to serve your LICNESE file. Lucky for you, Jupyter can do this exactly, as it’s built upon a Torando web server." }, { "code": null, "e": 14367, "s": 14144, "text": "with col9: linespace_generator(2) while not is_jupyter_up(): time.sleep(0) link = f\"[license](http://{state.jupyter_ip}:{state.jupyter_port}/files/Licence.html)\" st.markdown(link, unsafe_allow_html=True)" }, { "code": null, "e": 14431, "s": 14367, "text": "Problem: Streamlit has no option for delivering a trained model" }, { "code": null, "e": 14477, "s": 14431, "text": "Solution: Create a REST API flask web service" }, { "code": null, "e": 15047, "s": 14477, "text": "Building a model is easy but serving the model so that people can use it directly and on a daily basis — that’s a totally different challenge. The solution I’m presenting here has nothing to do with Streamlit, nonetheless it’s an essential part of any CRISP-DM app and so I chose to include it in the article. My solution is using Flask, which is a rather straightforward platform that will probably be suffice for your POC needs. Still, when things get serious and you need to manage multiple sessions, security and more, you might want to switch to Django or Node.js." }, { "code": null, "e": 15105, "s": 15047, "text": "My Image segmentation API have several independent paths:" }, { "code": null, "e": 15128, "s": 15105, "text": "www.AwsomeApp.com:8503" }, { "code": null, "e": 15297, "s": 15128, "text": "/models: Query trained models/configs: Set prediction arguments /base64: Convert image files formats to base64 strings/predict: Feed model with data and get predictions" }, { "code": null, "e": 15403, "s": 15297, "text": "Here’s is the entire API implementation, along with instructions on how to use it (right after the gist):" }, { "code": null, "e": 15456, "s": 15403, "text": "Query which algorithms are available for prediction:" }, { "code": null, "e": 15549, "s": 15456, "text": "import requestsIP = \"<IP address>\"res = requests.get(f\"http://{IP}:8503/models\"); res.json()" }, { "code": null, "e": 15613, "s": 15549, "text": "Query which trained weights are available for a specific model:" }, { "code": null, "e": 15764, "s": 15613, "text": "params = {\"algorithm\":\"FastFCN\", \"Model_path\":\"coco\", \"return_weights\":\"True\"}res = requests.post(f\"http://{IP}:8503/models\", data=params); res.json()" }, { "code": null, "e": 15817, "s": 15764, "text": "Query which classes a specific model was trained on:" }, { "code": null, "e": 15968, "s": 15817, "text": "params = {\"algorithm\":\"FastFCN\", \"Model_path\":\"coco\", \"return_classes\":\"True\"}res = requests.post(f\"http://{IP}:8503/models\", data=params); res.json()" }, { "code": null, "e": 16152, "s": 15968, "text": "First, create a json file containing the prediction configurations. Those configurations will be used for all subsequent predictions until a new configuration file is sent to the API." }, { "code": null, "e": 16182, "s": 16152, "text": "Example of configs.json file:" }, { "code": null, "e": 16376, "s": 16182, "text": "{'algorithm': 'FastFCN', 'Model_path': 'coco', 'weight': 'FastFCN_coco1', 'IMAGE_MIN_DIM': '1024', 'IMAGE_MAX_DIM': '2048', 'DETECTION_MIN_CONFIDENCE': '0.7', 'mode': '2', 'class_show': 'None'}" }, { "code": null, "e": 16439, "s": 16376, "text": "Second, Send the file and evaluate the current configurations:" }, { "code": null, "e": 16685, "s": 16439, "text": "IP = \"<IP>\"files = {'file': open('configs.json', 'rb')}; json.load(files['file'])files = {'file': open('configs.json', 'rb')}res = requests.post(f\"http://{IP}:8503/configs\", files=files)res = requests.get(f\"http://{IP}:8503/configs\"); res.json()" }, { "code": null, "e": 16798, "s": 16685, "text": "Optional: Preprocess a zip of images to a list of base64 strings, to be later fed into the model for prediction:" }, { "code": null, "e": 16973, "s": 16798, "text": "files = {'file': open('image_to_predict.zip', 'rb')}; res = requests.post(f\"http://{IP}:8503/base64\", files=files); list_of_base64=res.json()params['images'] = list_of_base64" }, { "code": null, "e": 17120, "s": 16973, "text": "First, define a dictionary called params with an images key of which its value is a list of base64 strings representing the images for prediction:" }, { "code": null, "e": 17190, "s": 17120, "text": "params = {'images':[<image0_base64>,<image1_base64>,<image2_base64>]}" }, { "code": null, "e": 17287, "s": 17190, "text": "Set this config to True to get the results in the form of image files instead of base64 strings:" }, { "code": null, "e": 17318, "s": 17287, "text": "params['create_images'] = True" }, { "code": null, "e": 17375, "s": 17318, "text": "Second, make a prediction request, and evaluate results:" }, { "code": null, "e": 17747, "s": 17375, "text": "IP = \"<IP>\"res = requests.post(f\"http://{IP}:8503/predict\", data=params)res = res.json()['Responses']predicted_image0 = res[0][1]json_result0 = res[0][0]print(f\"Classes found: {json_result0['results']['class_name']}\") print(f\"Prediction scores: {json_result0['results']['scores']}\")print(f\"Bounding Boxes: {json_result0['results']['rois [y_min, x_min, y_max, x_max]']}\")" }, { "code": null, "e": 18468, "s": 17747, "text": "Developing an ML app with Streamlit is like taking a ride on the wildest roller-coaster of the amusement park: it’s super quick, extremely exciting, dizzying at times but certainly a lot of fun. Yet after a speedy implementation in Streamlit of your brilliant Machine Learning ideas, it’s almost inevitable your app will not really be usable. That’s a result of Streamlit lacking some basic features: Preserving work on refresh and lost connection, Saving work for later use, Files explorer, Login screen, Multi-page App, Running long parallel calculations, Using models of different environments, Dynamically plotting training results, Embedding Jupyter and Serving a license file on new tab, Deploying a trained model." }, { "code": null, "e": 18658, "s": 18468, "text": "You could try to implement those features yourself or even “roll the dice” on google, but why waste the time? All those features’ codes are above - so sit back, relax, and enjoy the ride :)" } ]
AWT CheckBox Class
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it. Following is the declaration for java.awt.Checkbox class: public class Checkbox extends Component implements ItemSelectable,Accessible Checkbox() Creates a check box with an empty string for its label. Checkbox(String label) Creates a check box with the specified label. Checkbox(String label, boolean state) Creates a check box with the specified label and sets the specified state. Checkbox(String label, boolean state, CheckboxGroup group) Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group. Checkbox(String label, CheckboxGroup group, boolean state) Creates a check box with the specified label, in the specified check box group, and set to the specified state. void addItemListener(ItemListener l) Adds the specified item listener to receive item events from this check box. void addNotify() Creates the peer of the Checkbox. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Checkbox. CheckboxGroup getCheckboxGroup() Determines this check box's group. ItemListener[] getItemListeners() Returns an array of all the item listeners registered on this checkbox. String getLabel() Gets the label of this check box. <T extends EventListener>T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Checkbox. Object[] getSelectedObjects() Returns an array (length 1) containing the checkbox label or null if the checkbox is not selected. boolean getState() Determines whether this check box is in the on or off state. protected String paramString() Returns a string representing the state of this Checkbox. protected void processEvent(AWTEvent e) Processes events on this check box. protected void processItemEvent(ItemEvent e) Processes item events occurring on this check box by dispatching them to any registered ItemListener objects. void removeItemListener(ItemListener l) Removes the specified item listener so that the item listener no longer receives item events from this check box. void setCheckboxGroup(CheckboxGroup g) Sets this check box's group to the specified check box group. void setLabel(String label) Sets this check box's label to be the string argument. void setState(boolean state) Sets the state of this check box to the specified state. This class inherits methods from the following classes: java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showCheckBoxDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showCheckBoxDemo(){ headerLabel.setText("Control in action: CheckBox"); Checkbox chkApple = new Checkbox("Apple"); Checkbox chkMango = new Checkbox("Mango"); Checkbox chkPeer = new Checkbox("Peer"); chkApple.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { statusLabel.setText("Apple Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); chkMango.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { statusLabel.setText("Mango Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); chkPeer.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { statusLabel.setText("Peer Checkbox: " + (e.getStateChange()==1?"checked":"unchecked")); } }); controlPanel.add(chkApple); controlPanel.add(chkMango); controlPanel.add(chkPeer); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1942, "s": 1747, "text": "Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it." }, { "code": null, "e": 2000, "s": 1942, "text": "Following is the declaration for java.awt.Checkbox class:" }, { "code": null, "e": 2086, "s": 2000, "text": "public class Checkbox\n extends Component\n implements ItemSelectable,Accessible" }, { "code": null, "e": 2098, "s": 2086, "text": "Checkbox() " }, { "code": null, "e": 2154, "s": 2098, "text": "Creates a check box with an empty string for its label." }, { "code": null, "e": 2179, "s": 2154, "text": "Checkbox(String label) " }, { "code": null, "e": 2225, "s": 2179, "text": "Creates a check box with the specified label." }, { "code": null, "e": 2265, "s": 2225, "text": "Checkbox(String label, boolean state) " }, { "code": null, "e": 2340, "s": 2265, "text": "Creates a check box with the specified label and sets the specified state." }, { "code": null, "e": 2401, "s": 2340, "text": "Checkbox(String label, boolean state, CheckboxGroup group) " }, { "code": null, "e": 2515, "s": 2401, "text": "Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group." }, { "code": null, "e": 2576, "s": 2515, "text": "Checkbox(String label, CheckboxGroup group, boolean state) " }, { "code": null, "e": 2688, "s": 2576, "text": "Creates a check box with the specified label, in the specified check box group, and set to the specified state." }, { "code": null, "e": 2727, "s": 2688, "text": "void addItemListener(ItemListener l) " }, { "code": null, "e": 2804, "s": 2727, "text": "Adds the specified item listener to receive item events from this check box." }, { "code": null, "e": 2823, "s": 2804, "text": "void addNotify() " }, { "code": null, "e": 2857, "s": 2823, "text": "Creates the peer of the Checkbox." }, { "code": null, "e": 2899, "s": 2857, "text": "AccessibleContext getAccessibleContext() " }, { "code": null, "e": 2957, "s": 2899, "text": "Gets the AccessibleContext associated with this Checkbox." }, { "code": null, "e": 2992, "s": 2957, "text": "CheckboxGroup getCheckboxGroup() " }, { "code": null, "e": 3027, "s": 2992, "text": "Determines this check box's group." }, { "code": null, "e": 3063, "s": 3027, "text": "ItemListener[] getItemListeners() " }, { "code": null, "e": 3135, "s": 3063, "text": "Returns an array of all the item listeners registered on this checkbox." }, { "code": null, "e": 3155, "s": 3135, "text": "String getLabel() " }, { "code": null, "e": 3189, "s": 3155, "text": "Gets the label of this check box." }, { "code": null, "e": 3256, "s": 3189, "text": "<T extends EventListener>T[] getListeners(Class<T> listenerType) " }, { "code": null, "e": 3349, "s": 3256, "text": "Returns an array of all the objects currently registered as FooListeners upon this Checkbox." }, { "code": null, "e": 3382, "s": 3349, "text": "Object[] getSelectedObjects() \n" }, { "code": null, "e": 3481, "s": 3382, "text": "Returns an array (length 1) containing the checkbox label or null if the checkbox is not selected." }, { "code": null, "e": 3502, "s": 3481, "text": "boolean getState() " }, { "code": null, "e": 3563, "s": 3502, "text": "Determines whether this check box is in the on or off state." }, { "code": null, "e": 3596, "s": 3563, "text": "protected String paramString() " }, { "code": null, "e": 3654, "s": 3596, "text": "Returns a string representing the state of this Checkbox." }, { "code": null, "e": 3696, "s": 3654, "text": "protected void processEvent(AWTEvent e) " }, { "code": null, "e": 3732, "s": 3696, "text": "Processes events on this check box." }, { "code": null, "e": 3779, "s": 3732, "text": "protected void processItemEvent(ItemEvent e) " }, { "code": null, "e": 3889, "s": 3779, "text": "Processes item events occurring on this check box by dispatching them to any registered ItemListener objects." }, { "code": null, "e": 3931, "s": 3889, "text": "void removeItemListener(ItemListener l) " }, { "code": null, "e": 4045, "s": 3931, "text": "Removes the specified item listener so that the item listener no longer receives item events from this check box." }, { "code": null, "e": 4086, "s": 4045, "text": "void setCheckboxGroup(CheckboxGroup g) " }, { "code": null, "e": 4148, "s": 4086, "text": "Sets this check box's group to the specified check box group." }, { "code": null, "e": 4178, "s": 4148, "text": "void setLabel(String label) " }, { "code": null, "e": 4233, "s": 4178, "text": "Sets this check box's label to be the string argument." }, { "code": null, "e": 4264, "s": 4233, "text": "void setState(boolean state) " }, { "code": null, "e": 4321, "s": 4264, "text": "Sets the state of this check box to the specified state." }, { "code": null, "e": 4377, "s": 4321, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 4396, "s": 4377, "text": "java.awt.Component" }, { "code": null, "e": 4415, "s": 4396, "text": "java.awt.Component" }, { "code": null, "e": 4432, "s": 4415, "text": "java.lang.Object" }, { "code": null, "e": 4449, "s": 4432, "text": "java.lang.Object" }, { "code": null, "e": 4563, "s": 4449, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 6899, "s": 4563, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showCheckBoxDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showCheckBoxDemo(){\n\n headerLabel.setText(\"Control in action: CheckBox\"); \n\n Checkbox chkApple = new Checkbox(\"Apple\");\n Checkbox chkMango = new Checkbox(\"Mango\");\n Checkbox chkPeer = new Checkbox(\"Peer\");\n\n\n chkApple.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) { \n statusLabel.setText(\"Apple Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\"));\n }\n });\n\n chkMango.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n statusLabel.setText(\"Mango Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\"));\n }\n });\n\n chkPeer.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n statusLabel.setText(\"Peer Checkbox: \" \n + (e.getStateChange()==1?\"checked\":\"unchecked\"));\n }\n });\n\n controlPanel.add(chkApple);\n controlPanel.add(chkMango);\n controlPanel.add(chkPeer); \n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 6990, "s": 6899, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 7046, "s": 6990, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 7143, "s": 7046, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 7193, "s": 7143, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 7221, "s": 7193, "text": "Verify the following output" }, { "code": null, "e": 7254, "s": 7221, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7262, "s": 7254, "text": " EduOLC" }, { "code": null, "e": 7269, "s": 7262, "text": " Print" }, { "code": null, "e": 7280, "s": 7269, "text": " Add Notes" } ]
Kotlin - Generics
Like Java, Kotlin provides higher order of variable typing called as Generics. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer. In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin. The following example depicts how generics is implemented in Kotlin. fun main(args: Array<String>) { val integer: Int = 1 val number: Number = integer print(number) } In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”. Let us learn something more about generics in Kotlin. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier. In the following example, we will see how to use generic data types in Kotlin programming language. fun main(args: Array<String>) { var objet = genericsExample<String>("JAVA") var objet1 = genericsExample<Int>(10) } class genericsExample<T>(input:T) { init { println("I am getting called with the value "+input) } } In the above piece of code, we are creating one class with generic return type, which is represented as <T>. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. This is how generics is interpreted by Kotlin compiler. We will get the following output in the browser, once we run this code in our coding ground. I am getting called with the value JAVA I am getting called with the value 10 When we want to assign the generic type to any of its super type, then we need to use “out” keyword, and when we want to assign the generic type to any of its sub-type, then we need to use “in” keyword. In the following example, we will use “out” keyword. Similarly, you can try using “in” keyword. fun main(args: Array<String>) { var objet1 = genericsExample<Int>(10) var object2 = genericsExample<Double>(10.00) println(objet1) println(object2) } class genericsExample<out T>(input:T) { init { println("I am getting called with the value "+input) } } The above code will yield the following output in the browser. I am getting called with the value 10 I am getting called with the value 10.0 genericsExample@28d93b30 genericsExample@1b6d3586 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": 2847, "s": 2425, "text": "Like Java, Kotlin provides higher order of variable typing called as Generics. In this chapter, we will learn how Kotlin implements Generics and how as a developer we can use those functionalities provided inside the generics library. Implementation wise, generics is pretty similar to Java but Kotlin developer has introduced two new keywords “out” and “in” to make Kotlin codes more readable and easy for the developer." }, { "code": null, "e": 3067, "s": 2847, "text": "In Kotlin, a class and a type are totally different concepts. As per the example, List is a class in Kotlin, whereas List<String> is a type in Kotlin. The following example depicts how generics is implemented in Kotlin." }, { "code": null, "e": 3174, "s": 3067, "text": "fun main(args: Array<String>) {\n val integer: Int = 1\n val number: Number = integer\n print(number)\n}" }, { "code": null, "e": 3440, "s": 3174, "text": "In the above code, we have declared one “integer” and later we have assigned that variable to a number variable. This is possible because “Int” is a subclass of Number class, hence the type conversion happens automatically at runtime and produces the output as “1”." }, { "code": null, "e": 3855, "s": 3440, "text": "Let us learn something more about generics in Kotlin. It is better to go for generic data type whenever we are not sure about the data type we are going to use in the application. Generally, in Kotlin generics is defined by <T> where “T” stands for template, which can be determined dynamically by Kotlin complier. In the following example, we will see how to use generic data types in Kotlin programming language." }, { "code": null, "e": 4089, "s": 3855, "text": "fun main(args: Array<String>) {\n var objet = genericsExample<String>(\"JAVA\")\n var objet1 = genericsExample<Int>(10)\n}\nclass genericsExample<T>(input:T) {\n init {\n println(\"I am getting called with the value \"+input)\n }\n}" }, { "code": null, "e": 4502, "s": 4089, "text": "In the above piece of code, we are creating one class with generic return type, which is represented as <T>. Take a look at the main method, where we have dynamically defined its value at the run by proving the value type, while creating the object of this class. This is how generics is interpreted by Kotlin compiler. We will get the following output in the browser, once we run this code in our coding ground." }, { "code": null, "e": 4581, "s": 4502, "text": "I am getting called with the value JAVA\nI am getting called with the value 10\n" }, { "code": null, "e": 4880, "s": 4581, "text": "When we want to assign the generic type to any of its super type, then we need to use “out” keyword, and when we want to assign the generic type to any of its sub-type, then we need to use “in” keyword. In the following example, we will use “out” keyword. Similarly, you can try using “in” keyword." }, { "code": null, "e": 5158, "s": 4880, "text": "fun main(args: Array<String>) {\n var objet1 = genericsExample<Int>(10)\n var object2 = genericsExample<Double>(10.00)\n println(objet1)\n println(object2)\n}\nclass genericsExample<out T>(input:T) {\n init {\n println(\"I am getting called with the value \"+input)\n }\n}" }, { "code": null, "e": 5221, "s": 5158, "text": "The above code will yield the following output in the browser." }, { "code": null, "e": 5350, "s": 5221, "text": "I am getting called with the value 10\nI am getting called with the value 10.0\ngenericsExample@28d93b30\ngenericsExample@1b6d3586\n" }, { "code": null, "e": 5385, "s": 5350, "text": "\n 68 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5404, "s": 5385, "text": " Arnab Chakraborty" }, { "code": null, "e": 5439, "s": 5404, "text": "\n 71 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5456, "s": 5439, "text": " Frahaan Hussain" }, { "code": null, "e": 5491, "s": 5456, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5508, "s": 5491, "text": " Mahmoud Ramadan" }, { "code": null, "e": 5541, "s": 5508, "text": "\n 49 Lectures \n 6 hours \n" }, { "code": null, "e": 5557, "s": 5541, "text": " Catalin Stefan" }, { "code": null, "e": 5592, "s": 5557, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5612, "s": 5592, "text": " Skillbakerystudios" }, { "code": null, "e": 5645, "s": 5612, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 5662, "s": 5645, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 5669, "s": 5662, "text": " Print" }, { "code": null, "e": 5680, "s": 5669, "text": " Add Notes" } ]
JSON - Syntax
Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following − Data is represented in name/value pairs. Data is represented in name/value pairs. Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma). Square brackets hold arrays and values are separated by ,(comma). Below is a simple example − { "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ] } JSON supports the following two data structures − Collection of name/value pairs − This Data Structure is supported by different programming languages. Collection of name/value pairs − This Data Structure is supported by different programming languages. Ordered list of values − It includes array, list, vector or sequence etc. Ordered list of values − It includes array, list, vector or sequence etc. 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1931, "s": 1780, "text": "Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −" }, { "code": null, "e": 1972, "s": 1931, "text": "Data is represented in name/value pairs." }, { "code": null, "e": 2013, "s": 1972, "text": "Data is represented in name/value pairs." }, { "code": null, "e": 2129, "s": 2013, "text": "Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma)." }, { "code": null, "e": 2245, "s": 2129, "text": "Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma)." }, { "code": null, "e": 2311, "s": 2245, "text": "Square brackets hold arrays and values are separated by ,(comma)." }, { "code": null, "e": 2377, "s": 2311, "text": "Square brackets hold arrays and values are separated by ,(comma)." }, { "code": null, "e": 2405, "s": 2377, "text": "Below is a simple example −" }, { "code": null, "e": 2694, "s": 2405, "text": "{\n \"book\": [\n\n {\n \"id\": \"01\",\n \"language\": \"Java\",\n \"edition\": \"third\",\n \"author\": \"Herbert Schildt\"\n },\n\n {\n \"id\": \"07\",\n \"language\": \"C++\",\n \"edition\": \"second\",\n \"author\": \"E.Balagurusamy\"\n }\n\n ]\n}" }, { "code": null, "e": 2744, "s": 2694, "text": "JSON supports the following two data structures −" }, { "code": null, "e": 2846, "s": 2744, "text": "Collection of name/value pairs − This Data Structure is supported by different programming languages." }, { "code": null, "e": 2948, "s": 2846, "text": "Collection of name/value pairs − This Data Structure is supported by different programming languages." }, { "code": null, "e": 3022, "s": 2948, "text": "Ordered list of values − It includes array, list, vector or sequence etc." }, { "code": null, "e": 3096, "s": 3022, "text": "Ordered list of values − It includes array, list, vector or sequence etc." }, { "code": null, "e": 3129, "s": 3096, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 3146, "s": 3129, "text": " Laurence Svekis" }, { "code": null, "e": 3179, "s": 3146, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3196, "s": 3179, "text": " Laurence Svekis" }, { "code": null, "e": 3229, "s": 3196, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 3246, "s": 3229, "text": " Laurence Svekis" }, { "code": null, "e": 3281, "s": 3246, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3298, "s": 3281, "text": " Laurence Svekis" }, { "code": null, "e": 3329, "s": 3298, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 3342, "s": 3329, "text": " Nilay Mehta" }, { "code": null, "e": 3377, "s": 3342, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3400, "s": 3377, "text": " Stone River ELearning" }, { "code": null, "e": 3407, "s": 3400, "text": " Print" }, { "code": null, "e": 3418, "s": 3407, "text": " Add Notes" } ]
A Naive Bayes approach towards creating closed domain Chatbots! | by Dhruvil Shah | Towards Data Science
Have you ever experienced seeking customer support help for making an inquiry or paying bills or maybe while ordering food online? The chances are good that your first interaction was with a chatbot. Many companies use rule-based or retrieval-based chatbots that are trained for a specific subject, these are called closed domain chatbots. For example, if you want to check the status of your flight you may have a chat like this : In the conversation above, chatbot gave a reply that made the most sense to it or that was very similar to the question asked. This chatbot is specifically trained for handling customer reports or inquiries about flights. A rule-based chatbot uses RE (Regular Expression) patterns for matching the input user response to the responses it is trained on for carrying the conversation with a person when a retrieval-based chatbot uses Intent Classification, Entity Recognition and Response Selection for carrying out a real conversation. There is an easy and efficient approach for creating a closed domain chatbot that uses the Naive Bayes classifier. In this approach a closed domain dataset containing questions/user-responses and corresponding answers is made, in which each question/user-response is given a label, this label relates the question to its answer. Because of multiple questions could have the same response, there can be multiple questions having the same answer. To clear the clouds let’s look at the example. hi there 1hello how are you 1what is your name 2who are you 2you are who 2my name is 2how old are you 3what is your age 3are you getting older 3what about your age 3 The labels/digits at the end are nothing but the index of answers in our answers dataset. Hi there, how are you !?My name is etcetera, but you can call me etc.I'm 22 years old The first two questions contain the label ‘1’ so they refer to the response ‘Hi there, how are you !?’. Similarly, the last four questions refer to ‘I’m 22 years old’. The notion here is that the Naive Bayes classifier will predict the label based on the input we give it. So when you say ‘hi’ our classifier will predict the label ‘1’, which in return we can use to find a suitable answer. When the input is ‘what’s your age?’ classifier will predict the label ‘3’, which is an index of the answer ‘I’m 22 years old’. The below figure will dissolve any misgivings you have about the notion. If we have our questions formatted as above in a file called ‘que.txt’ and answers in a file ‘ans.txt’, we can prepare separate lists containing questions, labels, and answers with the help of the code below: labels = []questions = []for line in open('que.txt', encoding="utf8"): labels.append(line.strip().split(" ")[-1]) que.append(" ".join(line.strip().split(" ")[:-1]))answers = []for line in open('ans.txt', encoding="utf8"): ans.append(line.strip()) Each label is at the end of the question and we can get it as shown above. After this, we will have all the questions for training in a list called ‘questions’ and the labels of those questions in a list ‘labels’. Remember, the labels of questions relate them to their answers. In the ‘answers’ list all the possible answers will be stored. Note: Here, label numbers at the end of a question start from 1 but to map them to answers in the ‘answers’ list we will have to do a subtraction of 1 from the number because python list indexing starts from 0. Now, we need to convert our training questions to vectors to feed them to our classifier. For this purpose, we are going to use CountVectorizer from the machine learning library sci-kit learn. Below is the code snippet for doing this: from sklearn.feature_extraction.text import CountVectorizerbow_vectorizer = CountVectorizer()training_vectors = bow_vectorizer.fit_transform(questions) ‘Bow’ in bow_vectorizer stands for Bag-of-words. The .fit_transform() method of CountVectorizer() does two things: 1.) trains the features dictionary — dictionary of all the unique words in the training corpus 2.) transforms each question into vectors of a size of features dictionary that contains zeros in all the places except for the words used in the question If you didn’t understand the above explanation, let’s take an example. #our sentencesentence = “Help my fly fish fly away”#example features dictionary based on the training corpusfeatures_dictionary = {'all':0,'my':1, 'fish':2, 'fly':3, 'away':4, 'help':5, 'me':6, 'open':7}#Our vector for the sentence above will bevector = [0, 1, 1, 2, 1, 1, 0, 0] #size of vector = size of features dictionary The feature dictionary contains all the unique words from the training corpus as keys and their index as values. The word ‘fly’ appeared twice in our sentence. If we look at the feature dictionary for ‘fly’, we find that its index is 3. So, when we look at our vector we’d expect the number at index 3 to be ‘2’. As shown above the CountVectorizer() gives us the vectors for our questions we feed. Note: Here, we are training our classifier on a very small dataset containing 10 answers and 37 questions only to keep things simple. The size may differ according to various applications. Now that we have our training vectors it’s time we create our Naive Bayes classifier. For this, we will use sci-kit learn’s MultinomialNB(). from sklearn.naive_bayes import MultinomialNBclassifier = MultinomialNB()classifier.fit(training_vectors, labels) We train our classifier using .fit() method, passing in the training vectors and corresponding labels. Now, our classifier is ready to make predictions. We can take input from the user, convert it into the vector with the help of vectorizer we created earlier, and get predictions of the label from our classifier. It is time we create a chatbot class that comprises all methods to carry out a conversation. start_chat() method is to start the conversation. chat() method checks for exit commands like ‘quit’ or ‘bye’ and stops the conversation if found any of those words in a user’s response. class ChatBot: exit_commands = ("quit", "pause", "exit", "goodbye", "bye", "later", "stop") def start_chat(self): user_response = input("Hi, I'm a chatbot trained on random dialogs!!\n") self.chat(user_response) def chat(self, reply): while not self.make_exit(reply): reply = input(self.generate_response(reply)+"\n") return def generate_response(self, sentence): input_vector = bow_vectorizer.transform([sentence]) predict = classifier.predict(input_vector) index = int(predict[0]) print("Accurate:",str(classifier.predict_proba(input_vector)[0][index-1] * 100)[:5] + "%") return answers[index-1] def make_exit(self, reply): for exit_command in self.exit_commands: if exit_command in reply: print("Ok, have a great day!") return True return False Let’s create an instance of our ChatBot class and test our work. etcetera = ChatBot()etcetera.start_chat() When we call .start_chat() eventually call goes to .chat() for checking of exit words and then to .generate_response(). .generate_response() method takes user response as input, converts it to a vector-based on the training corpus, and feeds it to our classifier to get the prediction of a label which in turn will give us the index of the answer to be given to the user. Remember, here we have to access the answers list by index minus one. The above GIF shows how chatbot responds with the weather inquiry. In the training data, there is a user response/question — “tell me today’s weather report 8” which contains label ‘8’. In the answers dataset on line 8 is the response — “Today temperature will be 37 degrees Celsius and sky will be clear all day”. It is obvious that this response is hardcoded here, there can be functions to do the job of entity recognition from the user response (‘weather’) and getting the real-time data from the web using available APIs. Our chatbot is ready. The output above also shows how accurate the prediction is but for this project as a minimal dataset was used, the accuracy is relatively low. Still, it works just okay. Companies can simply adopt this system by replacing their larger closed domain dataset. GitHub’s link for this project is this. You can get all of the above code from there and you can find me here on LinkedIn. Intent Classification and Entity Recognition can be integrated into this approach to serve the applications like paying bills or suggesting songs based on different genres or providing the status of the flight specified by the user. Part-of-speech (POS) tagging could be used for this. This approach can not be applied to open-domain applications where user response can vary to various applications. This approach is strictly for the closed-domain applications where the responses can be determined beforehand and we can map the questions to them. To conclude, chatbots can be built using the Naive Bayes approach in which we just have to give each training question a corresponding label number of the answer and our classifier will predict the label of the user input. This label number is an index of a corresponding response in our answers’ dataset. This way, we do not need to worry much about Regular expression pattern matching like in regular rule-based chatbot approach. The chatbot built above is trained on a very smaller dataset as this is supposed to be a simple explanation of the new approach. The companies may create their datasets according to the specific application. For a production system, you will want to consider one of the existing bot frameworks and integrating this approach into it; this way, you do not have to start from scratch. The Internet is full of resources and after reading this article you may want to create a chatbot of your own.
[ { "code": null, "e": 603, "s": 171, "text": "Have you ever experienced seeking customer support help for making an inquiry or paying bills or maybe while ordering food online? The chances are good that your first interaction was with a chatbot. Many companies use rule-based or retrieval-based chatbots that are trained for a specific subject, these are called closed domain chatbots. For example, if you want to check the status of your flight you may have a chat like this :" }, { "code": null, "e": 825, "s": 603, "text": "In the conversation above, chatbot gave a reply that made the most sense to it or that was very similar to the question asked. This chatbot is specifically trained for handling customer reports or inquiries about flights." }, { "code": null, "e": 1138, "s": 825, "text": "A rule-based chatbot uses RE (Regular Expression) patterns for matching the input user response to the responses it is trained on for carrying the conversation with a person when a retrieval-based chatbot uses Intent Classification, Entity Recognition and Response Selection for carrying out a real conversation." }, { "code": null, "e": 1630, "s": 1138, "text": "There is an easy and efficient approach for creating a closed domain chatbot that uses the Naive Bayes classifier. In this approach a closed domain dataset containing questions/user-responses and corresponding answers is made, in which each question/user-response is given a label, this label relates the question to its answer. Because of multiple questions could have the same response, there can be multiple questions having the same answer. To clear the clouds let’s look at the example." }, { "code": null, "e": 1796, "s": 1630, "text": "hi there 1hello how are you 1what is your name 2who are you 2you are who 2my name is 2how old are you 3what is your age 3are you getting older 3what about your age 3" }, { "code": null, "e": 1886, "s": 1796, "text": "The labels/digits at the end are nothing but the index of answers in our answers dataset." }, { "code": null, "e": 1972, "s": 1886, "text": "Hi there, how are you !?My name is etcetera, but you can call me etc.I'm 22 years old" }, { "code": null, "e": 2140, "s": 1972, "text": "The first two questions contain the label ‘1’ so they refer to the response ‘Hi there, how are you !?’. Similarly, the last four questions refer to ‘I’m 22 years old’." }, { "code": null, "e": 2491, "s": 2140, "text": "The notion here is that the Naive Bayes classifier will predict the label based on the input we give it. So when you say ‘hi’ our classifier will predict the label ‘1’, which in return we can use to find a suitable answer. When the input is ‘what’s your age?’ classifier will predict the label ‘3’, which is an index of the answer ‘I’m 22 years old’." }, { "code": null, "e": 2564, "s": 2491, "text": "The below figure will dissolve any misgivings you have about the notion." }, { "code": null, "e": 2773, "s": 2564, "text": "If we have our questions formatted as above in a file called ‘que.txt’ and answers in a file ‘ans.txt’, we can prepare separate lists containing questions, labels, and answers with the help of the code below:" }, { "code": null, "e": 3029, "s": 2773, "text": "labels = []questions = []for line in open('que.txt', encoding=\"utf8\"): labels.append(line.strip().split(\" \")[-1]) que.append(\" \".join(line.strip().split(\" \")[:-1]))answers = []for line in open('ans.txt', encoding=\"utf8\"): ans.append(line.strip())" }, { "code": null, "e": 3370, "s": 3029, "text": "Each label is at the end of the question and we can get it as shown above. After this, we will have all the questions for training in a list called ‘questions’ and the labels of those questions in a list ‘labels’. Remember, the labels of questions relate them to their answers. In the ‘answers’ list all the possible answers will be stored." }, { "code": null, "e": 3581, "s": 3370, "text": "Note: Here, label numbers at the end of a question start from 1 but to map them to answers in the ‘answers’ list we will have to do a subtraction of 1 from the number because python list indexing starts from 0." }, { "code": null, "e": 3816, "s": 3581, "text": "Now, we need to convert our training questions to vectors to feed them to our classifier. For this purpose, we are going to use CountVectorizer from the machine learning library sci-kit learn. Below is the code snippet for doing this:" }, { "code": null, "e": 3968, "s": 3816, "text": "from sklearn.feature_extraction.text import CountVectorizerbow_vectorizer = CountVectorizer()training_vectors = bow_vectorizer.fit_transform(questions)" }, { "code": null, "e": 4333, "s": 3968, "text": "‘Bow’ in bow_vectorizer stands for Bag-of-words. The .fit_transform() method of CountVectorizer() does two things: 1.) trains the features dictionary — dictionary of all the unique words in the training corpus 2.) transforms each question into vectors of a size of features dictionary that contains zeros in all the places except for the words used in the question" }, { "code": null, "e": 4404, "s": 4333, "text": "If you didn’t understand the above explanation, let’s take an example." }, { "code": null, "e": 4729, "s": 4404, "text": "#our sentencesentence = “Help my fly fish fly away”#example features dictionary based on the training corpusfeatures_dictionary = {'all':0,'my':1, 'fish':2, 'fly':3, 'away':4, 'help':5, 'me':6, 'open':7}#Our vector for the sentence above will bevector = [0, 1, 1, 2, 1, 1, 0, 0] #size of vector = size of features dictionary" }, { "code": null, "e": 5127, "s": 4729, "text": "The feature dictionary contains all the unique words from the training corpus as keys and their index as values. The word ‘fly’ appeared twice in our sentence. If we look at the feature dictionary for ‘fly’, we find that its index is 3. So, when we look at our vector we’d expect the number at index 3 to be ‘2’. As shown above the CountVectorizer() gives us the vectors for our questions we feed." }, { "code": null, "e": 5316, "s": 5127, "text": "Note: Here, we are training our classifier on a very small dataset containing 10 answers and 37 questions only to keep things simple. The size may differ according to various applications." }, { "code": null, "e": 5457, "s": 5316, "text": "Now that we have our training vectors it’s time we create our Naive Bayes classifier. For this, we will use sci-kit learn’s MultinomialNB()." }, { "code": null, "e": 5571, "s": 5457, "text": "from sklearn.naive_bayes import MultinomialNBclassifier = MultinomialNB()classifier.fit(training_vectors, labels)" }, { "code": null, "e": 5674, "s": 5571, "text": "We train our classifier using .fit() method, passing in the training vectors and corresponding labels." }, { "code": null, "e": 5886, "s": 5674, "text": "Now, our classifier is ready to make predictions. We can take input from the user, convert it into the vector with the help of vectorizer we created earlier, and get predictions of the label from our classifier." }, { "code": null, "e": 6166, "s": 5886, "text": "It is time we create a chatbot class that comprises all methods to carry out a conversation. start_chat() method is to start the conversation. chat() method checks for exit commands like ‘quit’ or ‘bye’ and stops the conversation if found any of those words in a user’s response." }, { "code": null, "e": 6982, "s": 6166, "text": "class ChatBot: exit_commands = (\"quit\", \"pause\", \"exit\", \"goodbye\", \"bye\", \"later\", \"stop\") def start_chat(self): user_response = input(\"Hi, I'm a chatbot trained on random dialogs!!\\n\") self.chat(user_response) def chat(self, reply): while not self.make_exit(reply): reply = input(self.generate_response(reply)+\"\\n\") return def generate_response(self, sentence): input_vector = bow_vectorizer.transform([sentence]) predict = classifier.predict(input_vector) index = int(predict[0]) print(\"Accurate:\",str(classifier.predict_proba(input_vector)[0][index-1] * 100)[:5] + \"%\") return answers[index-1] def make_exit(self, reply): for exit_command in self.exit_commands: if exit_command in reply: print(\"Ok, have a great day!\") return True return False" }, { "code": null, "e": 7047, "s": 6982, "text": "Let’s create an instance of our ChatBot class and test our work." }, { "code": null, "e": 7089, "s": 7047, "text": "etcetera = ChatBot()etcetera.start_chat()" }, { "code": null, "e": 7531, "s": 7089, "text": "When we call .start_chat() eventually call goes to .chat() for checking of exit words and then to .generate_response(). .generate_response() method takes user response as input, converts it to a vector-based on the training corpus, and feeds it to our classifier to get the prediction of a label which in turn will give us the index of the answer to be given to the user. Remember, here we have to access the answers list by index minus one." }, { "code": null, "e": 8058, "s": 7531, "text": "The above GIF shows how chatbot responds with the weather inquiry. In the training data, there is a user response/question — “tell me today’s weather report 8” which contains label ‘8’. In the answers dataset on line 8 is the response — “Today temperature will be 37 degrees Celsius and sky will be clear all day”. It is obvious that this response is hardcoded here, there can be functions to do the job of entity recognition from the user response (‘weather’) and getting the real-time data from the web using available APIs." }, { "code": null, "e": 8338, "s": 8058, "text": "Our chatbot is ready. The output above also shows how accurate the prediction is but for this project as a minimal dataset was used, the accuracy is relatively low. Still, it works just okay. Companies can simply adopt this system by replacing their larger closed domain dataset." }, { "code": null, "e": 8461, "s": 8338, "text": "GitHub’s link for this project is this. You can get all of the above code from there and you can find me here on LinkedIn." }, { "code": null, "e": 8747, "s": 8461, "text": "Intent Classification and Entity Recognition can be integrated into this approach to serve the applications like paying bills or suggesting songs based on different genres or providing the status of the flight specified by the user. Part-of-speech (POS) tagging could be used for this." }, { "code": null, "e": 9010, "s": 8747, "text": "This approach can not be applied to open-domain applications where user response can vary to various applications. This approach is strictly for the closed-domain applications where the responses can be determined beforehand and we can map the questions to them." }, { "code": null, "e": 9650, "s": 9010, "text": "To conclude, chatbots can be built using the Naive Bayes approach in which we just have to give each training question a corresponding label number of the answer and our classifier will predict the label of the user input. This label number is an index of a corresponding response in our answers’ dataset. This way, we do not need to worry much about Regular expression pattern matching like in regular rule-based chatbot approach. The chatbot built above is trained on a very smaller dataset as this is supposed to be a simple explanation of the new approach. The companies may create their datasets according to the specific application." } ]
Spotify Data Project Part 1 — from Data Retrieval to First Insights | by Tomi Gelo | Towards Data Science
2018 has been a great year so far for us data nerds. There are so many great options to get interesting data, such as the biggest data science community Kaggle, with more than 10.000 published datasets from all kinds of industries. Or Google (who also happens to own Kaggle) with the newly introduced dataset search tool, makes finding datasets for practicing your data muscles as easy as installing Pandas (or any other data science library for that matter). And if you are willing to get your hands dirty for some nice data you can always go for the APIs. Tech companies such as Twitter, Slack and Google (again!) provide APIs so that others can build applications on top of those. There is nothing stopping you from using them for extracting data and doing some data analysis with it. In this series of articles, I’m going to describe how I utilized the Spotify Web API to retrieve data automatically (main topic of this article, mostly) as well as how to use data science tools such as Python, SQL and Bash to gain insights from the data (to be covered in the following articles). Note: if you are only interested in the coding stuff feel free to skip to the end of this article where you will find all the notebooks, tools and references used for this project. In order to get access to Spotify’s platform, you need to create an account at developer.spotify.com. After that, you can directly go to the Spotify Web API Console and start exploring the different API endpoints with an easy-to-use interface without the need for any Jupyter notebooks at all! Essentially, APIs work on a request/response basis. You ask the API about tracks from the golden years of 2010–2012 and the API responds with some of the best songs of our generation such as this gem. However, since the communication with the API is done in a machine-readable format such as JSON, you will want to use a programming language to do this. That is, if you want to make use of the millions of rows of music data available in the Spotify catalog. Since I’m using Python, there is a very nice library called Spotipy which makes the process of accessing the Spotify API a lot easier. Once you installed Spotipy, the below code is sufficient to get it up and running (use your own cid and secret from your Spotify developer account): import spotipy from spotipy.oauth2 import SpotifyClientCredentials cid ="xx" secret = "xx" client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) Now you can start with the actual data retrieval. By looking at the different endpoints of the Spotify API you might ask yourself: what data should I get? This is where you need to start digging and finding out what may be interesting for you. In this example, I used only 2 out of the 50+ endpoints available. You might find some other endpoints also useful for your analysis. I knew that I wanted to work with track data. That’s why I used the search endpoint (not the get several tracks endpoint since that one requires track IDs to be provided which I didn’t have). The search endpoint is fairly easy to use as there are only 2 required parameters: q and type. The first one can be any keyword such as ‘roadhouse blues’ or ‘2018’. The type can be album, artist, playlist or track. There are also a couple of limitations with this endpoint: limit: a maximum of 50 results can be returned per query offset: this is the index of the first result to return, so if you want to get the results with the index 50–100 you will need to set the offset to 50 etc. Also, the maximum offset is limited to 10.000 which means that you can’t get more results than that for a single search. Fun fact: when I first did the data retrieval (end of April 2018) the maximum offset was 100.000. Hopefully, I was not the reason why they decided to cut it down :) In order to work around the limitations, I used a nested for loop where I increased the offset by 50 in the outer loop until the maximum offset was reached. The inner for loop did the actual querying while appending the returned results to lists. for i in range(0,10000,50): track_results = sp.search(q='year:2018', type='track', limit=50,offset=i) for i, t in enumerate(track_results['tracks']['items']): artist_name.append(t['artists'][0]['name']) track_name.append(t['name']) track_id.append(t['id']) popularity.append(t['popularity']) After I loaded the data into a pandas dataframe, I got the following: artist_name popularity track_id track_name 0 Drake 100 2G7V7zsVDxg1yRsu7Ew9RJ In My Feelings 1 XXXTENTACION 97 3ee8Jmje8o58CHK66QrVC2 SAD! 2 Tyga 96 5IaHrVsrferBYDm0bDyABy Taste (feat. Offset) 3 Cardi B 97 58q2HKrzhC3ozto2nDdN4z I Like It 4 XXXTENTACION 95 0JP9xo3adEtGSdUEISiszL Moonlight This is already enough to work with, as I will show in the second part of this article when I will dig deeper into the ‘popularity’ feature provided by Spotify. Since I want to do some more advanced analysis as well (hint: machine learning) I also included data provided by the get several audio features endpoint. This endpoint only requires the track IDs to be provided. That wasn’t a problem since I had 10.000 track IDs from my previous query. The limitation here was that a maximum of 100 track IDs can be submitted per query. Again, I used a nested for loop. This time the outer loop was pulling track IDs in batches of size 100 and the inner for loop was doing the query and appending the results to the rows list. Additionally, I had to implement a check when a track ID didn’t return any audio features (i.e. None was returned) as this was causing issues: for i in range(0,len(df_tracks['track_id']),batchsize): batch = df_tracks['track_id'][i:i+batchsize] feature_results = sp.audio_features(batch) for i, t in enumerate(feature_results): if t == None: None_counter = None_counter + 1 else: rows.append(t) In return, I got a bunch of audio features for my tracks such as danceability, loudness, acousticness and so on. Those features, however, will be part of the next article in this series. Before doing some data analysis with the popularity feature, I want to show you how I set up a cron job on a Linux terminal (command line/ Bash) to do the data retrieval automatically while I’m sleeping! It’s super simple: you just need your Python file (if you are using Jupyter notebooks you can download it as a .py file) and then you create a Bash script (.sh file) which will run the file in Python: #!/usr/bin/env bash python3 /home/user/SpotifyDataScript.py Finally, you open your crontab editor and set up a cron job at the desired time and day like this: 30 00 * * 4 /home/user/Spotify.sh And voilà! You don’t need to worry anymore, the data will now be retrieved automatically. As you can see from the screenshot below taken from the Spotify for developers dashboard, the data is now being pulled automatically from the API on a weekly basis. If you want to find out more about Bash scripts and cron jobs I recommend this series of articles from data36 as well as this quick reference guide. Note: although this has been working for me quite well I would recommend to be careful when setting up automations for API calls. Try to minimize the impact on the provider side by using longer intervals for triggering the data such as weekly or even monthly. As promised, I will now use the retrieved data to get some insights from it. In this article, I’m going to focus on the popularity feature which, according to the Official Spotify documentation means: “The popularity of the track. The value will be between 0, for least popular, and 100 for most popular. The popularity of a track is a value between 0 and 100, with 100 being the most popular. Popularity is based mainly on the total number of playbacks. Duplicate tracks, such as both in a single and in an album, are popularity rated differently. Note: This value is not updated in real-time and may therefore lag behind in actual popularity.” Although Spotify isn’t being too precise about this feature this should still be enough for a data analysis. Ideally there would be another feature such as the number of streams per track, however, Spotify doesn’t share this information via their API at the moment. An important thing to know about the popularity feature has also been explained in this SO post from 2013 from a user named Sascha: “Spotify’s popularity is indeed based on the number of streams, but instead of total plays, it’s based on a short timeframe. This is why you’ll often see a more popular number on #1 on an artist profile that has less plays than the #2. We have used the API number as a percentage in our Stream Popularity, giving people insight in the current popularity of their track. So keep in mind this is a number the can increase, but just as easily decrease.” So basically, it represents the popularity of a track at a given moment. This explains also why it is changing from time to time as I could notice from my weekly data retrievals. Since I started collecting data regularly in August 2018, I decided to include the following 3 data retrievals for my analysis: 07th August 2018 30th August 2018 20th September 2018 Thanks to the supposed delay in the calculation of the popularity as mentioned by Spotify, this should cover the months of July, August and September pretty well so that I can market my analysis as the ‘most popular tracks of the summer 2018’. For this, I loaded the 3 CSV files into Pandas dataframes and merged them into one single dataframe. By using an outer join as the merging method, the individual popularities were preserved: # loop over dataframes and merge into one dataframe # outer join in order to keep the popularity column from each filefor df_, files in zip(df_from_each_file, all_files): # all_files are here to provide the column suffix (0920,0830 etc) df = df.merge(df_, how='outer', on=merge_columns, suffixes=('',str(files)[-8:-4]) This was already the trickiest part of the whole data preparation phase for this analysis. After that, I calculated an overall popularity score as well as a mean popularity score. The new dataframe sorted by the overall popularity score looks like this: artist_name track_name popularity popularity_mean 3 Drake In My Feelings 300.0 100.000000 4 XXXTENTACION SAD! 288.0 96.000000 12 Cardi B I Like It 288.0 96.000000 6 Tyga Taste (feat. Offset) 287.0 95.666667 10 Post Malone Better Now 287.0 95.666667 Seems like nothing comes close to Drake’s ‘In My Feelings’ when it comes to summer hits 2018. Grouping the dataframe by artist reveals some more interesting insights such as the number of tracks per artist in the top 100: track_name artist_name Drake 5 XXXTENTACION 5 Travis Scott 5 Post Malone 5 Juice WRLD 3 Every good data analysis should also have some visualization. In this example, I visualized the individual popularity scores during the measurement period for the top 10 tracks. This is part of the visualization (check out the notebook file at the end of the article for a full view): And that’s it for today! A decent amount of data was retrieved and analyzed to find out about the most popular tracks and artists of summer 2018. In the next article, I’m going to dig deeper into the audio features data and try out different clustering algorithms. If that sounds interesting to you, make sure to follow me on Twitter (@tgel0) as I will post the news there first. That’s also the best way to reach out to me if you feel like saying hi or something (I would love that). As promised, here are the links: Data retrieval notebook on github or as nbviewer render Data exploration notebook on github or as nbviewer render big thanks to Spotify for their Web API as well as to the creator of Spotipy for making my life easier last but not least, this wouldn’t be possible without the Python libraries Pandas, Numpy, Matplotlib and the amazing people building and maintaining them and if you feel like listening to music instead of just reading about it, I have created a Spotify playlist based on the most popular tracks from this analysis Originally published at tgel0.github.io on September 27, 2018.
[ { "code": null, "e": 632, "s": 172, "text": "2018 has been a great year so far for us data nerds. There are so many great options to get interesting data, such as the biggest data science community Kaggle, with more than 10.000 published datasets from all kinds of industries. Or Google (who also happens to own Kaggle) with the newly introduced dataset search tool, makes finding datasets for practicing your data muscles as easy as installing Pandas (or any other data science library for that matter)." }, { "code": null, "e": 960, "s": 632, "text": "And if you are willing to get your hands dirty for some nice data you can always go for the APIs. Tech companies such as Twitter, Slack and Google (again!) provide APIs so that others can build applications on top of those. There is nothing stopping you from using them for extracting data and doing some data analysis with it." }, { "code": null, "e": 1257, "s": 960, "text": "In this series of articles, I’m going to describe how I utilized the Spotify Web API to retrieve data automatically (main topic of this article, mostly) as well as how to use data science tools such as Python, SQL and Bash to gain insights from the data (to be covered in the following articles)." }, { "code": null, "e": 1438, "s": 1257, "text": "Note: if you are only interested in the coding stuff feel free to skip to the end of this article where you will find all the notebooks, tools and references used for this project." }, { "code": null, "e": 1732, "s": 1438, "text": "In order to get access to Spotify’s platform, you need to create an account at developer.spotify.com. After that, you can directly go to the Spotify Web API Console and start exploring the different API endpoints with an easy-to-use interface without the need for any Jupyter notebooks at all!" }, { "code": null, "e": 2191, "s": 1732, "text": "Essentially, APIs work on a request/response basis. You ask the API about tracks from the golden years of 2010–2012 and the API responds with some of the best songs of our generation such as this gem. However, since the communication with the API is done in a machine-readable format such as JSON, you will want to use a programming language to do this. That is, if you want to make use of the millions of rows of music data available in the Spotify catalog." }, { "code": null, "e": 2326, "s": 2191, "text": "Since I’m using Python, there is a very nice library called Spotipy which makes the process of accessing the Spotify API a lot easier." }, { "code": null, "e": 2475, "s": 2326, "text": "Once you installed Spotipy, the below code is sufficient to get it up and running (use your own cid and secret from your Spotify developer account):" }, { "code": null, "e": 2733, "s": 2475, "text": "import spotipy from spotipy.oauth2 import SpotifyClientCredentials cid =\"xx\" secret = \"xx\" client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)" }, { "code": null, "e": 2888, "s": 2733, "text": "Now you can start with the actual data retrieval. By looking at the different endpoints of the Spotify API you might ask yourself: what data should I get?" }, { "code": null, "e": 3111, "s": 2888, "text": "This is where you need to start digging and finding out what may be interesting for you. In this example, I used only 2 out of the 50+ endpoints available. You might find some other endpoints also useful for your analysis." }, { "code": null, "e": 3303, "s": 3111, "text": "I knew that I wanted to work with track data. That’s why I used the search endpoint (not the get several tracks endpoint since that one requires track IDs to be provided which I didn’t have)." }, { "code": null, "e": 3518, "s": 3303, "text": "The search endpoint is fairly easy to use as there are only 2 required parameters: q and type. The first one can be any keyword such as ‘roadhouse blues’ or ‘2018’. The type can be album, artist, playlist or track." }, { "code": null, "e": 3577, "s": 3518, "text": "There are also a couple of limitations with this endpoint:" }, { "code": null, "e": 3634, "s": 3577, "text": "limit: a maximum of 50 results can be returned per query" }, { "code": null, "e": 3790, "s": 3634, "text": "offset: this is the index of the first result to return, so if you want to get the results with the index 50–100 you will need to set the offset to 50 etc." }, { "code": null, "e": 4076, "s": 3790, "text": "Also, the maximum offset is limited to 10.000 which means that you can’t get more results than that for a single search. Fun fact: when I first did the data retrieval (end of April 2018) the maximum offset was 100.000. Hopefully, I was not the reason why they decided to cut it down :)" }, { "code": null, "e": 4323, "s": 4076, "text": "In order to work around the limitations, I used a nested for loop where I increased the offset by 50 in the outer loop until the maximum offset was reached. The inner for loop did the actual querying while appending the returned results to lists." }, { "code": null, "e": 4629, "s": 4323, "text": "for i in range(0,10000,50): track_results = sp.search(q='year:2018', type='track', limit=50,offset=i) for i, t in enumerate(track_results['tracks']['items']): artist_name.append(t['artists'][0]['name']) track_name.append(t['name']) track_id.append(t['id']) popularity.append(t['popularity'])" }, { "code": null, "e": 4699, "s": 4629, "text": "After I loaded the data into a pandas dataframe, I got the following:" }, { "code": null, "e": 4989, "s": 4699, "text": "artist_name\tpopularity\ttrack_id\ttrack_name 0\tDrake 100\t2G7V7zsVDxg1yRsu7Ew9RJ\tIn My Feelings 1\tXXXTENTACION\t97\t3ee8Jmje8o58CHK66QrVC2\tSAD! 2\tTyga 96\t5IaHrVsrferBYDm0bDyABy\tTaste (feat. Offset) 3\tCardi B 97\t58q2HKrzhC3ozto2nDdN4z\tI Like It 4\tXXXTENTACION\t95\t0JP9xo3adEtGSdUEISiszL\tMoonlight" }, { "code": null, "e": 5304, "s": 4989, "text": "This is already enough to work with, as I will show in the second part of this article when I will dig deeper into the ‘popularity’ feature provided by Spotify. Since I want to do some more advanced analysis as well (hint: machine learning) I also included data provided by the get several audio features endpoint." }, { "code": null, "e": 5437, "s": 5304, "text": "This endpoint only requires the track IDs to be provided. That wasn’t a problem since I had 10.000 track IDs from my previous query." }, { "code": null, "e": 5521, "s": 5437, "text": "The limitation here was that a maximum of 100 track IDs can be submitted per query." }, { "code": null, "e": 5711, "s": 5521, "text": "Again, I used a nested for loop. This time the outer loop was pulling track IDs in batches of size 100 and the inner for loop was doing the query and appending the results to the rows list." }, { "code": null, "e": 5854, "s": 5711, "text": "Additionally, I had to implement a check when a track ID didn’t return any audio features (i.e. None was returned) as this was causing issues:" }, { "code": null, "e": 6119, "s": 5854, "text": "for i in range(0,len(df_tracks['track_id']),batchsize): batch = df_tracks['track_id'][i:i+batchsize] feature_results = sp.audio_features(batch) for i, t in enumerate(feature_results): if t == None: None_counter = None_counter + 1 else: rows.append(t)" }, { "code": null, "e": 6306, "s": 6119, "text": "In return, I got a bunch of audio features for my tracks such as danceability, loudness, acousticness and so on. Those features, however, will be part of the next article in this series." }, { "code": null, "e": 6510, "s": 6306, "text": "Before doing some data analysis with the popularity feature, I want to show you how I set up a cron job on a Linux terminal (command line/ Bash) to do the data retrieval automatically while I’m sleeping!" }, { "code": null, "e": 6711, "s": 6510, "text": "It’s super simple: you just need your Python file (if you are using Jupyter notebooks you can download it as a .py file) and then you create a Bash script (.sh file) which will run the file in Python:" }, { "code": null, "e": 6771, "s": 6711, "text": "#!/usr/bin/env bash python3 /home/user/SpotifyDataScript.py" }, { "code": null, "e": 6870, "s": 6771, "text": "Finally, you open your crontab editor and set up a cron job at the desired time and day like this:" }, { "code": null, "e": 6904, "s": 6870, "text": "30 00 * * 4 /home/user/Spotify.sh" }, { "code": null, "e": 7160, "s": 6904, "text": "And voilà! You don’t need to worry anymore, the data will now be retrieved automatically. As you can see from the screenshot below taken from the Spotify for developers dashboard, the data is now being pulled automatically from the API on a weekly basis." }, { "code": null, "e": 7309, "s": 7160, "text": "If you want to find out more about Bash scripts and cron jobs I recommend this series of articles from data36 as well as this quick reference guide." }, { "code": null, "e": 7569, "s": 7309, "text": "Note: although this has been working for me quite well I would recommend to be careful when setting up automations for API calls. Try to minimize the impact on the provider side by using longer intervals for triggering the data such as weekly or even monthly." }, { "code": null, "e": 7770, "s": 7569, "text": "As promised, I will now use the retrieved data to get some insights from it. In this article, I’m going to focus on the popularity feature which, according to the Official Spotify documentation means:" }, { "code": null, "e": 8215, "s": 7770, "text": "“The popularity of the track. The value will be between 0, for least popular, and 100 for most popular. The popularity of a track is a value between 0 and 100, with 100 being the most popular. Popularity is based mainly on the total number of playbacks. Duplicate tracks, such as both in a single and in an album, are popularity rated differently. Note: This value is not updated in real-time and may therefore lag behind in actual popularity.”" }, { "code": null, "e": 8481, "s": 8215, "text": "Although Spotify isn’t being too precise about this feature this should still be enough for a data analysis. Ideally there would be another feature such as the number of streams per track, however, Spotify doesn’t share this information via their API at the moment." }, { "code": null, "e": 8613, "s": 8481, "text": "An important thing to know about the popularity feature has also been explained in this SO post from 2013 from a user named Sascha:" }, { "code": null, "e": 8849, "s": 8613, "text": "“Spotify’s popularity is indeed based on the number of streams, but instead of total plays, it’s based on a short timeframe. This is why you’ll often see a more popular number on #1 on an artist profile that has less plays than the #2." }, { "code": null, "e": 9064, "s": 8849, "text": "We have used the API number as a percentage in our Stream Popularity, giving people insight in the current popularity of their track. So keep in mind this is a number the can increase, but just as easily decrease.”" }, { "code": null, "e": 9243, "s": 9064, "text": "So basically, it represents the popularity of a track at a given moment. This explains also why it is changing from time to time as I could notice from my weekly data retrievals." }, { "code": null, "e": 9371, "s": 9243, "text": "Since I started collecting data regularly in August 2018, I decided to include the following 3 data retrievals for my analysis:" }, { "code": null, "e": 9388, "s": 9371, "text": "07th August 2018" }, { "code": null, "e": 9405, "s": 9388, "text": "30th August 2018" }, { "code": null, "e": 9425, "s": 9405, "text": "20th September 2018" }, { "code": null, "e": 9669, "s": 9425, "text": "Thanks to the supposed delay in the calculation of the popularity as mentioned by Spotify, this should cover the months of July, August and September pretty well so that I can market my analysis as the ‘most popular tracks of the summer 2018’." }, { "code": null, "e": 9860, "s": 9669, "text": "For this, I loaded the 3 CSV files into Pandas dataframes and merged them into one single dataframe. By using an outer join as the merging method, the individual popularities were preserved:" }, { "code": null, "e": 10179, "s": 9860, "text": "# loop over dataframes and merge into one dataframe # outer join in order to keep the popularity column from each filefor df_, files in zip(df_from_each_file, all_files): # all_files are here to provide the column suffix (0920,0830 etc) df = df.merge(df_, how='outer', on=merge_columns, suffixes=('',str(files)[-8:-4])" }, { "code": null, "e": 10359, "s": 10179, "text": "This was already the trickiest part of the whole data preparation phase for this analysis. After that, I calculated an overall popularity score as well as a mean popularity score." }, { "code": null, "e": 10433, "s": 10359, "text": "The new dataframe sorted by the overall popularity score looks like this:" }, { "code": null, "e": 10682, "s": 10433, "text": "artist_name\ttrack_name\tpopularity\tpopularity_mean 3\tDrake In My Feelings\t300.0 100.000000 4\tXXXTENTACION\tSAD! 288.0 96.000000 12\tCardi B I Like It\t288.0 96.000000 6\tTyga Taste (feat. Offset)\t287.0\t95.666667 10\tPost Malone\tBetter Now\t287.0 95.666667" }, { "code": null, "e": 10776, "s": 10682, "text": "Seems like nothing comes close to Drake’s ‘In My Feelings’ when it comes to summer hits 2018." }, { "code": null, "e": 10904, "s": 10776, "text": "Grouping the dataframe by artist reveals some more interesting insights such as the number of tracks per artist in the top 100:" }, { "code": null, "e": 10992, "s": 10904, "text": "track_name artist_name Drake 5 XXXTENTACION\t5 Travis Scott\t5 Post Malone\t5 Juice WRLD\t3" }, { "code": null, "e": 11277, "s": 10992, "text": "Every good data analysis should also have some visualization. In this example, I visualized the individual popularity scores during the measurement period for the top 10 tracks. This is part of the visualization (check out the notebook file at the end of the article for a full view):" }, { "code": null, "e": 11423, "s": 11277, "text": "And that’s it for today! A decent amount of data was retrieved and analyzed to find out about the most popular tracks and artists of summer 2018." }, { "code": null, "e": 11762, "s": 11423, "text": "In the next article, I’m going to dig deeper into the audio features data and try out different clustering algorithms. If that sounds interesting to you, make sure to follow me on Twitter (@tgel0) as I will post the news there first. That’s also the best way to reach out to me if you feel like saying hi or something (I would love that)." }, { "code": null, "e": 11795, "s": 11762, "text": "As promised, here are the links:" }, { "code": null, "e": 11851, "s": 11795, "text": "Data retrieval notebook on github or as nbviewer render" }, { "code": null, "e": 11909, "s": 11851, "text": "Data exploration notebook on github or as nbviewer render" }, { "code": null, "e": 12012, "s": 11909, "text": "big thanks to Spotify for their Web API as well as to the creator of Spotipy for making my life easier" }, { "code": null, "e": 12166, "s": 12012, "text": "last but not least, this wouldn’t be possible without the Python libraries Pandas, Numpy, Matplotlib and the amazing people building and maintaining them" }, { "code": null, "e": 12326, "s": 12166, "text": "and if you feel like listening to music instead of just reading about it, I have created a Spotify playlist based on the most popular tracks from this analysis" } ]
Get fields from multiple sub-documents that match a condition in MongoDB?
To get fields from multiple sub-documents, use MongoDB aggregate with $unwind. Let us create a collection with documents − > db.demo671.insertOne( ... { ... ... "details" : [ ... { ... "id" : "1" ... }, ... { ... CountryName:"US", ... "details1" : [ ... { ... "id" : "1" ... }, ... { ... "id" : "2" ... } ... ] ... }, ... { ... CountryName:"UK", ... "details1" : [ ... { ... "id" : "2" ... }, ... { ... "id" : "1" ... } ... ] ... }, ... { ... CountryName:"AUS", ... "details1" : [ ... { ... "id" : "1" ... } ... ] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5ea3e5d004263e90dac943e0") } Display all documents from a collection with the help of find() method − > db.demo671.find(); This will produce the following output − { "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] } Here is the query to get fields from multiple sub-documents that match a condition in MongoDB − > db.demo671.aggregate([ ... ... {$unwind: '$details'}, ... ... {$match: {'details.details1.id': '1'}}, ... ... {$project: {_id: 0, Country: '$details.CountryName'}} ... ]).pretty() This will produce the following output − { "Country" : "US" } { "Country" : "UK" } { "Country" : "AUS" }
[ { "code": null, "e": 1185, "s": 1062, "text": "To get fields from multiple sub-documents, use MongoDB aggregate with $unwind. Let us create a collection with documents −" }, { "code": null, "e": 1832, "s": 1185, "text": "> db.demo671.insertOne(\n... {\n...\n... \"details\" : [\n... {\n... \"id\" : \"1\"\n... },\n... {\n... CountryName:\"US\",\n... \"details1\" : [\n... {\n... \"id\" : \"1\"\n... },\n... {\n... \"id\" : \"2\"\n... }\n... ]\n... },\n... {\n... CountryName:\"UK\",\n... \"details1\" : [\n... {\n... \"id\" : \"2\"\n... },\n... {\n... \"id\" : \"1\"\n... }\n... ]\n... },\n... {\n... CountryName:\"AUS\",\n... \"details1\" : [\n... {\n... \"id\" : \"1\"\n... }\n... ]\n... }\n... ]\n... }\n... )\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea3e5d004263e90dac943e0\")\n}" }, { "code": null, "e": 1905, "s": 1832, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1926, "s": 1905, "text": "> db.demo671.find();" }, { "code": null, "e": 1967, "s": 1926, "text": "This will produce the following output −" }, { "code": null, "e": 2258, "s": 1967, "text": "{ \"_id\" : ObjectId(\"5ea3e5d004263e90dac943e0\"), \"details\" : [ { \"id\" : \"1\" }, { \"CountryName\" : \"US\", \"details1\" : [ { \"id\" : \"1\" }, { \"id\" : \"2\" } ] }, { \"CountryName\" : \"UK\", \"details1\" : [ { \"id\" : \"2\" }, { \"id\" : \"1\" } ] }, { \"CountryName\" : \"AUS\", \"details1\" : [ { \"id\" : \"1\" } ] } ] }" }, { "code": null, "e": 2354, "s": 2258, "text": "Here is the query to get fields from multiple sub-documents that match a condition in MongoDB −" }, { "code": null, "e": 2542, "s": 2354, "text": "> db.demo671.aggregate([\n...\n... {$unwind: '$details'},\n...\n... {$match: {'details.details1.id': '1'}},\n...\n... {$project: {_id: 0, Country: '$details.CountryName'}}\n... ]).pretty()" }, { "code": null, "e": 2583, "s": 2542, "text": "This will produce the following output −" }, { "code": null, "e": 2647, "s": 2583, "text": "{ \"Country\" : \"US\" }\n{ \"Country\" : \"UK\" }\n{ \"Country\" : \"AUS\" }" } ]
Explicit type casting operator in C++
A type cast provides a method for explicit conversion of the type of an object in a specific situation. It can be used as a unary expression − ( type-name ) cast-expression The compiler treats cast-expression as type type-name after a typecast has been made. Casts are used to convert objects of any scalar kind to or from the other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions. Additional restraints on casts could result from the actual sizes or representation of specific types #include using namespace std; int main() { float x = 3.1; int i; i = (int)x; cout << x << ", " << i << endl; return 0; } This will give the output − 3.1, 3
[ { "code": null, "e": 1205, "s": 1062, "text": "A type cast provides a method for explicit conversion of the type of an object in a specific situation. It can be used as a unary expression −" }, { "code": null, "e": 1235, "s": 1205, "text": "( type-name ) cast-expression" }, { "code": null, "e": 1617, "s": 1235, "text": "The compiler treats cast-expression as type type-name after a typecast has been made. Casts are used to convert objects of any scalar kind to or from the other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions. Additional restraints on casts could result from the actual sizes or representation of specific types " }, { "code": null, "e": 1754, "s": 1617, "text": "#include\nusing namespace std;\nint main() {\n float x = 3.1;\n int i;\n i = (int)x;\n\n cout << x << \", \" << i << endl;\n return 0;\n}" }, { "code": null, "e": 1782, "s": 1754, "text": "This will give the output −" }, { "code": null, "e": 1789, "s": 1782, "text": "3.1, 3" } ]
Given a binary string, count number of substrings that start and end with 1. - GeeksforGeeks
28 Apr, 2021 Given a binary string, count number of substrings that start and end with 1. For example, if the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.Source: Amazon Interview Experience | Set 162Difficulty Level: Rookie A Simple Solution is to run two loops. Outer loops picks every 1 as starting point and inner loop searches for ending 1 and increments count whenever it finds 1. C++ Java Python3 C# PHP Javascript // A simple C++ program to count number of// substrings starting and ending with 1#include<iostream> using namespace std; int countSubStr(char str[]){int res = 0; // Initialize result // Pick a starting pointfor (int i=0; str[i] !='\0'; i++){ if (str[i] == '1') { // Search for all possible ending point for (int j=i+1; str[j] !='\0'; j++) if (str[j] == '1') res++; }}return res;} // Driver program to test above functionint main(){char str[] = "00100101";cout << countSubStr(str);return 0;} // A simple C++ program to count number of//substrings starting and ending with 1 class CountSubString{ int countSubStr(char str[],int n) { int res = 0; // Initialize result // Pick a starting point for (int i = 0; i<n; i++) { if (str[i] == '1') { // Search for all possible ending point for (int j = i + 1; j< n; j++) { if (str[j] == '1') res++; } } } return res; } // Driver program to test the above function public static void main(String[] args) { CountSubString count = new CountSubString(); String string = "00100101"; char str[] = string.toCharArray(); int n = str.length; System.out.println(count.countSubStr(str,n)); }} # A simple Python 3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) : # Initialize result res = 0 # Pick a starting point for i in range(0, n) : if (st[i] == '1') : # Search for all possible ending point for j in range(i+1, n) : if (st[j] == '1') : res = res + 1 return res # Driver program to test above functionst = "00100101";list(st)n= len(st)print(countSubStr(st, n), end="") # This code is contributed# by Nikita Tiwari. // A simple C# program to count number of// substrings starting and ending with 1using System; class GFG{public virtual int countSubStr(char[] str, int n){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i < n; i++) { if (str[i] == '1') { // Search for all possible // ending point for (int j = i + 1; j < n; j++) { if (str[j] == '1') { res++; } } } } return res;} // Driver Codepublic static void Main(string[] args){ GFG count = new GFG(); string s = "00100101"; char[] str = s.ToCharArray(); int n = str.Length; Console.WriteLine(count.countSubStr(str,n));}} // This code is contributed by Shrikant13 <?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){ $res = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($str); $i++) { if ($str[$i] == '1') { // Search for all possible // ending point for ($j = $i + 1; $j < strlen($str); $j++) if ($str[$j] == '1') $res++; } } return $res;} // Driver Code$str = "00100101";echo countSubStr($str); // This code is contributed by ita_c?> <script> // A simple javascript program to count number of// substrings starting and ending with 1 function countSubStr(str,n) { let res = 0; // Initialize result // Pick a starting point for (let i = 0; i<n; i++) { if (str[i] == '1') { // Search for all possible ending point for (let j = i + 1; j< n; j++) { if (str[j] == '1') res++; } } } return res; } // Driver program to test the above function let string = "00100101"; let n=string.length; document.write(countSubStr(string,n)); // This code is contributed by rag2127 </script> Output: 3 Time Complexity of the above solution is O(n2). We can find count in O(n) using a single traversal of input string. Following are steps. a) Count the number of 1’s. Let the count of 1’s be m. b) Return m(m-1)/2 The idea is to count total number of possible pairs of 1’s. C++ Java Python3 C# PHP Javascript // A O(n) C++ program to count number of// substrings starting and ending with 1#include<iostream> using namespace std; int countSubStr(char str[]){ int m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (int i=0; str[i] !='\0'; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m*(m-1)/2;} // Driver program to test above functionint main(){ char str[] = "00100101"; cout << countSubStr(str); return 0;} // A O(n) C++ program to count number of substrings//starting and ending with 1 class CountSubString{ int countSubStr(char str[], int n) { int m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (int i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m * (m - 1) / 2; } // Driver program to test the above function public static void main(String[] args) { CountSubString count = new CountSubString(); String string = "00100101"; char str[] = string.toCharArray(); int n = str.length; System.out.println(count.countSubStr(str, n)); }} # A Python3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) : # Count of 1's in input string m = 0 # Traverse input string and # count of 1's in it for i in range(0, n) : if (st[i] == '1') : m = m + 1 # Return count of possible # pairs among m 1's return m * (m - 1) // 2 # Driver program to test above functionst = "00100101";list(st)n= len(st)print(countSubStr(st, n), end="") # This code is contributed# by Nikita Tiwari. // A O(n) C# program to count// number of substrings starting// and ending with 1using System; class GFG{int countSubStr(char []str, int n){ int m = 0; // Count of 1's in // input string // Traverse input string and // count of 1's in it for (int i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible // pairs among m 1's return m * (m - 1) / 2;} // Driver Codepublic static void Main(String[] args){ GFG count = new GFG(); String strings = "00100101"; char []str = strings.ToCharArray(); int n = str.Length; Console.Write(count.countSubStr(str, n));}} // This code is contributed by princiraj <?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){ $m = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($str); $i++) { if ($str[$i] == '1') { $m++; } } // Return count of possible // pairs among m 1's return $m * ($m - 1) / 2;} // Driver Code$str = "00100101";echo countSubStr($str); // This code is contributed// by Akanksha Rai?> <script>// A O(n) javascript program to count number of substrings//starting and ending with 1 function countSubStr(str,n) { let m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (let i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m * Math.floor((m - 1) / 2); } // Driver program to test the above function let str = "00100101"; let n = str.length; document.write(countSubStr(str, n)); // This code is contributed by avanitrachhadiya2155</script> Output: 3 YouTubeGeeksforGeeks500K subscribersCount number of substrings that start and end with 1 in a Binary String | GeeksforGeeksWatch 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:000:00 / 1:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h8UZKBq1ZR8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 princiraj1992 ukasp Akanksha_Rai rag2127 avanitrachhadiya2155 madarsh986 ashissingh640 Amazon binary-string Arrays Strings Amazon Arrays Strings 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 Linear Search Maximum and minimum of an array using minimum number of comparisons Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string Python program to check if a string is palindrome or not
[ { "code": null, "e": 25222, "s": 25194, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25477, "s": 25222, "text": "Given a binary string, count number of substrings that start and end with 1. For example, if the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.Source: Amazon Interview Experience | Set 162Difficulty Level: Rookie " }, { "code": null, "e": 25640, "s": 25477, "text": "A Simple Solution is to run two loops. Outer loops picks every 1 as starting point and inner loop searches for ending 1 and increments count whenever it finds 1. " }, { "code": null, "e": 25644, "s": 25640, "text": "C++" }, { "code": null, "e": 25649, "s": 25644, "text": "Java" }, { "code": null, "e": 25657, "s": 25649, "text": "Python3" }, { "code": null, "e": 25660, "s": 25657, "text": "C#" }, { "code": null, "e": 25664, "s": 25660, "text": "PHP" }, { "code": null, "e": 25675, "s": 25664, "text": "Javascript" }, { "code": "// A simple C++ program to count number of// substrings starting and ending with 1#include<iostream> using namespace std; int countSubStr(char str[]){int res = 0; // Initialize result // Pick a starting pointfor (int i=0; str[i] !='\\0'; i++){ if (str[i] == '1') { // Search for all possible ending point for (int j=i+1; str[j] !='\\0'; j++) if (str[j] == '1') res++; }}return res;} // Driver program to test above functionint main(){char str[] = \"00100101\";cout << countSubStr(str);return 0;}", "e": 26237, "s": 25675, "text": null }, { "code": "// A simple C++ program to count number of//substrings starting and ending with 1 class CountSubString{ int countSubStr(char str[],int n) { int res = 0; // Initialize result // Pick a starting point for (int i = 0; i<n; i++) { if (str[i] == '1') { // Search for all possible ending point for (int j = i + 1; j< n; j++) { if (str[j] == '1') res++; } } } return res; } // Driver program to test the above function public static void main(String[] args) { CountSubString count = new CountSubString(); String string = \"00100101\"; char str[] = string.toCharArray(); int n = str.length; System.out.println(count.countSubStr(str,n)); }}", "e": 27103, "s": 26237, "text": null }, { "code": "# A simple Python 3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) : # Initialize result res = 0 # Pick a starting point for i in range(0, n) : if (st[i] == '1') : # Search for all possible ending point for j in range(i+1, n) : if (st[j] == '1') : res = res + 1 return res # Driver program to test above functionst = \"00100101\";list(st)n= len(st)print(countSubStr(st, n), end=\"\") # This code is contributed# by Nikita Tiwari.", "e": 27674, "s": 27103, "text": null }, { "code": "// A simple C# program to count number of// substrings starting and ending with 1using System; class GFG{public virtual int countSubStr(char[] str, int n){ int res = 0; // Initialize result // Pick a starting point for (int i = 0; i < n; i++) { if (str[i] == '1') { // Search for all possible // ending point for (int j = i + 1; j < n; j++) { if (str[j] == '1') { res++; } } } } return res;} // Driver Codepublic static void Main(string[] args){ GFG count = new GFG(); string s = \"00100101\"; char[] str = s.ToCharArray(); int n = str.Length; Console.WriteLine(count.countSubStr(str,n));}} // This code is contributed by Shrikant13", "e": 28509, "s": 27674, "text": null }, { "code": "<?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){ $res = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($str); $i++) { if ($str[$i] == '1') { // Search for all possible // ending point for ($j = $i + 1; $j < strlen($str); $j++) if ($str[$j] == '1') $res++; } } return $res;} // Driver Code$str = \"00100101\";echo countSubStr($str); // This code is contributed by ita_c?>", "e": 29123, "s": 28509, "text": null }, { "code": "<script> // A simple javascript program to count number of// substrings starting and ending with 1 function countSubStr(str,n) { let res = 0; // Initialize result // Pick a starting point for (let i = 0; i<n; i++) { if (str[i] == '1') { // Search for all possible ending point for (let j = i + 1; j< n; j++) { if (str[j] == '1') res++; } } } return res; } // Driver program to test the above function let string = \"00100101\"; let n=string.length; document.write(countSubStr(string,n)); // This code is contributed by rag2127 </script>", "e": 29884, "s": 29123, "text": null }, { "code": null, "e": 29893, "s": 29884, "text": "Output: " }, { "code": null, "e": 29895, "s": 29893, "text": "3" }, { "code": null, "e": 30167, "s": 29895, "text": "Time Complexity of the above solution is O(n2). We can find count in O(n) using a single traversal of input string. Following are steps. a) Count the number of 1’s. Let the count of 1’s be m. b) Return m(m-1)/2 The idea is to count total number of possible pairs of 1’s. " }, { "code": null, "e": 30171, "s": 30167, "text": "C++" }, { "code": null, "e": 30176, "s": 30171, "text": "Java" }, { "code": null, "e": 30184, "s": 30176, "text": "Python3" }, { "code": null, "e": 30187, "s": 30184, "text": "C#" }, { "code": null, "e": 30191, "s": 30187, "text": "PHP" }, { "code": null, "e": 30202, "s": 30191, "text": "Javascript" }, { "code": "// A O(n) C++ program to count number of// substrings starting and ending with 1#include<iostream> using namespace std; int countSubStr(char str[]){ int m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (int i=0; str[i] !='\\0'; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m*(m-1)/2;} // Driver program to test above functionint main(){ char str[] = \"00100101\"; cout << countSubStr(str); return 0;}", "e": 30719, "s": 30202, "text": null }, { "code": "// A O(n) C++ program to count number of substrings//starting and ending with 1 class CountSubString{ int countSubStr(char str[], int n) { int m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (int i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m * (m - 1) / 2; } // Driver program to test the above function public static void main(String[] args) { CountSubString count = new CountSubString(); String string = \"00100101\"; char str[] = string.toCharArray(); int n = str.length; System.out.println(count.countSubStr(str, n)); }}", "e": 31475, "s": 30719, "text": null }, { "code": "# A Python3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) : # Count of 1's in input string m = 0 # Traverse input string and # count of 1's in it for i in range(0, n) : if (st[i] == '1') : m = m + 1 # Return count of possible # pairs among m 1's return m * (m - 1) // 2 # Driver program to test above functionst = \"00100101\";list(st)n= len(st)print(countSubStr(st, n), end=\"\") # This code is contributed# by Nikita Tiwari.", "e": 32002, "s": 31475, "text": null }, { "code": "// A O(n) C# program to count// number of substrings starting// and ending with 1using System; class GFG{int countSubStr(char []str, int n){ int m = 0; // Count of 1's in // input string // Traverse input string and // count of 1's in it for (int i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible // pairs among m 1's return m * (m - 1) / 2;} // Driver Codepublic static void Main(String[] args){ GFG count = new GFG(); String strings = \"00100101\"; char []str = strings.ToCharArray(); int n = str.Length; Console.Write(count.countSubStr(str, n));}} // This code is contributed by princiraj", "e": 32693, "s": 32002, "text": null }, { "code": "<?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){ $m = 0; // Initialize result // Pick a starting point for ($i = 0; $i < strlen($str); $i++) { if ($str[$i] == '1') { $m++; } } // Return count of possible // pairs among m 1's return $m * ($m - 1) / 2;} // Driver Code$str = \"00100101\";echo countSubStr($str); // This code is contributed// by Akanksha Rai?>", "e": 33178, "s": 32693, "text": null }, { "code": "<script>// A O(n) javascript program to count number of substrings//starting and ending with 1 function countSubStr(str,n) { let m = 0; // Count of 1's in input string // Traverse input string and count of 1's in it for (let i = 0; i < n; i++) { if (str[i] == '1') m++; } // Return count of possible pairs among m 1's return m * Math.floor((m - 1) / 2); } // Driver program to test the above function let str = \"00100101\"; let n = str.length; document.write(countSubStr(str, n)); // This code is contributed by avanitrachhadiya2155</script>", "e": 33834, "s": 33178, "text": null }, { "code": null, "e": 33844, "s": 33834, "text": "Output: " }, { "code": null, "e": 33846, "s": 33844, "text": "3" }, { "code": null, "e": 34718, "s": 33848, "text": "YouTubeGeeksforGeeks500K subscribersCount number of substrings that start and end with 1 in a Binary String | GeeksforGeeksWatch 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:000:00 / 1:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=h8UZKBq1ZR8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 34882, "s": 34718, "text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34894, "s": 34882, "text": "shrikanth13" }, { "code": null, "e": 34908, "s": 34894, "text": "princiraj1992" }, { "code": null, "e": 34914, "s": 34908, "text": "ukasp" }, { "code": null, "e": 34927, "s": 34914, "text": "Akanksha_Rai" }, { "code": null, "e": 34935, "s": 34927, "text": "rag2127" }, { "code": null, "e": 34956, "s": 34935, "text": "avanitrachhadiya2155" }, { "code": null, "e": 34967, "s": 34956, "text": "madarsh986" }, { "code": null, "e": 34981, "s": 34967, "text": "ashissingh640" }, { "code": null, "e": 34988, "s": 34981, "text": "Amazon" }, { "code": null, "e": 35002, "s": 34988, "text": "binary-string" }, { "code": null, "e": 35009, "s": 35002, "text": "Arrays" }, { "code": null, "e": 35017, "s": 35009, "text": "Strings" }, { "code": null, "e": 35024, "s": 35017, "text": "Amazon" }, { "code": null, "e": 35031, "s": 35024, "text": "Arrays" }, { "code": null, "e": 35039, "s": 35031, "text": "Strings" }, { "code": null, "e": 35137, "s": 35039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35146, "s": 35137, "text": "Comments" }, { "code": null, "e": 35159, "s": 35146, "text": "Old Comments" }, { "code": null, "e": 35207, "s": 35159, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 35251, "s": 35207, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 35274, "s": 35251, "text": "Introduction to Arrays" }, { "code": null, "e": 35288, "s": 35274, "text": "Linear Search" }, { "code": null, "e": 35356, "s": 35288, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35381, "s": 35356, "text": "Reverse a string in Java" }, { "code": null, "e": 35415, "s": 35381, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35430, "s": 35415, "text": "C++ Data Types" }, { "code": null, "e": 35490, "s": 35430, "text": "Write a program to print all permutations of a given string" } ]
What are C++ Manipulators (endl, setw, setprecision, setf)?
Stream Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example − std::cout << std::setw(10); They are still regular functions and can also be called as any other function using a stream object as an argument, for example − boolalpha (cout); Manipulators are used to changing formatting parameters on streams and to insert or extract certain special characters. Following are some of the most widely used C++ manipulators − This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream. Live Demo #include<iostream> int main() { std::cout << "Hello" << std::endl << "World!"; } Hello World! This manipulator controls whether decimal point is always included in the floating-point representation. Live Demo #include <iostream> int main() { std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n' << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n'; } 1.0 with showpoint: 1.00000 1.0 with noshowpoint: 1 This manipulator changes floating-point precision. When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or into exactly n. Live Demo #include <iostream> #include <iomanip> int main() { const long double pi = 3.141592653589793239; std::cout << "default precision (6): " << pi << '\n' << "std::setprecision(10): " << std::setprecision(10) << pi << '\n'; } default precision (6): 3.14159 std::setprecision(10): 3.141592654 This manipulator changes the width of the next input/output field. When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. Live Demo #include <iostream> #include <iomanip> int main() { std::cout << "no setw:" << 42 << '\n' << "setw(6):" << std::setw(6) << 42 << '\n' << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n'; } no setw:42 setw(6): 42 setw(6), several elements: 89 1234
[ { "code": null, "e": 1231, "s": 1062, "text": "Stream Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example −" }, { "code": null, "e": 1259, "s": 1231, "text": "std::cout << std::setw(10);" }, { "code": null, "e": 1389, "s": 1259, "text": "They are still regular functions and can also be called as any other function using a stream object as an argument, for example −" }, { "code": null, "e": 1407, "s": 1389, "text": "boolalpha (cout);" }, { "code": null, "e": 1527, "s": 1407, "text": "Manipulators are used to changing formatting parameters on streams and to insert or extract certain special characters." }, { "code": null, "e": 1589, "s": 1527, "text": "Following are some of the most widely used C++ manipulators −" }, { "code": null, "e": 1702, "s": 1589, "text": "This manipulator has the same functionality as ‘\\n’(newline character). But this also flushes the output stream." }, { "code": null, "e": 1712, "s": 1702, "text": "Live Demo" }, { "code": null, "e": 1796, "s": 1712, "text": "#include<iostream>\nint main() {\n std::cout << \"Hello\" << std::endl << \"World!\";\n}" }, { "code": null, "e": 1809, "s": 1796, "text": "Hello\nWorld!" }, { "code": null, "e": 1915, "s": 1809, "text": "This manipulator controls whether decimal point is always included in the floating-point representation. " }, { "code": null, "e": 1927, "s": 1915, "text": " Live Demo " }, { "code": null, "e": 2111, "s": 1927, "text": "#include <iostream>\nint main() {\n std::cout << \"1.0 with showpoint: \" << std::showpoint << 1.0 << '\\n'\n << \"1.0 with noshowpoint: \" << std::noshowpoint << 1.0 << '\\n';\n}" }, { "code": null, "e": 2163, "s": 2111, "text": "1.0 with showpoint: 1.00000\n1.0 with noshowpoint: 1" }, { "code": null, "e": 2357, "s": 2163, "text": "This manipulator changes floating-point precision. When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or into exactly n. " }, { "code": null, "e": 2369, "s": 2357, "text": " Live Demo " }, { "code": null, "e": 2609, "s": 2369, "text": "#include <iostream>\n#include <iomanip>\nint main() {\n const long double pi = 3.141592653589793239;\n std::cout << \"default precision (6): \" << pi << '\\n'\n << \"std::setprecision(10): \" << std::setprecision(10) << pi << '\\n';\n}" }, { "code": null, "e": 2675, "s": 2609, "text": "default precision (6): 3.14159\nstd::setprecision(10): 3.141592654" }, { "code": null, "e": 2866, "s": 2675, "text": "This manipulator changes the width of the next input/output field. When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. " }, { "code": null, "e": 2876, "s": 2866, "text": "Live Demo" }, { "code": null, "e": 3117, "s": 2876, "text": "#include <iostream>\n#include <iomanip>\nint main() {\n std::cout << \"no setw:\" << 42 << '\\n'\n << \"setw(6):\" << std::setw(6) << 42 << '\\n'\n << \"setw(6), several elements: \" << 89 << std::setw(6) << 12 << 34 << '\\n';\n}" }, { "code": null, "e": 3181, "s": 3117, "text": "no setw:42\nsetw(6): 42\nsetw(6), several elements: 89 1234" } ]
How to return the response from an asynchronous call in Javascript?
There are multiple ways to return the response from an asynchronous call in javascript. Let us understand the problem first. Say you have a function called foo that is asynchronous and will give the data after some time. It can do this in 2 ways. It can either accept a callback that it'll call when it is ready to execute with the data. Or it can return a promise. For example, the setTimeout function accepts a callback and executes it after a fixed amount of time. so lets say that you go with the first approach, then you can pass the function in the setTimeout. function myFunc(cb) { setTimeout(() => cb(100), 1000); } myFunc((a) => console.log(a)) 100 This will call the setTimeout function with a callback which will execute after 1000 ms. when that function is executed, it'll call the passed callback(cb) with the value returned from the setTimeout's callback. Using Promises You can also do this using promises. Wrap your async function with a promise and resolve this promise with the function's return value. You can the chain the then method and pass it a callback to use the value returned from the async function. , new Promise(resolve => setTimeout(() => resolve(100), 1000)) .then(console.log) 100
[ { "code": null, "e": 1428, "s": 1062, "text": "There are multiple ways to return the response from an asynchronous call in javascript. Let us understand the problem first. Say you have a function called foo that is asynchronous and will give the data after some time. It can do this in 2 ways. It can either accept a callback that it'll call when it is ready to execute with the data. Or it can return a promise." }, { "code": null, "e": 1629, "s": 1428, "text": "For example, the setTimeout function accepts a callback and executes it after a fixed amount of time. so lets say that you go with the first approach, then you can pass the function in the setTimeout." }, { "code": null, "e": 1719, "s": 1629, "text": "function myFunc(cb) {\n setTimeout(() => cb(100), 1000);\n}\nmyFunc((a) => console.log(a))" }, { "code": null, "e": 1723, "s": 1719, "text": "100" }, { "code": null, "e": 1935, "s": 1723, "text": "This will call the setTimeout function with a callback which will execute after 1000 ms. when that function is executed, it'll call the passed callback(cb) with the value returned from the setTimeout's callback." }, { "code": null, "e": 1950, "s": 1935, "text": "Using Promises" }, { "code": null, "e": 2194, "s": 1950, "text": "You can also do this using promises. Wrap your async function with a promise and resolve this promise with the function's return value. You can the chain the then method and pass it a callback to use the value returned from the async function." }, { "code": null, "e": 2196, "s": 2194, "text": "," }, { "code": null, "e": 2279, "s": 2196, "text": "new Promise(resolve => setTimeout(() => resolve(100), 1000))\n .then(console.log)" }, { "code": null, "e": 2283, "s": 2279, "text": "100" } ]
Sieve of Eratosthenes in java
Sieve of Eratosthenes is the ancient algorithm to find prime numbers up to a given number. 1. Generate integers from 2 to n (Given number). 2. Counting from 2 mark every 2nd integer. (multiples of 2) 3. Now, starting from 3 mark every third integer. (multiples of 3) 4. Finally, marking from 5 mark every 5th integer.(multiples of 5) import java.util.Scanner; public class SievePrimeFactors { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a number"); int num = sc.nextInt(); boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } System.out.println("List of prime numbers upto given number are : "); for (int i = 2; i< bool.length; i++) { if(bool[i]==true) { System.out.println(i); } } } } Enter a number 50 List of prime numbers up to given number are : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
[ { "code": null, "e": 1153, "s": 1062, "text": "Sieve of Eratosthenes is the ancient algorithm to find prime numbers up to a given number." }, { "code": null, "e": 1202, "s": 1153, "text": "1. Generate integers from 2 to n (Given number)." }, { "code": null, "e": 1262, "s": 1202, "text": "2. Counting from 2 mark every 2nd integer. (multiples of 2)" }, { "code": null, "e": 1329, "s": 1262, "text": "3. Now, starting from 3 mark every third integer. (multiples of 3)" }, { "code": null, "e": 1396, "s": 1329, "text": "4. Finally, marking from 5 mark every 5th integer.(multiples of 5)" }, { "code": null, "e": 2147, "s": 1396, "text": "import java.util.Scanner;\n\npublic class SievePrimeFactors {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a number\");\n int num = sc.nextInt();\n boolean[] bool = new boolean[num];\n \n for (int i = 0; i< bool.length; i++) {\n bool[i] = true;\n }\n for (int i = 2; i< Math.sqrt(num); i++) {\n if(bool[i] == true) {\n for(int j = (i*i); j<num; j = j+i) {\n bool[j] = false;\n }\n }\n }\n System.out.println(\"List of prime numbers upto given number are : \");\n for (int i = 2; i< bool.length; i++) {\n if(bool[i]==true) {\n System.out.println(i);\n }\n }\n }\n}" }, { "code": null, "e": 2253, "s": 2147, "text": "Enter a number\n50\nList of prime numbers up to given number are :\n2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47" } ]
numpy.char.encode()
This function calls str.encode function for each element in the array. Default encoding is utf_8, codecs available in standard Python library may be used. import numpy as np a = np.char.encode('hello', 'cp500') print a Its output is as follows − ����� 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2398, "s": 2243, "text": "This function calls str.encode function for each element in the array. Default encoding is utf_8, codecs available in standard Python library may be used." }, { "code": null, "e": 2464, "s": 2398, "text": "import numpy as np \na = np.char.encode('hello', 'cp500') \nprint a" }, { "code": null, "e": 2491, "s": 2464, "text": "Its output is as follows −" }, { "code": null, "e": 2498, "s": 2491, "text": "�����\n" }, { "code": null, "e": 2531, "s": 2498, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2548, "s": 2531, "text": " Abhilash Nelson" }, { "code": null, "e": 2581, "s": 2548, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 2616, "s": 2581, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2649, "s": 2616, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 2684, "s": 2649, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2719, "s": 2684, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2731, "s": 2719, "text": " Akbar Khan" }, { "code": null, "e": 2764, "s": 2731, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 2779, "s": 2764, "text": " Pruthviraja L" }, { "code": null, "e": 2812, "s": 2779, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2819, "s": 2812, "text": " Anmol" }, { "code": null, "e": 2826, "s": 2819, "text": " Print" }, { "code": null, "e": 2837, "s": 2826, "text": " Add Notes" } ]
ML Pipeline with Grid Search in Scikit-Learn | by Benjamin Wang | Towards Data Science
Let’s start by outlining some main benefits of using ML pipeline, already. Unified API for both data transformations and modelling No extra preprocessing steps needed during model serving time Joint grid search possible including data preprocessing steps/parameters and model selection/parameters Compatible with big data framework such as Spark The last point might not be immediately obvious for some. Imagine if one day your model needs to train on large amount of data. You might have no better choice but to use some distributed framework like Spark. Using ML pipeline will make migrating to Spark a breeze to work with. One reason is that Spark MLlib has a similar ML pipeline feature. Another more fundamental reason is functional programming. ML pipeline draws many similarities with functional programming (which Spark also follows), in that it treats transformations and estimators(models) as operators on data. Data maintains immutability (a core idea of FP), as they just pass through different components of the pipeline, get transformed into new format during the process. At the end of the pipeline, we get some prediction results out. In the example pipeline, we have a preprocessor step, which is of type ColumnTransformer, containing two sub-pipelines: num_transform is a sub-pipeline intended for numeric columns, which fills null values and convert the column to a standard distribution cat_transform is a another sub-pipeline intended for categorical columns, which does one-hot encoding Following the preprocessor transformer, we have an estimator , a default logistic regressor in this case. With this pipeline, one can combine data preprocessing together with modelling, and even include more complex feature engineering by creating custom transformers. To create your own transformer, you need to create a class which inherits from both sklearn.base.BaseEstimator and sklearn.base.TransformerMixin and implement fit and transform methods. Let’s go through a running example (the complete code is available on Github) with the Titanic dataset containing features of passengers and labels indicating if one has survived. We want to build a classifier to predict if a given passenger will survive. from sklearn.datasets import fetch_openmlimport numpy as npnp.random.seed(0)# Load data from https://www.openml.org/d/40945X, y = fetch_openml("titanic", version=1, as_frame=True, return_X_y=True) We will consider the following 4 features, of which age and fare are numeric and sex and pclass are categorical (note: one can also treat pclass as numeric, but that’s not relevant for discussion here). Now, let’s build the pipeline to do some data preprocessing as indicated previously. numeric_features = ["age", "fare"]numeric_transformer = Pipeline(steps=[ ("imputer", SimpleImputer(strategy="mean")), ("scaler", StandardScaler())])categorical_features = ["sex", "pclass"]categorical_transformer = OneHotEncoder(handle_unknown="ignore")preprocessor = ColumnTransformer(transformers=[ ("num_transform", numeric_transformer, numeric_features), ("cat_transform", categorical_transformer, categorical_features)])pipeline = Pipeline(steps=[("preprocesser", preprocessor), ("classifier", LogisticRegression())])pipeline Alternatively, there is a slightly more compact API make_pipeline and make_column_transformer where we don’t need to pass names of each step explicitly. However, the following section will be based on the previous verbose version, because we like to name things as we like :). from sklearn.compose import make_column_transformerfrom sklearn.pipeline import make_pipelinenumeric_transformer = make_pipeline( SimpleImputer(strategy='mean'), StandardScaler())categorical_transformer = make_pipeline(OneHotEncoder(handle_unknown='ignore'))preprocessor = make_column_transformer( (numeric_transformer, numeric_features), (categorical_transformer, categorical_features))pipeline = make_pipeline(preprocessor, LogisticRegression())pipeline One handy tip, one can visualize the pipeline in Jupyter notebook by including the code below. It creates a nice diagram as shown before. from sklearn import set_configset_config(display='diagram')pipeline Training a model is no different than a pure estimator. You just call fit. Below we first do a a standard train test data split to test model performance. Then, you just call pipeline.fit() on your training data, that’s it. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)pipeline.fit(X_train, y_train)score = pipeline.score(X_test, y_test)print(score)0.7977099236641222 What really happens under the hood is that the training data pass through the steps defined in the pipeline (including the classifier estimator) as if it is one model. At this point, one might wonder can I also save my pipelined model as I used to do with a standalone model? The answer is a definite yes. And there is a bonus point of putting the data processing and modelling together in one saved model. Now you don’t need to think about what preprocessing steps to take during prediction time, they are already an integral part of the model. This prevents strange prediction results from happening in production. import joblibjoblib.dump(pipeline, 'your_pipeline.pkl')joblib.load('your_pipeline.pkl').score(X_test, y_test)0.7977099236641222 We use joblib to save and load the pipeline, and it produces the same score, which verifies the correctness, and indeed we see no preprocessing is needed, as promised. ML pipeline enables us not only to search parameters for the estimator, but also parameters for all the preprocessing steps. In other words, we can now tune ML models, and preprocessing options all together. For argument sake, say, we are not sure if filling null values by mean ormedian strategy is a better option, and we are also not sure about how much regularization is needed for the LogisticRegressor . Therefore, we want to find out which is the best missing value filling strategy and the best regularization weight at the same time. To achieve that, we can construct the paramter grid as follows: param_grid = [ { "preprocesser__num_transform__imputer__strategy": ["mean", "median"], "classifier__C": [0.1, 1.0, 10.0, 100.0], "classifier": [LogisticRegression()] }] Note: sklearn uses double underscore as separator. classifier key is the same as the pipeline name for estimator in the pipeline definition, classifier__C basically tells the grid searcher that we would like to try these provided values for C which is a parameter for the classifier LogisticRegressor to define regularization weight. As you might notice, you can also concat the double underscore syntax. preprocesser__num_transform__imputer_strategy defines different values to try out for the imputer step’s strategy parameter. Finally, we can start the grid search, since we have 2 values for strategy and 4 values for C , in total there are 2*4=8 candidates to in the search space. grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)grid_search.fit(X_train, y_train) The output is shown below, since we have a 10 fold cross validation for each combination, in total we need to fit 80 models! One can see how easily grid search can explode. Fitting 10 folds for each of 8 candidates, totalling 80 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 4.5s finished What if we want to try out different classifiers? We can construct more complex parameter grid to achieve this. param_grid = [ { "preprocesser__num_transform__imputer__strategy": ["mean", "median"], "classifier__C": [0.1, 1.0, 10.0, 100.0], "classifier": [LogisticRegression()] }, { "preprocesser__num_transform__imputer__strategy": ["mean", "median"], "classifier__n_estimators": [10, 100, 1000], "classifier": [RandomForestClassifier()] }]grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)grid_search.fit(X_train, y_train) In the code above, we use two dictionaries in the parameter grid to add an extra set of search options, which uses a random forest classifier instead of a logistic regressor. One might ask, what is the number of combinations now? Since each dictionary defines a different set, we should add up across dictionaries, multiply within dictionaries. That gives us 2*4*1 + 2*3*1 = 14 candidates. This is verified in the output: Fitting 10 folds for each of 14 candidates, totalling 140 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 76 tasks | elapsed: 1.5s[Parallel(n_jobs=-1)]: Done 140 out of 140 | elapsed: 26.6s finished We have discussed the main benefits of using ML pipeline with a running example. We have also seen how convenient the pipeline concept can be, and powerful at the same time. The latter point becomes evident after we see how easy it is to do a joint grid search. Last but not least, it should not be a surprise to see that Spark MLlib has almost identical features as ML pipeline in scikit-learn , interested readers can checkout: https://spark.apache.org/docs/latest/ml-pipeline.html, or I might write another blog on that. Code available on GitHub: https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynbSome materials to read for making your own transformers: https://sklearn-template.readthedocs.io/en/latest/user_guide.html Code available on GitHub: https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynb Some materials to read for making your own transformers: https://sklearn-template.readthedocs.io/en/latest/user_guide.html
[ { "code": null, "e": 247, "s": 172, "text": "Let’s start by outlining some main benefits of using ML pipeline, already." }, { "code": null, "e": 303, "s": 247, "text": "Unified API for both data transformations and modelling" }, { "code": null, "e": 365, "s": 303, "text": "No extra preprocessing steps needed during model serving time" }, { "code": null, "e": 469, "s": 365, "text": "Joint grid search possible including data preprocessing steps/parameters and model selection/parameters" }, { "code": null, "e": 518, "s": 469, "text": "Compatible with big data framework such as Spark" }, { "code": null, "e": 923, "s": 518, "text": "The last point might not be immediately obvious for some. Imagine if one day your model needs to train on large amount of data. You might have no better choice but to use some distributed framework like Spark. Using ML pipeline will make migrating to Spark a breeze to work with. One reason is that Spark MLlib has a similar ML pipeline feature. Another more fundamental reason is functional programming." }, { "code": null, "e": 1323, "s": 923, "text": "ML pipeline draws many similarities with functional programming (which Spark also follows), in that it treats transformations and estimators(models) as operators on data. Data maintains immutability (a core idea of FP), as they just pass through different components of the pipeline, get transformed into new format during the process. At the end of the pipeline, we get some prediction results out." }, { "code": null, "e": 1443, "s": 1323, "text": "In the example pipeline, we have a preprocessor step, which is of type ColumnTransformer, containing two sub-pipelines:" }, { "code": null, "e": 1579, "s": 1443, "text": "num_transform is a sub-pipeline intended for numeric columns, which fills null values and convert the column to a standard distribution" }, { "code": null, "e": 1681, "s": 1579, "text": "cat_transform is a another sub-pipeline intended for categorical columns, which does one-hot encoding" }, { "code": null, "e": 1787, "s": 1681, "text": "Following the preprocessor transformer, we have an estimator , a default logistic regressor in this case." }, { "code": null, "e": 1950, "s": 1787, "text": "With this pipeline, one can combine data preprocessing together with modelling, and even include more complex feature engineering by creating custom transformers." }, { "code": null, "e": 2136, "s": 1950, "text": "To create your own transformer, you need to create a class which inherits from both sklearn.base.BaseEstimator and sklearn.base.TransformerMixin and implement fit and transform methods." }, { "code": null, "e": 2316, "s": 2136, "text": "Let’s go through a running example (the complete code is available on Github) with the Titanic dataset containing features of passengers and labels indicating if one has survived." }, { "code": null, "e": 2392, "s": 2316, "text": "We want to build a classifier to predict if a given passenger will survive." }, { "code": null, "e": 2589, "s": 2392, "text": "from sklearn.datasets import fetch_openmlimport numpy as npnp.random.seed(0)# Load data from https://www.openml.org/d/40945X, y = fetch_openml(\"titanic\", version=1, as_frame=True, return_X_y=True)" }, { "code": null, "e": 2792, "s": 2589, "text": "We will consider the following 4 features, of which age and fare are numeric and sex and pclass are categorical (note: one can also treat pclass as numeric, but that’s not relevant for discussion here)." }, { "code": null, "e": 2877, "s": 2792, "text": "Now, let’s build the pipeline to do some data preprocessing as indicated previously." }, { "code": null, "e": 3419, "s": 2877, "text": "numeric_features = [\"age\", \"fare\"]numeric_transformer = Pipeline(steps=[ (\"imputer\", SimpleImputer(strategy=\"mean\")), (\"scaler\", StandardScaler())])categorical_features = [\"sex\", \"pclass\"]categorical_transformer = OneHotEncoder(handle_unknown=\"ignore\")preprocessor = ColumnTransformer(transformers=[ (\"num_transform\", numeric_transformer, numeric_features), (\"cat_transform\", categorical_transformer, categorical_features)])pipeline = Pipeline(steps=[(\"preprocesser\", preprocessor), (\"classifier\", LogisticRegression())])pipeline" }, { "code": null, "e": 3696, "s": 3419, "text": "Alternatively, there is a slightly more compact API make_pipeline and make_column_transformer where we don’t need to pass names of each step explicitly. However, the following section will be based on the previous verbose version, because we like to name things as we like :)." }, { "code": null, "e": 4164, "s": 3696, "text": "from sklearn.compose import make_column_transformerfrom sklearn.pipeline import make_pipelinenumeric_transformer = make_pipeline( SimpleImputer(strategy='mean'), StandardScaler())categorical_transformer = make_pipeline(OneHotEncoder(handle_unknown='ignore'))preprocessor = make_column_transformer( (numeric_transformer, numeric_features), (categorical_transformer, categorical_features))pipeline = make_pipeline(preprocessor, LogisticRegression())pipeline" }, { "code": null, "e": 4302, "s": 4164, "text": "One handy tip, one can visualize the pipeline in Jupyter notebook by including the code below. It creates a nice diagram as shown before." }, { "code": null, "e": 4370, "s": 4302, "text": "from sklearn import set_configset_config(display='diagram')pipeline" }, { "code": null, "e": 4594, "s": 4370, "text": "Training a model is no different than a pure estimator. You just call fit. Below we first do a a standard train test data split to test model performance. Then, you just call pipeline.fit() on your training data, that’s it." }, { "code": null, "e": 4781, "s": 4594, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)pipeline.fit(X_train, y_train)score = pipeline.score(X_test, y_test)print(score)0.7977099236641222" }, { "code": null, "e": 4949, "s": 4781, "text": "What really happens under the hood is that the training data pass through the steps defined in the pipeline (including the classifier estimator) as if it is one model." }, { "code": null, "e": 5087, "s": 4949, "text": "At this point, one might wonder can I also save my pipelined model as I used to do with a standalone model? The answer is a definite yes." }, { "code": null, "e": 5398, "s": 5087, "text": "And there is a bonus point of putting the data processing and modelling together in one saved model. Now you don’t need to think about what preprocessing steps to take during prediction time, they are already an integral part of the model. This prevents strange prediction results from happening in production." }, { "code": null, "e": 5526, "s": 5398, "text": "import joblibjoblib.dump(pipeline, 'your_pipeline.pkl')joblib.load('your_pipeline.pkl').score(X_test, y_test)0.7977099236641222" }, { "code": null, "e": 5694, "s": 5526, "text": "We use joblib to save and load the pipeline, and it produces the same score, which verifies the correctness, and indeed we see no preprocessing is needed, as promised." }, { "code": null, "e": 5902, "s": 5694, "text": "ML pipeline enables us not only to search parameters for the estimator, but also parameters for all the preprocessing steps. In other words, we can now tune ML models, and preprocessing options all together." }, { "code": null, "e": 6301, "s": 5902, "text": "For argument sake, say, we are not sure if filling null values by mean ormedian strategy is a better option, and we are also not sure about how much regularization is needed for the LogisticRegressor . Therefore, we want to find out which is the best missing value filling strategy and the best regularization weight at the same time. To achieve that, we can construct the paramter grid as follows:" }, { "code": null, "e": 6497, "s": 6301, "text": "param_grid = [ { \"preprocesser__num_transform__imputer__strategy\": [\"mean\", \"median\"], \"classifier__C\": [0.1, 1.0, 10.0, 100.0], \"classifier\": [LogisticRegression()] }]" }, { "code": null, "e": 6831, "s": 6497, "text": "Note: sklearn uses double underscore as separator. classifier key is the same as the pipeline name for estimator in the pipeline definition, classifier__C basically tells the grid searcher that we would like to try these provided values for C which is a parameter for the classifier LogisticRegressor to define regularization weight." }, { "code": null, "e": 7027, "s": 6831, "text": "As you might notice, you can also concat the double underscore syntax. preprocesser__num_transform__imputer_strategy defines different values to try out for the imputer step’s strategy parameter." }, { "code": null, "e": 7183, "s": 7027, "text": "Finally, we can start the grid search, since we have 2 values for strategy and 4 values for C , in total there are 2*4=8 candidates to in the search space." }, { "code": null, "e": 7290, "s": 7183, "text": "grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)grid_search.fit(X_train, y_train)" }, { "code": null, "e": 7463, "s": 7290, "text": "The output is shown below, since we have a 10 fold cross validation for each combination, in total we need to fit 80 models! One can see how easily grid search can explode." }, { "code": null, "e": 7669, "s": 7463, "text": "Fitting 10 folds for each of 8 candidates, totalling 80 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 80 out of 80 | elapsed: 4.5s finished" }, { "code": null, "e": 7781, "s": 7669, "text": "What if we want to try out different classifiers? We can construct more complex parameter grid to achieve this." }, { "code": null, "e": 8271, "s": 7781, "text": "param_grid = [ { \"preprocesser__num_transform__imputer__strategy\": [\"mean\", \"median\"], \"classifier__C\": [0.1, 1.0, 10.0, 100.0], \"classifier\": [LogisticRegression()] }, { \"preprocesser__num_transform__imputer__strategy\": [\"mean\", \"median\"], \"classifier__n_estimators\": [10, 100, 1000], \"classifier\": [RandomForestClassifier()] }]grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)grid_search.fit(X_train, y_train)" }, { "code": null, "e": 8446, "s": 8271, "text": "In the code above, we use two dictionaries in the parameter grid to add an extra set of search options, which uses a random forest classifier instead of a logistic regressor." }, { "code": null, "e": 8661, "s": 8446, "text": "One might ask, what is the number of combinations now? Since each dictionary defines a different set, we should add up across dictionaries, multiply within dictionaries. That gives us 2*4*1 + 2*3*1 = 14 candidates." }, { "code": null, "e": 8693, "s": 8661, "text": "This is verified in the output:" }, { "code": null, "e": 8962, "s": 8693, "text": "Fitting 10 folds for each of 14 candidates, totalling 140 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 76 tasks | elapsed: 1.5s[Parallel(n_jobs=-1)]: Done 140 out of 140 | elapsed: 26.6s finished" }, { "code": null, "e": 9043, "s": 8962, "text": "We have discussed the main benefits of using ML pipeline with a running example." }, { "code": null, "e": 9224, "s": 9043, "text": "We have also seen how convenient the pipeline concept can be, and powerful at the same time. The latter point becomes evident after we see how easy it is to do a joint grid search." }, { "code": null, "e": 9486, "s": 9224, "text": "Last but not least, it should not be a surprise to see that Spark MLlib has almost identical features as ML pipeline in scikit-learn , interested readers can checkout: https://spark.apache.org/docs/latest/ml-pipeline.html, or I might write another blog on that." }, { "code": null, "e": 9720, "s": 9486, "text": "Code available on GitHub: https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynbSome materials to read for making your own transformers: https://sklearn-template.readthedocs.io/en/latest/user_guide.html" }, { "code": null, "e": 9832, "s": 9720, "text": "Code available on GitHub: https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynb" } ]
Flutter - Chip Widget - GeeksforGeeks
12 Nov, 2021 Chip is a material design widget which comes built-in with flutter. It can simply be described as a compact element holding an icon and text, usually a rounded rectangle in the background. It can serve many purposes, like it can be simply used as a button, representing a user with a CircleAvatar and text, or topic tags in the blog articles, etc. const Chip( {Key key, Widget avatar, @required Widget label, TextStyle labelStyle, EdgeInsetsGeometry labelPadding, Widget deleteIcon, VoidCallback onDeleted, Color deleteIconColor, String deleteButtonTooltipMessage, ShapeBorder shape, Clip clipBehavior: Clip.none, FocusNode focusNode, bool autofocus: false, Color backgroundColor, EdgeInsetsGeometry padding, VisualDensity visualDensity, MaterialTapTargetSize materialTapTargetSize, double elevation, Color shadowColor} ) autofocus: This property takes in a boolean value as the object to decide whether the widget will be selected on the initial focus or not. avatar: This property holds in a widget as the object to be displayed before the Chip label. backgroundColor: This property assigns a background color to the Chip widget by taking in Color class as the object. clipBehavior: This property takes Clip enum as the object to decide whether the content inside the Chip widget will be clipped or not. deleteButtonTooltipMessage: This property takes in a string as the object to be used for the tooltip of the delete button. deleteIcon: This property takes in a widget as the object to be displayed when onDelete function is called. deleteIconColor: This property assigns a color to the delete icon by taking in the Color class as the object. elevation: This widget holds a double value as the object decide the elevated height of the Chip widget. focusNode: The focusNode property takes in FocusNode class as the object assign an additional focus node to the widget. label: The label property takes in a widget as the object to be placed inside the chip widget as the primary element. labelPadding: This property controls the padding around the label by taking in EdgeInsetsGeometry as the object. labelStyle: The labelStyle property takes in TextStyle class as the object to style label text. materialTapTargetSize: This property determines the size of the area which is tapped on click. It takes in MaterialTapTargetSize as the object. onDeleted: The onDelete property holds VoidCalback typedef as the object. It controls the action after the delete icon is tapped. padding: This property controls the empty space in the Chip widget. It takes EdgeInsetsGeometry class as the object. shadowColor: This controls the color of the shadow beneath the Chip widget. It takes Color class as the object. shape: This defines the shape of the Chip widget. It holds ShapeBorder class as the object. visualDensity: This property controls the compactness of the Chip widget by taking in VisualDensity class as the object. Example: Dart import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( /** Chip Widget **/ child: Chip( elevation: 20, padding: EdgeInsets.all(8), backgroundColor: Colors.greenAccent[100], shadowColor: Colors.black, avatar: CircleAvatar( backgroundImage: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg"), //NetwordImage ), //CircleAvatar label: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 20), ), //Text ), //Chip ), //Center ), //Scaffold ), //MaterialApp );} Output: Explanation: In this flutter application the parent widget in the body is Center which is taking Chip widget as it child. Inside the chip widget the elevation property is set to 20 px which is making the Chip widget appear elevated from the background. Then we have the padding property adding 8 px empty space in the Chip. The backgroundColor is greenAccent[400] and the avatar is taking in CircleAvatar which is holding a gfg logo (NetworkImage). And at last the label property is holding text whose font-size is 20 px. Doing all this we get a nice looking Chip widget which can find it use in many places. sagartomar9927 singghakshay android Flutter Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - Flexible Widget ListView Class in Flutter Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Format Dates in Flutter
[ { "code": null, "e": 23645, "s": 23617, "text": "\n12 Nov, 2021" }, { "code": null, "e": 23993, "s": 23645, "text": "Chip is a material design widget which comes built-in with flutter. It can simply be described as a compact element holding an icon and text, usually a rounded rectangle in the background. It can serve many purposes, like it can be simply used as a button, representing a user with a CircleAvatar and text, or topic tags in the blog articles, etc." }, { "code": null, "e": 24467, "s": 23993, "text": "const Chip(\n{Key key,\nWidget avatar,\n@required Widget label,\nTextStyle labelStyle,\nEdgeInsetsGeometry labelPadding,\nWidget deleteIcon,\nVoidCallback onDeleted,\nColor deleteIconColor,\nString deleteButtonTooltipMessage,\nShapeBorder shape,\nClip clipBehavior: Clip.none,\nFocusNode focusNode,\nbool autofocus: false,\nColor backgroundColor,\nEdgeInsetsGeometry padding,\nVisualDensity visualDensity,\nMaterialTapTargetSize materialTapTargetSize,\ndouble elevation,\nColor shadowColor}\n)" }, { "code": null, "e": 24606, "s": 24467, "text": "autofocus: This property takes in a boolean value as the object to decide whether the widget will be selected on the initial focus or not." }, { "code": null, "e": 24699, "s": 24606, "text": "avatar: This property holds in a widget as the object to be displayed before the Chip label." }, { "code": null, "e": 24816, "s": 24699, "text": "backgroundColor: This property assigns a background color to the Chip widget by taking in Color class as the object." }, { "code": null, "e": 24951, "s": 24816, "text": "clipBehavior: This property takes Clip enum as the object to decide whether the content inside the Chip widget will be clipped or not." }, { "code": null, "e": 25074, "s": 24951, "text": "deleteButtonTooltipMessage: This property takes in a string as the object to be used for the tooltip of the delete button." }, { "code": null, "e": 25182, "s": 25074, "text": "deleteIcon: This property takes in a widget as the object to be displayed when onDelete function is called." }, { "code": null, "e": 25292, "s": 25182, "text": "deleteIconColor: This property assigns a color to the delete icon by taking in the Color class as the object." }, { "code": null, "e": 25397, "s": 25292, "text": "elevation: This widget holds a double value as the object decide the elevated height of the Chip widget." }, { "code": null, "e": 25517, "s": 25397, "text": "focusNode: The focusNode property takes in FocusNode class as the object assign an additional focus node to the widget." }, { "code": null, "e": 25635, "s": 25517, "text": "label: The label property takes in a widget as the object to be placed inside the chip widget as the primary element." }, { "code": null, "e": 25748, "s": 25635, "text": "labelPadding: This property controls the padding around the label by taking in EdgeInsetsGeometry as the object." }, { "code": null, "e": 25844, "s": 25748, "text": "labelStyle: The labelStyle property takes in TextStyle class as the object to style label text." }, { "code": null, "e": 25988, "s": 25844, "text": "materialTapTargetSize: This property determines the size of the area which is tapped on click. It takes in MaterialTapTargetSize as the object." }, { "code": null, "e": 26118, "s": 25988, "text": "onDeleted: The onDelete property holds VoidCalback typedef as the object. It controls the action after the delete icon is tapped." }, { "code": null, "e": 26235, "s": 26118, "text": "padding: This property controls the empty space in the Chip widget. It takes EdgeInsetsGeometry class as the object." }, { "code": null, "e": 26347, "s": 26235, "text": "shadowColor: This controls the color of the shadow beneath the Chip widget. It takes Color class as the object." }, { "code": null, "e": 26439, "s": 26347, "text": "shape: This defines the shape of the Chip widget. It holds ShapeBorder class as the object." }, { "code": null, "e": 26560, "s": 26439, "text": "visualDensity: This property controls the compactness of the Chip widget by taking in VisualDensity class as the object." }, { "code": null, "e": 26570, "s": 26560, "text": "Example: " }, { "code": null, "e": 26575, "s": 26570, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; //Material design libraryvoid main() { runApp( //widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Center( /** Chip Widget **/ child: Chip( elevation: 20, padding: EdgeInsets.all(8), backgroundColor: Colors.greenAccent[100], shadowColor: Colors.black, avatar: CircleAvatar( backgroundImage: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\"), //NetwordImage ), //CircleAvatar label: Text( 'GeeksforGeeks', style: TextStyle(fontSize: 20), ), //Text ), //Chip ), //Center ), //Scaffold ), //MaterialApp );}", "e": 27539, "s": 26575, "text": null }, { "code": null, "e": 27547, "s": 27539, "text": "Output:" }, { "code": null, "e": 28156, "s": 27547, "text": "Explanation: In this flutter application the parent widget in the body is Center which is taking Chip widget as it child. Inside the chip widget the elevation property is set to 20 px which is making the Chip widget appear elevated from the background. Then we have the padding property adding 8 px empty space in the Chip. The backgroundColor is greenAccent[400] and the avatar is taking in CircleAvatar which is holding a gfg logo (NetworkImage). And at last the label property is holding text whose font-size is 20 px. Doing all this we get a nice looking Chip widget which can find it use in many places." }, { "code": null, "e": 28171, "s": 28156, "text": "sagartomar9927" }, { "code": null, "e": 28184, "s": 28171, "text": "singghakshay" }, { "code": null, "e": 28192, "s": 28184, "text": "android" }, { "code": null, "e": 28200, "s": 28192, "text": "Flutter" }, { "code": null, "e": 28216, "s": 28200, "text": "Flutter-widgets" }, { "code": null, "e": 28221, "s": 28216, "text": "Dart" }, { "code": null, "e": 28229, "s": 28221, "text": "Flutter" }, { "code": null, "e": 28327, "s": 28229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28336, "s": 28327, "text": "Comments" }, { "code": null, "e": 28349, "s": 28336, "text": "Old Comments" }, { "code": null, "e": 28388, "s": 28349, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28414, "s": 28388, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28440, "s": 28414, "text": "ListView Class in Flutter" }, { "code": null, "e": 28463, "s": 28440, "text": "Flutter - Stack Widget" }, { "code": null, "e": 28508, "s": 28463, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 28547, "s": 28508, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28564, "s": 28547, "text": "Flutter Tutorial" }, { "code": null, "e": 28590, "s": 28564, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28613, "s": 28590, "text": "Flutter - Stack Widget" } ]
Design a Calculator using JavaScript with Neumorphism Effect/Soft UI
01 Oct, 2021 In this article, we will learn how to create a working calculator with the Neumorphism effect using HTML, CSS, and JavaScript. Basic mathematical operations such as addition, subtraction, multiplication, and division can be performed using this calculator. Approach: Neumorphism is a contemporary approach of decorating web-elements and creating a 3D effect on any web page. HTML and CSS can be used to create this animation effect. Neumorphism can be implemented using the CSS box-shadow feature. It is used to give an element a dark and light shadow on one side. The background appears to be tied to the neutral user interface elements as if they are extruded from or inset into it. Some have termed them “soft UI” because of how soft shadows are used to create the illusion, and the styling is almost three-dimensional. HTML code: In this section we will make the layout of the Neumorphism Calculator. index.html <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Neumorphism Calculator</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="cal-box"> <form name="calculator"> <input type="text" id="display" placeholder="0" readonly> <br> <input class="button" type="button" value="7" onclick="calculator.display.value +='7'"> <input class="button" type="button" value="8" onclick="calculator.display.value +='8'"> <input class="button" type="button" value="9" onclick="calculator.display.value +='9'"> <input class="button mathbutton" type="button" value="+" onclick="calculator.display.value +='+'"> <br> <input class="button" type="button" value="4" onclick="calculator.display.value +='4'"> <input class="button" type="button" value="5" onclick="calculator.display.value +='5'"> <input class="button" type="button" value="6" onclick="calculator.display.value +='6'"> <input class="button mathbutton" type="button" value="-" onclick="calculator.display.value +='-'"> <br> <input class="button" type="button" value="1" onclick="calculator.display.value +='1'"> <input class="button" type="button" value="2" onclick="calculator.display.value +='2'"> <input class="button" type="button" value="3" onclick="calculator.display.value +='3'"> <input class="button mathbutton" type="button" value="x" onclick="calculator.display.value +='*'"> <br> <input class="button clearButton" type="button" value="C" onclick="calculator.display.value =''"> <input class="button" type="button" value="0" onclick="calculator.display.value +='0'"> <input class="button mathbutton" type="button" value="=" onclick="calculator.display.value =eval(calculator.display.value)"> <!-- eval() evaluates arithmetic expressions in display box --> <input class="button mathbutton" type="button" value="/" onclick="calculator.display.value +='/'"> </form> </div> </div></body></html> CSS code: In this section, we will use some CSS properties to design the Neumorphism Calculator. style.css body { background-color: rgb(214, 214, 214);} .container { width: 250px; height: 400px; margin: 80px auto; border-radius: 10px; background-color: rgb(214, 214, 214); /* box-shadow is used to achieve Neumorphism by using a light shadow and a dark shadow*/ box-shadow: 5px 5px 10px #b6a9a9, -5px -5px 10px #ffffff;} .cal-box { width: 200px; margin: 20px auto;} #display { border: none; outline: none; color: black; text-align: right; font-weight: 600; padding: 15px; margin: 30px 0 20px 0; background: transparent; /* Inset shadow gives the appearance that the element is being pressed into it.*/ box-shadow: inset 2px 2px 5px #babecc, inset -5px -5px 10px #ffffff;} .button { margin: 15px 0 0 5px; width: 42px; height: 42px; border: none; outline: none; font-size: 18px; font-weight: bold; cursor: pointer; border-radius: 8px; background-color: rgb(214, 214, 214); /* box-shadow is used to achieve Neumorphism by using a light shadow and a dark shadow */ box-shadow: 5px 5px 10px #b6acac, -5px -5px 10px #faf4f4; display: inline-block;} .button:active { /* When the button is pressed, the inset shadow provides the impression that the element is being pressed into it */ box-shadow: inset 1px 1px 2px #babecc, inset -1px -1px 2px #fff;} .clearButton { color: white; background-color: red;} .mathbutton { color: white; background-color: black;} Output: HTML, CSS, and JavaScript working Calculator using Neumorphism Effect/Soft UI adnanirshad158 sagartomar9927 Blogathon-2021 CSS-Basics CSS-Properties HTML-Questions javascript-math JavaScript-Questions Blogathon CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? 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? CSS to put icon inside an input element in a form
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Oct, 2021" }, { "code": null, "e": 311, "s": 54, "text": "In this article, we will learn how to create a working calculator with the Neumorphism effect using HTML, CSS, and JavaScript. Basic mathematical operations such as addition, subtraction, multiplication, and division can be performed using this calculator." }, { "code": null, "e": 877, "s": 311, "text": "Approach: Neumorphism is a contemporary approach of decorating web-elements and creating a 3D effect on any web page. HTML and CSS can be used to create this animation effect. Neumorphism can be implemented using the CSS box-shadow feature. It is used to give an element a dark and light shadow on one side. The background appears to be tied to the neutral user interface elements as if they are extruded from or inset into it. Some have termed them “soft UI” because of how soft shadows are used to create the illusion, and the styling is almost three-dimensional." }, { "code": null, "e": 959, "s": 877, "text": "HTML code: In this section we will make the layout of the Neumorphism Calculator." }, { "code": null, "e": 970, "s": 959, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Neumorphism Calculator</title> <link rel=\"stylesheet\" href=\"style.css\"> </head> <body> <div class=\"container\"> <div class=\"cal-box\"> <form name=\"calculator\"> <input type=\"text\" id=\"display\" placeholder=\"0\" readonly> <br> <input class=\"button\" type=\"button\" value=\"7\" onclick=\"calculator.display.value +='7'\"> <input class=\"button\" type=\"button\" value=\"8\" onclick=\"calculator.display.value +='8'\"> <input class=\"button\" type=\"button\" value=\"9\" onclick=\"calculator.display.value +='9'\"> <input class=\"button mathbutton\" type=\"button\" value=\"+\" onclick=\"calculator.display.value +='+'\"> <br> <input class=\"button\" type=\"button\" value=\"4\" onclick=\"calculator.display.value +='4'\"> <input class=\"button\" type=\"button\" value=\"5\" onclick=\"calculator.display.value +='5'\"> <input class=\"button\" type=\"button\" value=\"6\" onclick=\"calculator.display.value +='6'\"> <input class=\"button mathbutton\" type=\"button\" value=\"-\" onclick=\"calculator.display.value +='-'\"> <br> <input class=\"button\" type=\"button\" value=\"1\" onclick=\"calculator.display.value +='1'\"> <input class=\"button\" type=\"button\" value=\"2\" onclick=\"calculator.display.value +='2'\"> <input class=\"button\" type=\"button\" value=\"3\" onclick=\"calculator.display.value +='3'\"> <input class=\"button mathbutton\" type=\"button\" value=\"x\" onclick=\"calculator.display.value +='*'\"> <br> <input class=\"button clearButton\" type=\"button\" value=\"C\" onclick=\"calculator.display.value =''\"> <input class=\"button\" type=\"button\" value=\"0\" onclick=\"calculator.display.value +='0'\"> <input class=\"button mathbutton\" type=\"button\" value=\"=\" onclick=\"calculator.display.value =eval(calculator.display.value)\"> <!-- eval() evaluates arithmetic expressions in display box --> <input class=\"button mathbutton\" type=\"button\" value=\"/\" onclick=\"calculator.display.value +='/'\"> </form> </div> </div></body></html>", "e": 3353, "s": 970, "text": null }, { "code": null, "e": 3452, "s": 3355, "text": "CSS code: In this section, we will use some CSS properties to design the Neumorphism Calculator." }, { "code": null, "e": 3462, "s": 3452, "text": "style.css" }, { "code": "body { background-color: rgb(214, 214, 214);} .container { width: 250px; height: 400px; margin: 80px auto; border-radius: 10px; background-color: rgb(214, 214, 214); /* box-shadow is used to achieve Neumorphism by using a light shadow and a dark shadow*/ box-shadow: 5px 5px 10px #b6a9a9, -5px -5px 10px #ffffff;} .cal-box { width: 200px; margin: 20px auto;} #display { border: none; outline: none; color: black; text-align: right; font-weight: 600; padding: 15px; margin: 30px 0 20px 0; background: transparent; /* Inset shadow gives the appearance that the element is being pressed into it.*/ box-shadow: inset 2px 2px 5px #babecc, inset -5px -5px 10px #ffffff;} .button { margin: 15px 0 0 5px; width: 42px; height: 42px; border: none; outline: none; font-size: 18px; font-weight: bold; cursor: pointer; border-radius: 8px; background-color: rgb(214, 214, 214); /* box-shadow is used to achieve Neumorphism by using a light shadow and a dark shadow */ box-shadow: 5px 5px 10px #b6acac, -5px -5px 10px #faf4f4; display: inline-block;} .button:active { /* When the button is pressed, the inset shadow provides the impression that the element is being pressed into it */ box-shadow: inset 1px 1px 2px #babecc, inset -1px -1px 2px #fff;} .clearButton { color: white; background-color: red;} .mathbutton { color: white; background-color: black;}", "e": 4895, "s": 3462, "text": null }, { "code": null, "e": 4903, "s": 4895, "text": "Output:" }, { "code": null, "e": 4981, "s": 4903, "text": "HTML, CSS, and JavaScript working Calculator using Neumorphism Effect/Soft UI" }, { "code": null, "e": 4996, "s": 4981, "text": "adnanirshad158" }, { "code": null, "e": 5011, "s": 4996, "text": "sagartomar9927" }, { "code": null, "e": 5026, "s": 5011, "text": "Blogathon-2021" }, { "code": null, "e": 5037, "s": 5026, "text": "CSS-Basics" }, { "code": null, "e": 5052, "s": 5037, "text": "CSS-Properties" }, { "code": null, "e": 5067, "s": 5052, "text": "HTML-Questions" }, { "code": null, "e": 5083, "s": 5067, "text": "javascript-math" }, { "code": null, "e": 5104, "s": 5083, "text": "JavaScript-Questions" }, { "code": null, "e": 5114, "s": 5104, "text": "Blogathon" }, { "code": null, "e": 5118, "s": 5114, "text": "CSS" }, { "code": null, "e": 5123, "s": 5118, "text": "HTML" }, { "code": null, "e": 5134, "s": 5123, "text": "JavaScript" }, { "code": null, "e": 5151, "s": 5134, "text": "Web Technologies" }, { "code": null, "e": 5156, "s": 5151, "text": "HTML" }, { "code": null, "e": 5254, "s": 5156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5295, "s": 5254, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 5333, "s": 5295, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 5377, "s": 5333, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 5437, "s": 5377, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 5504, "s": 5437, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 5552, "s": 5504, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5614, "s": 5552, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5664, "s": 5614, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5722, "s": 5664, "text": "How to create footer to stay at the bottom of a Web page?" } ]
PyQt5 – How to make editable ComboBox
22 Apr, 2020 In this article we will see how we can make a combo box such that user and change the value of it by typing. By default when we create a combo box we can only choose from the option in the drop down menu although in editable combo box we can set the text by our self. In order to do this we will use setEditable method Syntax : combo_box.setEditable(True) Argument : It takes bool as argument Action performed : It will combo box editable Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating a editable combo box self.combo_box.setEditable(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 296, "s": 28, "text": "In this article we will see how we can make a combo box such that user and change the value of it by typing. By default when we create a combo box we can only choose from the option in the drop down menu although in editable combo box we can set the text by our self." }, { "code": null, "e": 347, "s": 296, "text": "In order to do this we will use setEditable method" }, { "code": null, "e": 384, "s": 347, "text": "Syntax : combo_box.setEditable(True)" }, { "code": null, "e": 421, "s": 384, "text": "Argument : It takes bool as argument" }, { "code": null, "e": 467, "s": 421, "text": "Action performed : It will combo box editable" }, { "code": null, "e": 495, "s": 467, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating a editable combo box self.combo_box.setEditable(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1598, "s": 495, "text": null }, { "code": null, "e": 1607, "s": 1598, "text": "Output :" }, { "code": null, "e": 1629, "s": 1607, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 1640, "s": 1629, "text": "Python-gui" }, { "code": null, "e": 1652, "s": 1640, "text": "Python-PyQt" }, { "code": null, "e": 1659, "s": 1652, "text": "Python" }, { "code": null, "e": 1757, "s": 1659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1775, "s": 1757, "text": "Python Dictionary" }, { "code": null, "e": 1817, "s": 1775, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1839, "s": 1817, "text": "Enumerate() in Python" }, { "code": null, "e": 1865, "s": 1839, "text": "Python String | replace()" }, { "code": null, "e": 1897, "s": 1865, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1926, "s": 1897, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1953, "s": 1926, "text": "Python Classes and Objects" }, { "code": null, "e": 1974, "s": 1953, "text": "Python OOPs Concepts" }, { "code": null, "e": 1997, "s": 1974, "text": "Introduction To PYTHON" } ]
MongoDB Projection
10 Feb, 2021 MongoDB provides a special feature that is known as Projection. It allows you to select only the necessary data rather than selecting whole data from the document. For example, a document contains 5 fields, i.e., { name: "Roma", age: 30, branch: EEE, department: "HR", salary: 20000 } But we only want to display the name and the age of the employee rather than displaying whole details. Now, here we use projection to display the name and age of the employee. One can use projection with db.collection.find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents. Syntax: db.collection.find({}, {field1: value2, field2: value2, ..}) If the value of the field is set to 1 or true, then it means the field will include in the return document. If the value of the field is set to 0 or false, then it means the field will not include in the return document. You are allowed to use projection operators, but find() method does not support following projection operators, i.e., $, $elemMatch, $slice, and $meta. There is no need to set _id field to 1 to return _id field, the find() method always return _id unless you set a _id field to 0. Examples: In the following examples, we are working with: Database: GeeksforGeeks Collection: employee Document: five documents that contain the details of the employees in the form of field-value pairs. nikhilchhipa9 MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Basics of API Testing Using Postman Copying Files to and from Docker Containers Markov Decision Process Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture ML | Introduction to Data in Machine Learning Fuzzy Logic | Introduction
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2021" }, { "code": null, "e": 241, "s": 28, "text": "MongoDB provides a special feature that is known as Projection. It allows you to select only the necessary data rather than selecting whole data from the document. For example, a document contains 5 fields, i.e.," }, { "code": null, "e": 314, "s": 241, "text": "{\nname: \"Roma\",\nage: 30,\nbranch: EEE,\ndepartment: \"HR\",\nsalary: 20000\n}\n" }, { "code": null, "e": 490, "s": 314, "text": "But we only want to display the name and the age of the employee rather than displaying whole details. Now, here we use projection to display the name and age of the employee." }, { "code": null, "e": 691, "s": 490, "text": "One can use projection with db.collection.find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents." }, { "code": null, "e": 699, "s": 691, "text": "Syntax:" }, { "code": null, "e": 760, "s": 699, "text": "db.collection.find({}, {field1: value2, field2: value2, ..})" }, { "code": null, "e": 868, "s": 760, "text": "If the value of the field is set to 1 or true, then it means the field will include in the return document." }, { "code": null, "e": 981, "s": 868, "text": "If the value of the field is set to 0 or false, then it means the field will not include in the return document." }, { "code": null, "e": 1133, "s": 981, "text": "You are allowed to use projection operators, but find() method does not support following projection operators, i.e., $, $elemMatch, $slice, and $meta." }, { "code": null, "e": 1262, "s": 1133, "text": "There is no need to set _id field to 1 to return _id field, the find() method always return _id unless you set a _id field to 0." }, { "code": null, "e": 1272, "s": 1262, "text": "Examples:" }, { "code": null, "e": 1320, "s": 1272, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1466, "s": 1320, "text": "Database: GeeksforGeeks\nCollection: employee\nDocument: five documents that contain the details of the employees in the form of field-value pairs." }, { "code": null, "e": 1480, "s": 1466, "text": "nikhilchhipa9" }, { "code": null, "e": 1488, "s": 1480, "text": "MongoDB" }, { "code": null, "e": 1514, "s": 1488, "text": "Advanced Computer Subject" }, { "code": null, "e": 1612, "s": 1514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1648, "s": 1612, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 1684, "s": 1648, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 1728, "s": 1684, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 1752, "s": 1728, "text": "Markov Decision Process" }, { "code": null, "e": 1787, "s": 1752, "text": "Getting Started with System Design" }, { "code": null, "e": 1828, "s": 1787, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 1876, "s": 1828, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 1917, "s": 1876, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 1963, "s": 1917, "text": "ML | Introduction to Data in Machine Learning" } ]
Aptitude Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Aptitude. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - A is twice as quick as B and B is thrice as quick as C. The excursion secured by C in 42 min. will be secured by A in A - 7 min. B - 14 min. C - 28 min. D - 63 min. Let c speed be x meters/min. Then, B speed=3x meters /min and A speed =6x meters/ min. Ratio of speed of A and C =ratio of times taken by C and A 6x:x=42:ymin⇒6x/x=42/y⇒y=42/6min=7 min. Q 2 - 9 men working 7 hours a day can finish a bit of work in 15 days. In how long can 6 men functioning for 9 hours a day, complete the same bit of work? A - 63/4 days B - 16 days C - 67/4 days D - 35/2 days (9*7) men working 1 hr a day can finish the work in 15 days. 63 men finish it in 15 days. 1 man can finish it in (15*63) days. (6*9) men can finish it in (15*63)/ (6*9) days = 35/2 days Q 3 - Two no. are in the extent 3/2 :8/3, when each of these are extended by 15 , their extent gets the chance to be 5/3 :5/2 . The greater of the no. is : A - 27 B - 36 C - 48 D - 64 Explanation Ratio of the given numbers = 3/2:8/3 = 9 :16 Let the numbers be 9x and 16 x, Then, (9x+15)/ (16 x+15) = (5/3)/ (5/2) =2/3 => 3(9x+15)= 2 (16x+15) => 5x= 15 =x= 3. ∴ Larger no.= (16*3)= 48 Q 4 - 15% of 180 = 50% of? A - 48 B - 50 C - 52 D - 54 Let 15% of 180=50% of x Then 15/100*180=50/100*x =>x=54 Q 5 - The range of a square field is 6050m2. The length of its corner to corner is A - 110 m B - 112 m C - 120 m D - 135 m Let the diagonal be d meter. Then, 1/2 d2=6050⇒ d2= 12100 ⇒d=√12100= 110 m. Q 6 - The average age of five officers in a department is 32 years. If the age of their supervisor is added the average increases by 1. What is the supervisor's age? A - 32 years B - 48 years C - 38 years D - 42 years Supervisor?s age = 32 + 6 = 38 years Q 7 - On solving p/x+q/y = m, q/x+p/y = n, we get: A - x=(q2-p2)/(mp-nq) , y = (q2-p2)/(np-mq) B - x=(p2-q2)/(mp-nq), y=(p2-q2)/(np-mq) C - x=(p2-q2)/(mp-nq) , y= (q2-p2)/(np-mq) D - x=(q2-p2)/(mp-nq), y = (p2-q2)/(np-mq) Given equations are p/x+q/y = m...(i), q/x+ p/y = n ...(ii) On multiplying (i) by q, (ii) by p and subtracting, we get: q2/y- p2/y = mq-np ⇒y (mp-np) = (q2- p2) ⇒y = (q2-p2)/(mq- np) = (p2- q2)/(np-mq) On multiplying (i) by p, (ii) by q and subtracting, we get: p2/x - q2/x = mp- nq ⇒ (p2- q2) = x (mp- nq) ⇒x = (p2- q2)/ (mp-nq) ∴ x= (p2-q2)/(mp-nq) , y = (p2-q2)/(np- mq) Q 8 - When the sun's altitude changes from 45° to 60°, the length of the shadow of a tower decreases by 45m. What is the height of the tower? A - (45√3)/(√3-1) B - (45√3)/(√3+1) C - (45+√3)/(√3-1) D - (45-√3)/(√3-1) Let AD be the tower, BD be the initial shadow and CD be the final shadow. Given that BC = 45 m, ABD = 45°, ACD = 60°, Let CD = x, AD = h From the right CDA, tan60=h/x From the right BDA, tan45=(45+x)/h=>h=45+x =>h=45+h/√3 =>h(1-1/√3)=45 =>h=45/(1-1/√3)=(45√3)/(√3-1) Q 9 - If the the total investment of a business is an amount of rs. 5000. Ajay invested 4000 Rs. more in the comparision of Bijender and Bijender invested 5000 more in the comparision of Chman . At the end of the year, Rs. 35000 earned in the form of profit then what should be the share of Ajay? A - Rs. 14700 B - Rs. 5000 C - Rs. 11000 D - Rs. 12000 If we can assume that the C , B and A have the investment of Rs. x , (x+5000) and Rs. (x+9000) respectively. Then, X+(x+5000)+(x+9000) =50000 ⇒ 3x = 36000 ⇒ x =12000. C =Rs. 12000 , B = Rs. 17000 and C = Rs. 21000 A : B : C = 21000 : 17000: 12000 = 21: 17: 12 Share of A = Rs. (35000* 21/50) = Rs. 14700 Q 10 - If a monkey can climb 6m on a round pole during 1 min. but he slipped 3 m in the next attempt or next min. The length of the pole is 21 m then how much time he will take to complete the task? A - 10 min B - 11 min C - 12 min D - 13 min Time taken to climb 6m in the last = 1 min. remaining distance = (21-6) = 15 m . total distance covered in 2 min. = (6-3 ) = 3m . ∴ distance of 15m covered in ( 2/3* 15) = 10 min. total time taken = (10+1) = 11 min.
[ { "code": null, "e": 4348, "s": 4026, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Aptitude. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4472, "s": 4348, "text": "Q 1 - A is twice as quick as B and B is thrice as quick as C. The excursion secured by C in 42 min. will be secured by A in" }, { "code": null, "e": 4483, "s": 4472, "text": "A - 7 min." }, { "code": null, "e": 4495, "s": 4483, "text": "B - 14 min." }, { "code": null, "e": 4507, "s": 4495, "text": "C - 28 min." }, { "code": null, "e": 4519, "s": 4507, "text": "D - 63 min." }, { "code": null, "e": 4705, "s": 4519, "text": "Let c speed be x meters/min.\nThen, B speed=3x meters /min and A speed =6x meters/ min.\nRatio of speed of A and C =ratio of times taken by C and A\n6x:x=42:ymin⇒6x/x=42/y⇒y=42/6min=7 min." }, { "code": null, "e": 4860, "s": 4705, "text": "Q 2 - 9 men working 7 hours a day can finish a bit of work in 15 days. In how long can 6 men functioning for 9 hours a day, complete the same bit of work?" }, { "code": null, "e": 4874, "s": 4860, "text": "A - 63/4 days" }, { "code": null, "e": 4886, "s": 4874, "text": "B - 16 days" }, { "code": null, "e": 4900, "s": 4886, "text": "C - 67/4 days" }, { "code": null, "e": 4914, "s": 4900, "text": "D - 35/2 days" }, { "code": null, "e": 5100, "s": 4914, "text": "(9*7) men working 1 hr a day can finish the work in 15 days.\n63 men finish it in 15 days.\n1 man can finish it in (15*63) days.\n(6*9) men can finish it in (15*63)/ (6*9) days = 35/2 days" }, { "code": null, "e": 5256, "s": 5100, "text": "Q 3 - Two no. are in the extent 3/2 :8/3, when each of these are extended by 15 , their extent gets the chance to be 5/3 :5/2 . The greater of the no. is :" }, { "code": null, "e": 5263, "s": 5256, "text": "A - 27" }, { "code": null, "e": 5270, "s": 5263, "text": "B - 36" }, { "code": null, "e": 5277, "s": 5270, "text": "C - 48" }, { "code": null, "e": 5284, "s": 5277, "text": "D - 64" }, { "code": null, "e": 5296, "s": 5284, "text": "Explanation" }, { "code": null, "e": 5490, "s": 5296, "text": "Ratio of the given numbers = 3/2:8/3 = 9 :16\nLet the numbers be 9x and 16 x, Then,\n (9x+15)/ (16 x+15) = (5/3)/ (5/2) =2/3\n=> 3(9x+15)= 2 (16x+15)\n=> 5x= 15 =x= 3.\n ∴ Larger no.= (16*3)= 48\n" }, { "code": null, "e": 5517, "s": 5490, "text": "Q 4 - 15% of 180 = 50% of?" }, { "code": null, "e": 5524, "s": 5517, "text": "A - 48" }, { "code": null, "e": 5531, "s": 5524, "text": "B - 50" }, { "code": null, "e": 5538, "s": 5531, "text": "C - 52" }, { "code": null, "e": 5545, "s": 5538, "text": "D - 54" }, { "code": null, "e": 5601, "s": 5545, "text": "Let 15% of 180=50% of x\nThen 15/100*180=50/100*x\n=>x=54" }, { "code": null, "e": 5684, "s": 5601, "text": "Q 5 - The range of a square field is 6050m2. The length of its corner to corner is" }, { "code": null, "e": 5694, "s": 5684, "text": "A - 110 m" }, { "code": null, "e": 5704, "s": 5694, "text": "B - 112 m" }, { "code": null, "e": 5714, "s": 5704, "text": "C - 120 m" }, { "code": null, "e": 5724, "s": 5714, "text": "D - 135 m" }, { "code": null, "e": 5800, "s": 5724, "text": "Let the diagonal be d meter. Then,\n1/2 d2=6050⇒ d2= 12100 ⇒d=√12100= 110 m." }, { "code": null, "e": 5966, "s": 5800, "text": "Q 6 - The average age of five officers in a department is 32 years. If the age of their supervisor is added the average increases by 1. What is the supervisor's age?" }, { "code": null, "e": 5979, "s": 5966, "text": "A - 32 years" }, { "code": null, "e": 5992, "s": 5979, "text": "B - 48 years" }, { "code": null, "e": 6005, "s": 5992, "text": "C - 38 years" }, { "code": null, "e": 6018, "s": 6005, "text": "D - 42 years" }, { "code": null, "e": 6055, "s": 6018, "text": "Supervisor?s age = 32 + 6 = 38 years" }, { "code": null, "e": 6106, "s": 6055, "text": "Q 7 - On solving p/x+q/y = m, q/x+p/y = n, we get:" }, { "code": null, "e": 6150, "s": 6106, "text": "A - x=(q2-p2)/(mp-nq) , y = (q2-p2)/(np-mq)" }, { "code": null, "e": 6191, "s": 6150, "text": "B - x=(p2-q2)/(mp-nq), y=(p2-q2)/(np-mq)" }, { "code": null, "e": 6234, "s": 6191, "text": "C - x=(p2-q2)/(mp-nq) , y= (q2-p2)/(np-mq)" }, { "code": null, "e": 6277, "s": 6234, "text": "D - x=(q2-p2)/(mp-nq), y = (p2-q2)/(np-mq)" }, { "code": null, "e": 6653, "s": 6277, "text": "Given equations are p/x+q/y = m...(i), q/x+ p/y = n ...(ii)\nOn multiplying (i) by q, (ii) by p and subtracting, we get:\nq2/y- p2/y = mq-np\n⇒y (mp-np) = (q2- p2)\n⇒y = (q2-p2)/(mq- np)\n= (p2- q2)/(np-mq)\nOn multiplying (i) by p, (ii) by q and subtracting, we get:\np2/x - q2/x = mp- nq\n⇒ (p2- q2) = x (mp- nq)\n⇒x = (p2- q2)/ (mp-nq)\n∴ x= (p2-q2)/(mp-nq) , y = (p2-q2)/(np- mq)" }, { "code": null, "e": 6795, "s": 6653, "text": "Q 8 - When the sun's altitude changes from 45° to 60°, the length of the shadow of a tower decreases by 45m. What is the height of the tower?" }, { "code": null, "e": 6813, "s": 6795, "text": "A - (45√3)/(√3-1)" }, { "code": null, "e": 6831, "s": 6813, "text": "B - (45√3)/(√3+1)" }, { "code": null, "e": 6850, "s": 6831, "text": "C - (45+√3)/(√3-1)" }, { "code": null, "e": 6869, "s": 6850, "text": "D - (45-√3)/(√3-1)" }, { "code": null, "e": 7142, "s": 6869, "text": "Let AD be the tower, BD be the initial shadow and CD be the final shadow.\nGiven that BC = 45 m, ABD = 45°, ACD = 60°,\nLet CD = x, AD = h\nFrom the right CDA, tan60=h/x\nFrom the right BDA, tan45=(45+x)/h=>h=45+x\n=>h=45+h/√3\n=>h(1-1/√3)=45\n=>h=45/(1-1/√3)=(45√3)/(√3-1)" }, { "code": null, "e": 7441, "s": 7142, "text": "Q 9 - If the the total investment of a business is an amount of rs. 5000. Ajay invested 4000 Rs. more in the comparision of Bijender and Bijender invested 5000 more in the comparision of Chman . At the end of the year, Rs. 35000 earned in the form of profit then what should be the share of Ajay?" }, { "code": null, "e": 7455, "s": 7441, "text": "A - Rs. 14700" }, { "code": null, "e": 7468, "s": 7455, "text": "B - Rs. 5000" }, { "code": null, "e": 7482, "s": 7468, "text": "C - Rs. 11000" }, { "code": null, "e": 7496, "s": 7482, "text": "D - Rs. 12000" }, { "code": null, "e": 7804, "s": 7496, "text": "If we can assume that the C , B and A have the investment of Rs. x ,\n(x+5000) and Rs. (x+9000) respectively. Then,\nX+(x+5000)+(x+9000) =50000 ⇒ 3x = 36000 ⇒ x =12000.\nC =Rs. 12000 , B = Rs. 17000 and C = Rs. 21000\nA : B : C = 21000 : 17000: 12000 = 21: 17: 12\nShare of A = Rs. (35000* 21/50) = Rs. 14700" }, { "code": null, "e": 8008, "s": 7804, "text": "Q 10 - If a monkey can climb 6m on a round pole during 1 min. but he slipped 3 m in the next attempt or next min. The length of the pole is 21 m then how much time he will take to complete the task?" }, { "code": null, "e": 8019, "s": 8008, "text": "A - 10 min" }, { "code": null, "e": 8030, "s": 8019, "text": "B - 11 min" }, { "code": null, "e": 8041, "s": 8030, "text": "C - 12 min" }, { "code": null, "e": 8052, "s": 8041, "text": "D - 13 min" } ]
Java AWT | Cursor class with examples
23 Oct, 2019 Cursor class is a part of Java AWT package and it is used to create custom cursors or inherit system or predefined cursors.Cursor class is mainly used to encapsulate the bitmap representation of the mouse cursor. Constructor of cursor class are : Cursor(int t) : Creates a cursor with specified classCursor(String name) : Creates a custom cursor with specified name. Cursor(int t) : Creates a cursor with specified class Cursor(String name) : Creates a custom cursor with specified name. Commonly used methods 1. Program to apply some predefined and system cursors to components (label) // Java Program to apply some predefined and system cursors to components (label)import java.awt.*;import javax.swing.*;class cursor extends JFrame { // frame static JFrame f; // label static Label l, l1, l2; // default constructor cursor() { } // main class public static void main(String args[]) { try { // create a frame f = new JFrame("cursor"); // create e panel JPanel p = new JPanel(); // create labels l = new Label("label one"); l1 = new Label("label two"); l2 = new Label("label three"); // create cursors Cursor c = new Cursor(CROSSHAIR_CURSOR); Cursor c1 = new Cursor(HAND_CURSOR); // get System cursor Cursor c2 = Cursor.getSystemCustomCursor("Invalid.32x32"); // set cursor l.setCursor(c); l1.setCursor(c1); l2.setCursor(c2); // add labels to panel p.add(l); p.add(l1); p.add(l2); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } catch (Exception e) { System.err.println(e.getMessage()); } }} Output : // Java Program to add all predefined cursors to a choiceimport java.awt.*;import java.awt.event.*;import javax.swing.*;class cursor extends JFrame implements ItemListener { // frame static JFrame f; // labels static Label l; // create a choice static Choice c; // default constructor cursor() { } // main class public static void main(String args[]) { // create a frame f = new JFrame("cursor"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add items to choice for (int i = 0; i < 14; i++) c.add(Cursor.getPredefinedCursor(i).getName()); // object of class cursor cu = new cursor(); // create a label l = new Label(" label one "); // add item listener to the choice c.addItemListener(cu); // add labels to panel p.add(l); p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item of choice is selected public void itemStateChanged(ItemEvent e) { // set the cursor l.setCursor(Cursor.getPredefinedCursor(c.getSelectedIndex())); }} Output : // Java program to create a custom cursor and add it to labelsimport java.awt.*;import javax.swing.*;class cursor extends JFrame { // frame static JFrame f; // label static Label l, l1, l2; // default constructor cursor() { // create a frame f = new JFrame("cursor"); // create e panel JPanel p = new JPanel(); // extract image // the files gfg.jpg and gfg.png contains image of cursor Image i = Toolkit.getDefaultToolkit().getImage("f:\\gfg.jpg"); Image i1 = Toolkit.getDefaultToolkit().getImage("f:\\gfg.png"); // point p Point p11 = new Point(0, 0); // create labels l = new Label("label one"); l1 = new Label("label two"); // create cursors Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(i, p11, "cursor1"); Cursor c1 = Toolkit.getDefaultToolkit().createCustomCursor(i1, p11, "cursor2"); // set cursor l.setCursor(c); l1.setCursor(c1); // add labels to panel p.add(l); p.add(l1); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // main class public static void main(String args[]) { cursor c = new cursor(); }} Output : ManasChhabra2 java-swing Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Oct, 2019" }, { "code": null, "e": 241, "s": 28, "text": "Cursor class is a part of Java AWT package and it is used to create custom cursors or inherit system or predefined cursors.Cursor class is mainly used to encapsulate the bitmap representation of the mouse cursor." }, { "code": null, "e": 275, "s": 241, "text": "Constructor of cursor class are :" }, { "code": null, "e": 395, "s": 275, "text": "Cursor(int t) : Creates a cursor with specified classCursor(String name) : Creates a custom cursor with specified name." }, { "code": null, "e": 449, "s": 395, "text": "Cursor(int t) : Creates a cursor with specified class" }, { "code": null, "e": 516, "s": 449, "text": "Cursor(String name) : Creates a custom cursor with specified name." }, { "code": null, "e": 538, "s": 516, "text": "Commonly used methods" }, { "code": null, "e": 615, "s": 538, "text": "1. Program to apply some predefined and system cursors to components (label)" }, { "code": "// Java Program to apply some predefined and system cursors to components (label)import java.awt.*;import javax.swing.*;class cursor extends JFrame { // frame static JFrame f; // label static Label l, l1, l2; // default constructor cursor() { } // main class public static void main(String args[]) { try { // create a frame f = new JFrame(\"cursor\"); // create e panel JPanel p = new JPanel(); // create labels l = new Label(\"label one\"); l1 = new Label(\"label two\"); l2 = new Label(\"label three\"); // create cursors Cursor c = new Cursor(CROSSHAIR_CURSOR); Cursor c1 = new Cursor(HAND_CURSOR); // get System cursor Cursor c2 = Cursor.getSystemCustomCursor(\"Invalid.32x32\"); // set cursor l.setCursor(c); l1.setCursor(c1); l2.setCursor(c2); // add labels to panel p.add(l); p.add(l1); p.add(l2); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } catch (Exception e) { System.err.println(e.getMessage()); } }}", "e": 1944, "s": 615, "text": null }, { "code": null, "e": 1953, "s": 1944, "text": "Output :" }, { "code": "// Java Program to add all predefined cursors to a choiceimport java.awt.*;import java.awt.event.*;import javax.swing.*;class cursor extends JFrame implements ItemListener { // frame static JFrame f; // labels static Label l; // create a choice static Choice c; // default constructor cursor() { } // main class public static void main(String args[]) { // create a frame f = new JFrame(\"cursor\"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add items to choice for (int i = 0; i < 14; i++) c.add(Cursor.getPredefinedCursor(i).getName()); // object of class cursor cu = new cursor(); // create a label l = new Label(\" label one \"); // add item listener to the choice c.addItemListener(cu); // add labels to panel p.add(l); p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item of choice is selected public void itemStateChanged(ItemEvent e) { // set the cursor l.setCursor(Cursor.getPredefinedCursor(c.getSelectedIndex())); }}", "e": 3236, "s": 1953, "text": null }, { "code": null, "e": 3245, "s": 3236, "text": "Output :" }, { "code": "// Java program to create a custom cursor and add it to labelsimport java.awt.*;import javax.swing.*;class cursor extends JFrame { // frame static JFrame f; // label static Label l, l1, l2; // default constructor cursor() { // create a frame f = new JFrame(\"cursor\"); // create e panel JPanel p = new JPanel(); // extract image // the files gfg.jpg and gfg.png contains image of cursor Image i = Toolkit.getDefaultToolkit().getImage(\"f:\\\\gfg.jpg\"); Image i1 = Toolkit.getDefaultToolkit().getImage(\"f:\\\\gfg.png\"); // point p Point p11 = new Point(0, 0); // create labels l = new Label(\"label one\"); l1 = new Label(\"label two\"); // create cursors Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(i, p11, \"cursor1\"); Cursor c1 = Toolkit.getDefaultToolkit().createCustomCursor(i1, p11, \"cursor2\"); // set cursor l.setCursor(c); l1.setCursor(c1); // add labels to panel p.add(l); p.add(l1); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // main class public static void main(String args[]) { cursor c = new cursor(); }}", "e": 4566, "s": 3245, "text": null }, { "code": null, "e": 4575, "s": 4566, "text": "Output :" }, { "code": null, "e": 4589, "s": 4575, "text": "ManasChhabra2" }, { "code": null, "e": 4600, "s": 4589, "text": "java-swing" }, { "code": null, "e": 4605, "s": 4600, "text": "Java" }, { "code": null, "e": 4619, "s": 4605, "text": "Java Programs" }, { "code": null, "e": 4624, "s": 4619, "text": "Java" }, { "code": null, "e": 4722, "s": 4624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4773, "s": 4722, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4804, "s": 4773, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4823, "s": 4804, "text": "Interfaces in Java" }, { "code": null, "e": 4853, "s": 4823, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4871, "s": 4853, "text": "ArrayList in Java" }, { "code": null, "e": 4899, "s": 4871, "text": "Initializing a List in Java" }, { "code": null, "e": 4925, "s": 4899, "text": "Java Programming Examples" }, { "code": null, "e": 4969, "s": 4925, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 5003, "s": 4969, "text": "Convert Double to Integer in Java" } ]
v-else-if Directive in Vue.js
25 Jun, 2020 v-else-if directive is a Vue.js directive used to toggle the display CSS property of an element depending on a condition when the if condition is not satisfied. First, we will create a div element with id as app and let’s apply the v-else-if directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value. Syntax: v-else-if="data" Parameters: This function accepts a single parameter which is data or a condition. Example 1: This example uses Vue.js to show an element with v-else-if using arithmetic conditions. <!DOCTYPE html><html> <head> <title> VueJS | v-else-if directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-else-if directive </b> </div> <div id="canvas" style= "border:1px solid #000000; width: 600px;height: 200px;"> <div id="app"> <h2 v-if="data > 50"> data is greater than 50 </h2> <h2 v-else-if="data < 50"> data is smaller than 50 </h2> <h2 v-else> data is equal to 50 </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: 40 } }) </script></body> </html> Output: Example 2: This example uses Vue.js to show an element with v-else-if using Booleans. <!DOCTYPE html><html> <head> <title> VueJS | v-else-if directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-else-if directive </b> </div> <div id="canvas" style= "border:1px solid #000000; width: 600px;height: 200px;"> <div id="app"> <h2 v-if="data"> if is executed </h2> <h2 v-else-if="!data"> else-if is executed </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body> </html> Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2020" }, { "code": null, "e": 411, "s": 28, "text": "v-else-if directive is a Vue.js directive used to toggle the display CSS property of an element depending on a condition when the if condition is not satisfied. First, we will create a div element with id as app and let’s apply the v-else-if directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value." }, { "code": null, "e": 419, "s": 411, "text": "Syntax:" }, { "code": null, "e": 436, "s": 419, "text": "v-else-if=\"data\"" }, { "code": null, "e": 519, "s": 436, "text": "Parameters: This function accepts a single parameter which is data or a condition." }, { "code": null, "e": 618, "s": 519, "text": "Example 1: This example uses Vue.js to show an element with v-else-if using arithmetic conditions." }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS | v-else-if directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-else-if directive </b> </div> <div id=\"canvas\" style= \"border:1px solid #000000; width: 600px;height: 200px;\"> <div id=\"app\"> <h2 v-if=\"data > 50\"> data is greater than 50 </h2> <h2 v-else-if=\"data < 50\"> data is smaller than 50 </h2> <h2 v-else> data is equal to 50 </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: 40 } }) </script></body> </html> ", "e": 1605, "s": 618, "text": null }, { "code": null, "e": 1613, "s": 1605, "text": "Output:" }, { "code": null, "e": 1699, "s": 1613, "text": "Example 2: This example uses Vue.js to show an element with v-else-if using Booleans." }, { "code": "<!DOCTYPE html><html> <head> <title> VueJS | v-else-if directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-else-if directive </b> </div> <div id=\"canvas\" style= \"border:1px solid #000000; width: 600px;height: 200px;\"> <div id=\"app\"> <h2 v-if=\"data\"> if is executed </h2> <h2 v-else-if=\"!data\"> else-if is executed </h2> </div> </div> <script> var app = new Vue({ el: '#app', data: { data: false } }) </script></body> </html> ", "e": 2605, "s": 1699, "text": null }, { "code": null, "e": 2613, "s": 2605, "text": "Output:" }, { "code": null, "e": 2620, "s": 2613, "text": "Vue.JS" }, { "code": null, "e": 2631, "s": 2620, "text": "JavaScript" }, { "code": null, "e": 2648, "s": 2631, "text": "Web Technologies" }, { "code": null, "e": 2746, "s": 2648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2807, "s": 2746, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2879, "s": 2807, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2919, "s": 2879, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2960, "s": 2919, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3002, "s": 2960, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3035, "s": 3002, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3097, "s": 3035, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3158, "s": 3097, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3208, "s": 3158, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to call ‘npm start’ though docker ?
04 Jul, 2021 The following article covers how to call npm start through docker. While doing so, we will dockerize a simple React App. Docker is an open-source platform for running, shipping, and managing applications. It allows us to manage our infrastructure in the same way as we manage our applications. It runs the application in a kind of isolated environment called container. A container is lightweight and contains everything needed to run the application. Multiple containers can run on the same host, and they can also share data between them securely. Creating the React Application: Step 1: Create a React application using the following command.npx create-react-app docker-react Step 1: Create a React application using the following command. npx create-react-app docker-react Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command.cd docker-react Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command. cd docker-react Step 3: Create a file named Dockerfile in the root of your app. Step 3: Create a file named Dockerfile in the root of your app. Project Structure: It will look like this. Writing the Dockerfile: Write down the following lines to your Dockerfile. FROM node:alpine RUN mkdir /app WORKDIR /app COPY package.json /app RUN npm install COPY . /app CMD ["npm", "start"] Explanation: First, we load the base image node:alpine which is a lightweight Linux distribution with a node installed in it. Then we copy the package.json file which contains the app’s dependencies into our working directly. And then we install the dependencies and copy the project files into our working directory. Finally, we run the command npm start. Creating docker image: Run the following command from the project’s root directory. Make sure your docker daemon is running. docker build -t <yourname/projectname> . Steps to run the application: Run the application using following command from the root directory of your folder. docker run -d -it -p 3000:3000 <yourname/projectname> Here we need to map our localhost port to the one of the container which in our case is 3000. Output: Now open your browser and go to http://localhost:3000/, you will see the following output. docker Node-npm NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jul, 2021" }, { "code": null, "e": 173, "s": 52, "text": "The following article covers how to call npm start through docker. While doing so, we will dockerize a simple React App." }, { "code": null, "e": 347, "s": 173, "text": "Docker is an open-source platform for running, shipping, and managing applications. It allows us to manage our infrastructure in the same way as we manage our applications. " }, { "code": null, "e": 603, "s": 347, "text": "It runs the application in a kind of isolated environment called container. A container is lightweight and contains everything needed to run the application. Multiple containers can run on the same host, and they can also share data between them securely." }, { "code": null, "e": 637, "s": 605, "text": "Creating the React Application:" }, { "code": null, "e": 734, "s": 637, "text": "Step 1: Create a React application using the following command.npx create-react-app docker-react" }, { "code": null, "e": 798, "s": 734, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 832, "s": 798, "text": "npx create-react-app docker-react" }, { "code": null, "e": 953, "s": 832, "text": "Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command.cd docker-react" }, { "code": null, "e": 1059, "s": 953, "text": "Step 2: After creating your project folder(i.e. docker-react), move to it by using the following command." }, { "code": null, "e": 1075, "s": 1059, "text": "cd docker-react" }, { "code": null, "e": 1139, "s": 1075, "text": "Step 3: Create a file named Dockerfile in the root of your app." }, { "code": null, "e": 1203, "s": 1139, "text": "Step 3: Create a file named Dockerfile in the root of your app." }, { "code": null, "e": 1246, "s": 1203, "text": "Project Structure: It will look like this." }, { "code": null, "e": 1321, "s": 1246, "text": "Writing the Dockerfile: Write down the following lines to your Dockerfile." }, { "code": null, "e": 1438, "s": 1321, "text": "FROM node:alpine\nRUN mkdir /app\nWORKDIR /app\nCOPY package.json /app\nRUN npm install\nCOPY . /app\nCMD [\"npm\", \"start\"]" }, { "code": null, "e": 1451, "s": 1438, "text": "Explanation:" }, { "code": null, "e": 1564, "s": 1451, "text": "First, we load the base image node:alpine which is a lightweight Linux distribution with a node installed in it." }, { "code": null, "e": 1664, "s": 1564, "text": "Then we copy the package.json file which contains the app’s dependencies into our working directly." }, { "code": null, "e": 1756, "s": 1664, "text": "And then we install the dependencies and copy the project files into our working directory." }, { "code": null, "e": 1795, "s": 1756, "text": "Finally, we run the command npm start." }, { "code": null, "e": 1920, "s": 1795, "text": "Creating docker image: Run the following command from the project’s root directory. Make sure your docker daemon is running." }, { "code": null, "e": 1961, "s": 1920, "text": "docker build -t <yourname/projectname> ." }, { "code": null, "e": 2075, "s": 1961, "text": "Steps to run the application: Run the application using following command from the root directory of your folder." }, { "code": null, "e": 2129, "s": 2075, "text": "docker run -d -it -p 3000:3000 <yourname/projectname>" }, { "code": null, "e": 2223, "s": 2129, "text": "Here we need to map our localhost port to the one of the container which in our case is 3000." }, { "code": null, "e": 2322, "s": 2223, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 2329, "s": 2322, "text": "docker" }, { "code": null, "e": 2338, "s": 2329, "text": "Node-npm" }, { "code": null, "e": 2355, "s": 2338, "text": "NodeJS-Questions" }, { "code": null, "e": 2362, "s": 2355, "text": "Picked" }, { "code": null, "e": 2370, "s": 2362, "text": "Node.js" }, { "code": null, "e": 2387, "s": 2370, "text": "Web Technologies" }, { "code": null, "e": 2485, "s": 2387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2517, "s": 2485, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2552, "s": 2517, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2622, "s": 2552, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2649, "s": 2622, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2674, "s": 2649, "text": "Mongoose find() Function" }, { "code": null, "e": 2736, "s": 2674, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2797, "s": 2736, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2847, "s": 2797, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2890, "s": 2847, "text": "How to fetch data from an API in ReactJS ?" } ]
How to generate JSON output using Python?
The json module in python allows you to dump a dict to json format directly. To use it, import json my_dict = { 'foo': 42, 'bar': { 'baz': "Hello", 'poo': 124.2 } } my_json = json.dumps(my_dict) print(my_json) This will give the output − '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}' You can also pass indent argument to prettyprint the json. import json my_dict = { 'foo': 42, 'bar': { 'baz': "Hello", 'poo': 124.2 } } my_json = json.dumps(my_dict, indent=2) print(my_json) This will give the output − { "foo": 42, "bar": { "baz": "Hello", "poo": 124.2 } }
[ { "code": null, "e": 1275, "s": 1187, "text": "The json module in python allows you to dump a dict to json format directly. To use it," }, { "code": null, "e": 1419, "s": 1275, "text": "import json\n\nmy_dict = {\n 'foo': 42,\n 'bar': {\n 'baz': \"Hello\",\n 'poo': 124.2\n }\n}\nmy_json = json.dumps(my_dict)\nprint(my_json)" }, { "code": null, "e": 1447, "s": 1419, "text": "This will give the output −" }, { "code": null, "e": 1500, "s": 1447, "text": "'{\"foo\": 42, \"bar\": {\"baz\": \"Hello\", \"poo\": 124.2}}'" }, { "code": null, "e": 1560, "s": 1500, "text": "You can also pass indent argument to prettyprint the json. " }, { "code": null, "e": 1714, "s": 1560, "text": "import json\n\nmy_dict = {\n 'foo': 42,\n 'bar': {\n 'baz': \"Hello\",\n 'poo': 124.2\n }\n}\nmy_json = json.dumps(my_dict, indent=2)\nprint(my_json)" }, { "code": null, "e": 1742, "s": 1714, "text": "This will give the output −" }, { "code": null, "e": 1821, "s": 1742, "text": "{\n \"foo\": 42,\n \"bar\":\n {\n \"baz\": \"Hello\",\n \"poo\": 124.2\n }\n}" } ]
R – Objects
10 May, 2020 Every programming language has its own data types to store values or any information so that the user can assign these data types to the variables and perform operations respectively. Operations are performed accordingly to the data types.These data types can be character, integer, float, long, etc. Based on the data type, memory/storage is allocated to the variable. For example, in C language character variables are assigned with 1 byte of memory, integer variable with 2 or 4 bytes of memory and other data types have different memory allocation for them.Unlike other programming languages, variables are assigned to objects rather than data types in R programming. There are 5 basic types of objects in the R language: Atomic vectors are one of the basic types of objects in R programming. Atomic vectors can store homogeneous data types such as character, doubles, integers, raw, logical, and complex. A single element variable is also said to be vector. Example: # Create vectorsx <- c(1, 2, 3, 4)y <- c("a", "b", "c", "d")z <- 5 # Print vector and class of vectorprint(x)print(class(x)) print(y)print(class(y)) print(z)print(class(z)) Output: [1] 1 2 3 4 [1] "numeric" [1] "a" "b" "c" "d" [1] "character" [1] 5 [1] "numeric" List is another type of object in R programming. List can contain heterogeneous data types such as vectors or another lists. Example: # Create listls <- list(c(1, 2, 3, 4), list("a", "b", "c")) # Printprint(ls)print(class(ls)) Output: [[1]] [1] 1 2 3 4 [[2]] [[2]][[1]] [1] "a" [[2]][[2]] [1] "b" [[2]][[3]] [1] "c" [1] "list" To store values as 2-Dimensional array, matrices are used in R. Data, number of rows and columns are defined in the matrix() function. Syntax: matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) Example: x <- c(1, 2, 3, 4, 5, 6) # Create matrixmat <- matrix(x, nrow = 2) print(mat)print(class(mat)) Output: [, 1] [, 2] [, 3] [1, ] 1 3 5 [2, ] 2 4 6 [1] "matrix" Factor object encodes a vector of unique elements (levels) from the given data vector. Example: # Create vectors <- c("spring", "autumn", "winter", "summer", "spring", "autumn") print(factor(s))print(nlevels(factor(s))) Output: [1] spring autumn winter summer spring autumn Levels: autumn spring summer winter [1] 4 array() function is used to create n-dimensional array. This function takes dim attribute as an argument and creates required length of each dimension as specified in the attribute.Syntax: array(data, dim = length(data), dimnames = NULL) Example: # Create 3-dimensional array# and filling values by columnarr <- array(c(1, 2, 3), dim = c(3, 3, 3)) print(arr) Output: ,, 1 [, 1] [, 2] [, 3] [1, ] 1 1 1 [2, ] 2 2 2 [3, ] 3 3 3,, 2 [, 1] [, 2] [, 3] [1, ] 1 1 1 [2, ] 2 2 2 [3, ] 3 3 3,, 3 [, 1] [, 2] [, 3] [1, ] 1 1 1 [2, ] 2 2 2 [3, ] 3 3 3 Data frames are 2-dimensional tabular data object in R programming. Data frames consists of multiple columns and each column represents a vector. Columns in data frame can have different modes of data unlike matrices. Example: # Create vectorsx <- 1:5y <- LETTERS[1:5]z <- c("Albert", "Bob", "Charlie", "Denver", "Elie") # Create data frame of vectorsdf <- data.frame(x, y, z) # Print data frameprint(df) Output: x y z 1 1 A Albert 2 2 B Bob 3 3 C Charlie 4 4 D Denver 5 5 E Elie Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 May, 2020" }, { "code": null, "e": 725, "s": 53, "text": "Every programming language has its own data types to store values or any information so that the user can assign these data types to the variables and perform operations respectively. Operations are performed accordingly to the data types.These data types can be character, integer, float, long, etc. Based on the data type, memory/storage is allocated to the variable. For example, in C language character variables are assigned with 1 byte of memory, integer variable with 2 or 4 bytes of memory and other data types have different memory allocation for them.Unlike other programming languages, variables are assigned to objects rather than data types in R programming." }, { "code": null, "e": 779, "s": 725, "text": "There are 5 basic types of objects in the R language:" }, { "code": null, "e": 1016, "s": 779, "text": "Atomic vectors are one of the basic types of objects in R programming. Atomic vectors can store homogeneous data types such as character, doubles, integers, raw, logical, and complex. A single element variable is also said to be vector." }, { "code": null, "e": 1025, "s": 1016, "text": "Example:" }, { "code": "# Create vectorsx <- c(1, 2, 3, 4)y <- c(\"a\", \"b\", \"c\", \"d\")z <- 5 # Print vector and class of vectorprint(x)print(class(x)) print(y)print(class(y)) print(z)print(class(z))", "e": 1201, "s": 1025, "text": null }, { "code": null, "e": 1209, "s": 1201, "text": "Output:" }, { "code": null, "e": 1292, "s": 1209, "text": "[1] 1 2 3 4\n[1] \"numeric\"\n[1] \"a\" \"b\" \"c\" \"d\"\n[1] \"character\"\n[1] 5\n[1] \"numeric\"\n" }, { "code": null, "e": 1417, "s": 1292, "text": "List is another type of object in R programming. List can contain heterogeneous data types such as vectors or another lists." }, { "code": null, "e": 1426, "s": 1417, "text": "Example:" }, { "code": "# Create listls <- list(c(1, 2, 3, 4), list(\"a\", \"b\", \"c\")) # Printprint(ls)print(class(ls))", "e": 1520, "s": 1426, "text": null }, { "code": null, "e": 1528, "s": 1520, "text": "Output:" }, { "code": null, "e": 1625, "s": 1528, "text": "[[1]]\n[1] 1 2 3 4\n\n[[2]]\n[[2]][[1]]\n[1] \"a\"\n\n[[2]][[2]]\n[1] \"b\"\n\n[[2]][[3]]\n[1] \"c\"\n\n[1] \"list\"\n" }, { "code": null, "e": 1760, "s": 1625, "text": "To store values as 2-Dimensional array, matrices are used in R. Data, number of rows and columns are defined in the matrix() function." }, { "code": null, "e": 1768, "s": 1760, "text": "Syntax:" }, { "code": null, "e": 1839, "s": 1768, "text": "matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)\n" }, { "code": null, "e": 1848, "s": 1839, "text": "Example:" }, { "code": "x <- c(1, 2, 3, 4, 5, 6) # Create matrixmat <- matrix(x, nrow = 2) print(mat)print(class(mat))", "e": 1945, "s": 1848, "text": null }, { "code": null, "e": 1953, "s": 1945, "text": "Output:" }, { "code": null, "e": 2033, "s": 1953, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 3 5\n[2, ] 2 4 6\n\n[1] \"matrix\"\n" }, { "code": null, "e": 2120, "s": 2033, "text": "Factor object encodes a vector of unique elements (levels) from the given data vector." }, { "code": null, "e": 2129, "s": 2120, "text": "Example:" }, { "code": "# Create vectors <- c(\"spring\", \"autumn\", \"winter\", \"summer\", \"spring\", \"autumn\") print(factor(s))print(nlevels(factor(s)))", "e": 2254, "s": 2129, "text": null }, { "code": null, "e": 2262, "s": 2254, "text": "Output:" }, { "code": null, "e": 2351, "s": 2262, "text": "[1] spring autumn winter summer spring autumn\nLevels: autumn spring summer winter\n[1] 4\n" }, { "code": null, "e": 2540, "s": 2351, "text": "array() function is used to create n-dimensional array. This function takes dim attribute as an argument and creates required length of each dimension as specified in the attribute.Syntax:" }, { "code": null, "e": 2590, "s": 2540, "text": "array(data, dim = length(data), dimnames = NULL)\n" }, { "code": null, "e": 2599, "s": 2590, "text": "Example:" }, { "code": "# Create 3-dimensional array# and filling values by columnarr <- array(c(1, 2, 3), dim = c(3, 3, 3)) print(arr)", "e": 2712, "s": 2599, "text": null }, { "code": null, "e": 2720, "s": 2712, "text": "Output:" }, { "code": null, "e": 2995, "s": 2720, "text": ",, 1\n\n [, 1] [, 2] [, 3]\n[1, ] 1 1 1\n[2, ] 2 2 2\n[3, ] 3 3 3,, 2\n\n [, 1] [, 2] [, 3]\n[1, ] 1 1 1\n[2, ] 2 2 2\n[3, ] 3 3 3,, 3\n\n [, 1] [, 2] [, 3]\n[1, ] 1 1 1\n[2, ] 2 2 2\n[3, ] 3 3 3\n" }, { "code": null, "e": 3213, "s": 2995, "text": "Data frames are 2-dimensional tabular data object in R programming. Data frames consists of multiple columns and each column represents a vector. Columns in data frame can have different modes of data unlike matrices." }, { "code": null, "e": 3222, "s": 3213, "text": "Example:" }, { "code": "# Create vectorsx <- 1:5y <- LETTERS[1:5]z <- c(\"Albert\", \"Bob\", \"Charlie\", \"Denver\", \"Elie\") # Create data frame of vectorsdf <- data.frame(x, y, z) # Print data frameprint(df)", "e": 3402, "s": 3222, "text": null }, { "code": null, "e": 3410, "s": 3402, "text": "Output:" }, { "code": null, "e": 3495, "s": 3410, "text": " x y z\n1 1 A Albert\n2 2 B Bob\n3 3 C Charlie\n4 4 D Denver\n5 5 E Elie\n" }, { "code": null, "e": 3502, "s": 3495, "text": "Picked" }, { "code": null, "e": 3513, "s": 3502, "text": "R Language" } ]
Ruby/DBI - Database Access
This chapter teaches you how to access a database using Ruby. The Ruby DBI module provides a database-independent interface for Ruby scripts similar to that of the Perl DBI module. DBI stands for Database Independent Interface for Ruby, which means DBI provides an abstraction layer between the Ruby code and the underlying database, allowing you to switch database implementations really easily. It defines a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used. DBI can interface with the following − ADO (ActiveX Data Objects) DB2 Frontbase mSQL MySQL ODBC Oracle OCI8 (Oracle) PostgreSQL Proxy/Server SQLite SQLRelay DBI is independent of any database available in the backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architecture diagram. The general architecture for Ruby DBI uses two layers − The database interface (DBI) layer. This layer is database independent and provides a set of common access methods that are used the same way regardless of the type of database server with which you're communicating. The database interface (DBI) layer. This layer is database independent and provides a set of common access methods that are used the same way regardless of the type of database server with which you're communicating. The database driver (DBD) layer. This layer is database dependent; different drivers provide access to different database engines. There is one driver for MySQL, another for PostgreSQL, another for InterBase, another for Oracle, and so forth. Each driver interprets requests from the DBI layer and maps them onto requests appropriate for a given type of database server. The database driver (DBD) layer. This layer is database dependent; different drivers provide access to different database engines. There is one driver for MySQL, another for PostgreSQL, another for InterBase, another for Oracle, and so forth. Each driver interprets requests from the DBI layer and maps them onto requests appropriate for a given type of database server. If you want to write Ruby scripts to access MySQL databases, you'll need to have the Ruby MySQL module installed. This module acts as a DBD as explained above and can be downloaded from https://www.tmtm.org/en/mysql/ruby/ You can install ruby DBI using the Ruby Gems packaging manager: gem install dbi Before starting this installation make sure you have the root privilege. Now, follow the steps given below − $ tar zxf dbi-0.2.0.tar.gz Go in distribution directory dbi-0.2.0 nd configure it using the setup.rb script in that directory. The most general configuration command looks like this, with no arguments following the config argument. This command configures the distribution to install all drivers by default. $ ruby setup.rb config To be more specific, provide a --with option that lists the particular parts of the distribution you want to use. For example, to configure only the main DBI module and the MySQL DBD-level driver, issue the following command − $ ruby setup.rb config --with = dbi,dbd_mysql Final step is to build the driver and install it using the following commands − $ ruby setup.rb setup $ ruby setup.rb install Assuming we are going to work with MySQL database, before connecting to a database make sure of the following − You have created a database TESTDB. You have created a database TESTDB. You have created EMPLOYEE in TESTDB. You have created EMPLOYEE in TESTDB. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. User ID "testuser" and password "test123" are set to access TESTDB. Ruby Module DBI is installed properly on your machine. Ruby Module DBI is installed properly on your machine. You have gone through MySQL tutorial to understand MySQL Basics. You have gone through MySQL tutorial to understand MySQL Basics. Following is the example of connecting with MySQL database "TESTDB" #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") # get server version string and display it row = dbh.select_one("SELECT VERSION()") puts "Server version: " + row[0] rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" ensure # disconnect from server dbh.disconnect if dbh end While running this script, it produces the following result at our Linux machine. Server version: 5.0.45 If a connection is established with the data source, then a Database Handle is returned and saved into dbh for further use otherwise dbh is set to nil value and e.err and e::errstr return error code and an error string respectively. Finally, before coming out it, ensure that database connection is closed and resources are released. INSERT operation is required when you want to create your records into a database table. Once a database connection is established, we are ready to create tables or records into the database tables using do method or prepare and execute method. Statements that do not return rows can be issued by invoking the do database handle method. This method takes a statement string argument and returns a count of the number of rows affected by the statement. dbh.do("DROP TABLE IF EXISTS EMPLOYEE") dbh.do("CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )" ); Similarly, you can execute the SQL INSERT statement to create a record into the EMPLOYEE table. #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") dbh.do( "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)" ) puts "Record has been created" dbh.commit rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" dbh.rollback ensure # disconnect from server dbh.disconnect if dbh end You can use prepare and execute methods of DBI class to execute the SQL statement through Ruby code. Record creation takes the following steps − Preparing SQL statement with INSERT statement. This will be done using the prepare method. Preparing SQL statement with INSERT statement. This will be done using the prepare method. Executing SQL query to select all the results from the database. This will be done using the execute method. Executing SQL query to select all the results from the database. This will be done using the execute method. Releasing Statement handle. This will be done using finish API Releasing Statement handle. This will be done using finish API If everything goes fine, then commit this operation otherwise you can rollback the complete transaction. If everything goes fine, then commit this operation otherwise you can rollback the complete transaction. Following is the syntax to use these two methods − sth = dbh.prepare(statement) sth.execute ... zero or more SQL operations ... sth.finish These two methods can be used to pass bind values to SQL statements. There may be a case when values to be entered is not given in advance. In such a case, binding values are used. A question mark (?) is used in place of actual values and then actual values are passed through execute() API. Following is the example to create two records in the EMPLOYEE table − #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") sth = dbh.prepare( "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (?, ?, ?, ?, ?)" ) sth.execute('John', 'Poul', 25, 'M', 2300) sth.execute('Zara', 'Ali', 17, 'F', 1000) sth.finish dbh.commit puts "Record has been created" rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" dbh.rollback ensure # disconnect from server dbh.disconnect if dbh end If there are multiple INSERTs at a time, then preparing a statement first and then executing it multiple times within a loop is more efficient than invoking do each time through the loop. READ Operation on any database means to fetch some useful information from the database. Once our database connection is established, we are ready to make a query into this database. We can use either do method or prepare and execute methods to fetch values from a database table. Record fetching takes following steps − Preparing SQL query based on required conditions. This will be done using the prepare method. Preparing SQL query based on required conditions. This will be done using the prepare method. Executing SQL query to select all the results from the database. This will be done using the execute method. Executing SQL query to select all the results from the database. This will be done using the execute method. Fetching all the results one by one and printing those results. This will be done using the fetch method. Fetching all the results one by one and printing those results. This will be done using the fetch method. Releasing Statement handle. This will be done using the finish method. Releasing Statement handle. This will be done using the finish method. Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000. #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") sth = dbh.prepare("SELECT * FROM EMPLOYEE WHERE INCOME > ?") sth.execute(1000) sth.fetch do |row| printf "First Name: %s, Last Name : %s\n", row[0], row[1] printf "Age: %d, Sex : %s\n", row[2], row[3] printf "Salary :%d \n\n", row[4] end sth.finish rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" ensure # disconnect from server dbh.disconnect if dbh end This will produce the following result − First Name: Mac, Last Name : Mohan Age: 20, Sex : M Salary :2000 First Name: John, Last Name : Poul Age: 25, Sex : M Salary :2300 There are more short cut methods to fetch records from the database. If you are interested then go through the Fetching the Result otherwise proceed to the next section. UPDATE Operation on any database means to update one or more records, which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here, we will increase AGE of all the males by one year. This will take three steps − Preparing SQL query based on required conditions. This will be done using the prepare method. Preparing SQL query based on required conditions. This will be done using the prepare method. Executing SQL query to select all the results from the database. This will be done using the execute method. Executing SQL query to select all the results from the database. This will be done using the execute method. Releasing Statement handle. This will be done using the finish method. Releasing Statement handle. This will be done using the finish method. If everything goes fine then commit this operation otherwise you can rollback the complete transaction. If everything goes fine then commit this operation otherwise you can rollback the complete transaction. #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") sth = dbh.prepare("UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ?") sth.execute('M') sth.finish dbh.commit rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" dbh.rollback ensure # disconnect from server dbh.disconnect if dbh end DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. This operation will take following steps. Preparing SQL query based on required conditions. This will be done using the prepare method. Preparing SQL query based on required conditions. This will be done using the prepare method. Executing SQL query to delete required records from the database. This will be done using the execute method. Executing SQL query to delete required records from the database. This will be done using the execute method. Releasing Statement handle. This will be done using the finish method. Releasing Statement handle. This will be done using the finish method. If everything goes fine then commit this operation otherwise you can rollback the complete transaction. If everything goes fine then commit this operation otherwise you can rollback the complete transaction. #!/usr/bin/ruby -w require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") sth = dbh.prepare("DELETE FROM EMPLOYEE WHERE AGE > ?") sth.execute(20) sth.finish dbh.commit rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" dbh.rollback ensure # disconnect from server dbh.disconnect if dbh end Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties − Atomicity − Either a transaction completes or nothing happens at all. Atomicity − Either a transaction completes or nothing happens at all. Consistency − A transaction must start in a consistent state and leave the system is a consistent state. Consistency − A transaction must start in a consistent state and leave the system is a consistent state. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. The DBI provides two methods to either commit or rollback a transaction. There is one more method called transaction which can be used to implement transactions. There are two simple approaches to implement transactions − The first approach uses DBI's commit and rollback methods to explicitly commit or cancel the transaction − dbh['AutoCommit'] = false # Set auto commit to false. begin dbh.do("UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'") dbh.do("UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'") dbh.commit rescue puts "transaction failed" dbh.rollback end dbh['AutoCommit'] = true The second approach uses the transaction method. This is simpler, because it takes a code block containing the statements that make up the transaction. The transaction method executes the block, then invokes commit or rollback automatically, depending on whether the block succeeds or fails − dbh['AutoCommit'] = false # Set auto commit to false. dbh.transaction do |dbh| dbh.do("UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'") dbh.do("UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'") end dbh['AutoCommit'] = true Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back. Here is a simple example to call the commit method. dbh.commit If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use the rollback method. Here is a simple example to call the rollback method. dbh.rollback To disconnect Database connection, use disconnect API. dbh.disconnect If the connection to a database is closed by the user with the disconnect method, any outstanding transactions are rolled back by the DBI. However, instead of depending on any of DBI's implementation details, your application would be better off calling the commit or rollback explicitly. There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle. If a DBI method fails, DBI raises an exception. DBI methods may raise any of several types of exception but the two most important exception classes are DBI::InterfaceError and DBI::DatabaseError. Exception objects of these classes have three attributes named err, errstr, and state, which represent the error number, a descriptive error string, and a standard error code. The attributes are explained below − err − Returns an integer representation of the occurred error or nil if this is not supported by the DBD.The Oracle DBD for example returns the numerical part of an ORA-XXXX error message. err − Returns an integer representation of the occurred error or nil if this is not supported by the DBD.The Oracle DBD for example returns the numerical part of an ORA-XXXX error message. errstr − Returns a string representation of the occurred error. errstr − Returns a string representation of the occurred error. state − Returns the SQLSTATE code of the occurred error.The SQLSTATE is a five-character-long string. Most DBDs do not support this and return nil instead. state − Returns the SQLSTATE code of the occurred error.The SQLSTATE is a five-character-long string. Most DBDs do not support this and return nil instead. You have seen following code above in most of the examples − rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" dbh.rollback ensure # disconnect from server dbh.disconnect if dbh end To get debugging information about what your script is doing as it executes, you can enable tracing. To do this, you must first load the dbi/trace module and then call the trace method that controls the trace mode and output destination − require "dbi/trace" .............. trace(mode, destination) The mode value may be 0 (off), 1, 2, or 3, and the destination should be an IO object. The default values are 2 and STDERR, respectively. There are some methods that create handles. These methods can be invoked with a code block. The advantage of using code block along with methods is that they provide the handle to the code block as its parameter and automatically cleans up the handle when the block terminates. There are few examples to understand the concept. DBI.connect − This method generates a database handle and it is recommended to call disconnect at the end of the block to disconnect the database. DBI.connect − This method generates a database handle and it is recommended to call disconnect at the end of the block to disconnect the database. dbh.prepare − This method generates a statement handle and it is recommended to finish at the end of the block. Within the block, you must invoke execute method to execute the statement. dbh.prepare − This method generates a statement handle and it is recommended to finish at the end of the block. Within the block, you must invoke execute method to execute the statement. dbh.execute − This method is similar except we don't need to invoke execute within the block. The statement handle is automatically executed. dbh.execute − This method is similar except we don't need to invoke execute within the block. The statement handle is automatically executed. DBI.connect can take a code block, passes the database handle to it, and automatically disconnects the handle at the end of the block as follows. dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") do |dbh| dbh.prepare can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows. dbh.prepare("SHOW DATABASES") do |sth| sth.execute puts "Databases: " + sth.fetch_all.join(", ") end dbh.execute can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows − dbh.execute("SHOW DATABASES") do |sth| puts "Databases: " + sth.fetch_all.join(", ") end DBI transaction method also takes a code block which has been described in above. The DBI lets the database drivers provide additional database-specific functions, which can be called by the user through the func method of any Handle object. Driver-specific attributes are supported and can be set or gotten using the []= or [] methods. dbh.func(:createdb, db_name) Creates a new database. dbh.func(:dropdb, db_name) Drops a database. dbh.func(:reload) Performs a reload operation. dbh.func(:shutdown) Shuts down the server. dbh.func(:insert_id) => Fixnum Returns the most recent AUTO_INCREMENT value for a connection. dbh.func(:client_info) => String Returns MySQL client information in terms of version. dbh.func(:client_version) => Fixnum Returns client information in terms of version. It's similar to :client_info but it return a fixnum instead of sting. dbh.func(:host_info) => String Returns host information. dbh.func(:proto_info) => Fixnum Returns protocol being used for the communication. dbh.func(:server_info) => String Returns MySQL server information in terms of version. dbh.func(:stat) => String Returns current state of the database. dbh.func(:thread_id) => Fixnum Returns current thread ID. #!/usr/bin/ruby require "dbi" begin # connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") puts dbh.func(:client_info) puts dbh.func(:client_version) puts dbh.func(:host_info) puts dbh.func(:proto_info) puts dbh.func(:server_info) puts dbh.func(:thread_id) puts dbh.func(:stat) rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" ensure dbh.disconnect if dbh end This will produce the following result − 5.0.45 50045 Localhost via UNIX socket 10 5.0.45 150621 Uptime: 384981 Threads: 1 Questions: 1101078 Slow queries: 4 \ Opens: 324 Flush tables: 1 Open tables: 64 \ Queries per second avg: 2.860
[ { "code": null, "e": 2609, "s": 2428, "text": "This chapter teaches you how to access a database using Ruby. The Ruby DBI module provides a database-independent interface for Ruby scripts similar to that of the Perl DBI module." }, { "code": null, "e": 2974, "s": 2609, "text": "DBI stands for Database Independent Interface for Ruby, which means DBI provides an abstraction layer between the Ruby code and the underlying database, allowing you to switch database implementations really easily. It defines a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used." }, { "code": null, "e": 3013, "s": 2974, "text": "DBI can interface with the following −" }, { "code": null, "e": 3040, "s": 3013, "text": "ADO (ActiveX Data Objects)" }, { "code": null, "e": 3044, "s": 3040, "text": "DB2" }, { "code": null, "e": 3054, "s": 3044, "text": "Frontbase" }, { "code": null, "e": 3059, "s": 3054, "text": "mSQL" }, { "code": null, "e": 3065, "s": 3059, "text": "MySQL" }, { "code": null, "e": 3070, "s": 3065, "text": "ODBC" }, { "code": null, "e": 3077, "s": 3070, "text": "Oracle" }, { "code": null, "e": 3091, "s": 3077, "text": "OCI8 (Oracle)" }, { "code": null, "e": 3102, "s": 3091, "text": "PostgreSQL" }, { "code": null, "e": 3115, "s": 3102, "text": "Proxy/Server" }, { "code": null, "e": 3122, "s": 3115, "text": "SQLite" }, { "code": null, "e": 3131, "s": 3122, "text": "SQLRelay" }, { "code": null, "e": 3324, "s": 3131, "text": "DBI is independent of any database available in the backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architecture diagram." }, { "code": null, "e": 3380, "s": 3324, "text": "The general architecture for Ruby DBI uses two layers −" }, { "code": null, "e": 3597, "s": 3380, "text": "The database interface (DBI) layer. This layer is database independent and provides a set of common access methods that are used the same way regardless of the type of database server with which you're communicating." }, { "code": null, "e": 3814, "s": 3597, "text": "The database interface (DBI) layer. This layer is database independent and provides a set of common access methods that are used the same way regardless of the type of database server with which you're communicating." }, { "code": null, "e": 4185, "s": 3814, "text": "The database driver (DBD) layer. This layer is database dependent; different drivers provide access to different database engines. There is one driver for MySQL, another for PostgreSQL, another for InterBase, another for Oracle, and so forth. Each driver interprets requests from the DBI layer and maps them onto requests appropriate for a given type of database server." }, { "code": null, "e": 4556, "s": 4185, "text": "The database driver (DBD) layer. This layer is database dependent; different drivers provide access to different database engines. There is one driver for MySQL, another for PostgreSQL, another for InterBase, another for Oracle, and so forth. Each driver interprets requests from the DBI layer and maps them onto requests appropriate for a given type of database server." }, { "code": null, "e": 4670, "s": 4556, "text": "If you want to write Ruby scripts to access MySQL databases, you'll need to have the Ruby MySQL module installed." }, { "code": null, "e": 4778, "s": 4670, "text": "This module acts as a DBD as explained above and can be downloaded from https://www.tmtm.org/en/mysql/ruby/" }, { "code": null, "e": 4842, "s": 4778, "text": "You can install ruby DBI using the Ruby Gems packaging manager:" }, { "code": null, "e": 4859, "s": 4842, "text": "gem install dbi\n" }, { "code": null, "e": 4968, "s": 4859, "text": "Before starting this installation make sure you have the root privilege. Now, follow the steps given below −" }, { "code": null, "e": 4996, "s": 4968, "text": "$ tar zxf dbi-0.2.0.tar.gz\n" }, { "code": null, "e": 5277, "s": 4996, "text": "Go in distribution directory dbi-0.2.0 nd configure it using the setup.rb script in that directory. The most general configuration command looks like this, with no arguments following the config argument. This command configures the distribution to install all drivers by default." }, { "code": null, "e": 5301, "s": 5277, "text": "$ ruby setup.rb config\n" }, { "code": null, "e": 5528, "s": 5301, "text": "To be more specific, provide a --with option that lists the particular parts of the distribution you want to use. For example, to configure only the main DBI module and the MySQL DBD-level driver, issue the following command −" }, { "code": null, "e": 5575, "s": 5528, "text": "$ ruby setup.rb config --with = dbi,dbd_mysql\n" }, { "code": null, "e": 5655, "s": 5575, "text": "Final step is to build the driver and install it using the following commands −" }, { "code": null, "e": 5702, "s": 5655, "text": "$ ruby setup.rb setup\n$ ruby setup.rb install\n" }, { "code": null, "e": 5814, "s": 5702, "text": "Assuming we are going to work with MySQL database, before connecting to a database make sure of the following −" }, { "code": null, "e": 5850, "s": 5814, "text": "You have created a database TESTDB." }, { "code": null, "e": 5886, "s": 5850, "text": "You have created a database TESTDB." }, { "code": null, "e": 5923, "s": 5886, "text": "You have created EMPLOYEE in TESTDB." }, { "code": null, "e": 5960, "s": 5923, "text": "You have created EMPLOYEE in TESTDB." }, { "code": null, "e": 6033, "s": 5960, "text": "This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME." }, { "code": null, "e": 6106, "s": 6033, "text": "This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME." }, { "code": null, "e": 6174, "s": 6106, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 6242, "s": 6174, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 6297, "s": 6242, "text": "Ruby Module DBI is installed properly on your machine." }, { "code": null, "e": 6352, "s": 6297, "text": "Ruby Module DBI is installed properly on your machine." }, { "code": null, "e": 6417, "s": 6352, "text": "You have gone through MySQL tutorial to understand MySQL Basics." }, { "code": null, "e": 6482, "s": 6417, "text": "You have gone through MySQL tutorial to understand MySQL Basics." }, { "code": null, "e": 6550, "s": 6482, "text": "Following is the example of connecting with MySQL database \"TESTDB\"" }, { "code": null, "e": 7018, "s": 6550, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n # get server version string and display it\n row = dbh.select_one(\"SELECT VERSION()\")\n puts \"Server version: \" + row[0]\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 7100, "s": 7018, "text": "While running this script, it produces the following result at our Linux machine." }, { "code": null, "e": 7124, "s": 7100, "text": "Server version: 5.0.45\n" }, { "code": null, "e": 7357, "s": 7124, "text": "If a connection is established with the data source, then a Database Handle is returned and saved into dbh for further use otherwise dbh is set to nil value and e.err and e::errstr return error code and an error string respectively." }, { "code": null, "e": 7458, "s": 7357, "text": "Finally, before coming out it, ensure that database connection is closed and resources are released." }, { "code": null, "e": 7547, "s": 7458, "text": "INSERT operation is required when you want to create your records into a database table." }, { "code": null, "e": 7703, "s": 7547, "text": "Once a database connection is established, we are ready to create tables or records into the database tables using do method or prepare and execute method." }, { "code": null, "e": 7910, "s": 7703, "text": "Statements that do not return rows can be issued by invoking the do database handle method. This method takes a statement string argument and returns a count of the number of rows affected by the statement." }, { "code": null, "e": 8092, "s": 7910, "text": "dbh.do(\"DROP TABLE IF EXISTS EMPLOYEE\")\ndbh.do(\"CREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT, \n SEX CHAR(1),\n INCOME FLOAT )\" );" }, { "code": null, "e": 8188, "s": 8092, "text": "Similarly, you can execute the SQL INSERT statement to create a record into the EMPLOYEE table." }, { "code": null, "e": 8716, "s": 8188, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n dbh.do( \"INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)\n VALUES ('Mac', 'Mohan', 20, 'M', 2000)\" )\n puts \"Record has been created\"\n dbh.commit\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n dbh.rollback\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 8817, "s": 8716, "text": "You can use prepare and execute methods of DBI class to execute the SQL statement through Ruby code." }, { "code": null, "e": 8861, "s": 8817, "text": "Record creation takes the following steps −" }, { "code": null, "e": 8952, "s": 8861, "text": "Preparing SQL statement with INSERT statement. This will be done using the prepare method." }, { "code": null, "e": 9043, "s": 8952, "text": "Preparing SQL statement with INSERT statement. This will be done using the prepare method." }, { "code": null, "e": 9152, "s": 9043, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 9261, "s": 9152, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 9324, "s": 9261, "text": "Releasing Statement handle. This will be done using finish API" }, { "code": null, "e": 9387, "s": 9324, "text": "Releasing Statement handle. This will be done using finish API" }, { "code": null, "e": 9492, "s": 9387, "text": "If everything goes fine, then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 9597, "s": 9492, "text": "If everything goes fine, then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 9648, "s": 9597, "text": "Following is the syntax to use these two methods −" }, { "code": null, "e": 9740, "s": 9648, "text": "sth = dbh.prepare(statement)\nsth.execute\n ... zero or more SQL operations ...\nsth.finish\n" }, { "code": null, "e": 10032, "s": 9740, "text": "These two methods can be used to pass bind values to SQL statements. There may be a case when values to be entered is not given in advance. In such a case, binding values are used. A question mark (?) is used in place of actual values and then actual values are passed through execute() API." }, { "code": null, "e": 10103, "s": 10032, "text": "Following is the example to create two records in the EMPLOYEE table −" }, { "code": null, "e": 10731, "s": 10103, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n sth = dbh.prepare( \"INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)\n VALUES (?, ?, ?, ?, ?)\" )\n sth.execute('John', 'Poul', 25, 'M', 2300)\n sth.execute('Zara', 'Ali', 17, 'F', 1000)\n sth.finish\n dbh.commit\n puts \"Record has been created\"\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n dbh.rollback\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 10919, "s": 10731, "text": "If there are multiple INSERTs at a time, then preparing a statement first and then executing it multiple times within a loop is more efficient than invoking do each time through the loop." }, { "code": null, "e": 11008, "s": 10919, "text": "READ Operation on any database means to fetch some useful information from the database." }, { "code": null, "e": 11200, "s": 11008, "text": "Once our database connection is established, we are ready to make a query into this database. We can use either do method or prepare and execute methods to fetch values from a database table." }, { "code": null, "e": 11240, "s": 11200, "text": "Record fetching takes following steps −" }, { "code": null, "e": 11334, "s": 11240, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 11428, "s": 11334, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 11537, "s": 11428, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 11646, "s": 11537, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 11752, "s": 11646, "text": "Fetching all the results one by one and printing those results. This will be done using the fetch method." }, { "code": null, "e": 11858, "s": 11752, "text": "Fetching all the results one by one and printing those results. This will be done using the fetch method." }, { "code": null, "e": 11929, "s": 11858, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 12000, "s": 11929, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 12102, "s": 12000, "text": "Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000." }, { "code": null, "e": 12715, "s": 12102, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n sth = dbh.prepare(\"SELECT * FROM EMPLOYEE WHERE INCOME > ?\")\n sth.execute(1000)\n\n sth.fetch do |row|\n printf \"First Name: %s, Last Name : %s\\n\", row[0], row[1]\n printf \"Age: %d, Sex : %s\\n\", row[2], row[3]\n printf \"Salary :%d \\n\\n\", row[4]\nend\n sth.finish\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 12756, "s": 12715, "text": "This will produce the following result −" }, { "code": null, "e": 12888, "s": 12756, "text": "First Name: Mac, Last Name : Mohan\nAge: 20, Sex : M\nSalary :2000\n\nFirst Name: John, Last Name : Poul\nAge: 25, Sex : M\nSalary :2300\n" }, { "code": null, "e": 13058, "s": 12888, "text": "There are more short cut methods to fetch records from the database. If you are interested then go through the Fetching the Result otherwise proceed to the next section." }, { "code": null, "e": 13331, "s": 13058, "text": "UPDATE Operation on any database means to update one or more records, which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here, we will increase AGE of all the males by one year. This will take three steps −" }, { "code": null, "e": 13425, "s": 13331, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 13519, "s": 13425, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 13628, "s": 13519, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 13737, "s": 13628, "text": "Executing SQL query to select all the results from the database. This will be done using the execute method." }, { "code": null, "e": 13808, "s": 13737, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 13879, "s": 13808, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 13983, "s": 13879, "text": "If everything goes fine then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 14087, "s": 13983, "text": "If everything goes fine then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 14565, "s": 14087, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n sth = dbh.prepare(\"UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ?\")\n sth.execute('M')\n sth.finish\n dbh.commit\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n dbh.rollback\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 14787, "s": 14565, "text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. This operation will take following steps." }, { "code": null, "e": 14881, "s": 14787, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 14975, "s": 14881, "text": "Preparing SQL query based on required conditions. This will be done using the prepare method." }, { "code": null, "e": 15085, "s": 14975, "text": "Executing SQL query to delete required records from the database. This will be done using the execute method." }, { "code": null, "e": 15195, "s": 15085, "text": "Executing SQL query to delete required records from the database. This will be done using the execute method." }, { "code": null, "e": 15266, "s": 15195, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 15337, "s": 15266, "text": "Releasing Statement handle. This will be done using the finish method." }, { "code": null, "e": 15441, "s": 15337, "text": "If everything goes fine then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 15545, "s": 15441, "text": "If everything goes fine then commit this operation otherwise you can rollback the complete transaction." }, { "code": null, "e": 16009, "s": 15545, "text": "#!/usr/bin/ruby -w\n\nrequire \"dbi\"\n\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\")\n sth = dbh.prepare(\"DELETE FROM EMPLOYEE WHERE AGE > ?\")\n sth.execute(20)\n sth.finish\n dbh.commit\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n dbh.rollback\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 16126, "s": 16009, "text": "Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties −" }, { "code": null, "e": 16196, "s": 16126, "text": "Atomicity − Either a transaction completes or nothing happens at all." }, { "code": null, "e": 16266, "s": 16196, "text": "Atomicity − Either a transaction completes or nothing happens at all." }, { "code": null, "e": 16371, "s": 16266, "text": "Consistency − A transaction must start in a consistent state and leave the system is a consistent state." }, { "code": null, "e": 16476, "s": 16371, "text": "Consistency − A transaction must start in a consistent state and leave the system is a consistent state." }, { "code": null, "e": 16575, "s": 16476, "text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction." }, { "code": null, "e": 16674, "s": 16575, "text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction." }, { "code": null, "e": 16778, "s": 16674, "text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure." }, { "code": null, "e": 16882, "s": 16778, "text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure." }, { "code": null, "e": 17104, "s": 16882, "text": "The DBI provides two methods to either commit or rollback a transaction. There is one more method called transaction which can be used to implement transactions. There are two simple approaches to implement transactions −" }, { "code": null, "e": 17211, "s": 17104, "text": "The first approach uses DBI's commit and rollback methods to explicitly commit or cancel the transaction −" }, { "code": null, "e": 17508, "s": 17211, "text": "dbh['AutoCommit'] = false # Set auto commit to false.\nbegin\n dbh.do(\"UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'\")\n dbh.do(\"UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'\")\n dbh.commit\nrescue\n puts \"transaction failed\"\n dbh.rollback\nend\ndbh['AutoCommit'] = true" }, { "code": null, "e": 17801, "s": 17508, "text": "The second approach uses the transaction method. This is simpler, because it takes a code block containing the statements that make up the transaction. The transaction method executes the block, then invokes commit or rollback automatically, depending on whether the block succeeds or fails −" }, { "code": null, "e": 18051, "s": 17801, "text": "dbh['AutoCommit'] = false # Set auto commit to false.\ndbh.transaction do |dbh|\n dbh.do(\"UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'\")\n dbh.do(\"UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'\")\nend\ndbh['AutoCommit'] = true" }, { "code": null, "e": 18198, "s": 18051, "text": "Commit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back." }, { "code": null, "e": 18250, "s": 18198, "text": "Here is a simple example to call the commit method." }, { "code": null, "e": 18261, "s": 18250, "text": "dbh.commit" }, { "code": null, "e": 18402, "s": 18261, "text": "If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use the rollback method." }, { "code": null, "e": 18456, "s": 18402, "text": "Here is a simple example to call the rollback method." }, { "code": null, "e": 18469, "s": 18456, "text": "dbh.rollback" }, { "code": null, "e": 18524, "s": 18469, "text": "To disconnect Database connection, use disconnect API." }, { "code": null, "e": 18539, "s": 18524, "text": "dbh.disconnect" }, { "code": null, "e": 18828, "s": 18539, "text": "If the connection to a database is closed by the user with the disconnect method, any outstanding transactions are rolled back by the DBI. However, instead of depending on any of DBI's implementation details, your application would be better off calling the commit or rollback explicitly." }, { "code": null, "e": 19030, "s": 18828, "text": "There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle." }, { "code": null, "e": 19227, "s": 19030, "text": "If a DBI method fails, DBI raises an exception. DBI methods may raise any of several types of exception but the two most important exception classes are DBI::InterfaceError and DBI::DatabaseError." }, { "code": null, "e": 19440, "s": 19227, "text": "Exception objects of these classes have three attributes named err, errstr, and state, which represent the error number, a descriptive error string, and a standard error code. The attributes are explained below −" }, { "code": null, "e": 19629, "s": 19440, "text": "err − Returns an integer representation of the occurred error or nil if this is not supported by the DBD.The Oracle DBD for example returns the numerical part of an ORA-XXXX error message." }, { "code": null, "e": 19818, "s": 19629, "text": "err − Returns an integer representation of the occurred error or nil if this is not supported by the DBD.The Oracle DBD for example returns the numerical part of an ORA-XXXX error message." }, { "code": null, "e": 19882, "s": 19818, "text": "errstr − Returns a string representation of the occurred error." }, { "code": null, "e": 19946, "s": 19882, "text": "errstr − Returns a string representation of the occurred error." }, { "code": null, "e": 20102, "s": 19946, "text": "state − Returns the SQLSTATE code of the occurred error.The SQLSTATE is a five-character-long string. Most DBDs do not support this and return nil instead." }, { "code": null, "e": 20258, "s": 20102, "text": "state − Returns the SQLSTATE code of the occurred error.The SQLSTATE is a five-character-long string. Most DBDs do not support this and return nil instead." }, { "code": null, "e": 20319, "s": 20258, "text": "You have seen following code above in most of the examples −" }, { "code": null, "e": 20529, "s": 20319, "text": "rescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\n dbh.rollback\nensure\n # disconnect from server\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 20768, "s": 20529, "text": "To get debugging information about what your script is doing as it executes, you can enable tracing. To do this, you must first load the dbi/trace module and then call the trace method that controls the trace mode and output destination −" }, { "code": null, "e": 20829, "s": 20768, "text": "require \"dbi/trace\"\n..............\n\ntrace(mode, destination)" }, { "code": null, "e": 20967, "s": 20829, "text": "The mode value may be 0 (off), 1, 2, or 3, and the destination should be an IO object. The default values are 2 and STDERR, respectively." }, { "code": null, "e": 21295, "s": 20967, "text": "There are some methods that create handles. These methods can be invoked with a code block. The advantage of using code block along with methods is that they provide the handle to the code block as its parameter and automatically cleans up the handle when the block terminates. There are few examples to understand the concept." }, { "code": null, "e": 21442, "s": 21295, "text": "DBI.connect − This method generates a database handle and it is recommended to call disconnect at the end of the block to disconnect the database." }, { "code": null, "e": 21589, "s": 21442, "text": "DBI.connect − This method generates a database handle and it is recommended to call disconnect at the end of the block to disconnect the database." }, { "code": null, "e": 21776, "s": 21589, "text": "dbh.prepare − This method generates a statement handle and it is recommended to finish at the end of the block. Within the block, you must invoke execute method to execute the statement." }, { "code": null, "e": 21963, "s": 21776, "text": "dbh.prepare − This method generates a statement handle and it is recommended to finish at the end of the block. Within the block, you must invoke execute method to execute the statement." }, { "code": null, "e": 22105, "s": 21963, "text": "dbh.execute − This method is similar except we don't need to invoke execute within the block. The statement handle is automatically executed." }, { "code": null, "e": 22247, "s": 22105, "text": "dbh.execute − This method is similar except we don't need to invoke execute within the block. The statement handle is automatically executed." }, { "code": null, "e": 22393, "s": 22247, "text": "DBI.connect can take a code block, passes the database handle to it, and automatically disconnects the handle at the end of the block as follows." }, { "code": null, "e": 22473, "s": 22393, "text": "dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\") do |dbh|" }, { "code": null, "e": 22610, "s": 22473, "text": "dbh.prepare can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows." }, { "code": null, "e": 22717, "s": 22610, "text": "dbh.prepare(\"SHOW DATABASES\") do |sth|\n sth.execute\n puts \"Databases: \" + sth.fetch_all.join(\", \")\nend" }, { "code": null, "e": 22855, "s": 22717, "text": "dbh.execute can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows −" }, { "code": null, "e": 22947, "s": 22855, "text": "dbh.execute(\"SHOW DATABASES\") do |sth|\n puts \"Databases: \" + sth.fetch_all.join(\", \")\nend" }, { "code": null, "e": 23029, "s": 22947, "text": "DBI transaction method also takes a code block which has been described in above." }, { "code": null, "e": 23189, "s": 23029, "text": "The DBI lets the database drivers provide additional database-specific functions, which can be called by the user through the func method of any Handle object." }, { "code": null, "e": 23284, "s": 23189, "text": "Driver-specific attributes are supported and can be set or gotten using the []= or [] methods." }, { "code": null, "e": 23313, "s": 23284, "text": "dbh.func(:createdb, db_name)" }, { "code": null, "e": 23337, "s": 23313, "text": "Creates a new database." }, { "code": null, "e": 23364, "s": 23337, "text": "dbh.func(:dropdb, db_name)" }, { "code": null, "e": 23382, "s": 23364, "text": "Drops a database." }, { "code": null, "e": 23400, "s": 23382, "text": "dbh.func(:reload)" }, { "code": null, "e": 23429, "s": 23400, "text": "Performs a reload operation." }, { "code": null, "e": 23449, "s": 23429, "text": "dbh.func(:shutdown)" }, { "code": null, "e": 23472, "s": 23449, "text": "Shuts down the server." }, { "code": null, "e": 23503, "s": 23472, "text": "dbh.func(:insert_id) => Fixnum" }, { "code": null, "e": 23566, "s": 23503, "text": "Returns the most recent AUTO_INCREMENT value for a connection." }, { "code": null, "e": 23599, "s": 23566, "text": "dbh.func(:client_info) => String" }, { "code": null, "e": 23653, "s": 23599, "text": "Returns MySQL client information in terms of version." }, { "code": null, "e": 23689, "s": 23653, "text": "dbh.func(:client_version) => Fixnum" }, { "code": null, "e": 23807, "s": 23689, "text": "Returns client information in terms of version. It's similar to :client_info but it return a fixnum instead of sting." }, { "code": null, "e": 23838, "s": 23807, "text": "dbh.func(:host_info) => String" }, { "code": null, "e": 23864, "s": 23838, "text": "Returns host information." }, { "code": null, "e": 23896, "s": 23864, "text": "dbh.func(:proto_info) => Fixnum" }, { "code": null, "e": 23947, "s": 23896, "text": "Returns protocol being used for the communication." }, { "code": null, "e": 23980, "s": 23947, "text": "dbh.func(:server_info) => String" }, { "code": null, "e": 24034, "s": 23980, "text": "Returns MySQL server information in terms of version." }, { "code": null, "e": 24060, "s": 24034, "text": "dbh.func(:stat) => String" }, { "code": null, "e": 24099, "s": 24060, "text": "Returns current state of the database." }, { "code": null, "e": 24130, "s": 24099, "text": "dbh.func(:thread_id) => Fixnum" }, { "code": null, "e": 24157, "s": 24130, "text": "Returns current thread ID." }, { "code": null, "e": 24676, "s": 24157, "text": "#!/usr/bin/ruby\n\nrequire \"dbi\"\nbegin\n # connect to the MySQL server\n dbh = DBI.connect(\"DBI:Mysql:TESTDB:localhost\", \"testuser\", \"test123\") \n puts dbh.func(:client_info)\n puts dbh.func(:client_version)\n puts dbh.func(:host_info)\n puts dbh.func(:proto_info)\n puts dbh.func(:server_info)\n puts dbh.func(:thread_id)\n puts dbh.func(:stat)\nrescue DBI::DatabaseError => e\n puts \"An error occurred\"\n puts \"Error code: #{e.err}\"\n puts \"Error message: #{e.errstr}\"\nensure\n dbh.disconnect if dbh\nend" }, { "code": null, "e": 24717, "s": 24676, "text": "This will produce the following result −" } ]
Is Python call by reference or call by value
19 Apr, 2021 Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function. Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function.Example 1: Python3 # Python code to demonstrate# call by value string = "Geeks" def test(string): string = "GeeksforGeeks" print("Inside Function:", string) # Driver's codetest(string)print("Outside Function:", string) Output Inside Function: GeeksforGeeks Outside Function: Geeks Example 2 Python3 # Python code to demonstrate# call by reference def add_more(list): list.append(50) print("Inside Function", list) # Driver's codemylist = [10,20,30,40] add_more(mylist)print("Outside Function:", mylist) Output Inside Function [10, 20, 30, 40, 50] Outside Function: [10, 20, 30, 40, 50] In python, each variable to which we assign a value/container is treated as an object. When we are assigning a value to a variable, we are actually binding a name to an object. Python3 a = "first"b = "first" # Returns the actual location# where the variable is storedprint(id(a)) # Returns the actual location# where the variable is storedprint(id(b)) # Returns true if both the variables# are stored in same locationprint(a is b) Output 110001234557894 110001234557894 True Now, let’s try and understand this better with another example.Example 2: Python3 a = [10, 20, 30]b = [10, 20, 30] # return the location# where the variable# is storedprint(id(a)) # return the location# where the variable# is storedprint(id(b)) # returns false if the# location is not sameprint(a is b) Output 541190289536222 541190288737777 False The output of the above two examples are different because the list is mutable and the string is immutable. An immutable variable cannot be changed once created. If we wish to change an immutable variable, such as a string, we must create a new instance and bind the variable to the new instance. Whereas, mutable variable can be changed in place.Example 3: Python3 def foo(a): # A new variable is assigned # for the new string a = "new value" print("Inside Function:", a) # Driver's codestring = "old value"foo(string) print("Outside Function:", string) Output: Inside Function: new value Outside Function: old value In the above example, a string which is an immutable type of object is passed as argument to the function foo. Within the scope of the given function foo, a= “new value” has been bounded to the same object that string has been bound outside. Within the scope of the function foo, we modify “old value”` to “new value”. Once we leave the scope of function foo , a=”new value” is no longer in the name space, and the value that string refers to was never changed.Example 4: Now, let us look at how mutable variable is passed into the function. Python3 def foo(a): a[0] = "Nothing" # Driver' codebar = ['Hi', 'how', 'are', 'you', 'doing']foo(bar)print(bar) Output: ['Nothing, 'how', 'are', 'you', 'doing'] When we pass a mutable variable into the function foo and modify it to some other name the function foo still points to that object and continue to point to that object during its execution. simmytarika5 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2021" }, { "code": null, "e": 559, "s": 52, "text": "Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function. Whereas passing mutable objects can be considered as call by reference because when their values are changed inside the function, then it will also be reflected outside the function.Example 1: " }, { "code": null, "e": 567, "s": 559, "text": "Python3" }, { "code": "# Python code to demonstrate# call by value string = \"Geeks\" def test(string): string = \"GeeksforGeeks\" print(\"Inside Function:\", string) # Driver's codetest(string)print(\"Outside Function:\", string)", "e": 784, "s": 567, "text": null }, { "code": null, "e": 793, "s": 784, "text": "Output " }, { "code": null, "e": 848, "s": 793, "text": "Inside Function: GeeksforGeeks\nOutside Function: Geeks" }, { "code": null, "e": 860, "s": 848, "text": "Example 2 " }, { "code": null, "e": 868, "s": 860, "text": "Python3" }, { "code": "# Python code to demonstrate# call by reference def add_more(list): list.append(50) print(\"Inside Function\", list) # Driver's codemylist = [10,20,30,40] add_more(mylist)print(\"Outside Function:\", mylist)", "e": 1079, "s": 868, "text": null }, { "code": null, "e": 1088, "s": 1079, "text": "Output " }, { "code": null, "e": 1164, "s": 1088, "text": "Inside Function [10, 20, 30, 40, 50]\nOutside Function: [10, 20, 30, 40, 50]" }, { "code": null, "e": 1344, "s": 1166, "text": "In python, each variable to which we assign a value/container is treated as an object. When we are assigning a value to a variable, we are actually binding a name to an object. " }, { "code": null, "e": 1352, "s": 1344, "text": "Python3" }, { "code": "a = \"first\"b = \"first\" # Returns the actual location# where the variable is storedprint(id(a)) # Returns the actual location# where the variable is storedprint(id(b)) # Returns true if both the variables# are stored in same locationprint(a is b)", "e": 1599, "s": 1352, "text": null }, { "code": null, "e": 1608, "s": 1599, "text": "Output " }, { "code": null, "e": 1645, "s": 1608, "text": "110001234557894\n110001234557894\nTrue" }, { "code": null, "e": 1720, "s": 1645, "text": "Now, let’s try and understand this better with another example.Example 2: " }, { "code": null, "e": 1728, "s": 1720, "text": "Python3" }, { "code": "a = [10, 20, 30]b = [10, 20, 30] # return the location# where the variable# is storedprint(id(a)) # return the location# where the variable# is storedprint(id(b)) # returns false if the# location is not sameprint(a is b)", "e": 1949, "s": 1728, "text": null }, { "code": null, "e": 1958, "s": 1949, "text": "Output " }, { "code": null, "e": 1996, "s": 1958, "text": "541190289536222\n541190288737777\nFalse" }, { "code": null, "e": 2356, "s": 1996, "text": "The output of the above two examples are different because the list is mutable and the string is immutable. An immutable variable cannot be changed once created. If we wish to change an immutable variable, such as a string, we must create a new instance and bind the variable to the new instance. Whereas, mutable variable can be changed in place.Example 3: " }, { "code": null, "e": 2364, "s": 2356, "text": "Python3" }, { "code": "def foo(a): # A new variable is assigned # for the new string a = \"new value\" print(\"Inside Function:\", a) # Driver's codestring = \"old value\"foo(string) print(\"Outside Function:\", string)", "e": 2579, "s": 2364, "text": null }, { "code": null, "e": 2588, "s": 2579, "text": "Output: " }, { "code": null, "e": 2643, "s": 2588, "text": "Inside Function: new value\nOutside Function: old value" }, { "code": null, "e": 3186, "s": 2643, "text": "In the above example, a string which is an immutable type of object is passed as argument to the function foo. Within the scope of the given function foo, a= “new value” has been bounded to the same object that string has been bound outside. Within the scope of the function foo, we modify “old value”` to “new value”. Once we leave the scope of function foo , a=”new value” is no longer in the name space, and the value that string refers to was never changed.Example 4: Now, let us look at how mutable variable is passed into the function. " }, { "code": null, "e": 3194, "s": 3186, "text": "Python3" }, { "code": "def foo(a): a[0] = \"Nothing\" # Driver' codebar = ['Hi', 'how', 'are', 'you', 'doing']foo(bar)print(bar)", "e": 3305, "s": 3194, "text": null }, { "code": null, "e": 3315, "s": 3305, "text": "Output: " }, { "code": null, "e": 3356, "s": 3315, "text": "['Nothing, 'how', 'are', 'you', 'doing']" }, { "code": null, "e": 3549, "s": 3356, "text": "When we pass a mutable variable into the function foo and modify it to some other name the function foo still points to that object and continue to point to that object during its execution. " }, { "code": null, "e": 3562, "s": 3549, "text": "simmytarika5" }, { "code": null, "e": 3576, "s": 3562, "text": "python-basics" }, { "code": null, "e": 3583, "s": 3576, "text": "Python" }, { "code": null, "e": 3681, "s": 3583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3723, "s": 3681, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3745, "s": 3723, "text": "Enumerate() in Python" }, { "code": null, "e": 3771, "s": 3745, "text": "Python String | replace()" }, { "code": null, "e": 3803, "s": 3771, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3832, "s": 3803, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3859, "s": 3832, "text": "Python Classes and Objects" }, { "code": null, "e": 3895, "s": 3859, "text": "Convert integer to string in Python" }, { "code": null, "e": 3916, "s": 3895, "text": "Python OOPs Concepts" }, { "code": null, "e": 3947, "s": 3916, "text": "Python | os.path.join() method" } ]
Simple Contact Form using HTML CSS and PHP
02 Feb, 2022 In this article, we will learn to create a basic contact form using HTML, CSS, and PHP. We are creating a simple HTML form that has three fields name, email address, and a message. The design part is implemented using CSS. Any functionality is added to the form using PHP. We can add our own details, such as an address, phone number, email address, etc as per the application’s need. We can create the form in multiple sections and HTML divs so that it will be easier to add the styles later. Example: In the example below, several Font Awesome icons are used. We have created a different section with a heading. In addition to the modified form, we have added the icons and other contact information. HTML Code: HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="style.css" /> </head> <body> <section id="last"> <!-- heading --> <div class="full"> <h3>Drop a Message</h3> <div class="lt"> <!-- form starting --> <form class="form-horizontal" method="post" action="contact.php"> <div class="form-group"> <div class="col-sm-12"> <!-- name --> <input type="text" class="form-control" id="name" placeholder="NAME" name="name" value="" /> </div> </div> <div class="form-group"> <div class="col-sm-12"> <!-- email --> <input type="email" class="form-control" id="email" placeholder="EMAIL" name="email" value="" /> </div> </div> <!-- message --> <textarea class="form-control" rows="10" placeholder="MESSAGE" name="message"> </textarea> <button class="btn btn-primary send-button" id="submit" type="submit" value="SEND"> <i class="fa fa-paper-plane"></i> <span class="send-text">SEND</span> </button> </form> <!-- end of form --> </div> <!-- Contact information --> <div class="rt"> <ul class="contact-list"> <li class="list-item"> <i class="fa fa-map-marker fa-1x"> <span class="contact-text place"> your address </span> </i> </li> <li class="list-item"> <i class="fa fa-envelope fa-1x"> <span class="contact-text gmail"> <a href="mailto:yourmail@gmail.com" title="Send me an email"> email@gmail.com</a> </span> </i> </li> <li class="list-item"> <i class="fa fa-phone fa-1x"> <span class="contact-text phone"> (033) 12345678 </span> </i> </li> </ul> </div> </div> </section> </body></html> Output: CSS Code: After creating the HTML file, we have to add CSS to improve its appearance. Once we add the styles to the code, we have to take care of another thing. Our website should be able to adapt to different screen sizes and resolutions. So we have to add media queries. The following CSS code is the content for the file “style.css” used in the above HTML code. style.css CSS #last{width: 100%;height: auto;justify-content: center;background-color: #ffb3b3;}.full{width: 80%;display: inline-block;margin:2%;margin-left: 10%;text-align: center;background-color: black;color: white;border:15px solid orange;border-radius: 5px;margin-bottom: 8%;margin-top: 8%;}.full h3{font-size: 2rem;display:block;margin: 2%;margin-bottom: 0;}.lt{padding: 2%;margin: 2%;}.rt{padding: 2%;margin: 2%;}.lt textarea{width: 94%;margin-left: 2.8%;}button{margin: 2%;}.btn-primary{background-color: black;border: 2px solid white;border-radius: 5%;}.list-item{margin-bottom: 2%;list-style-type: none;}.list-item span{margin-left: 10px;font-size: 1.4rem;}.list-item a{color: white;display: inline-block;}.list-item a:hover{text-decoration: underline;}.form-control{background-color: black;} @media screen and (min-width: 770px){.full{ width: 70%; margin-left: 15%;}.lt textarea{width: 95%;margin-left: 2.4%;}} @media screen and (min-width: 1100px){.full{ width: 65%; margin-left: 17%; margin-top: 5%;}.lt{ width: 55%; display: inline-block; float: left; margin-right: 0;}.rt{ width: 35%; display: inline-block; margin-left: 0;}.list-item{margin-bottom: 10%;}.contact-list{ margin-top: 22%; padding-right: 8%;}.fa-envelope, .gmail{ display: inline-block; width: auto;}} PHP code: To add functionality to the form, we are using phpmailer. A separate php file “contact.php” is created and the name of the file is added in the HTML file in the form action field. <form class="form-horizontal" method="post" action="contact.php"> In the following code, we are getting the name, email, and message from the contact form. When “SEND” button is clicked, an email is sent from the website to the email address specified in the PHP code, with the subject line “This is the subject line”. PHP <?php// Get data from form $name = $_POST['name'];$email= $_POST['email'];$message= $_POST['message']; $to = "yourEmail@gmail.com";$subject = "This is the subject line"; // The following text will be sent// Name = user entered name// Email = user entered email// Message = user entered message$txt ="Name = ". $name . "\r\n Email = " . $email . "\r\n Message =" . $message; $headers = "From: noreply@demosite.com" . "\r\n" . "CC: somebodyelse@example.com";if($email != NULL) { mail($to, $subject, $txt, $headers);} // Redirect toheader("Location:last.html");?> In the above example, the redirection location is given as “last.html”. We can redirect to any file name. The above code cannot be tested in the web browser or live server. To test the working of the emails, paid host server is needed. Output: contact form example varshagumber28 banerjeesneha090 CSS-Properties CSS-Questions HTML-Questions HTML-Tags PHP-Questions CSS HTML PHP Web Technologies HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? How to select all child elements recursively using CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Feb, 2022" }, { "code": null, "e": 116, "s": 28, "text": "In this article, we will learn to create a basic contact form using HTML, CSS, and PHP." }, { "code": null, "e": 523, "s": 116, "text": "We are creating a simple HTML form that has three fields name, email address, and a message. The design part is implemented using CSS. Any functionality is added to the form using PHP. We can add our own details, such as an address, phone number, email address, etc as per the application’s need. We can create the form in multiple sections and HTML divs so that it will be easier to add the styles later. " }, { "code": null, "e": 733, "s": 523, "text": "Example: In the example below, several Font Awesome icons are used. We have created a different section with a heading. In addition to the modified form, we have added the icons and other contact information." }, { "code": null, "e": 744, "s": 733, "text": "HTML Code:" }, { "code": null, "e": 749, "s": 744, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\" /> <link rel=\"stylesheet\" href=\"style.css\" /> </head> <body> <section id=\"last\"> <!-- heading --> <div class=\"full\"> <h3>Drop a Message</h3> <div class=\"lt\"> <!-- form starting --> <form class=\"form-horizontal\" method=\"post\" action=\"contact.php\"> <div class=\"form-group\"> <div class=\"col-sm-12\"> <!-- name --> <input type=\"text\" class=\"form-control\" id=\"name\" placeholder=\"NAME\" name=\"name\" value=\"\" /> </div> </div> <div class=\"form-group\"> <div class=\"col-sm-12\"> <!-- email --> <input type=\"email\" class=\"form-control\" id=\"email\" placeholder=\"EMAIL\" name=\"email\" value=\"\" /> </div> </div> <!-- message --> <textarea class=\"form-control\" rows=\"10\" placeholder=\"MESSAGE\" name=\"message\"> </textarea> <button class=\"btn btn-primary send-button\" id=\"submit\" type=\"submit\" value=\"SEND\"> <i class=\"fa fa-paper-plane\"></i> <span class=\"send-text\">SEND</span> </button> </form> <!-- end of form --> </div> <!-- Contact information --> <div class=\"rt\"> <ul class=\"contact-list\"> <li class=\"list-item\"> <i class=\"fa fa-map-marker fa-1x\"> <span class=\"contact-text place\"> your address </span> </i> </li> <li class=\"list-item\"> <i class=\"fa fa-envelope fa-1x\"> <span class=\"contact-text gmail\"> <a href=\"mailto:yourmail@gmail.com\" title=\"Send me an email\"> email@gmail.com</a> </span> </i> </li> <li class=\"list-item\"> <i class=\"fa fa-phone fa-1x\"> <span class=\"contact-text phone\"> (033) 12345678 </span> </i> </li> </ul> </div> </div> </section> </body></html>", "e": 3509, "s": 749, "text": null }, { "code": null, "e": 3517, "s": 3509, "text": "Output:" }, { "code": null, "e": 3882, "s": 3517, "text": "CSS Code: After creating the HTML file, we have to add CSS to improve its appearance. Once we add the styles to the code, we have to take care of another thing. Our website should be able to adapt to different screen sizes and resolutions. So we have to add media queries. The following CSS code is the content for the file “style.css” used in the above HTML code." }, { "code": null, "e": 3892, "s": 3882, "text": "style.css" }, { "code": null, "e": 3896, "s": 3892, "text": "CSS" }, { "code": "#last{width: 100%;height: auto;justify-content: center;background-color: #ffb3b3;}.full{width: 80%;display: inline-block;margin:2%;margin-left: 10%;text-align: center;background-color: black;color: white;border:15px solid orange;border-radius: 5px;margin-bottom: 8%;margin-top: 8%;}.full h3{font-size: 2rem;display:block;margin: 2%;margin-bottom: 0;}.lt{padding: 2%;margin: 2%;}.rt{padding: 2%;margin: 2%;}.lt textarea{width: 94%;margin-left: 2.8%;}button{margin: 2%;}.btn-primary{background-color: black;border: 2px solid white;border-radius: 5%;}.list-item{margin-bottom: 2%;list-style-type: none;}.list-item span{margin-left: 10px;font-size: 1.4rem;}.list-item a{color: white;display: inline-block;}.list-item a:hover{text-decoration: underline;}.form-control{background-color: black;} @media screen and (min-width: 770px){.full{ width: 70%; margin-left: 15%;}.lt textarea{width: 95%;margin-left: 2.4%;}} @media screen and (min-width: 1100px){.full{ width: 65%; margin-left: 17%; margin-top: 5%;}.lt{ width: 55%; display: inline-block; float: left; margin-right: 0;}.rt{ width: 35%; display: inline-block; margin-left: 0;}.list-item{margin-bottom: 10%;}.contact-list{ margin-top: 22%; padding-right: 8%;}.fa-envelope, .gmail{ display: inline-block; width: auto;}}", "e": 5219, "s": 3896, "text": null }, { "code": null, "e": 5411, "s": 5219, "text": "PHP code: To add functionality to the form, we are using phpmailer. A separate php file “contact.php” is created and the name of the file is added in the HTML file in the form action field. " }, { "code": null, "e": 5477, "s": 5411, "text": "<form class=\"form-horizontal\" method=\"post\" action=\"contact.php\">" }, { "code": null, "e": 5731, "s": 5477, "text": "In the following code, we are getting the name, email, and message from the contact form. When “SEND” button is clicked, an email is sent from the website to the email address specified in the PHP code, with the subject line “This is the subject line”." }, { "code": null, "e": 5735, "s": 5731, "text": "PHP" }, { "code": "<?php// Get data from form $name = $_POST['name'];$email= $_POST['email'];$message= $_POST['message']; $to = \"yourEmail@gmail.com\";$subject = \"This is the subject line\"; // The following text will be sent// Name = user entered name// Email = user entered email// Message = user entered message$txt =\"Name = \". $name . \"\\r\\n Email = \" . $email . \"\\r\\n Message =\" . $message; $headers = \"From: noreply@demosite.com\" . \"\\r\\n\" . \"CC: somebodyelse@example.com\";if($email != NULL) { mail($to, $subject, $txt, $headers);} // Redirect toheader(\"Location:last.html\");?>", "e": 6314, "s": 5735, "text": null }, { "code": null, "e": 6551, "s": 6314, "text": "In the above example, the redirection location is given as “last.html”. We can redirect to any file name. The above code cannot be tested in the web browser or live server. To test the working of the emails, paid host server is needed." }, { "code": null, "e": 6559, "s": 6551, "text": "Output:" }, { "code": null, "e": 6580, "s": 6559, "text": "contact form example" }, { "code": null, "e": 6595, "s": 6580, "text": "varshagumber28" }, { "code": null, "e": 6612, "s": 6595, "text": "banerjeesneha090" }, { "code": null, "e": 6627, "s": 6612, "text": "CSS-Properties" }, { "code": null, "e": 6641, "s": 6627, "text": "CSS-Questions" }, { "code": null, "e": 6656, "s": 6641, "text": "HTML-Questions" }, { "code": null, "e": 6666, "s": 6656, "text": "HTML-Tags" }, { "code": null, "e": 6680, "s": 6666, "text": "PHP-Questions" }, { "code": null, "e": 6684, "s": 6680, "text": "CSS" }, { "code": null, "e": 6689, "s": 6684, "text": "HTML" }, { "code": null, "e": 6693, "s": 6689, "text": "PHP" }, { "code": null, "e": 6710, "s": 6693, "text": "Web Technologies" }, { "code": null, "e": 6715, "s": 6710, "text": "HTML" }, { "code": null, "e": 6719, "s": 6715, "text": "PHP" }, { "code": null, "e": 6817, "s": 6719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6856, "s": 6817, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 6895, "s": 6856, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 6959, "s": 6895, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 7020, "s": 6959, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 7076, "s": 7020, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 7100, "s": 7076, "text": "REST API (Introduction)" }, { "code": null, "e": 7153, "s": 7100, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 7213, "s": 7153, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 7274, "s": 7213, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Remove duplicate words from Sentence using Regular Expression
16 Feb, 2021 Given a string str which represents a sentence, the task is to remove the duplicate words from sentences using regular expression in java.Examples: Input: str = “Good bye bye world world” Output: Good bye world Explanation: We remove the second occurrence of bye and world from Good bye bye world worldInput: str = “Ram went went to to to his home” Output: Ram went to his home Explanation: We remove the second occurrence of went and the second and third occurrences of to from Ram went went to to to his home.Input: str = “Hello hello world world” Output: Hello world Explanation: We remove the second occurrence of hello and world from Hello hello world world. Approach Get the sentence.Form a regular expression to remove duplicate words from sentences. Get the sentence. Form a regular expression to remove duplicate words from sentences. regex = "\\b(\\w+)(?:\\W+\\1\\b)+"; The details of the above regular expression can be understood as: “\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.“\\w+” A word character: [a-zA-Z_0-9] “\\W+”: A non-word character: [^\w] “\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\w+) “+”: Match whatever it’s placed after 1 or more times Match the sentence with the Regex. In Java, this can be done using Pattern.matcher(). return the modified sentence. The details of the above regular expression can be understood as: “\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.“\\w+” A word character: [a-zA-Z_0-9] “\\W+”: A non-word character: [^\w] “\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\w+) “+”: Match whatever it’s placed after 1 or more times “\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice. “\\w+” A word character: [a-zA-Z_0-9] “\\W+”: A non-word character: [^\w] “\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\w+) “+”: Match whatever it’s placed after 1 or more times Match the sentence with the Regex. In Java, this can be done using Pattern.matcher(). return the modified sentence. Below is the implementation of the above approach: C++ Java Python3 // C++ program to remove duplicate words// using Regular Expression or ReGex.#include <iostream>#include <regex>using namespace std; // Function to validate the sentence// and remove the duplicate wordsstring removeDuplicateWords(string s){ // Regex to matching repeated words. const regex pattern("\\b(\\w+)(?:\\W+\\1\\b)+", regex_constants::icase); string answer = s; for (auto it = sregex_iterator(s.begin(), s.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch match; match = *it; answer.replace(answer.find(match.str(0)), match.str(0).length(), match.str(1)); } return answer;} // Driver Codeint main(){ // Test Case: 1 string str1 = "Good bye bye world world"; cout << removeDuplicateWords(str1) << endl; // Test Case: 2 string str2 = "Ram went went to to his home"; cout << removeDuplicateWords(str2) << endl; // Test Case: 3 string str3 = "Hello hello world world"; cout << removeDuplicateWords(str3) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to remove duplicate words// using Regular Expression or ReGex. import java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { // Function to validate the sentence // and remove the duplicate words public static String removeDuplicateWords(String input) { // Regex to matching repeated words. String regex = "\\b(\\w+)(?:\\W+\\1\\b)+"; Pattern p = Pattern.compile( regex, Pattern.CASE_INSENSITIVE); // Pattern class contains matcher() method // to find matching between given sentence // and regular expression. Matcher m = p.matcher(input); // Check for subsequences of input // that match the compiled pattern while (m.find()) { input = input.replaceAll( m.group(), m.group(1)); } return input; } // Driver code public static void main(String args[]) { // Test Case: 1 String str1 = "Good bye bye world world"; System.out.println( removeDuplicateWords(str1)); // Test Case: 2 String str2 = "Ram went went to to his home"; System.out.println( removeDuplicateWords(str2)); // Test Case: 3 String str3 = "Hello hello world world"; System.out.println( removeDuplicateWords(str3)); }} # Python program to remove duplicate words# using Regular Expression or ReGex.import re # Function to validate the sentence# and remove the duplicate wordsdef removeDuplicateWords(input): # Regex to matching repeated words regex = r'\b(\w+)(?:\W+\1\b)+' return re.sub(regex, r'\1', input, flags=re.IGNORECASE) # Driver Code # Test Case: 1str1 = "Good bye bye world world"print(removeDuplicateWords(str1)) # Test Case: 2str2 = "Ram went went to to his home"print(removeDuplicateWords(str2)) # Test Case: 3str3 = "Hello hello world world"print(removeDuplicateWords(str3)) # This code is contributed by yuvraj_chandra Good bye world Ram went to his home Hello world yuvraj_chandra CPP-regex java-regular-expression python-regex Java Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Differences between Procedural and Object Oriented Programming Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Decorators with parameters in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Feb, 2021" }, { "code": null, "e": 204, "s": 54, "text": "Given a string str which represents a sentence, the task is to remove the duplicate words from sentences using regular expression in java.Examples: " }, { "code": null, "e": 722, "s": 204, "text": "Input: str = “Good bye bye world world” Output: Good bye world Explanation: We remove the second occurrence of bye and world from Good bye bye world worldInput: str = “Ram went went to to to his home” Output: Ram went to his home Explanation: We remove the second occurrence of went and the second and third occurrences of to from Ram went went to to to his home.Input: str = “Hello hello world world” Output: Hello world Explanation: We remove the second occurrence of hello and world from Hello hello world world. " }, { "code": null, "e": 734, "s": 724, "text": "Approach " }, { "code": null, "e": 821, "s": 734, "text": "Get the sentence.Form a regular expression to remove duplicate words from sentences. " }, { "code": null, "e": 839, "s": 821, "text": "Get the sentence." }, { "code": null, "e": 909, "s": 839, "text": "Form a regular expression to remove duplicate words from sentences. " }, { "code": null, "e": 945, "s": 909, "text": "regex = \"\\\\b(\\\\w+)(?:\\\\W+\\\\1\\\\b)+\";" }, { "code": null, "e": 1490, "s": 945, "text": "The details of the above regular expression can be understood as: “\\\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.“\\\\w+” A word character: [a-zA-Z_0-9] “\\\\W+”: A non-word character: [^\\w] “\\\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\\w+) “+”: Match whatever it’s placed after 1 or more times Match the sentence with the Regex. In Java, this can be done using Pattern.matcher(). return the modified sentence." }, { "code": null, "e": 1920, "s": 1490, "text": "The details of the above regular expression can be understood as: “\\\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.“\\\\w+” A word character: [a-zA-Z_0-9] “\\\\W+”: A non-word character: [^\\w] “\\\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\\w+) “+”: Match whatever it’s placed after 1 or more times " }, { "code": null, "e": 2051, "s": 1920, "text": "“\\\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice." }, { "code": null, "e": 2091, "s": 2051, "text": "“\\\\w+” A word character: [a-zA-Z_0-9] " }, { "code": null, "e": 2129, "s": 2091, "text": "“\\\\W+”: A non-word character: [^\\w] " }, { "code": null, "e": 2232, "s": 2129, "text": "“\\\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\\w+) " }, { "code": null, "e": 2288, "s": 2232, "text": "“+”: Match whatever it’s placed after 1 or more times " }, { "code": null, "e": 2375, "s": 2288, "text": "Match the sentence with the Regex. In Java, this can be done using Pattern.matcher(). " }, { "code": null, "e": 2405, "s": 2375, "text": "return the modified sentence." }, { "code": null, "e": 2457, "s": 2405, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2461, "s": 2457, "text": "C++" }, { "code": null, "e": 2466, "s": 2461, "text": "Java" }, { "code": null, "e": 2474, "s": 2466, "text": "Python3" }, { "code": "// C++ program to remove duplicate words// using Regular Expression or ReGex.#include <iostream>#include <regex>using namespace std; // Function to validate the sentence// and remove the duplicate wordsstring removeDuplicateWords(string s){ // Regex to matching repeated words. const regex pattern(\"\\\\b(\\\\w+)(?:\\\\W+\\\\1\\\\b)+\", regex_constants::icase); string answer = s; for (auto it = sregex_iterator(s.begin(), s.end(), pattern); it != sregex_iterator(); it++) { // flag type for determining the matching behavior // here it is for matches on 'string' objects smatch match; match = *it; answer.replace(answer.find(match.str(0)), match.str(0).length(), match.str(1)); } return answer;} // Driver Codeint main(){ // Test Case: 1 string str1 = \"Good bye bye world world\"; cout << removeDuplicateWords(str1) << endl; // Test Case: 2 string str2 = \"Ram went went to to his home\"; cout << removeDuplicateWords(str2) << endl; // Test Case: 3 string str3 = \"Hello hello world world\"; cout << removeDuplicateWords(str3) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 3621, "s": 2474, "text": null }, { "code": "// Java program to remove duplicate words// using Regular Expression or ReGex. import java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { // Function to validate the sentence // and remove the duplicate words public static String removeDuplicateWords(String input) { // Regex to matching repeated words. String regex = \"\\\\b(\\\\w+)(?:\\\\W+\\\\1\\\\b)+\"; Pattern p = Pattern.compile( regex, Pattern.CASE_INSENSITIVE); // Pattern class contains matcher() method // to find matching between given sentence // and regular expression. Matcher m = p.matcher(input); // Check for subsequences of input // that match the compiled pattern while (m.find()) { input = input.replaceAll( m.group(), m.group(1)); } return input; } // Driver code public static void main(String args[]) { // Test Case: 1 String str1 = \"Good bye bye world world\"; System.out.println( removeDuplicateWords(str1)); // Test Case: 2 String str2 = \"Ram went went to to his home\"; System.out.println( removeDuplicateWords(str2)); // Test Case: 3 String str3 = \"Hello hello world world\"; System.out.println( removeDuplicateWords(str3)); }}", "e": 5097, "s": 3621, "text": null }, { "code": "# Python program to remove duplicate words# using Regular Expression or ReGex.import re # Function to validate the sentence# and remove the duplicate wordsdef removeDuplicateWords(input): # Regex to matching repeated words regex = r'\\b(\\w+)(?:\\W+\\1\\b)+' return re.sub(regex, r'\\1', input, flags=re.IGNORECASE) # Driver Code # Test Case: 1str1 = \"Good bye bye world world\"print(removeDuplicateWords(str1)) # Test Case: 2str2 = \"Ram went went to to his home\"print(removeDuplicateWords(str2)) # Test Case: 3str3 = \"Hello hello world world\"print(removeDuplicateWords(str3)) # This code is contributed by yuvraj_chandra", "e": 5725, "s": 5097, "text": null }, { "code": null, "e": 5773, "s": 5725, "text": "Good bye world\nRam went to his home\nHello world" }, { "code": null, "e": 5790, "s": 5775, "text": "yuvraj_chandra" }, { "code": null, "e": 5800, "s": 5790, "text": "CPP-regex" }, { "code": null, "e": 5824, "s": 5800, "text": "java-regular-expression" }, { "code": null, "e": 5837, "s": 5824, "text": "python-regex" }, { "code": null, "e": 5842, "s": 5837, "text": "Java" }, { "code": null, "e": 5863, "s": 5842, "text": "Programming Language" }, { "code": null, "e": 5868, "s": 5863, "text": "Java" }, { "code": null, "e": 5966, "s": 5868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6017, "s": 5966, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6048, "s": 6017, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6067, "s": 6048, "text": "Interfaces in Java" }, { "code": null, "e": 6097, "s": 6067, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6112, "s": 6097, "text": "Stream In Java" }, { "code": null, "e": 6175, "s": 6112, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 6216, "s": 6175, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 6259, "s": 6216, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 6277, "s": 6259, "text": "Structures in C++" } ]
Expedia Hackerrank test for SDE (8 Years Experienced)
05 Nov, 2020 The test was conducted on Hackerrank platform and there were three questions that needed to be solved in 100 minutes: Run-length Encoding.Device name system: Given a list of IoT devices having names say:int[] deviceNames={"tv","fridge","microwave", "tv","microwave","tv","fridge"} Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={"tv","fridge","microwave", "tv1","microwave1","tv2","fridge1"} Longest ordered subsequence of vowels. Run-length Encoding. Run-length Encoding. Device name system: Given a list of IoT devices having names say:int[] deviceNames={"tv","fridge","microwave", "tv","microwave","tv","fridge"} Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={"tv","fridge","microwave", "tv1","microwave1","tv2","fridge1"} Device name system: Given a list of IoT devices having names say: int[] deviceNames={"tv","fridge","microwave", "tv","microwave","tv","fridge"} Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be: outputDeviceNames={"tv","fridge","microwave", "tv1","microwave1","tv2","fridge1"} Longest ordered subsequence of vowels. Longest ordered subsequence of vowels. The last question is of Dynamic Programming and was the most important question of the whole test, I was not able to solve all the test cases of this question and was rejected, even though I was able to solve the first two questions with 100 percent test cases passed. My advice for these tests should be to quickly solve the first two questions and give maximum time to the last question as it holds the maximum weightage. Expedia Marketing Experienced Interview Experiences Expedia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2020" }, { "code": null, "e": 146, "s": 28, "text": "The test was conducted on Hackerrank platform and there were three questions that needed to be solved in 100 minutes:" }, { "code": null, "e": 598, "s": 146, "text": "Run-length Encoding.Device name system: Given a list of IoT devices having names say:int[] deviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv\",\"microwave\",\"tv\",\"fridge\"}\nGenerate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv1\",\"microwave1\",\"tv2\",\"fridge1\"}\nLongest ordered subsequence of vowels." }, { "code": null, "e": 619, "s": 598, "text": "Run-length Encoding." }, { "code": null, "e": 640, "s": 619, "text": "Run-length Encoding." }, { "code": null, "e": 1034, "s": 640, "text": "Device name system: Given a list of IoT devices having names say:int[] deviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv\",\"microwave\",\"tv\",\"fridge\"}\nGenerate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:outputDeviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv1\",\"microwave1\",\"tv2\",\"fridge1\"}\n" }, { "code": null, "e": 1100, "s": 1034, "text": "Device name system: Given a list of IoT devices having names say:" }, { "code": null, "e": 1198, "s": 1100, "text": "int[] deviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv\",\"microwave\",\"tv\",\"fridge\"}\n" }, { "code": null, "e": 1329, "s": 1198, "text": "Generate a list that uniquely identifies these names, in case of conflicts add a number at the end. Output device names should be:" }, { "code": null, "e": 1431, "s": 1329, "text": "outputDeviceNames={\"tv\",\"fridge\",\"microwave\",\n \"tv1\",\"microwave1\",\"tv2\",\"fridge1\"}\n" }, { "code": null, "e": 1470, "s": 1431, "text": "Longest ordered subsequence of vowels." }, { "code": null, "e": 1509, "s": 1470, "text": "Longest ordered subsequence of vowels." }, { "code": null, "e": 1778, "s": 1509, "text": "The last question is of Dynamic Programming and was the most important question of the whole test, I was not able to solve all the test cases of this question and was rejected, even though I was able to solve the first two questions with 100 percent test cases passed." }, { "code": null, "e": 1933, "s": 1778, "text": "My advice for these tests should be to quickly solve the first two questions and give maximum time to the last question as it holds the maximum weightage." }, { "code": null, "e": 1941, "s": 1933, "text": "Expedia" }, { "code": null, "e": 1951, "s": 1941, "text": "Marketing" }, { "code": null, "e": 1963, "s": 1951, "text": "Experienced" }, { "code": null, "e": 1985, "s": 1963, "text": "Interview Experiences" }, { "code": null, "e": 1993, "s": 1985, "text": "Expedia" } ]
Bifid Cipher in Cryptography - GeeksforGeeks
06 Nov, 2019 This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It just only ever used by amateur cryptographers. Encrypting Algorithm:For this cipher technique algorithm, we use the 25-letter “key-Square” table. Example: 1 2 3 4 5 1 R A N C H 2 O B D E F 3 G I K L M 4 P Q S T U 5 V W X Y Z Here we merged J with the I because we are using a 5 X 5 square key matrix so we can use only 25 characters out of the 26. Let us take “RAMSWARUP IS THE STUDENT OF THE NIT CALICUT” as our plain text. Step-1:Now find each letter of the plain text in the key-square and write the corresponding row number and column in two separate lines. For example, our first letter is the “R” which is present in the first row and first column, so the key cipher text key value for it is “1-1”. RAMSWARUP IS THE STUDENT OF THE NIT CALICUT ROW : 113451144 34 412 4442214 22 412 134 1133144 COL : 125322151 23 454 3453434 15 454 324 4242454 Step-2:Now select a certain amount of size (this is called the period) which indicate how many key values we are going to take. for example in this example take the block size is 5. So divide the values in the block of the period. ROW: 11345 11443 44124 44221 42241 21341 13314 4 COL: 12532 21512 34543 45343 41545 43244 24245 4 Step-3:Now merge the values of rows and columns. Rows values followed by the columns. Final values after combining the values of rows and columns: 1134512532 1144321512 4412434543 4422145343 4224141545 2134143244 1331424245 44 Step-4 (Final Step):Now select pair values from the final combined values and take corresponding character value from the key-square matrix. (first value indicates the row number and second value indicates the column values). For example first taken value is 11 which indicates the character “R” and then we took 34 which is representing the character “L”. CIPHER-TEXT: RLVFIRTIHATASUSTBCXSQECHUOLCITNGQQUT ramswarup_kulhary Rohit Mahali cryptography Computer Networks cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Socket Programming in Python Types of Network Topology TCP 3-Way Handshake Process User Datagram Protocol (UDP) UDP Server-Client implementation in C Types of Transmission Media Distance Vector Routing (DVR) Protocol Hamming Code in Computer Network Advanced Encryption Standard (AES)
[ { "code": null, "e": 24516, "s": 24488, "text": "\n06 Nov, 2019" }, { "code": null, "e": 24913, "s": 24516, "text": "This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It just only ever used by amateur cryptographers." }, { "code": null, "e": 25012, "s": 24913, "text": "Encrypting Algorithm:For this cipher technique algorithm, we use the 25-letter “key-Square” table." }, { "code": null, "e": 25021, "s": 25012, "text": "Example:" }, { "code": null, "e": 25154, "s": 25021, "text": " 1 2 3 4 5\n1 R A N C H\n\n2 O B D E F\n\n3 G I K L M\n \n4 P Q S T U \n\n5 V W X Y Z " }, { "code": null, "e": 25277, "s": 25154, "text": "Here we merged J with the I because we are using a 5 X 5 square key matrix so we can use only 25 characters out of the 26." }, { "code": null, "e": 25354, "s": 25277, "text": "Let us take “RAMSWARUP IS THE STUDENT OF THE NIT CALICUT” as our plain text." }, { "code": null, "e": 25634, "s": 25354, "text": "Step-1:Now find each letter of the plain text in the key-square and write the corresponding row number and column in two separate lines. For example, our first letter is the “R” which is present in the first row and first column, so the key cipher text key value for it is “1-1”." }, { "code": null, "e": 25891, "s": 25634, "text": " RAMSWARUP IS THE STUDENT OF THE NIT CALICUT \nROW : 113451144 34 412 4442214 22 412 134 1133144\nCOL : 125322151 23 454 3453434 15 454 324 4242454 " }, { "code": null, "e": 26122, "s": 25891, "text": "Step-2:Now select a certain amount of size (this is called the period) which indicate how many key values we are going to take. for example in this example take the block size is 5. So divide the values in the block of the period." }, { "code": null, "e": 26245, "s": 26122, "text": "ROW: 11345 11443 44124 44221 42241 21341 13314 4\nCOL: 12532 21512 34543 45343 41545 43244 24245 4 " }, { "code": null, "e": 26392, "s": 26245, "text": "Step-3:Now merge the values of rows and columns. Rows values followed by the columns. Final values after combining the values of rows and columns:" }, { "code": null, "e": 26496, "s": 26392, "text": "1134512532 1144321512 4412434543 4422145343 4224141545 2134143244 1331424245 44 " }, { "code": null, "e": 26722, "s": 26496, "text": "Step-4 (Final Step):Now select pair values from the final combined values and take corresponding character value from the key-square matrix. (first value indicates the row number and second value indicates the column values)." }, { "code": null, "e": 26853, "s": 26722, "text": "For example first taken value is 11 which indicates the character “R” and then we took 34 which is representing the character “L”." }, { "code": null, "e": 26905, "s": 26853, "text": "CIPHER-TEXT: RLVFIRTIHATASUSTBCXSQECHUOLCITNGQQUT " }, { "code": null, "e": 26923, "s": 26905, "text": "ramswarup_kulhary" }, { "code": null, "e": 26936, "s": 26923, "text": "Rohit Mahali" }, { "code": null, "e": 26949, "s": 26936, "text": "cryptography" }, { "code": null, "e": 26967, "s": 26949, "text": "Computer Networks" }, { "code": null, "e": 26980, "s": 26967, "text": "cryptography" }, { "code": null, "e": 26998, "s": 26980, "text": "Computer Networks" }, { "code": null, "e": 27096, "s": 26998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27130, "s": 27096, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27159, "s": 27130, "text": "Socket Programming in Python" }, { "code": null, "e": 27185, "s": 27159, "text": "Types of Network Topology" }, { "code": null, "e": 27213, "s": 27185, "text": "TCP 3-Way Handshake Process" }, { "code": null, "e": 27242, "s": 27213, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 27280, "s": 27242, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27308, "s": 27280, "text": "Types of Transmission Media" }, { "code": null, "e": 27347, "s": 27308, "text": "Distance Vector Routing (DVR) Protocol" }, { "code": null, "e": 27380, "s": 27347, "text": "Hamming Code in Computer Network" } ]
Count the Arithmetic sequences in the Array of size at least 3 - GeeksforGeeks
18 Aug, 2021 Given an array arr[] of size N, the task is to find the count of all arithmetic sequences in the array. Examples: Input: arr = [1, 2, 3, 4] Output: 3 Explanation: The arithmetic sequences in arr are [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. Input: arr = [1, 3, 5, 6, 7, 8] Output: 4 Explanation: The arithmetic sequences in arr are [1, 3, 5], [5, 6, 7], [5, 6, 7, 8] and [6, 7, 8]. Naive approach: Run two loops and check for each sequence of length at least 3. If the sequence is an arithmetic sequence, then increment the answer by 1. Finally, return the count of all the arithmetic subarray of size at least 3. Time Complexity: O(N2) Efficient approach: We will use a dynamic programming approach to maintain a count of all arithmetic sequences till any position. Initialize a variable, res with 0. It will store the count of sequences. Initialize a variable, count with 0. It will store the size of the sequence minus 2. Increase the value of count if the current element forms an arithmetic sequence else make it zero. If the current element L[i] is making an arithmetic sequence with L[i-1] and L[i-2], then the number of arithmetic sequences till the ith iteration is given by: res = res + count Finally, return the res variable. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find all arithmetic// sequences of size atleast 3 #include <bits/stdc++.h>using namespace std; // Function to find all arithmetic// sequences of size atleast 3int numberOfArithmeticSequences(int L[], int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for (int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} // Driver codeint main(){ int L[] = { 1, 3, 5, 6, 7, 8 }; int N = sizeof(L) / sizeof(L[0]); // Function to find arithmetic sequences cout << numberOfArithmeticSequences(L, N); return 0;} // Java program to find all arithmetic// sequences of size atleast 3 class GFG{ // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int L[], int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for (int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} // Driver codepublic static void main(String[] args){ int L[] = { 1, 3, 5, 6, 7, 8 }; int N = L.length; // Function to find arithmetic sequences System.out.print(numberOfArithmeticSequences(L, N)); }} // This code contributed by sapnasingh4991 # Python3 program to find all arithmetic# sequences of size atleast 3 # Function to find all arithmetic# sequences of size atleast 3def numberOfArithmeticSequences(L, N) : # If array size is less than 3 if (N <= 2) : return 0 # Finding arithmetic subarray length count = 0 # To store all arithmetic subarray # of length at least 3 res = 0 for i in range(2,N): # Check if current element makes # arithmetic sequence with # previous two elements if ( (L[i] - L[i - 1]) == (L[i - 1] - L[i - 2])) : count += 1 # Begin with a new element for # new arithmetic sequences else : count = 0 # Accumulate result in till i. res += count # Return final count return res # Driver code L = [ 1, 3, 5, 6, 7, 8 ]N = len(L) # Function to find arithmetic sequencesprint(numberOfArithmeticSequences(L, N)) # This code is contributed by Sanjit_Prasad // C# program to find all arithmetic// sequences of size atleast 3using System; class GFG{ // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int []L, int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for(int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return readonly count return res;} // Driver codepublic static void Main(String[] args){ int []L = { 1, 3, 5, 6, 7, 8 }; int N = L.Length; // Function to find arithmetic sequences Console.Write(numberOfArithmeticSequences(L, N));}} // This code is contributed by amal kumar choubey <script>//Javascript program to find all arithmetic// sequences of size atleast 3 // Function to find all arithmetic// sequences of size atleast 3function numberOfArithmeticSequences( L, N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length var count = 0; // To store all arithmetic subarray // of length at least 3 var res = 0; for (var i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} var L = [ 1, 3, 5, 6, 7, 8 ]; var N = L.length; // Function to find arithmetic sequences document.write(numberOfArithmeticSequences(L, N)); // This code contributed by SoumikMondal</script> 4 Time Complexity: O(N) Sanjit_Prasad sapnasingh4991 Amal Kumar Choubey SoumikMondal arorakashish0911 arithmetic progression series Arrays Dynamic Programming Mathematical Pattern Searching Arrays Dynamic Programming Mathematical series Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Move all negative numbers to beginning and positive to end with constant extra space Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Bellman–Ford Algorithm | DP-23 Longest Common Subsequence | DP-4 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24822, "s": 24794, "text": "\n18 Aug, 2021" }, { "code": null, "e": 24927, "s": 24822, "text": "Given an array arr[] of size N, the task is to find the count of all arithmetic sequences in the array. " }, { "code": null, "e": 24938, "s": 24927, "text": "Examples: " }, { "code": null, "e": 25069, "s": 24938, "text": "Input: arr = [1, 2, 3, 4] Output: 3 Explanation: The arithmetic sequences in arr are [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself." }, { "code": null, "e": 25210, "s": 25069, "text": "Input: arr = [1, 3, 5, 6, 7, 8] Output: 4 Explanation: The arithmetic sequences in arr are [1, 3, 5], [5, 6, 7], [5, 6, 7, 8] and [6, 7, 8]." }, { "code": null, "e": 25228, "s": 25210, "text": "Naive approach: " }, { "code": null, "e": 25292, "s": 25228, "text": "Run two loops and check for each sequence of length at least 3." }, { "code": null, "e": 25367, "s": 25292, "text": "If the sequence is an arithmetic sequence, then increment the answer by 1." }, { "code": null, "e": 25444, "s": 25367, "text": "Finally, return the count of all the arithmetic subarray of size at least 3." }, { "code": null, "e": 25467, "s": 25444, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 25599, "s": 25467, "text": "Efficient approach: We will use a dynamic programming approach to maintain a count of all arithmetic sequences till any position. " }, { "code": null, "e": 25672, "s": 25599, "text": "Initialize a variable, res with 0. It will store the count of sequences." }, { "code": null, "e": 25757, "s": 25672, "text": "Initialize a variable, count with 0. It will store the size of the sequence minus 2." }, { "code": null, "e": 25856, "s": 25757, "text": "Increase the value of count if the current element forms an arithmetic sequence else make it zero." }, { "code": null, "e": 26018, "s": 25856, "text": "If the current element L[i] is making an arithmetic sequence with L[i-1] and L[i-2], then the number of arithmetic sequences till the ith iteration is given by: " }, { "code": null, "e": 26036, "s": 26018, "text": "res = res + count" }, { "code": null, "e": 26070, "s": 26036, "text": "Finally, return the res variable." }, { "code": null, "e": 26123, "s": 26070, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26127, "s": 26123, "text": "C++" }, { "code": null, "e": 26132, "s": 26127, "text": "Java" }, { "code": null, "e": 26140, "s": 26132, "text": "Python3" }, { "code": null, "e": 26143, "s": 26140, "text": "C#" }, { "code": null, "e": 26154, "s": 26143, "text": "Javascript" }, { "code": "// C++ program to find all arithmetic// sequences of size atleast 3 #include <bits/stdc++.h>using namespace std; // Function to find all arithmetic// sequences of size atleast 3int numberOfArithmeticSequences(int L[], int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for (int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} // Driver codeint main(){ int L[] = { 1, 3, 5, 6, 7, 8 }; int N = sizeof(L) / sizeof(L[0]); // Function to find arithmetic sequences cout << numberOfArithmeticSequences(L, N); return 0;}", "e": 27249, "s": 26154, "text": null }, { "code": "// Java program to find all arithmetic// sequences of size atleast 3 class GFG{ // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int L[], int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for (int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} // Driver codepublic static void main(String[] args){ int L[] = { 1, 3, 5, 6, 7, 8 }; int N = L.length; // Function to find arithmetic sequences System.out.print(numberOfArithmeticSequences(L, N)); }} // This code contributed by sapnasingh4991", "e": 28383, "s": 27249, "text": null }, { "code": "# Python3 program to find all arithmetic# sequences of size atleast 3 # Function to find all arithmetic# sequences of size atleast 3def numberOfArithmeticSequences(L, N) : # If array size is less than 3 if (N <= 2) : return 0 # Finding arithmetic subarray length count = 0 # To store all arithmetic subarray # of length at least 3 res = 0 for i in range(2,N): # Check if current element makes # arithmetic sequence with # previous two elements if ( (L[i] - L[i - 1]) == (L[i - 1] - L[i - 2])) : count += 1 # Begin with a new element for # new arithmetic sequences else : count = 0 # Accumulate result in till i. res += count # Return final count return res # Driver code L = [ 1, 3, 5, 6, 7, 8 ]N = len(L) # Function to find arithmetic sequencesprint(numberOfArithmeticSequences(L, N)) # This code is contributed by Sanjit_Prasad", "e": 29344, "s": 28383, "text": null }, { "code": "// C# program to find all arithmetic// sequences of size atleast 3using System; class GFG{ // Function to find all arithmetic// sequences of size atleast 3static int numberOfArithmeticSequences(int []L, int N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length int count = 0; // To store all arithmetic subarray // of length at least 3 int res = 0; for(int i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return readonly count return res;} // Driver codepublic static void Main(String[] args){ int []L = { 1, 3, 5, 6, 7, 8 }; int N = L.Length; // Function to find arithmetic sequences Console.Write(numberOfArithmeticSequences(L, N));}} // This code is contributed by amal kumar choubey", "e": 30557, "s": 29344, "text": null }, { "code": "<script>//Javascript program to find all arithmetic// sequences of size atleast 3 // Function to find all arithmetic// sequences of size atleast 3function numberOfArithmeticSequences( L, N){ // If array size is less than 3 if (N <= 2) return 0; // Finding arithmetic subarray length var count = 0; // To store all arithmetic subarray // of length at least 3 var res = 0; for (var i = 2; i < N; ++i) { // Check if current element makes // arithmetic sequence with // previous two elements if (L[i] - L[i - 1] == L[i - 1] - L[i - 2]) { ++count; } // Begin with a new element for // new arithmetic sequences else { count = 0; } // Accumulate result in till i. res += count; } // Return final count return res;} var L = [ 1, 3, 5, 6, 7, 8 ]; var N = L.length; // Function to find arithmetic sequences document.write(numberOfArithmeticSequences(L, N)); // This code contributed by SoumikMondal</script>", "e": 31610, "s": 30557, "text": null }, { "code": null, "e": 31612, "s": 31610, "text": "4" }, { "code": null, "e": 31637, "s": 31614, "text": "Time Complexity: O(N) " }, { "code": null, "e": 31651, "s": 31637, "text": "Sanjit_Prasad" }, { "code": null, "e": 31666, "s": 31651, "text": "sapnasingh4991" }, { "code": null, "e": 31685, "s": 31666, "text": "Amal Kumar Choubey" }, { "code": null, "e": 31698, "s": 31685, "text": "SoumikMondal" }, { "code": null, "e": 31715, "s": 31698, "text": "arorakashish0911" }, { "code": null, "e": 31738, "s": 31715, "text": "arithmetic progression" }, { "code": null, "e": 31745, "s": 31738, "text": "series" }, { "code": null, "e": 31752, "s": 31745, "text": "Arrays" }, { "code": null, "e": 31772, "s": 31752, "text": "Dynamic Programming" }, { "code": null, "e": 31785, "s": 31772, "text": "Mathematical" }, { "code": null, "e": 31803, "s": 31785, "text": "Pattern Searching" }, { "code": null, "e": 31810, "s": 31803, "text": "Arrays" }, { "code": null, "e": 31830, "s": 31810, "text": "Dynamic Programming" }, { "code": null, "e": 31843, "s": 31830, "text": "Mathematical" }, { "code": null, "e": 31850, "s": 31843, "text": "series" }, { "code": null, "e": 31868, "s": 31850, "text": "Pattern Searching" }, { "code": null, "e": 31966, "s": 31868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31975, "s": 31966, "text": "Comments" }, { "code": null, "e": 31988, "s": 31975, "text": "Old Comments" }, { "code": null, "e": 32013, "s": 31988, "text": "Window Sliding Technique" }, { "code": null, "e": 32062, "s": 32013, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32147, "s": 32062, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 32185, "s": 32147, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32243, "s": 32185, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 32272, "s": 32243, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 32302, "s": 32272, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32333, "s": 32302, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32367, "s": 32333, "text": "Longest Common Subsequence | DP-4" } ]
Minimum Swaps for Bracket Balancing | Practice | GeeksforGeeks
You are given a string S of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balanced. Note - Strings S1 and S2 can be empty. Example 1: Input : []][][ Output : 2 Explanation : First swap: Position 3 and 4 [][]][ Second swap: Position 5 and 6 [][][] Example 2: Input : [[][]] Output : 0 Explanation: String is already balanced. Your Task: You don't need to read input or print anything. Your task is to complete the function minimumNumberOfSwaps() which takes the string S and return minimum number of operations required to balance the bracket sequence. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1<=|S|<=100000 0 gulshankumaransh9796 hours ago PYTHON### class Solution: def minimumNumberOfSwaps(self,S): chars = S countLeft = 0 countRight = 0 swap = 0 imbalance = 0 for i in range(len(chars)): if chars[i] == '[': countLeft += 1 if imbalance > 0: swap += imbalance imbalance -= 1 elif chars[i] == ']': countRight += 1 imbalance = (countRight - countLeft) return swap 0 shilsoumyadip2 weeks ago int minimumNumberOfSwaps(string S){ // code here int c =0; int swap =0; for(int i =0;i<S.length();i++) { if(S[i] ==']') { c++; if(c > 0) swap += c; } else { c--; } } return swap; } 0 govidkrishna772 weeks ago class Solution{ static int minimumNumberOfSwaps(String S){ int swap=0; int count=0; for(int i=0;i<S.length();i++){ if(S.charAt(i)=='['){ count--; } if(S.charAt(i)==']'){ count++; if(count>0){ swap+=count; } } } return swap; // code here }} 0 anubhavnegi54 This comment was deleted. 0 badgujarsachin831 month ago int minimumNumberOfSwaps(string S){ // code here int swap=0,x=0; for(int i=0;i<S.size();i++){ if(S[i]=='['){ x--; }else{ x++; if(x>0){ swap+=x; } } } return swap; } 0 aloksinghbais022 months ago C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- Execution Time :- 0.0 / 1.1 sec int minimumNumberOfSwaps(string s){ int n = s.length(); int open = 0, close = 0, fault = 0; int swaps = 0; for(int i = 0; i < n; i++){ if(s[i] == ']'){ close++; fault = close - open; } else{ open++; if(fault > 0){ swaps += fault; fault--; } } } return (swaps); } +1 2020010432 months ago //Easy solution int minimumNumberOfSwaps(string S){ int ans=0,c=0,n=S.length(); for(int i=0;i<n;i++){ if(S[i]=='[')c++; else{ c--; if(c<0)ans-=c; } } return ans+c; } +1 manishmaheshwari81332 months ago JAVA CODE TC: O(N) SC=O(1) class Solution{ static int minimumNumberOfSwaps(String S){ int open=0,close=0,fault=0,swap=0; for(int i=0;i<S.length();i++){ if(S.charAt(i)==']'){ close++; fault=close-open; }else { open++; if(fault>0){ swap+=fault; fault --; } } } return swap; } } 0 absaarali15482 months ago int minimumNumberOfSwaps(string S){ int x = 0 ,swaps = 0 , n = S.length(); for(int i = 0 ; i<n ; i++) { if(S[i]=='[') x--; else { x++; if(x>0) swaps+=x; } } return swaps; } 0 sinhaabhijeet92 months ago int minimumNumberOfSwaps(string S){ // code here int size = S.size(); stack<char> t; int count= 0; for(int i = 0;i<size;i++) { if(S[i] == '[') { if(t.size() == 0) { t.push(S[i]); continue; } else if(t.top()=='[') { t.push(S[i]); } else if(t.top()==']') { count+= t.size(); t.pop(); } } else if(S[i]==']') { if(t.size() == 0) { t.push(S[i]); continue; } else if(t.top()=='[') { t.pop(); } else if(t.top()==']') { t.push(S[i]); } } } return count; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 631, "s": 238, "text": "You are given a string S of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balanced.\nNote - Strings S1 and S2 can be empty." }, { "code": null, "e": 644, "s": 633, "text": "Example 1:" }, { "code": null, "e": 760, "s": 644, "text": "Input : []][][\nOutput : 2\nExplanation :\nFirst swap: Position 3 and 4\n[][]][\nSecond swap: Position 5 and 6\n[][][]\n\n" }, { "code": null, "e": 773, "s": 762, "text": "Example 2:" }, { "code": null, "e": 841, "s": 773, "text": "Input : [[][]]\nOutput : 0 \nExplanation:\nString is already balanced." }, { "code": null, "e": 854, "s": 843, "text": "Your Task:" }, { "code": null, "e": 1070, "s": 854, "text": "You don't need to read input or print anything. Your task is to complete the function minimumNumberOfSwaps() which takes the string S and return minimum number of operations required to balance the bracket sequence." }, { "code": null, "e": 1136, "s": 1072, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1151, "s": 1138, "text": "Constraints:" }, { "code": null, "e": 1166, "s": 1151, "text": "1<=|S|<=100000" }, { "code": null, "e": 1170, "s": 1168, "text": "0" }, { "code": null, "e": 1201, "s": 1170, "text": "gulshankumaransh9796 hours ago" }, { "code": null, "e": 1211, "s": 1201, "text": "PYTHON###" }, { "code": null, "e": 1684, "s": 1211, "text": "class Solution: def minimumNumberOfSwaps(self,S): chars = S countLeft = 0 countRight = 0 swap = 0 imbalance = 0 for i in range(len(chars)): if chars[i] == '[': countLeft += 1 if imbalance > 0: swap += imbalance imbalance -= 1 elif chars[i] == ']': countRight += 1 imbalance = (countRight - countLeft) return swap" }, { "code": null, "e": 1686, "s": 1684, "text": "0" }, { "code": null, "e": 1711, "s": 1686, "text": "shilsoumyadip2 weeks ago" }, { "code": null, "e": 2075, "s": 1711, "text": " int minimumNumberOfSwaps(string S){ // code here int c =0; int swap =0; for(int i =0;i<S.length();i++) { if(S[i] ==']') { c++; if(c > 0) swap += c; } else { c--; } } return swap; }" }, { "code": null, "e": 2077, "s": 2075, "text": "0" }, { "code": null, "e": 2103, "s": 2077, "text": "govidkrishna772 weeks ago" }, { "code": null, "e": 2497, "s": 2103, "text": "class Solution{ static int minimumNumberOfSwaps(String S){ int swap=0; int count=0; for(int i=0;i<S.length();i++){ if(S.charAt(i)=='['){ count--; } if(S.charAt(i)==']'){ count++; if(count>0){ swap+=count; } } } return swap; // code here }}" }, { "code": null, "e": 2499, "s": 2497, "text": "0" }, { "code": null, "e": 2513, "s": 2499, "text": "anubhavnegi54" }, { "code": null, "e": 2539, "s": 2513, "text": "This comment was deleted." }, { "code": null, "e": 2541, "s": 2539, "text": "0" }, { "code": null, "e": 2569, "s": 2541, "text": "badgujarsachin831 month ago" }, { "code": null, "e": 2900, "s": 2569, "text": " int minimumNumberOfSwaps(string S){\n // code here \n int swap=0,x=0;\n for(int i=0;i<S.size();i++){\n if(S[i]=='['){\n x--;\n }else{\n x++;\n if(x>0){\n swap+=x;\n }\n }\n }\n return swap;\n }" }, { "code": null, "e": 2902, "s": 2900, "text": "0" }, { "code": null, "e": 2930, "s": 2902, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 3021, "s": 2930, "text": "C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- " }, { "code": null, "e": 3055, "s": 3023, "text": "Execution Time :- 0.0 / 1.1 sec" }, { "code": null, "e": 3504, "s": 3057, "text": "int minimumNumberOfSwaps(string s){ int n = s.length(); int open = 0, close = 0, fault = 0; int swaps = 0; for(int i = 0; i < n; i++){ if(s[i] == ']'){ close++; fault = close - open; } else{ open++; if(fault > 0){ swaps += fault; fault--; } } } return (swaps); }" }, { "code": null, "e": 3507, "s": 3504, "text": "+1" }, { "code": null, "e": 3529, "s": 3507, "text": "2020010432 months ago" }, { "code": null, "e": 3545, "s": 3529, "text": "//Easy solution" }, { "code": null, "e": 3779, "s": 3545, "text": "int minimumNumberOfSwaps(string S){ int ans=0,c=0,n=S.length(); for(int i=0;i<n;i++){ if(S[i]=='[')c++; else{ c--; if(c<0)ans-=c; } } return ans+c; }" }, { "code": null, "e": 3782, "s": 3779, "text": "+1" }, { "code": null, "e": 3815, "s": 3782, "text": "manishmaheshwari81332 months ago" }, { "code": null, "e": 3825, "s": 3815, "text": "JAVA CODE" }, { "code": null, "e": 3834, "s": 3825, "text": "TC: O(N)" }, { "code": null, "e": 3842, "s": 3834, "text": "SC=O(1)" }, { "code": null, "e": 4300, "s": 3842, "text": "class Solution{\n static int minimumNumberOfSwaps(String S){\n int open=0,close=0,fault=0,swap=0;\n for(int i=0;i<S.length();i++){\n \n if(S.charAt(i)==']'){\n close++;\n fault=close-open;\n }else {\n open++;\n if(fault>0){\n swap+=fault;\n fault --;\n }\n }\n }\n return swap;\n }\n}" }, { "code": null, "e": 4302, "s": 4300, "text": "0" }, { "code": null, "e": 4328, "s": 4302, "text": "absaarali15482 months ago" }, { "code": null, "e": 4633, "s": 4328, "text": "int minimumNumberOfSwaps(string S){ int x = 0 ,swaps = 0 , n = S.length(); for(int i = 0 ; i<n ; i++) { if(S[i]=='[') x--; else { x++; if(x>0) swaps+=x; } } return swaps; }" }, { "code": null, "e": 4635, "s": 4633, "text": "0" }, { "code": null, "e": 4662, "s": 4635, "text": "sinhaabhijeet92 months ago" }, { "code": null, "e": 5544, "s": 4662, "text": "int minimumNumberOfSwaps(string S){ // code here int size = S.size(); stack<char> t; int count= 0; for(int i = 0;i<size;i++) { if(S[i] == '[') { if(t.size() == 0) { t.push(S[i]); continue; } else if(t.top()=='[') { t.push(S[i]); } else if(t.top()==']') { count+= t.size(); t.pop(); } } else if(S[i]==']') { if(t.size() == 0) { t.push(S[i]); continue; } else if(t.top()=='[') { t.pop(); } else if(t.top()==']') { t.push(S[i]); } } } return count; }" }, { "code": null, "e": 5690, "s": 5544, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5726, "s": 5690, "text": " Login to access your submissions. " }, { "code": null, "e": 5736, "s": 5726, "text": "\nProblem\n" }, { "code": null, "e": 5746, "s": 5736, "text": "\nContest\n" }, { "code": null, "e": 5809, "s": 5746, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5957, "s": 5809, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6165, "s": 5957, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6271, "s": 6165, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Angular Highcharts - Basic Pie Chart
Following is an example of a Pie Chart. We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic pie chart. We will also understand additional configuration. We have changed the type attribute in chart. Configure the chart type to be 'pie' based. chart.type decides the series type for the chart. Here, the default value is "line". var series = { type: 'pie' }; app.component.ts import { Component } from '@angular/core'; import * as Highcharts from 'highcharts'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { highcharts = Highcharts; chartOptions = { chart : { plotBorderWidth: null, plotShadow: false }, title : { text: 'Browser market shares at a specific website, 2014' }, tooltip : { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions : { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}%</b>: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor)|| 'black' } } } }, series : [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2075, "s": 2035, "text": "Following is an example of a Pie Chart." }, { "code": null, "e": 2324, "s": 2075, "text": "We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic pie chart. We will also understand additional configuration. We have changed the type attribute in chart." }, { "code": null, "e": 2453, "s": 2324, "text": "Configure the chart type to be 'pie' based. chart.type decides the series type for the chart. Here, the default value is \"line\"." }, { "code": null, "e": 2486, "s": 2453, "text": "var series = {\n type: 'pie'\n};" }, { "code": null, "e": 2503, "s": 2486, "text": "app.component.ts" }, { "code": null, "e": 3900, "s": 2503, "text": "import { Component } from '@angular/core';\nimport * as Highcharts from 'highcharts';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n highcharts = Highcharts;\n chartOptions = { \n chart : {\n plotBorderWidth: null,\n plotShadow: false\n },\n title : {\n text: 'Browser market shares at a specific website, 2014' \n },\n tooltip : {\n pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'\n },\n plotOptions : {\n pie: {\n allowPointSelect: true,\n cursor: 'pointer',\n dataLabels: {\n enabled: true,\n format: '<b>{point.name}%</b>: {point.percentage:.1f} %',\n style: {\n color: (Highcharts.theme && Highcharts.theme.contrastTextColor)||\n 'black'\n }\n }\n }\n },\n series : [{\n type: 'pie',\n name: 'Browser share',\n data: [\n ['Firefox', 45.0],\n ['IE', 26.8],\n {\n name: 'Chrome',\n y: 12.8,\n sliced: true,\n selected: true\n },\n ['Safari', 8.5],\n ['Opera', 6.2],\n ['Others', 0.7]\n ]\n }]\n };\n}" }, { "code": null, "e": 3919, "s": 3900, "text": "Verify the result." }, { "code": null, "e": 3954, "s": 3919, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3968, "s": 3954, "text": " Anadi Sharma" }, { "code": null, "e": 4003, "s": 3968, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4017, "s": 4003, "text": " Anadi Sharma" }, { "code": null, "e": 4052, "s": 4017, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4072, "s": 4052, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 4107, "s": 4072, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4124, "s": 4107, "text": " Frahaan Hussain" }, { "code": null, "e": 4157, "s": 4124, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 4169, "s": 4157, "text": " Senol Atac" }, { "code": null, "e": 4204, "s": 4169, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4216, "s": 4204, "text": " Senol Atac" }, { "code": null, "e": 4223, "s": 4216, "text": " Print" }, { "code": null, "e": 4234, "s": 4223, "text": " Add Notes" } ]
Make a Beautiful Nightingale Rose Chart in Python | by Di(Candice) Han | Towards Data Science
Nightingale’s Rose chart, also referred to as “polar area chart” or “coxcomb chart”, is a circular graph that combines elements of a radar chart and a column graph. This special chart is named after a nurse, statistician, and reformer Florence Nightingale. She invented a color statistical graphic entitled “Diagram of the Causes of Mortality in the Army of the East” to dramatize the extent of needless deaths in British military hospitals during the Cirmean War (1954–56). The chart showed that epidemic disease was responsible for more British deaths in the course of the war than battlefield wounds. This tutorial, we will create a Nightingale rose chart in Python using the Pyechart library. We don’t even need to import data! It only takes few steps, and you will have a rose chart like this! Step 1: import libraries import numpy as npimport pandas as pdfrom pyecharts.charts import Piefrom pyecharts import options as opts Step 2: open the website and get data by clipboard function import webbrowserwebsite = ‘https://www.worldometers.info/coronavirus/'webbrowser.open(website) Worldmeters refreshes covid-19 information daily with a good format, so data for this tutorial is from this website. read_clipboard() in Pandas can read, copy, paste tabular data and parse it into a Data Frame. It is a very useful function if you want to practice on small dataset. One of the limitation is that it cannot handle merged cells. When you copy the table from Worldmeters, please do not include the first row, which has column names. Each cell in the first row is merged cell and clipboard() cannot process it. It will return error. After you copy the whole table except the first row, execute below codes data = pd.read_clipboard()data You will get a table like this Step3: the first row will be replaced by proper column names data.columns = [‘Country’,’TotalCases’,’NewCases’,’TotalDeaths’,’NewDeaths’,’TotalRecovered’,’ActiveCases’,’CriticalCondition’,‘TotCasesPerMillion’,’DeathsPerMillion’,’TotalTests’,’TestsPerMillion’]data Then, the dataframe looks much better. Step 4: data manipulation # remove "," from the datasetfor x in range(1,len(data.columns)): data[data.columns[x]] = data[data.columns[x]].str.replace(‘,’,’’) #replace NaNs with zerosdata = data.fillna(0)#change the datatype from object to integerfor i in range (1,len(data.columns)): data[data.columns[i]] = data[data.columns[i]].astype(float).astype(int)#create a column 'Death Rate'data['DeathRate'] = data['TotalDeaths']/data['TotalCases']#sort the data frame by 'Death Rate' in descending orderdata.sort_values(by=['DeathRate'], inplace=True, ascending=False) Step 5: Select the top 15 countries which have the highest death rate df=data[[‘Country’,’DeathRate’]].head(15) #select two columns and top 15 rowsdf[‘DeathRate’] = (df[‘DeathRate’]*100).round(1)df The data frame for further visualization is ready. Step 6: visualize the data c = df[‘Country’].values.tolist()d = df[‘DeathRate’].values.tolist()#create the color_series for the rosechartcolor_series = [‘#802200’,’#B33000',’#FF4500',’#FAA327',’#9ECB3C’, ‘#6DBC49’,’#37B44E’,’#14ADCF’,’#209AC9',’#1E91CA’, ‘#2C6BA0’,’#2B55A1',’#2D3D8E’,’#44388E’,’#6A368B’, ‘#D02C2A’,’#D44C2D’,’#F57A34',’#FA8F2F’,’#D99D21']rosechart = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))# set the colorrosechart.set_colors(color_series)# add the data to the rosechartrosechart.add("", [list(z) for z in zip(c, d)], radius=["20%", "95%"], # 20% inside radius,95% ourside radius center=["30%", "60%"], # center of the chart rosetype="area")# set the global options for the chartrosechart.set_global_opts(title_opts=opts.TitleOpts(title='Nightingale Rose Chart',subtitle="Covid-19 Death Rate"), legend_opts=opts.LegendOpts(is_show=False), toolbox_opts=opts.ToolboxOpts())# set the series optionsrosechart.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position="inside", font_size=12,formatter="{b}:{c}%", font_style="italic",font_weight="bold", font_family="Century"),)rosechart.render_notebook() Finally, the beautiful Nightingale rose chart is generated! From the chart, it is easy to see that the MS Zaandam, which is a cruise ship, has the highest death rate. Next to it are Burundi, Bahamas and Sudan. And the death rates of the top 15 countries all exceeded 10%, considerably higher than the death rate of normal seasonal flu, which is typically around 0.1% in the U.S., according to The New York Times. So, stay at home and enjoy learning data visualization! If you are interested in making other types of beautiful charts, you may want to check out my other posts. Make a beautiful water polo chart in a few lines in PythonMake a beautiful bar chart in just few lines in PythonMake a beautiful scatterplot in a few lines in Python to make your report outstandingMake an impressive animated bubble chart with Plotly in Python — inspired by professor Hans RoslingMake the cutest chart in Python — visualize your data with hand-drawn charts Make a beautiful water polo chart in a few lines in Python Make a beautiful bar chart in just few lines in Python Make a beautiful scatterplot in a few lines in Python to make your report outstanding Make an impressive animated bubble chart with Plotly in Python — inspired by professor Hans Rosling Make the cutest chart in Python — visualize your data with hand-drawn charts
[ { "code": null, "e": 776, "s": 172, "text": "Nightingale’s Rose chart, also referred to as “polar area chart” or “coxcomb chart”, is a circular graph that combines elements of a radar chart and a column graph. This special chart is named after a nurse, statistician, and reformer Florence Nightingale. She invented a color statistical graphic entitled “Diagram of the Causes of Mortality in the Army of the East” to dramatize the extent of needless deaths in British military hospitals during the Cirmean War (1954–56). The chart showed that epidemic disease was responsible for more British deaths in the course of the war than battlefield wounds." }, { "code": null, "e": 971, "s": 776, "text": "This tutorial, we will create a Nightingale rose chart in Python using the Pyechart library. We don’t even need to import data! It only takes few steps, and you will have a rose chart like this!" }, { "code": null, "e": 996, "s": 971, "text": "Step 1: import libraries" }, { "code": null, "e": 1103, "s": 996, "text": "import numpy as npimport pandas as pdfrom pyecharts.charts import Piefrom pyecharts import options as opts" }, { "code": null, "e": 1163, "s": 1103, "text": "Step 2: open the website and get data by clipboard function" }, { "code": null, "e": 1259, "s": 1163, "text": "import webbrowserwebsite = ‘https://www.worldometers.info/coronavirus/'webbrowser.open(website)" }, { "code": null, "e": 1602, "s": 1259, "text": "Worldmeters refreshes covid-19 information daily with a good format, so data for this tutorial is from this website. read_clipboard() in Pandas can read, copy, paste tabular data and parse it into a Data Frame. It is a very useful function if you want to practice on small dataset. One of the limitation is that it cannot handle merged cells." }, { "code": null, "e": 1804, "s": 1602, "text": "When you copy the table from Worldmeters, please do not include the first row, which has column names. Each cell in the first row is merged cell and clipboard() cannot process it. It will return error." }, { "code": null, "e": 1877, "s": 1804, "text": "After you copy the whole table except the first row, execute below codes" }, { "code": null, "e": 1908, "s": 1877, "text": "data = pd.read_clipboard()data" }, { "code": null, "e": 1939, "s": 1908, "text": "You will get a table like this" }, { "code": null, "e": 2000, "s": 1939, "text": "Step3: the first row will be replaced by proper column names" }, { "code": null, "e": 2203, "s": 2000, "text": "data.columns = [‘Country’,’TotalCases’,’NewCases’,’TotalDeaths’,’NewDeaths’,’TotalRecovered’,’ActiveCases’,’CriticalCondition’,‘TotCasesPerMillion’,’DeathsPerMillion’,’TotalTests’,’TestsPerMillion’]data" }, { "code": null, "e": 2242, "s": 2203, "text": "Then, the dataframe looks much better." }, { "code": null, "e": 2268, "s": 2242, "text": "Step 4: data manipulation" }, { "code": null, "e": 2809, "s": 2268, "text": "# remove \",\" from the datasetfor x in range(1,len(data.columns)): data[data.columns[x]] = data[data.columns[x]].str.replace(‘,’,’’) #replace NaNs with zerosdata = data.fillna(0)#change the datatype from object to integerfor i in range (1,len(data.columns)): data[data.columns[i]] = data[data.columns[i]].astype(float).astype(int)#create a column 'Death Rate'data['DeathRate'] = data['TotalDeaths']/data['TotalCases']#sort the data frame by 'Death Rate' in descending orderdata.sort_values(by=['DeathRate'], inplace=True, ascending=False)" }, { "code": null, "e": 2879, "s": 2809, "text": "Step 5: Select the top 15 countries which have the highest death rate" }, { "code": null, "e": 3007, "s": 2879, "text": "df=data[[‘Country’,’DeathRate’]].head(15) #select two columns and top 15 rowsdf[‘DeathRate’] = (df[‘DeathRate’]*100).round(1)df" }, { "code": null, "e": 3058, "s": 3007, "text": "The data frame for further visualization is ready." }, { "code": null, "e": 3085, "s": 3058, "text": "Step 6: visualize the data" }, { "code": null, "e": 4267, "s": 3085, "text": "c = df[‘Country’].values.tolist()d = df[‘DeathRate’].values.tolist()#create the color_series for the rosechartcolor_series = [‘#802200’,’#B33000',’#FF4500',’#FAA327',’#9ECB3C’, ‘#6DBC49’,’#37B44E’,’#14ADCF’,’#209AC9',’#1E91CA’, ‘#2C6BA0’,’#2B55A1',’#2D3D8E’,’#44388E’,’#6A368B’, ‘#D02C2A’,’#D44C2D’,’#F57A34',’#FA8F2F’,’#D99D21']rosechart = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))# set the colorrosechart.set_colors(color_series)# add the data to the rosechartrosechart.add(\"\", [list(z) for z in zip(c, d)], radius=[\"20%\", \"95%\"], # 20% inside radius,95% ourside radius center=[\"30%\", \"60%\"], # center of the chart rosetype=\"area\")# set the global options for the chartrosechart.set_global_opts(title_opts=opts.TitleOpts(title='Nightingale Rose Chart',subtitle=\"Covid-19 Death Rate\"), legend_opts=opts.LegendOpts(is_show=False), toolbox_opts=opts.ToolboxOpts())# set the series optionsrosechart.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position=\"inside\", font_size=12,formatter=\"{b}:{c}%\", font_style=\"italic\",font_weight=\"bold\", font_family=\"Century\"),)rosechart.render_notebook()" }, { "code": null, "e": 4327, "s": 4267, "text": "Finally, the beautiful Nightingale rose chart is generated!" }, { "code": null, "e": 4680, "s": 4327, "text": "From the chart, it is easy to see that the MS Zaandam, which is a cruise ship, has the highest death rate. Next to it are Burundi, Bahamas and Sudan. And the death rates of the top 15 countries all exceeded 10%, considerably higher than the death rate of normal seasonal flu, which is typically around 0.1% in the U.S., according to The New York Times." }, { "code": null, "e": 4736, "s": 4680, "text": "So, stay at home and enjoy learning data visualization!" }, { "code": null, "e": 4843, "s": 4736, "text": "If you are interested in making other types of beautiful charts, you may want to check out my other posts." }, { "code": null, "e": 5216, "s": 4843, "text": "Make a beautiful water polo chart in a few lines in PythonMake a beautiful bar chart in just few lines in PythonMake a beautiful scatterplot in a few lines in Python to make your report outstandingMake an impressive animated bubble chart with Plotly in Python — inspired by professor Hans RoslingMake the cutest chart in Python — visualize your data with hand-drawn charts" }, { "code": null, "e": 5275, "s": 5216, "text": "Make a beautiful water polo chart in a few lines in Python" }, { "code": null, "e": 5330, "s": 5275, "text": "Make a beautiful bar chart in just few lines in Python" }, { "code": null, "e": 5416, "s": 5330, "text": "Make a beautiful scatterplot in a few lines in Python to make your report outstanding" }, { "code": null, "e": 5516, "s": 5416, "text": "Make an impressive animated bubble chart with Plotly in Python — inspired by professor Hans Rosling" } ]
Function Interposition in C with an example of user defined malloc() - GeeksforGeeks
29 May, 2017 Function interposition is the concept of replacing calls to functions in dynamic libraries with calls to user-defined wrappers. What are applications? We can count number of calls to function.Store caller’s information and arguments passed to function to track usage.Detect memory leak, we can override malloc() and keep track of allocated spaces.We can add our own security policies. For example, we can add a policy that fork cannot be called with more that specified recursion depth. We can count number of calls to function. Store caller’s information and arguments passed to function to track usage. Detect memory leak, we can override malloc() and keep track of allocated spaces. We can add our own security policies. For example, we can add a policy that fork cannot be called with more that specified recursion depth. How to do function interposition?The task is to write our own malloc() and make sure our own malloc() is called inplace of library malloc(). Below is a driver program to test different types of interpositions of malloc(). // File Name : hello.c #include <stdio.h>#include <stdlib.h>#include <malloc.h> int main(void){ // Call to user defined malloc void *ptr = malloc(4); printf("Hello World\n"); return 0;} Compile time : Replace library call with our own function when the source code is compiled./* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf("My malloc called"); return NULL;}// filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size);Steps to execute above on Linux:// Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output file name as helloc. // -I. is used to include current folder (.) for header // files to make sure our malloc.h is becomes available. :~$ gcc -I. -o helloc hello.c mymalloc.o // Run the generated executable :~$ ./helloc My malloc called Hello World .Link time : When the relocatable object files are statically linked to form an executable object file.// filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) "--wrap symbol" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf("My malloc called"); return NULL;}Steps to execute above on Linux:// Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output name as hellol // "-Wl,--wrap=malloc" is used tell the linker to use // malloc() to call __wrap_malloc(). And to use // __real_malloc() to actual library malloc() :~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o // Run the generated executable :~$ ./hellol My malloc called Hello World .Load/run time : When an executable object file is loaded into memory, dynamically linked, and then executed.The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c./* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf("My malloc called\n"); return NULL;}Steps to execute above on Linux: // Compile hello.c with output name as helloc :~$ gcc -o hellor hello.c // Generate a shared library myalloc.so. Refer // https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/ // for details. :~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c // Make sure shared library is loaded and run before . :~$ LD_PRELOAD=./mymalloc.so ./hellor My malloc called Hello World .The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc().Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdfThis article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 aboveMy Personal Notes arrow_drop_upSave Compile time : Replace library call with our own function when the source code is compiled./* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf("My malloc called"); return NULL;}// filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size);Steps to execute above on Linux:// Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output file name as helloc. // -I. is used to include current folder (.) for header // files to make sure our malloc.h is becomes available. :~$ gcc -I. -o helloc hello.c mymalloc.o // Run the generated executable :~$ ./helloc My malloc called Hello World . /* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf("My malloc called"); return NULL;} // filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size); Steps to execute above on Linux: // Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output file name as helloc. // -I. is used to include current folder (.) for header // files to make sure our malloc.h is becomes available. :~$ gcc -I. -o helloc hello.c mymalloc.o // Run the generated executable :~$ ./helloc My malloc called Hello World . Link time : When the relocatable object files are statically linked to form an executable object file.// filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) "--wrap symbol" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf("My malloc called"); return NULL;}Steps to execute above on Linux:// Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output name as hellol // "-Wl,--wrap=malloc" is used tell the linker to use // malloc() to call __wrap_malloc(). And to use // __real_malloc() to actual library malloc() :~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o // Run the generated executable :~$ ./hellol My malloc called Hello World . // filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) "--wrap symbol" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf("My malloc called"); return NULL;} Steps to execute above on Linux: // Compile the file containing user defined malloc() :~$ gcc -c mymalloc.c // Compile hello.c with output name as hellol // "-Wl,--wrap=malloc" is used tell the linker to use // malloc() to call __wrap_malloc(). And to use // __real_malloc() to actual library malloc() :~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o // Run the generated executable :~$ ./hellol My malloc called Hello World . Load/run time : When an executable object file is loaded into memory, dynamically linked, and then executed.The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c./* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf("My malloc called\n"); return NULL;}Steps to execute above on Linux: // Compile hello.c with output name as helloc :~$ gcc -o hellor hello.c // Generate a shared library myalloc.so. Refer // https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/ // for details. :~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c // Make sure shared library is loaded and run before . :~$ LD_PRELOAD=./mymalloc.so ./hellor My malloc called Hello World .The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc().Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdfThis article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 aboveMy Personal Notes arrow_drop_upSave The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c. /* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf("My malloc called\n"); return NULL;} Steps to execute above on Linux: // Compile hello.c with output name as helloc :~$ gcc -o hellor hello.c // Generate a shared library myalloc.so. Refer // https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/ // for details. :~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c // Make sure shared library is loaded and run before . :~$ LD_PRELOAD=./mymalloc.so ./hellor My malloc called Hello World . The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc(). Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdf This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 CPP-Functions system-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 23843, "s": 23815, "text": "\n29 May, 2017" }, { "code": null, "e": 23971, "s": 23843, "text": "Function interposition is the concept of replacing calls to functions in dynamic libraries with calls to user-defined wrappers." }, { "code": null, "e": 23994, "s": 23971, "text": "What are applications?" }, { "code": null, "e": 24330, "s": 23994, "text": "We can count number of calls to function.Store caller’s information and arguments passed to function to track usage.Detect memory leak, we can override malloc() and keep track of allocated spaces.We can add our own security policies. For example, we can add a policy that fork cannot be called with more that specified recursion depth." }, { "code": null, "e": 24372, "s": 24330, "text": "We can count number of calls to function." }, { "code": null, "e": 24448, "s": 24372, "text": "Store caller’s information and arguments passed to function to track usage." }, { "code": null, "e": 24529, "s": 24448, "text": "Detect memory leak, we can override malloc() and keep track of allocated spaces." }, { "code": null, "e": 24669, "s": 24529, "text": "We can add our own security policies. For example, we can add a policy that fork cannot be called with more that specified recursion depth." }, { "code": null, "e": 24891, "s": 24669, "text": "How to do function interposition?The task is to write our own malloc() and make sure our own malloc() is called inplace of library malloc(). Below is a driver program to test different types of interpositions of malloc()." }, { "code": "// File Name : hello.c #include <stdio.h>#include <stdlib.h>#include <malloc.h> int main(void){ // Call to user defined malloc void *ptr = malloc(4); printf(\"Hello World\\n\"); return 0;}", "e": 25097, "s": 24891, "text": null }, { "code": null, "e": 28491, "s": 25097, "text": "Compile time : Replace library call with our own function when the source code is compiled./* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf(\"My malloc called\"); return NULL;}// filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size);Steps to execute above on Linux:// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output file name as helloc. \n// -I. is used to include current folder (.) for header\n// files to make sure our malloc.h is becomes available.\n:~$ gcc -I. -o helloc hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./helloc\nMy malloc called\nHello World .Link time : When the relocatable object files are statically linked to form an executable object file.// filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) \"--wrap symbol\" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf(\"My malloc called\"); return NULL;}Steps to execute above on Linux:// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output name as hellol \n// \"-Wl,--wrap=malloc\" is used tell the linker to use\n// malloc() to call __wrap_malloc(). And to use \n// __real_malloc() to actual library malloc() \n:~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./hellol\nMy malloc called\nHello World .Load/run time : When an executable object file is loaded into memory, dynamically linked, and then executed.The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c./* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf(\"My malloc called\\n\"); return NULL;}Steps to execute above on Linux:\n// Compile hello.c with output name as helloc\n:~$ gcc -o hellor hello.c\n\n// Generate a shared library myalloc.so. Refer\n// https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/\n// for details.\n:~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c\n\n// Make sure shared library is loaded and run before .\n:~$ LD_PRELOAD=./mymalloc.so ./hellor\nMy malloc called\nHello World\n.The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc().Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdfThis article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 aboveMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29405, "s": 28491, "text": "Compile time : Replace library call with our own function when the source code is compiled./* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf(\"My malloc called\"); return NULL;}// filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size);Steps to execute above on Linux:// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output file name as helloc. \n// -I. is used to include current folder (.) for header\n// files to make sure our malloc.h is becomes available.\n:~$ gcc -I. -o helloc hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./helloc\nMy malloc called\nHello World ." }, { "code": "/* Compile-time interposition of malloc using C preprocessor. A local malloc.h file defines malloc as wrapper */ // A file that contains our own malloc function// File Name : mymalloc.c#include <stdio.h>#include <malloc.h>void *mymalloc(size_t s){ printf(\"My malloc called\"); return NULL;}", "e": 29703, "s": 29405, "text": null }, { "code": "// filename : malloc.h// To replace all calls to malloc with mymalloc#define malloc(size) mymalloc(size)void *mymalloc(size_t size);", "e": 29836, "s": 29703, "text": null }, { "code": null, "e": 29869, "s": 29836, "text": "Steps to execute above on Linux:" }, { "code": null, "e": 30230, "s": 29869, "text": "// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output file name as helloc. \n// -I. is used to include current folder (.) for header\n// files to make sure our malloc.h is becomes available.\n:~$ gcc -I. -o helloc hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./helloc\nMy malloc called\nHello World " }, { "code": null, "e": 30232, "s": 30230, "text": "." }, { "code": null, "e": 31125, "s": 30232, "text": "Link time : When the relocatable object files are statically linked to form an executable object file.// filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) \"--wrap symbol\" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf(\"My malloc called\"); return NULL;}Steps to execute above on Linux:// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output name as hellol \n// \"-Wl,--wrap=malloc\" is used tell the linker to use\n// malloc() to call __wrap_malloc(). And to use \n// __real_malloc() to actual library malloc() \n:~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./hellol\nMy malloc called\nHello World ." }, { "code": "// filename : mymalloc.c/* Link-time interposition of malloc using the static linker’s (ld) \"--wrap symbol\" flag. */#include <stdio.h> // __real_malloc() is used to called actual library// malloc()void *__real_malloc(size_t size); // User defined wrapper for malloc()void *__wrap_malloc(size_t size){ printf(\"My malloc called\"); return NULL;}", "e": 31476, "s": 31125, "text": null }, { "code": null, "e": 31509, "s": 31476, "text": "Steps to execute above on Linux:" }, { "code": null, "e": 31917, "s": 31509, "text": "// Compile the file containing user defined malloc()\n:~$ gcc -c mymalloc.c\n\n// Compile hello.c with output name as hellol \n// \"-Wl,--wrap=malloc\" is used tell the linker to use\n// malloc() to call __wrap_malloc(). And to use \n// __real_malloc() to actual library malloc() \n:~$ gcc -Wl,--wrap=malloc -o hellol hello.c mymalloc.o\n\n// Run the generated executable\n:~$ ./hellol\nMy malloc called\nHello World " }, { "code": null, "e": 31919, "s": 31917, "text": "." }, { "code": null, "e": 33508, "s": 31919, "text": "Load/run time : When an executable object file is loaded into memory, dynamically linked, and then executed.The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c./* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf(\"My malloc called\\n\"); return NULL;}Steps to execute above on Linux:\n// Compile hello.c with output name as helloc\n:~$ gcc -o hellor hello.c\n\n// Generate a shared library myalloc.so. Refer\n// https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/\n// for details.\n:~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c\n\n// Make sure shared library is loaded and run before .\n:~$ LD_PRELOAD=./mymalloc.so ./hellor\nMy malloc called\nHello World\n.The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc().Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdfThis article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 aboveMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33718, "s": 33508, "text": "The environment variable LD_PRELOAD gives the loader a list of libraries to load be loaded before a command or executable.We make a dynamic library and make sure it is loaded before our executable for hello.c." }, { "code": "/* Run-time interposition of malloc based on dynamic linker’s (ld-linux.so) LD_PRELOAD mechanism */#define _GNU_SOURCE#include <stdio.h> void *malloc(size_t s){ printf(\"My malloc called\\n\"); return NULL;}", "e": 33930, "s": 33718, "text": null }, { "code": null, "e": 33963, "s": 33930, "text": "Steps to execute above on Linux:" }, { "code": null, "e": 34342, "s": 33963, "text": "\n// Compile hello.c with output name as helloc\n:~$ gcc -o hellor hello.c\n\n// Generate a shared library myalloc.so. Refer\n// https://www.geeksforgeeks.org/working-with-shared-libraries-set-2/\n// for details.\n:~$ gcc -shared -fPIC -o mymalloc.so mymalloc.c\n\n// Make sure shared library is loaded and run before .\n:~$ LD_PRELOAD=./mymalloc.so ./hellor\nMy malloc called\nHello World\n" }, { "code": null, "e": 34344, "s": 34342, "text": "." }, { "code": null, "e": 34488, "s": 34344, "text": "The code for user defined malloc is kept small for better readability. Ideally, it should allocate memory by making a call to library malloc()." }, { "code": null, "e": 34567, "s": 34488, "text": "Source:https://www.utdallas.edu/~zxl111930/spring2012/public/lec18-handout.pdf" }, { "code": null, "e": 34838, "s": 34567, "text": "This article is contributed by Aditya Chatterjee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34962, "s": 34838, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 34976, "s": 34962, "text": "CPP-Functions" }, { "code": null, "e": 34995, "s": 34976, "text": "system-programming" }, { "code": null, "e": 35006, "s": 34995, "text": "C Language" }, { "code": null, "e": 35010, "s": 35006, "text": "C++" }, { "code": null, "e": 35014, "s": 35010, "text": "CPP" }, { "code": null, "e": 35112, "s": 35014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35121, "s": 35112, "text": "Comments" }, { "code": null, "e": 35134, "s": 35121, "text": "Old Comments" }, { "code": null, "e": 35172, "s": 35134, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 35198, "s": 35172, "text": "Exception Handling in C++" }, { "code": null, "e": 35218, "s": 35198, "text": "Multithreading in C" }, { "code": null, "e": 35259, "s": 35218, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35281, "s": 35259, "text": "'this' pointer in C++" }, { "code": null, "e": 35299, "s": 35281, "text": "Vector in C++ STL" }, { "code": null, "e": 35345, "s": 35299, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 35388, "s": 35345, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 35407, "s": 35388, "text": "Inheritance in C++" } ]
How to combine lists of data frames in R?
If we have a list of data frames and the size of those data frames is same then we might want to combine the lists so that the data frames can be combined. This can be done by using mapply function along with cbind. For example, if we have two lists of data frames defined as List1 and List2 then we can combine them using the command − mapply(cbind,List1,List2,SIMPLIFY=FALSE). Consider the below data frame − Live Demo > x1<-rnorm(10) > x2<-rnorm(10) > df1<-data.frame(x1,x2) > df1 x1 x2 1 0.2378371 0.51433808 2 0.0638975 -1.66077353 3 0.3987209 0.68480587 4 -1.1321073 0.29528261 5 -0.5603269 1.14556819 6 2.2072545 -1.20718355 7 0.8196423 0.38380242 8 -2.2394064 0.06741712 9 -0.7356725 -1.46968026 10 -1.4642820 -1.39423679 Live Demo > y1<-rnorm(10) > y2<-rnorm(10) > df2<-data.frame(y1,y2) > df2 y1 y2 1 2.2307515 0.375538934 2 -1.3539616 -0.169574915 3 -0.1332480 -0.788416414 4 1.3181498 1.887995737 5 -1.4384012 1.261034365 6 0.3725585 -0.493219141 7 -0.7806511 -1.177616450 8 -0.4772392 0.250962895 9 -0.8932982 -0.004567268 10 0.2224190 -0.203232106 > List1<-list(df1,df2) > List1 [[1]] x1 x2 1 0.2378371 0.51433808 2 0.0638975 -1.66077353 3 0.3987209 0.68480587 4 -1.1321073 0.29528261 5 -0.5603269 1.14556819 6 2.2072545 -1.20718355 7 0.8196423 0.38380242 8 -2.2394064 0.06741712 9 -0.7356725 -1.46968026 10 -1.4642820 -1.39423679 [[2]] y1 y2 1 2.2307515 0.375538934 2 -1.3539616 -0.169574915 3 -0.1332480 -0.788416414 4 1.3181498 1.887995737 5 -1.4384012 1.261034365 6 0.3725585 -0.493219141 7 -0.7806511 -1.177616450 8 -0.4772392 0.250962895 9 -0.8932982 -0.004567268 10 0.2224190 -0.203232106 Live Demo > a1<-rnorm(10) > a2<-rnorm(10) > df3<-data.frame(a1,a2) > df3 a1 a2 1 1.5711728 0.2861241 2 0.8062374 0.9469154 3 1.1505496 -0.5894829 4 0.9164866 -0.3137043 5 -1.3424446 -1.2921698 6 -0.1499540 -0.8940665 7 -0.1498557 -1.1361156 8 0.9299988 0.7679135 9 -1.7079005 -0.7099908 10 0.8146867 1.3921303 Live Demo > b1<-rnorm(10) > b2<-rnorm(10) > df4<-data.frame(b1,b2) > df4 b1 b2 1 -1.7113866 1.7014637 2 -0.0202485 1.2428109 3 -0.3892979 -1.5831333 4 0.2127277 -0.4943695 5 -0.4846616 1.0283278 6 -1.4116239 -1.4882983 7 -0.1737286 -0.1101114 8 1.4613389 0.1531942 9 -0.1573986 0.3431330 10 -0.2782074 0.5439397 > List2<-list(df3,df4) > List2 [[1]] a1 a2 1 1.5711728 0.2861241 2 0.8062374 0.9469154 3 1.1505496 -0.5894829 4 0.9164866 -0.3137043 5 -1.3424446 -1.2921698 6 -0.1499540 -0.8940665 7 -0.1498557 -1.1361156 8 0.9299988 0.7679135 9 -1.7079005 -0.7099908 10 0.8146867 1.3921303 [[2]] b1 b2 1 -1.7113866 1.7014637 2 -0.0202485 1.2428109 3 -0.3892979 -1.5831333 4 0.2127277 -0.4943695 5 -0.4846616 1.0283278 6 -1.4116239 -1.4882983 7 -0.1737286 -0.1101114 8 1.4613389 0.1531942 9 -0.1573986 0.3431330 10 -0.2782074 0.5439397 Combining the list of data frames − > mapply(cbind,List1,List2,SIMPLIFY=FALSE) [[1]] x1 x2 a1 a2 1 0.2378371 0.51433808 1.5711728 0.2861241 2 0.0638975 -1.66077353 0.8062374 0.9469154 3 0.3987209 0.68480587 1.1505496 -0.5894829 4 -1.1321073 0.29528261 0.9164866 -0.3137043 5 -0.5603269 1.14556819 -1.3424446 -1.2921698 6 2.2072545 -1.20718355 -0.1499540 -0.8940665 7 0.8196423 0.38380242 -0.1498557 -1.1361156 8 -2.2394064 0.06741712 0.9299988 0.7679135 9 -0.7356725 -1.46968026 -1.7079005 -0.7099908 10 -1.4642820 -1.39423679 0.8146867 1.3921303 [[2]] y1 y2 b1 b2 1 2.2307515 0.375538934 -1.7113866 1.7014637 2 -1.3539616 -0.169574915 -0.0202485 1.2428109 3 -0.1332480 -0.788416414 -0.3892979 -1.5831333 4 1.3181498 1.887995737 0.2127277 -0.4943695 5 -1.4384012 1.261034365 -0.4846616 1.0283278 6 0.3725585 -0.493219141 -1.4116239 -1.4882983 7 -0.7806511 -1.177616450 -0.1737286 -0.1101114 8 -0.4772392 0.250962895 1.4613389 0.1531942 9 -0.8932982 -0.004567268 -0.1573986 0.3431330 10 0.2224190 -0.203232106 -0.2782074 0.5439397
[ { "code": null, "e": 1399, "s": 1062, "text": "If we have a list of data frames and the size of those data frames is same then we might want to combine the lists so that the data frames can be combined. This can be done by using mapply function along with cbind. For example, if we have two lists of data frames defined as List1 and List2 then we can combine them using the command −" }, { "code": null, "e": 1441, "s": 1399, "text": "mapply(cbind,List1,List2,SIMPLIFY=FALSE)." }, { "code": null, "e": 1473, "s": 1441, "text": "Consider the below data frame −" }, { "code": null, "e": 1483, "s": 1473, "text": "Live Demo" }, { "code": null, "e": 1546, "s": 1483, "text": "> x1<-rnorm(10)\n> x2<-rnorm(10)\n> df1<-data.frame(x1,x2)\n> df1" }, { "code": null, "e": 1825, "s": 1546, "text": " x1 x2\n1 0.2378371 0.51433808\n2 0.0638975 -1.66077353\n3 0.3987209 0.68480587\n4 -1.1321073 0.29528261\n5 -0.5603269 1.14556819\n6 2.2072545 -1.20718355\n7 0.8196423 0.38380242\n8 -2.2394064 0.06741712\n9 -0.7356725 -1.46968026\n10 -1.4642820 -1.39423679" }, { "code": null, "e": 1835, "s": 1825, "text": "Live Demo" }, { "code": null, "e": 1898, "s": 1835, "text": "> y1<-rnorm(10)\n> y2<-rnorm(10)\n> df2<-data.frame(y1,y2)\n> df2" }, { "code": null, "e": 2178, "s": 1898, "text": " y1 y2\n1 2.2307515 0.375538934\n2 -1.3539616 -0.169574915\n3 -0.1332480 -0.788416414\n4 1.3181498 1.887995737\n5 -1.4384012 1.261034365\n6 0.3725585 -0.493219141\n7 -0.7806511 -1.177616450\n8 -0.4772392 0.250962895\n9 -0.8932982 -0.004567268\n10 0.2224190 -0.203232106" }, { "code": null, "e": 2209, "s": 2178, "text": "> List1<-list(df1,df2)\n> List1" }, { "code": null, "e": 2758, "s": 2209, "text": "[[1]]\n x1 x2\n1 0.2378371 0.51433808\n2 0.0638975 -1.66077353\n3 0.3987209 0.68480587\n4 -1.1321073 0.29528261\n5 -0.5603269 1.14556819\n6 2.2072545 -1.20718355\n7 0.8196423 0.38380242\n8 -2.2394064 0.06741712\n9 -0.7356725 -1.46968026\n10 -1.4642820 -1.39423679\n\n[[2]]\ny1 y2\n1 2.2307515 0.375538934\n2 -1.3539616 -0.169574915\n3 -0.1332480 -0.788416414\n4 1.3181498 1.887995737\n5 -1.4384012 1.261034365\n6 0.3725585 -0.493219141\n7 -0.7806511 -1.177616450\n8 -0.4772392 0.250962895\n9 -0.8932982 -0.004567268\n10 0.2224190 -0.203232106" }, { "code": null, "e": 2768, "s": 2758, "text": "Live Demo" }, { "code": null, "e": 2831, "s": 2768, "text": "> a1<-rnorm(10)\n> a2<-rnorm(10)\n> df3<-data.frame(a1,a2)\n> df3" }, { "code": null, "e": 3090, "s": 2831, "text": " a1 a2\n1 1.5711728 0.2861241\n2 0.8062374 0.9469154\n3 1.1505496 -0.5894829\n4 0.9164866 -0.3137043\n5 -1.3424446 -1.2921698\n6 -0.1499540 -0.8940665\n7 -0.1498557 -1.1361156\n8 0.9299988 0.7679135\n9 -1.7079005 -0.7099908\n10 0.8146867 1.3921303" }, { "code": null, "e": 3100, "s": 3090, "text": "Live Demo" }, { "code": null, "e": 3163, "s": 3100, "text": "> b1<-rnorm(10)\n> b2<-rnorm(10)\n> df4<-data.frame(b1,b2)\n> df4" }, { "code": null, "e": 3421, "s": 3163, "text": " b1 b2\n1 -1.7113866 1.7014637\n2 -0.0202485 1.2428109\n3 -0.3892979 -1.5831333\n4 0.2127277 -0.4943695\n5 -0.4846616 1.0283278\n6 -1.4116239 -1.4882983\n7 -0.1737286 -0.1101114\n8 1.4613389 0.1531942\n9 -0.1573986 0.3431330\n10 -0.2782074 0.5439397" }, { "code": null, "e": 3452, "s": 3421, "text": "> List2<-list(df3,df4)\n> List2" }, { "code": null, "e": 3963, "s": 3452, "text": "[[1]]\n\n a1 a2\n1 1.5711728 0.2861241\n2 0.8062374 0.9469154\n3 1.1505496 -0.5894829\n4 0.9164866 -0.3137043\n5 -1.3424446 -1.2921698\n6 -0.1499540 -0.8940665\n7 -0.1498557 -1.1361156\n8 0.9299988 0.7679135\n9 -1.7079005 -0.7099908\n10 0.8146867 1.3921303\n\n[[2]]\nb1 b2\n1 -1.7113866 1.7014637\n2 -0.0202485 1.2428109\n3 -0.3892979 -1.5831333\n4 0.2127277 -0.4943695\n5 -0.4846616 1.0283278\n6 -1.4116239 -1.4882983\n7 -0.1737286 -0.1101114\n8 1.4613389 0.1531942\n9 -0.1573986 0.3431330\n10 -0.2782074 0.5439397" }, { "code": null, "e": 3999, "s": 3963, "text": "Combining the list of data frames −" }, { "code": null, "e": 4042, "s": 3999, "text": "> mapply(cbind,List1,List2,SIMPLIFY=FALSE)" }, { "code": null, "e": 4994, "s": 4042, "text": "[[1]]\nx1 x2 a1 a2\n1 0.2378371 0.51433808 1.5711728 0.2861241\n2 0.0638975 -1.66077353 0.8062374 0.9469154\n3 0.3987209 0.68480587 1.1505496 -0.5894829\n4 -1.1321073 0.29528261 0.9164866 -0.3137043\n5 -0.5603269 1.14556819 -1.3424446 -1.2921698\n6 2.2072545 -1.20718355 -0.1499540 -0.8940665\n7 0.8196423 0.38380242 -0.1498557 -1.1361156\n8 -2.2394064 0.06741712 0.9299988 0.7679135\n9 -0.7356725 -1.46968026 -1.7079005 -0.7099908\n10 -1.4642820 -1.39423679 0.8146867 1.3921303\n\n[[2]]\ny1 y2 b1 b2\n1 2.2307515 0.375538934 -1.7113866 1.7014637\n2 -1.3539616 -0.169574915 -0.0202485 1.2428109\n3 -0.1332480 -0.788416414 -0.3892979 -1.5831333\n4 1.3181498 1.887995737 0.2127277 -0.4943695\n5 -1.4384012 1.261034365 -0.4846616 1.0283278\n6 0.3725585 -0.493219141 -1.4116239 -1.4882983\n7 -0.7806511 -1.177616450 -0.1737286 -0.1101114\n8 -0.4772392 0.250962895 1.4613389 0.1531942\n9 -0.8932982 -0.004567268 -0.1573986 0.3431330\n10 0.2224190 -0.203232106 -0.2782074 0.5439397" } ]
Unary operators in C/C++ - GeeksforGeeks
19 Oct, 2021 Unary operator: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-)increment(++)decrement(- -)NOT(!)Addressof operator(&)sizeof() unary minus(-) increment(++) decrement(- -) NOT(!) Addressof operator(&) sizeof() unary minusThe minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. int a = 10; int b = -a; // b = -10 unary minus is different from subtraction operator, as subtraction requires two operands.incrementIt is used to increment the value of the variable by 1. The increment can be done in two ways:prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1; int b = ++a; // b = 2 postfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1; int b = a++; // b = 1 int c = a; // c = 2 decrementIt is used to decrement the value of the variable by 1. The decrement can be done in two ways:prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1; int b = --a; // b = 0 postfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1; int b = a--; // b = 1 int c = a; // c = 0 C++ program for combination of prefix and postfix operations:// C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << "a value: " << a << endl; int b = a++; cout << "b value after a++ : " << b << endl; cout << "a value after a++ : " << a << endl; // Pre increment a = 1; cout << "a value:" << a << endl; b = ++a; cout << "b value after ++a : " << b << endl; cout << "a value after ++a : "<< a << endl; // Post decrement a = 5; cout << "a value before decrement: " << a << endl; b = a--; cout << "b value after a-- : " << b << endl; cout << "a value after a-- : " << a << endl; // Pre decrement a = 5; cout << "a value: "<< a<<endl; b = --a; cout << "b value after --a : " << b << endl; cout << "a value after --a : " << a << endl; return 0;}Output:a value: 1 b value after a++ : 1 a value after a++ : 2 a value:1 b value after ++a : 2 a value after ++a : 2 a value before decrement: 5 b value after a-- : 5 a value after a-- : 4 a value: 5 b value after --a : 4 a value after --a : 4 The above program shows how the postfix and prefix works.NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. If x is true, then !x is false If x is false, then !x is true Addressof operator(&): It gives an address of a variable. It is used to return the memory address of a variable. These addresses returned by the address-of operator are known as pointers because they “point” to the variable in memory.& gives an address on variable n int a; int *ptr; ptr = &a; // address of a is copied to the location ptr. sizeof(): This operator returns the size of its operand, in bytes. The sizeof operator always precedes its operand.The operand is an expression, or it may be a cast.#include <iostream>using namespace std; int main(){ float n = 0; cout << "size of n: " << sizeof(n); return 1;}Output:size of n: 4 This article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.My Personal Notes arrow_drop_upSave unary minusThe minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. int a = 10; int b = -a; // b = -10 unary minus is different from subtraction operator, as subtraction requires two operands. int a = 10; int b = -a; // b = -10 unary minus is different from subtraction operator, as subtraction requires two operands. incrementIt is used to increment the value of the variable by 1. The increment can be done in two ways:prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1; int b = ++a; // b = 2 postfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1; int b = a++; // b = 1 int c = a; // c = 2 prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1; int b = ++a; // b = 2 postfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1; int b = a++; // b = 1 int c = a; // c = 2 prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1; int b = ++a; // b = 2 int a = 1; int b = ++a; // b = 2 postfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1; int b = a++; // b = 1 int c = a; // c = 2 int a = 1; int b = a++; // b = 1 int c = a; // c = 2 decrementIt is used to decrement the value of the variable by 1. The decrement can be done in two ways:prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1; int b = --a; // b = 0 postfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1; int b = a--; // b = 1 int c = a; // c = 0 C++ program for combination of prefix and postfix operations:// C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << "a value: " << a << endl; int b = a++; cout << "b value after a++ : " << b << endl; cout << "a value after a++ : " << a << endl; // Pre increment a = 1; cout << "a value:" << a << endl; b = ++a; cout << "b value after ++a : " << b << endl; cout << "a value after ++a : "<< a << endl; // Post decrement a = 5; cout << "a value before decrement: " << a << endl; b = a--; cout << "b value after a-- : " << b << endl; cout << "a value after a-- : " << a << endl; // Pre decrement a = 5; cout << "a value: "<< a<<endl; b = --a; cout << "b value after --a : " << b << endl; cout << "a value after --a : " << a << endl; return 0;}Output:a value: 1 b value after a++ : 1 a value after a++ : 2 a value:1 b value after ++a : 2 a value after ++a : 2 a value before decrement: 5 b value after a-- : 5 a value after a-- : 4 a value: 5 b value after --a : 4 a value after --a : 4 The above program shows how the postfix and prefix works. prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1; int b = --a; // b = 0 postfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1; int b = a--; // b = 1 int c = a; // c = 0 prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1; int b = --a; // b = 0 int a = 1; int b = --a; // b = 0 postfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1; int b = a--; // b = 1 int c = a; // c = 0 int a = 1; int b = a--; // b = 1 int c = a; // c = 0 C++ program for combination of prefix and postfix operations: // C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << "a value: " << a << endl; int b = a++; cout << "b value after a++ : " << b << endl; cout << "a value after a++ : " << a << endl; // Pre increment a = 1; cout << "a value:" << a << endl; b = ++a; cout << "b value after ++a : " << b << endl; cout << "a value after ++a : "<< a << endl; // Post decrement a = 5; cout << "a value before decrement: " << a << endl; b = a--; cout << "b value after a-- : " << b << endl; cout << "a value after a-- : " << a << endl; // Pre decrement a = 5; cout << "a value: "<< a<<endl; b = --a; cout << "b value after --a : " << b << endl; cout << "a value after --a : " << a << endl; return 0;} Output: a value: 1 b value after a++ : 1 a value after a++ : 2 a value:1 b value after ++a : 2 a value after ++a : 2 a value before decrement: 5 b value after a-- : 5 a value after a-- : 4 a value: 5 b value after --a : 4 a value after --a : 4 The above program shows how the postfix and prefix works. NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. If x is true, then !x is false If x is false, then !x is true If x is true, then !x is false If x is false, then !x is true Addressof operator(&): It gives an address of a variable. It is used to return the memory address of a variable. These addresses returned by the address-of operator are known as pointers because they “point” to the variable in memory.& gives an address on variable n int a; int *ptr; ptr = &a; // address of a is copied to the location ptr. & gives an address on variable n int a; int *ptr; ptr = &a; // address of a is copied to the location ptr. sizeof(): This operator returns the size of its operand, in bytes. The sizeof operator always precedes its operand.The operand is an expression, or it may be a cast.#include <iostream>using namespace std; int main(){ float n = 0; cout << "size of n: " << sizeof(n); return 1;}Output:size of n: 4 This article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.My Personal Notes arrow_drop_upSave #include <iostream>using namespace std; int main(){ float n = 0; cout << "size of n: " << sizeof(n); return 1;} Output: size of n: 4 This article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. SRKReddy1 tusharmalhotra494 gulshankumarar231 khushboogoyal499 C-Operators CBSE - Class 11 cpp-operator school-programming C Language C++ cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Socket Programming in C/C++
[ { "code": null, "e": 26570, "s": 26542, "text": "\n19 Oct, 2021" }, { "code": null, "e": 26655, "s": 26570, "text": "Unary operator: are operators that act upon a single operand to produce a new value." }, { "code": null, "e": 26681, "s": 26655, "text": "Types of unary operators:" }, { "code": null, "e": 26758, "s": 26681, "text": "unary minus(-)increment(++)decrement(- -)NOT(!)Addressof operator(&)sizeof()" }, { "code": null, "e": 26773, "s": 26758, "text": "unary minus(-)" }, { "code": null, "e": 26787, "s": 26773, "text": "increment(++)" }, { "code": null, "e": 26802, "s": 26787, "text": "decrement(- -)" }, { "code": null, "e": 26809, "s": 26802, "text": "NOT(!)" }, { "code": null, "e": 26831, "s": 26809, "text": "Addressof operator(&)" }, { "code": null, "e": 26840, "s": 26831, "text": "sizeof()" }, { "code": null, "e": 30588, "s": 26840, "text": "unary minusThe minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. int a = 10;\n int b = -a; // b = -10\nunary minus is different from subtraction operator, as subtraction requires two operands.incrementIt is used to increment the value of the variable by 1. The increment can be done in two ways:prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1;\n int b = ++a; // b = 2\npostfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1;\n int b = a++; // b = 1\n int c = a; // c = 2\ndecrementIt is used to decrement the value of the variable by 1. The decrement can be done in two ways:prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1;\n int b = --a; // b = 0\npostfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1;\n int b = a--; // b = 1\n int c = a; // c = 0\nC++ program for combination of prefix and postfix operations:// C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << \"a value: \" << a << endl; int b = a++; cout << \"b value after a++ : \" << b << endl; cout << \"a value after a++ : \" << a << endl; // Pre increment a = 1; cout << \"a value:\" << a << endl; b = ++a; cout << \"b value after ++a : \" << b << endl; cout << \"a value after ++a : \"<< a << endl; // Post decrement a = 5; cout << \"a value before decrement: \" << a << endl; b = a--; cout << \"b value after a-- : \" << b << endl; cout << \"a value after a-- : \" << a << endl; // Pre decrement a = 5; cout << \"a value: \"<< a<<endl; b = --a; cout << \"b value after --a : \" << b << endl; cout << \"a value after --a : \" << a << endl; return 0;}Output:a value: 1\nb value after a++ : 1\na value after a++ : 2\na value:1\nb value after ++a : 2\na value after ++a : 2\na value before decrement: 5\nb value after a-- : 5\na value after a-- : 4\na value: 5\nb value after --a : 4\na value after --a : 4\nThe above program shows how the postfix and prefix works.NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. If x is true, then !x is false\n If x is false, then !x is true\nAddressof operator(&): It gives an address of a variable. It is used to return the memory address of a variable. These addresses returned by the address-of operator are known as pointers because they “point” to the variable in memory.& gives an address on variable n\nint a;\nint *ptr;\nptr = &a; // address of a is copied to the location ptr. \nsizeof(): This operator returns the size of its operand, in bytes. The sizeof operator always precedes its operand.The operand is an expression, or it may be a cast.#include <iostream>using namespace std; int main(){ float n = 0; cout << \"size of n: \" << sizeof(n); return 1;}Output:size of n: 4\nThis article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30855, "s": 30588, "text": "unary minusThe minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive. int a = 10;\n int b = -a; // b = -10\nunary minus is different from subtraction operator, as subtraction requires two operands." }, { "code": null, "e": 30894, "s": 30855, "text": " int a = 10;\n int b = -a; // b = -10\n" }, { "code": null, "e": 30984, "s": 30894, "text": "unary minus is different from subtraction operator, as subtraction requires two operands." }, { "code": null, "e": 31452, "s": 30984, "text": "incrementIt is used to increment the value of the variable by 1. The increment can be done in two ways:prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1;\n int b = ++a; // b = 2\npostfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1;\n int b = a++; // b = 1\n int c = a; // c = 2\n" }, { "code": null, "e": 31817, "s": 31452, "text": "prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1;\n int b = ++a; // b = 2\npostfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1;\n int b = a++; // b = 1\n int c = a; // c = 2\n" }, { "code": null, "e": 31990, "s": 31817, "text": "prefix incrementIn this method, the operator precedes the operand (e.g., ++a). The value of operand will be altered before it is used. int a = 1;\n int b = ++a; // b = 2\n" }, { "code": null, "e": 32029, "s": 31990, "text": " int a = 1;\n int b = ++a; // b = 2\n" }, { "code": null, "e": 32222, "s": 32029, "text": "postfix incrementIn this method, the operator follows the operand (e.g., a++). The value operand will be altered after it is used. int a = 1;\n int b = a++; // b = 1\n int c = a; // c = 2\n" }, { "code": null, "e": 32285, "s": 32222, "text": " int a = 1;\n int b = a++; // b = 1\n int c = a; // c = 2\n" }, { "code": null, "e": 33997, "s": 32285, "text": "decrementIt is used to decrement the value of the variable by 1. The decrement can be done in two ways:prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1;\n int b = --a; // b = 0\npostfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1;\n int b = a--; // b = 1\n int c = a; // c = 0\nC++ program for combination of prefix and postfix operations:// C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << \"a value: \" << a << endl; int b = a++; cout << \"b value after a++ : \" << b << endl; cout << \"a value after a++ : \" << a << endl; // Pre increment a = 1; cout << \"a value:\" << a << endl; b = ++a; cout << \"b value after ++a : \" << b << endl; cout << \"a value after ++a : \"<< a << endl; // Post decrement a = 5; cout << \"a value before decrement: \" << a << endl; b = a--; cout << \"b value after a-- : \" << b << endl; cout << \"a value after a-- : \" << a << endl; // Pre decrement a = 5; cout << \"a value: \"<< a<<endl; b = --a; cout << \"b value after --a : \" << b << endl; cout << \"a value after --a : \" << a << endl; return 0;}Output:a value: 1\nb value after a++ : 1\na value after a++ : 2\na value:1\nb value after ++a : 2\na value after ++a : 2\na value before decrement: 5\nb value after a-- : 5\na value after a-- : 4\na value: 5\nb value after --a : 4\na value after --a : 4\nThe above program shows how the postfix and prefix works." }, { "code": null, "e": 34367, "s": 33997, "text": "prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1;\n int b = --a; // b = 0\npostfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1;\n int b = a--; // b = 1\n int c = a; // c = 0\n" }, { "code": null, "e": 34541, "s": 34367, "text": "prefix decrementIn this method, the operator precedes the operand (e.g., – -a). The value of operand will be altered before it is used. int a = 1;\n int b = --a; // b = 0\n" }, { "code": null, "e": 34580, "s": 34541, "text": " int a = 1;\n int b = --a; // b = 0\n" }, { "code": null, "e": 34777, "s": 34580, "text": "postfix decrementIn this method, the operator follows the operand (e.g., a- -). The value of operand will be altered after it is used. int a = 1;\n int b = a--; // b = 1\n int c = a; // c = 0\n" }, { "code": null, "e": 34840, "s": 34777, "text": " int a = 1;\n int b = a--; // b = 1\n int c = a; // c = 0\n" }, { "code": null, "e": 34902, "s": 34840, "text": "C++ program for combination of prefix and postfix operations:" }, { "code": "// C++ program to demonstrate working of unary increment// and decrement operators#include <iostream>using namespace std; int main(){ // Post increment int a = 1; cout << \"a value: \" << a << endl; int b = a++; cout << \"b value after a++ : \" << b << endl; cout << \"a value after a++ : \" << a << endl; // Pre increment a = 1; cout << \"a value:\" << a << endl; b = ++a; cout << \"b value after ++a : \" << b << endl; cout << \"a value after ++a : \"<< a << endl; // Post decrement a = 5; cout << \"a value before decrement: \" << a << endl; b = a--; cout << \"b value after a-- : \" << b << endl; cout << \"a value after a-- : \" << a << endl; // Pre decrement a = 5; cout << \"a value: \"<< a<<endl; b = --a; cout << \"b value after --a : \" << b << endl; cout << \"a value after --a : \" << a << endl; return 0;}", "e": 35781, "s": 34902, "text": null }, { "code": null, "e": 35789, "s": 35781, "text": "Output:" }, { "code": null, "e": 36026, "s": 35789, "text": "a value: 1\nb value after a++ : 1\na value after a++ : 2\na value:1\nb value after ++a : 2\na value after ++a : 2\na value before decrement: 5\nb value after a-- : 5\na value after a-- : 4\na value: 5\nb value after --a : 4\na value after --a : 4\n" }, { "code": null, "e": 36084, "s": 36026, "text": "The above program shows how the postfix and prefix works." }, { "code": null, "e": 36286, "s": 36084, "text": "NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. If x is true, then !x is false\n If x is false, then !x is true\n" }, { "code": null, "e": 36355, "s": 36286, "text": " If x is true, then !x is false\n If x is false, then !x is true\n" }, { "code": null, "e": 36698, "s": 36355, "text": "Addressof operator(&): It gives an address of a variable. It is used to return the memory address of a variable. These addresses returned by the address-of operator are known as pointers because they “point” to the variable in memory.& gives an address on variable n\nint a;\nint *ptr;\nptr = &a; // address of a is copied to the location ptr. \n" }, { "code": null, "e": 36807, "s": 36698, "text": "& gives an address on variable n\nint a;\nint *ptr;\nptr = &a; // address of a is copied to the location ptr. \n" }, { "code": null, "e": 37568, "s": 36807, "text": "sizeof(): This operator returns the size of its operand, in bytes. The sizeof operator always precedes its operand.The operand is an expression, or it may be a cast.#include <iostream>using namespace std; int main(){ float n = 0; cout << \"size of n: \" << sizeof(n); return 1;}Output:size of n: 4\nThis article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.My Personal Notes\narrow_drop_upSave" }, { "code": "#include <iostream>using namespace std; int main(){ float n = 0; cout << \"size of n: \" << sizeof(n); return 1;}", "e": 37687, "s": 37568, "text": null }, { "code": null, "e": 37695, "s": 37687, "text": "Output:" }, { "code": null, "e": 37709, "s": 37695, "text": "size of n: 4\n" }, { "code": null, "e": 38008, "s": 37709, "text": "This article is contributed by I. HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 38133, "s": 38008, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38143, "s": 38133, "text": "SRKReddy1" }, { "code": null, "e": 38161, "s": 38143, "text": "tusharmalhotra494" }, { "code": null, "e": 38179, "s": 38161, "text": "gulshankumarar231" }, { "code": null, "e": 38196, "s": 38179, "text": "khushboogoyal499" }, { "code": null, "e": 38208, "s": 38196, "text": "C-Operators" }, { "code": null, "e": 38224, "s": 38208, "text": "CBSE - Class 11" }, { "code": null, "e": 38237, "s": 38224, "text": "cpp-operator" }, { "code": null, "e": 38256, "s": 38237, "text": "school-programming" }, { "code": null, "e": 38267, "s": 38256, "text": "C Language" }, { "code": null, "e": 38271, "s": 38267, "text": "C++" }, { "code": null, "e": 38284, "s": 38271, "text": "cpp-operator" }, { "code": null, "e": 38288, "s": 38284, "text": "CPP" }, { "code": null, "e": 38386, "s": 38288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38395, "s": 38386, "text": "Comments" }, { "code": null, "e": 38408, "s": 38395, "text": "Old Comments" }, { "code": null, "e": 38486, "s": 38408, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 38509, "s": 38486, "text": "std::sort() in C++ STL" }, { "code": null, "e": 38536, "s": 38509, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 38564, "s": 38536, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 38610, "s": 38564, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 38628, "s": 38610, "text": "Vector in C++ STL" }, { "code": null, "e": 38674, "s": 38628, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 38697, "s": 38674, "text": "std::sort() in C++ STL" }, { "code": null, "e": 38724, "s": 38697, "text": "Bitwise Operators in C/C++" } ]
rename command in Linux with Examples - GeeksforGeeks
24 May, 2019 rename command in Linux is used to rename the named files according to the regular expression perlexpr. It can change the name of the multiple files. If the user will not specify any file names on the command line with this command then it will take the file name from the standard input. Syntax: rename [options] expression replacement file... Options: rename -s: This option renames the files ignoring the symbolic links.Example:rename -s 's/root/new/' sym.png Example: rename -s 's/root/new/' sym.png rename -v: This option is used to show which files is being renamed, if there is any.Example:rename -v 's/jpeg/png/' *.jpeg Example: rename -v 's/jpeg/png/' *.jpeg rename -n : This option comes into play when the user wants to see only the final change.Example:rename -n 's/png/jpeg/' *.png Example: rename -n 's/png/jpeg/' *.png rename -o : This option will not going to overwrite the existing files.Example:rename -o 's/jpeg/png/' *.jpeg Example: rename -o 's/jpeg/png/' *.jpeg rename -V: This option will show the version information and exit.Example:rename -V 's/jpeg/png/' *.jpeg Example: rename -V 's/jpeg/png/' *.jpeg rename -help : This option will going show the help message and exit.Example:rename -help Example: rename -help linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24040, "s": 24012, "text": "\n24 May, 2019" }, { "code": null, "e": 24329, "s": 24040, "text": "rename command in Linux is used to rename the named files according to the regular expression perlexpr. It can change the name of the multiple files. If the user will not specify any file names on the command line with this command then it will take the file name from the standard input." }, { "code": null, "e": 24337, "s": 24329, "text": "Syntax:" }, { "code": null, "e": 24386, "s": 24337, "text": "rename [options] expression replacement file...\n" }, { "code": null, "e": 24395, "s": 24386, "text": "Options:" }, { "code": null, "e": 24504, "s": 24395, "text": "rename -s: This option renames the files ignoring the symbolic links.Example:rename -s 's/root/new/' sym.png" }, { "code": null, "e": 24513, "s": 24504, "text": "Example:" }, { "code": null, "e": 24545, "s": 24513, "text": "rename -s 's/root/new/' sym.png" }, { "code": null, "e": 24669, "s": 24545, "text": "rename -v: This option is used to show which files is being renamed, if there is any.Example:rename -v 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 24678, "s": 24669, "text": "Example:" }, { "code": null, "e": 24709, "s": 24678, "text": "rename -v 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 24836, "s": 24709, "text": "rename -n : This option comes into play when the user wants to see only the final change.Example:rename -n 's/png/jpeg/' *.png" }, { "code": null, "e": 24845, "s": 24836, "text": "Example:" }, { "code": null, "e": 24875, "s": 24845, "text": "rename -n 's/png/jpeg/' *.png" }, { "code": null, "e": 24985, "s": 24875, "text": "rename -o : This option will not going to overwrite the existing files.Example:rename -o 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 24994, "s": 24985, "text": "Example:" }, { "code": null, "e": 25025, "s": 24994, "text": "rename -o 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 25130, "s": 25025, "text": "rename -V: This option will show the version information and exit.Example:rename -V 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 25139, "s": 25130, "text": "Example:" }, { "code": null, "e": 25170, "s": 25139, "text": "rename -V 's/jpeg/png/' *.jpeg" }, { "code": null, "e": 25260, "s": 25170, "text": "rename -help : This option will going show the help message and exit.Example:rename -help" }, { "code": null, "e": 25269, "s": 25260, "text": "Example:" }, { "code": null, "e": 25282, "s": 25269, "text": "rename -help" }, { "code": null, "e": 25296, "s": 25282, "text": "linux-command" }, { "code": null, "e": 25316, "s": 25296, "text": "Linux-file-commands" }, { "code": null, "e": 25327, "s": 25316, "text": "Linux-Unix" }, { "code": null, "e": 25425, "s": 25327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25434, "s": 25425, "text": "Comments" }, { "code": null, "e": 25447, "s": 25434, "text": "Old Comments" }, { "code": null, "e": 25482, "s": 25447, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25519, "s": 25482, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25553, "s": 25519, "text": "mv command in Linux with examples" }, { "code": null, "e": 25579, "s": 25553, "text": "Thread functions in C/C++" }, { "code": null, "e": 25605, "s": 25579, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25642, "s": 25605, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25682, "s": 25642, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 25711, "s": 25682, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25753, "s": 25711, "text": "Named Pipe or FIFO with example C program" } ]
Python | Merge Tuple String List values to String
03 Nov, 2019 Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + join()The combination of above functionalities can be used to achieve to solution of above task. In this, we get the character list using list comprehension and conversion task is performed by join(). # Python3 code to demonstrate working of# Merge Tuple String List values to String# using list comprehension + join() # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)] # printing original listprint("The original list : " + str(test_list)) # Merge Tuple String List values to String# using list comprehension + join()res = [''.join(i) for i, j in test_list] # printing resultprint("The joined character list tuple element to string is : " + str(res)) The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’] Method #2 : Using map() + join() + lambdaThe task performed by list comprehension in the above method can be performed by map() and lambda function can be used to construct the logic to achieve the solution to this task. # Python3 code to demonstrate working of# Merge Tuple String List values to String# using map() + join() + lambda # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)] # printing original listprint("The original list : " + str(test_list)) # Merge Tuple String List values to String# using map() + join() + lambdares = list(map(lambda sub : "".join(sub[0]), test_list)) # printing resultprint("The joined character list tuple element to string is : " + str(res)) The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Deque in Python Defaultdict in Python Queue in Python Rotate axis tick labels in Seaborn and Matplotlib Defaultdict in Python Python program to add two numbers Python | Get dictionary keys as a list Python Program for Fibonacci numbers Python Program for factorial of a number
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Nov, 2019" }, { "code": null, "e": 310, "s": 28, "text": "Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 550, "s": 310, "text": "Method #1 : Using list comprehension + join()The combination of above functionalities can be used to achieve to solution of above task. In this, we get the character list using list comprehension and conversion task is performed by join()." }, { "code": "# Python3 code to demonstrate working of# Merge Tuple String List values to String# using list comprehension + join() # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)] # printing original listprint(\"The original list : \" + str(test_list)) # Merge Tuple String List values to String# using list comprehension + join()res = [''.join(i) for i, j in test_list] # printing resultprint(\"The joined character list tuple element to string is : \" + str(res))", "e": 1051, "s": 550, "text": null }, { "code": null, "e": 1214, "s": 1051, "text": "The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]" }, { "code": null, "e": 1437, "s": 1216, "text": "Method #2 : Using map() + join() + lambdaThe task performed by list comprehension in the above method can be performed by map() and lambda function can be used to construct the logic to achieve the solution to this task." }, { "code": "# Python3 code to demonstrate working of# Merge Tuple String List values to String# using map() + join() + lambda # initialize listtest_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)] # printing original listprint(\"The original list : \" + str(test_list)) # Merge Tuple String List values to String# using map() + join() + lambdares = list(map(lambda sub : \"\".join(sub[0]), test_list)) # printing resultprint(\"The joined character list tuple element to string is : \" + str(res))", "e": 1945, "s": 1437, "text": null }, { "code": null, "e": 2108, "s": 1945, "text": "The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]" }, { "code": null, "e": 2129, "s": 2108, "text": "Python list-programs" }, { "code": null, "e": 2136, "s": 2129, "text": "Python" }, { "code": null, "e": 2152, "s": 2136, "text": "Python Programs" }, { "code": null, "e": 2250, "s": 2152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2295, "s": 2250, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2311, "s": 2295, "text": "Deque in Python" }, { "code": null, "e": 2333, "s": 2311, "text": "Defaultdict in Python" }, { "code": null, "e": 2349, "s": 2333, "text": "Queue in Python" }, { "code": null, "e": 2399, "s": 2349, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2421, "s": 2399, "text": "Defaultdict in Python" }, { "code": null, "e": 2455, "s": 2421, "text": "Python program to add two numbers" }, { "code": null, "e": 2494, "s": 2455, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2531, "s": 2494, "text": "Python Program for Fibonacci numbers" } ]
Convert a string to lowercase in Julia – lowercase() and lowercasefirst() Methods
01 Apr, 2020 The lowercase() is an inbuilt function in julia which is used to return a string with all characters converted to lowercase. Syntax: lowercase(s::AbstractString) Parameters: s::AbstractString: Specified string. Returns: It returns a string with all characters converted to lowercase. Example: # Julia program to illustrate # the use of lowercase() method # Getting a string with all # characters converted to lowercaseprintln(lowercase("GFG"))println(lowercase("GEEKS"))println(lowercase("GEEKSFORGEEKS")) Output: gfg geeks geeksforgeeks The lowercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to lowercase. Syntax: lowercasefirst(s::AbstractString) Parameters: s::AbstractString: Specified string. Returns: It returns a string with first character converted to lowercase. Example: # Julia program to illustrate # the use of lowercasefirst() method # Getting a string with first# character converted to lowercaseprintln(lowercasefirst("GFG"))println(lowercasefirst("GEEKS"))println(lowercasefirst("GEEKSFORGEEKS")) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) NamedTuple in Julia Find maximum element along with its index in Julia - findmax() Method Searching in Array for a given element in Julia Difference Between MATLAB and Julia Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods Broadcasting across arrays in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2020" }, { "code": null, "e": 153, "s": 28, "text": "The lowercase() is an inbuilt function in julia which is used to return a string with all characters converted to lowercase." }, { "code": null, "e": 190, "s": 153, "text": "Syntax: lowercase(s::AbstractString)" }, { "code": null, "e": 202, "s": 190, "text": "Parameters:" }, { "code": null, "e": 239, "s": 202, "text": "s::AbstractString: Specified string." }, { "code": null, "e": 312, "s": 239, "text": "Returns: It returns a string with all characters converted to lowercase." }, { "code": null, "e": 321, "s": 312, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of lowercase() method # Getting a string with all # characters converted to lowercaseprintln(lowercase(\"GFG\"))println(lowercase(\"GEEKS\"))println(lowercase(\"GEEKSFORGEEKS\"))", "e": 536, "s": 321, "text": null }, { "code": null, "e": 544, "s": 536, "text": "Output:" }, { "code": null, "e": 569, "s": 544, "text": "gfg\ngeeks\ngeeksforgeeks\n" }, { "code": null, "e": 700, "s": 569, "text": "The lowercasefirst() is an inbuilt function in julia which is used to return a string with first character converted to lowercase." }, { "code": null, "e": 742, "s": 700, "text": "Syntax: lowercasefirst(s::AbstractString)" }, { "code": null, "e": 754, "s": 742, "text": "Parameters:" }, { "code": null, "e": 791, "s": 754, "text": "s::AbstractString: Specified string." }, { "code": null, "e": 865, "s": 791, "text": "Returns: It returns a string with first character converted to lowercase." }, { "code": null, "e": 874, "s": 865, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of lowercasefirst() method # Getting a string with first# character converted to lowercaseprintln(lowercasefirst(\"GFG\"))println(lowercasefirst(\"GEEKS\"))println(lowercasefirst(\"GEEKSFORGEEKS\"))", "e": 1109, "s": 874, "text": null }, { "code": null, "e": 1117, "s": 1109, "text": "Output:" }, { "code": null, "e": 1123, "s": 1117, "text": "Julia" }, { "code": null, "e": 1221, "s": 1123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1249, "s": 1221, "text": "Exception handling in Julia" }, { "code": null, "e": 1319, "s": 1249, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 1378, "s": 1319, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 1451, "s": 1378, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 1471, "s": 1451, "text": "NamedTuple in Julia" }, { "code": null, "e": 1541, "s": 1471, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 1589, "s": 1541, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 1625, "s": 1589, "text": "Difference Between MATLAB and Julia" }, { "code": null, "e": 1706, "s": 1625, "text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods" } ]
.NET Core - Migrations
In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (*.csproj). So, we have an old project which contains the following files. Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error. This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command. dotnet help In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project. Let us now run the following command. dotnet migrate You will see a summary of the migration process and here you can also see that a project is migrated successfully. Let us now see the directory structure by using the following command. tree /f You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder. Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command. dotnet restore You can now see that all the packages are restored. You can now build your project with the following command. dotnet build You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\bin\Debug\netcoreapp1.0 folder. The following screenshot shows the directory structure and files.
[ { "code": null, "e": 2721, "s": 2520, "text": "In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (*.csproj). So, we have an old project which contains the following files." }, { "code": null, "e": 3006, "s": 2721, "text": "Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error." }, { "code": null, "e": 3209, "s": 3006, "text": "This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command." }, { "code": null, "e": 3223, "s": 3209, "text": "dotnet help \n" }, { "code": null, "e": 3400, "s": 3223, "text": "In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project." }, { "code": null, "e": 3438, "s": 3400, "text": "Let us now run the following command." }, { "code": null, "e": 3455, "s": 3438, "text": "dotnet migrate \n" }, { "code": null, "e": 3570, "s": 3455, "text": "You will see a summary of the migration process and here you can also see that a project is migrated successfully." }, { "code": null, "e": 3641, "s": 3570, "text": "Let us now see the directory structure by using the following command." }, { "code": null, "e": 3651, "s": 3641, "text": "tree /f \n" }, { "code": null, "e": 3791, "s": 3651, "text": "You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder." }, { "code": null, "e": 3930, "s": 3791, "text": "Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command." }, { "code": null, "e": 3947, "s": 3930, "text": "dotnet restore \n" }, { "code": null, "e": 3999, "s": 3947, "text": "You can now see that all the packages are restored." }, { "code": null, "e": 4058, "s": 3999, "text": "You can now build your project with the following command." }, { "code": null, "e": 4073, "s": 4058, "text": "dotnet build \n" }, { "code": null, "e": 4214, "s": 4073, "text": "You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\\bin\\Debug\\netcoreapp1.0 folder." } ]
Interpolator in Android with Example
23 Feb, 2021 An interpolator is a function (in the mathematical sense) that outputs values “interpolated” between a range of values that are given to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these generated data points are determined by the kind of interpolation is performed. For example, in linear interpolation, all the generated values are evenly distributed between the fixed points. While an understanding of interpolation is helpful, it isn’t necessary to get started animating your views in your apps. In fact, the animation perspective of interpolation might prove helpful in understanding it! So, let’s get started. In this example, we’ll create a simple app with a list of buttons. Each of these buttons is for a specific type of interpolated animation which kicks off when you press it. The animation is a simple horizontal translation that moves the button to the right. In the Android development framework, Interpolator is defined as an interface. This allows methods to accept an interpolator that can bring its own configuration and not tie developers to a specific implementation. As of this writing, there are 11 indirect subclasses of the Interpolator interface. They are: Linear Interpolator: The generated values between the two fixed points are evenly distributed. For example, consider a = 1 and b = 5 to be the fixed points. Linear interpolation between a and b would look like: 1 -> 2 -> 3 -> 4 -> 5, where the numbers between 1 and 5 have been generated. Accelerate Interpolator: This interpolator generates values that initially have a small difference between them and then ramps up the difference gradually until it reaches the endpoint. For example, the generated values between 1 -> 5 with accelerated interpolation could be 1 -> 1.2 -> 1.5 -> 1.9 -> 2.4 -> 3.0 -> 3.6 -> 4.3 -> 5. Notice how the difference between consecutive values grows consistently. Decelerate Interpolator: In the sense that the accelerate interpolator generates values in an accelerating fashion, a decelerate interpolator generates values that are “slowing down” as you move forward in the list of generated values. So, the values generated initially have a greater difference between them and the difference gradually reduces until the endpoint is reached. Therefore, the generated values between 1 -> 5 could look like 1 -> 1.8 -> 2.5 -> 3.1 -> 3.6 -> 4.0 -> 4.3 -> 4.5 -> 4.6 -> 4.7 -> 4.8 -> 4.9 -> 5. Again, pay attention to the difference between consecutive values growing smaller. Accelerate Decelerate Interpolator: This interpolator starts out with a slow rate of change and accelerates towards the middle. As it approaches the end, it starts decelerating, i.e. reducing the rate of change. Anticipate Interpolator: This interpolation starts by first moving backward, then “flings” forward, and then proceeds gradually to the end. This gives it an effect similar to cartoons where the characters pull back before shooting off running. For example, generated values between 1 -> 3 could look like: 1 -> 0.5 -> 2 -> 2.5 -> 3. Notice how the first generated value is “behind” the starting value and how it jumps forward to a value ahead of the starting value. It then proceeds uniformly to the endpoint. Bounce Interpolator: To understand this interpolator, consider a meter scale that’s standing vertically on a solid surface. The starting value is at the top and the end value is at the bottom, touching the surface. Consider now, a ball that is dropped next to the meter scale. The ball on hitting the surface bounces up and down a few times until finally coming to rest on the surface. With the bounce interpolator, the generated values are similar to the list of values the ball passes by alongside the meter scale. For example, the generated values between 1 -> 5 could be 1 -> 2 -> 3 -> 4 -> 5 -> 4.2 -> 5 -> 4.5 -> 5. Notice how the generated values bounce. Overshoot Interpolator: This interpolator generates values uniformly from the start to end. However, after hitting the end, it overshoots or goes beyond the last value by a small amount and then comes back to the endpoint. For example, the generated values between 1 -> 5 could look like: 1 -> 2 -> 3 -> 4 -> 5 -> 5.5 -> 5. Anticipate Overshoot Interpolator: This interpolator is a combination of the anticipate and overshoot interpolators. That is, it first goes backward from the starting value, flings forward and uniformly moves to the endpoint, overshoots it, and then returns to the endpoint. To better understand the above-mentioned classes and see them in action, it’s highly recommended you follow along with an actual project and run the app as you build it. Enable and Setup View Binding (Optional)View binding is a neat little feature that was introduced not too long ago that makes it easier to work with views in your app. Essentially it does away with findViewById calls and gives you handles to views that are easier to use. They also make your code cleaner. It’s a very simple process and you can see how to turn it on and set it up in the official docs. This step is optional, however, and if you prefer to wire up your views manually, you can proceed with that as well. The end result just needs to be that you have handles to the buttons you aim to configure. Create the LayoutIn your activity_main.xml file, create the list of buttons as shown in the code section below. The layout basically consists of repeated code for the different buttons, so if you understand what’s going on with one button, you can apply the same to the other buttons as well. Step 1: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:gravity="center" android:orientation="vertical" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Interpolators" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/linear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Linear" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/accelerate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Accelerate" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/decelerate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Decelerate" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/bounce" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Bounce" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/overshoot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Overshoot" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/anticipate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Anticipate" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/cycle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Cycle" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/accelerateDecelerate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Accelerate Decelerate" android:textColor="#FFF" /> <androidx.appcompat.widget.AppCompatButton android:id="@+id/anticipateOvershoot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Anticipate Overshoot" android:textColor="#FFF" /> </LinearLayout></ScrollView> Step 2: Working with the MainActivity.java file Setup ObjectAnimator Object: For this example, we’ll use a single ObjectAnimator to animate the different buttons. We’ll also use a fixed duration of 2 seconds for the animations to play out, this gives us ample time to observe the animation behaviors. You can have this set up with 2 lines of code as below. Java // 2-second animation durationfinal private static int ANIMATION_DURATION = 2000;private ObjectAnimator animator; Setup Animations on Button Click: Now that we have the pre-requisites setup, we can finally get to configuring the buttons to trigger their respective animations. For each button, you can configure the specific property to animate, its duration, and the interpolation, among other things. The basic three-step configuration is performed as shown in the code snippet below: Java // Linearbinding.linear.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.linear,"translationX", 200f); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start();}); Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.animation.ObjectAnimator;import android.os.Bundle;import android.view.View;import android.view.animation.AccelerateDecelerateInterpolator;import android.view.animation.AccelerateInterpolator;import android.view.animation.AnticipateInterpolator;import android.view.animation.AnticipateOvershootInterpolator;import android.view.animation.BounceInterpolator;import android.view.animation.CycleInterpolator;import android.view.animation.DecelerateInterpolator;import android.view.animation.LinearInterpolator;import android.view.animation.OvershootInterpolator;import androidx.appcompat.app.AppCompatActivity;import com.example.doobar.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { // 2-second animation duration final private static int ANIMATION_DURATION = 2000; private ActivityMainBinding binding; private ObjectAnimator animator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); // setup animation buttons // Linear binding.linear.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.linear, "translationX", 200f); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Accelerate binding.accelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.accelerate, "translationX", 200f); animator.setInterpolator(new AccelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Decelerate binding.decelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.decelerate, "translationX", 200f); animator.setInterpolator(new DecelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Bounce binding.bounce.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.bounce, "translationX", 200f); animator.setInterpolator(new BounceInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Overshoot binding.overshoot.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.overshoot, "translationX", 200f); animator.setInterpolator(new OvershootInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Anticipate binding.anticipate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.anticipate, "translationX", 200f); animator.setInterpolator(new AnticipateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Cycle binding.cycle.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.cycle, "translationX", 200f); animator.setInterpolator(new CycleInterpolator(2)); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Accelerate Decelerate binding.accelerateDecelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.accelerateDecelerate, "translationX", 200f); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Anticipate Overshoot binding.anticipateOvershoot.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.anticipateOvershoot, "translationX", 200f); animator.setInterpolator(new AnticipateOvershootInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); }} Having built the buttons and having set them up to trigger animations when pressed, you’re all set to fire up the app and see your animations come to life. And you’re done! That’s how you use interpolators in your animations to spice them up and not make them look monotonic. You can view the entire application here: https://github.com/krishnakeshan/android-interpolators. Android-Animation Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 983, "s": 28, "text": "An interpolator is a function (in the mathematical sense) that outputs values “interpolated” between a range of values that are given to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these generated data points are determined by the kind of interpolation is performed. For example, in linear interpolation, all the generated values are evenly distributed between the fixed points. While an understanding of interpolation is helpful, it isn’t necessary to get started animating your views in your apps. In fact, the animation perspective of interpolation might prove helpful in understanding it! So, let’s get started. In this example, we’ll create a simple app with a list of buttons. Each of these buttons is for a specific type of interpolated animation which kicks off when you press it. The animation is a simple horizontal translation that moves the button to the right." }, { "code": null, "e": 1292, "s": 983, "text": "In the Android development framework, Interpolator is defined as an interface. This allows methods to accept an interpolator that can bring its own configuration and not tie developers to a specific implementation. As of this writing, there are 11 indirect subclasses of the Interpolator interface. They are:" }, { "code": null, "e": 1581, "s": 1292, "text": "Linear Interpolator: The generated values between the two fixed points are evenly distributed. For example, consider a = 1 and b = 5 to be the fixed points. Linear interpolation between a and b would look like: 1 -> 2 -> 3 -> 4 -> 5, where the numbers between 1 and 5 have been generated." }, { "code": null, "e": 1986, "s": 1581, "text": "Accelerate Interpolator: This interpolator generates values that initially have a small difference between them and then ramps up the difference gradually until it reaches the endpoint. For example, the generated values between 1 -> 5 with accelerated interpolation could be 1 -> 1.2 -> 1.5 -> 1.9 -> 2.4 -> 3.0 -> 3.6 -> 4.3 -> 5. Notice how the difference between consecutive values grows consistently." }, { "code": null, "e": 2595, "s": 1986, "text": "Decelerate Interpolator: In the sense that the accelerate interpolator generates values in an accelerating fashion, a decelerate interpolator generates values that are “slowing down” as you move forward in the list of generated values. So, the values generated initially have a greater difference between them and the difference gradually reduces until the endpoint is reached. Therefore, the generated values between 1 -> 5 could look like 1 -> 1.8 -> 2.5 -> 3.1 -> 3.6 -> 4.0 -> 4.3 -> 4.5 -> 4.6 -> 4.7 -> 4.8 -> 4.9 -> 5. Again, pay attention to the difference between consecutive values growing smaller." }, { "code": null, "e": 2807, "s": 2595, "text": "Accelerate Decelerate Interpolator: This interpolator starts out with a slow rate of change and accelerates towards the middle. As it approaches the end, it starts decelerating, i.e. reducing the rate of change." }, { "code": null, "e": 3317, "s": 2807, "text": "Anticipate Interpolator: This interpolation starts by first moving backward, then “flings” forward, and then proceeds gradually to the end. This gives it an effect similar to cartoons where the characters pull back before shooting off running. For example, generated values between 1 -> 3 could look like: 1 -> 0.5 -> 2 -> 2.5 -> 3. Notice how the first generated value is “behind” the starting value and how it jumps forward to a value ahead of the starting value. It then proceeds uniformly to the endpoint." }, { "code": null, "e": 3979, "s": 3317, "text": "Bounce Interpolator: To understand this interpolator, consider a meter scale that’s standing vertically on a solid surface. The starting value is at the top and the end value is at the bottom, touching the surface. Consider now, a ball that is dropped next to the meter scale. The ball on hitting the surface bounces up and down a few times until finally coming to rest on the surface. With the bounce interpolator, the generated values are similar to the list of values the ball passes by alongside the meter scale. For example, the generated values between 1 -> 5 could be 1 -> 2 -> 3 -> 4 -> 5 -> 4.2 -> 5 -> 4.5 -> 5. Notice how the generated values bounce." }, { "code": null, "e": 4303, "s": 3979, "text": "Overshoot Interpolator: This interpolator generates values uniformly from the start to end. However, after hitting the end, it overshoots or goes beyond the last value by a small amount and then comes back to the endpoint. For example, the generated values between 1 -> 5 could look like: 1 -> 2 -> 3 -> 4 -> 5 -> 5.5 -> 5." }, { "code": null, "e": 4578, "s": 4303, "text": "Anticipate Overshoot Interpolator: This interpolator is a combination of the anticipate and overshoot interpolators. That is, it first goes backward from the starting value, flings forward and uniformly moves to the endpoint, overshoots it, and then returns to the endpoint." }, { "code": null, "e": 4748, "s": 4578, "text": "To better understand the above-mentioned classes and see them in action, it’s highly recommended you follow along with an actual project and run the app as you build it." }, { "code": null, "e": 5359, "s": 4748, "text": "Enable and Setup View Binding (Optional)View binding is a neat little feature that was introduced not too long ago that makes it easier to work with views in your app. Essentially it does away with findViewById calls and gives you handles to views that are easier to use. They also make your code cleaner. It’s a very simple process and you can see how to turn it on and set it up in the official docs. This step is optional, however, and if you prefer to wire up your views manually, you can proceed with that as well. The end result just needs to be that you have handles to the buttons you aim to configure." }, { "code": null, "e": 5653, "s": 5359, "text": "Create the LayoutIn your activity_main.xml file, create the list of buttons as shown in the code section below. The layout basically consists of repeated code for the different buttons, so if you understand what’s going on with one button, you can apply the same to the other buttons as well. " }, { "code": null, "e": 5701, "s": 5653, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 5817, "s": 5701, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 5821, "s": 5817, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"16dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Interpolators\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/linear\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Linear\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/accelerate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Accelerate\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/decelerate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Decelerate\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/bounce\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Bounce\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/overshoot\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Overshoot\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/anticipate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Anticipate\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/cycle\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Cycle\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/accelerateDecelerate\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Accelerate Decelerate\" android:textColor=\"#FFF\" /> <androidx.appcompat.widget.AppCompatButton android:id=\"@+id/anticipateOvershoot\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Anticipate Overshoot\" android:textColor=\"#FFF\" /> </LinearLayout></ScrollView>", "e": 9575, "s": 5821, "text": null }, { "code": null, "e": 9623, "s": 9575, "text": "Step 2: Working with the MainActivity.java file" }, { "code": null, "e": 9932, "s": 9623, "text": "Setup ObjectAnimator Object: For this example, we’ll use a single ObjectAnimator to animate the different buttons. We’ll also use a fixed duration of 2 seconds for the animations to play out, this gives us ample time to observe the animation behaviors. You can have this set up with 2 lines of code as below." }, { "code": null, "e": 9937, "s": 9932, "text": "Java" }, { "code": "// 2-second animation durationfinal private static int ANIMATION_DURATION = 2000;private ObjectAnimator animator;", "e": 10051, "s": 9937, "text": null }, { "code": null, "e": 10424, "s": 10051, "text": "Setup Animations on Button Click: Now that we have the pre-requisites setup, we can finally get to configuring the buttons to trigger their respective animations. For each button, you can configure the specific property to animate, its duration, and the interpolation, among other things. The basic three-step configuration is performed as shown in the code snippet below:" }, { "code": null, "e": 10429, "s": 10424, "text": "Java" }, { "code": "// Linearbinding.linear.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.linear,\"translationX\", 200f); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start();});", "e": 10688, "s": 10429, "text": null }, { "code": null, "e": 10821, "s": 10688, "text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 10826, "s": 10821, "text": "Java" }, { "code": "import android.animation.ObjectAnimator;import android.os.Bundle;import android.view.View;import android.view.animation.AccelerateDecelerateInterpolator;import android.view.animation.AccelerateInterpolator;import android.view.animation.AnticipateInterpolator;import android.view.animation.AnticipateOvershootInterpolator;import android.view.animation.BounceInterpolator;import android.view.animation.CycleInterpolator;import android.view.animation.DecelerateInterpolator;import android.view.animation.LinearInterpolator;import android.view.animation.OvershootInterpolator;import androidx.appcompat.app.AppCompatActivity;import com.example.doobar.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { // 2-second animation duration final private static int ANIMATION_DURATION = 2000; private ActivityMainBinding binding; private ObjectAnimator animator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); View view = binding.getRoot(); setContentView(view); // setup animation buttons // Linear binding.linear.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.linear, \"translationX\", 200f); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Accelerate binding.accelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.accelerate, \"translationX\", 200f); animator.setInterpolator(new AccelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Decelerate binding.decelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.decelerate, \"translationX\", 200f); animator.setInterpolator(new DecelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Bounce binding.bounce.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.bounce, \"translationX\", 200f); animator.setInterpolator(new BounceInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Overshoot binding.overshoot.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.overshoot, \"translationX\", 200f); animator.setInterpolator(new OvershootInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Anticipate binding.anticipate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.anticipate, \"translationX\", 200f); animator.setInterpolator(new AnticipateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Cycle binding.cycle.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.cycle, \"translationX\", 200f); animator.setInterpolator(new CycleInterpolator(2)); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Accelerate Decelerate binding.accelerateDecelerate.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.accelerateDecelerate, \"translationX\", 200f); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); // Anticipate Overshoot binding.anticipateOvershoot.setOnClickListener(clickedView -> { animator = ObjectAnimator.ofFloat(binding.anticipateOvershoot, \"translationX\", 200f); animator.setInterpolator(new AnticipateOvershootInterpolator()); animator.setDuration(ANIMATION_DURATION); animator.start(); }); }}", "e": 15042, "s": 10826, "text": null }, { "code": null, "e": 15318, "s": 15042, "text": "Having built the buttons and having set them up to trigger animations when pressed, you’re all set to fire up the app and see your animations come to life. And you’re done! That’s how you use interpolators in your animations to spice them up and not make them look monotonic." }, { "code": null, "e": 15416, "s": 15318, "text": "You can view the entire application here: https://github.com/krishnakeshan/android-interpolators." }, { "code": null, "e": 15434, "s": 15416, "text": "Android-Animation" }, { "code": null, "e": 15441, "s": 15434, "text": "Picked" }, { "code": null, "e": 15449, "s": 15441, "text": "Android" }, { "code": null, "e": 15454, "s": 15449, "text": "Java" }, { "code": null, "e": 15459, "s": 15454, "text": "Java" }, { "code": null, "e": 15467, "s": 15459, "text": "Android" }, { "code": null, "e": 15565, "s": 15467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15634, "s": 15565, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 15666, "s": 15634, "text": "Android SDK and it's Components" }, { "code": null, "e": 15715, "s": 15666, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 15754, "s": 15715, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 15796, "s": 15754, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 15811, "s": 15796, "text": "Arrays in Java" }, { "code": null, "e": 15855, "s": 15811, "text": "Split() String method in Java with examples" }, { "code": null, "e": 15891, "s": 15855, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 15942, "s": 15891, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
PyQt5 | How to adjust the image inside Push Button ?
22 Apr, 2020 When we set image to a push button we see that if the push button size is smaller than the image then image will get cropped. In this article we will see how we can retain the actual size of the image. There are two ways to do this : -> Change the size of Push Button according to the size of image.-> Instead of using background image use image as a skin. Note : In first way, push button size may or may not be changed. It depends on the image size and in second way no change will occur to push button size. Method #1 : Changing the size of button. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 1000, 800) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(10, 15, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # setting background image button.setStyleSheet("background-image : url(image.png);") # resizing button according to size of image button.resize(724, 430) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output :Note: This method is not preferable if image size is to large. Method #2 : Setting image as a skin. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(100, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # setting image as skin button.setStyleSheet("border-image : url(image.png);") # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output :Note : This method is not preferable if image shape is not as of button. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 230, "s": 28, "text": "When we set image to a push button we see that if the push button size is smaller than the image then image will get cropped. In this article we will see how we can retain the actual size of the image." }, { "code": null, "e": 262, "s": 230, "text": "There are two ways to do this :" }, { "code": null, "e": 385, "s": 262, "text": "-> Change the size of Push Button according to the size of image.-> Instead of using background image use image as a skin." }, { "code": null, "e": 539, "s": 385, "text": "Note : In first way, push button size may or may not be changed. It depends on the image size and in second way no change will occur to push button size." }, { "code": null, "e": 580, "s": 539, "text": "Method #1 : Changing the size of button." }, { "code": null, "e": 587, "s": 580, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 1000, 800) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(10, 15, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # setting background image button.setStyleSheet(\"background-image : url(image.png);\") # resizing button according to size of image button.resize(724, 430) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1737, "s": 587, "text": null }, { "code": null, "e": 1809, "s": 1737, "text": "Output :Note: This method is not preferable if image size is to large. " }, { "code": null, "e": 1846, "s": 1809, "text": "Method #2 : Setting image as a skin." }, { "code": null, "e": 1853, "s": 1846, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(100, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # setting image as skin button.setStyleSheet(\"border-image : url(image.png);\") # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2914, "s": 1853, "text": null }, { "code": null, "e": 2995, "s": 2914, "text": "Output :Note : This method is not preferable if image shape is not as of button." }, { "code": null, "e": 3006, "s": 2995, "text": "Python-gui" }, { "code": null, "e": 3018, "s": 3006, "text": "Python-PyQt" }, { "code": null, "e": 3025, "s": 3018, "text": "Python" } ]
How to access the last element in a Pandas series?
26 Nov, 2020 Prerequisite: Pandas Pandas series is useful in handling various analytical operations independently or as being a part of pandas data frame. So it is important for us to know how various operations are performed in pandas series. The following article discusses various ways in which last element of a pandas series can be retrieved. Method 1: Naive approach There are two naive approaches for accessing the last element: Iterate through the entire series till we reach the end. Find the length of the series. The last element would be length-1 (as indexing starts from 0). Program: Python3 # importing the pandas libraryimport pandas as pd # initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) # iterating the series until the iterator reaches the end of the seriesfor i in range(0, ser.size): if i == ser.size-1: # printing the last element i.e, size of the series-1 print("The last element in the series using loop is : ", ser[i]) # calculating the length of the serieslen = ser.size # printing the last element i.e len-1 as indexing starts from 0print("The last element in the series by calculating length is : ", ser[len-1]) Output: Method 2: Using .iloc or .iat Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result. Pandas iat is used to access data of a passed location. iat is comparatively faster than iloc. Also note that ser[-1] will not print the last element of series, as series supports positive indexes only. However, we can use negative indexing in iloc and iat. Program: Python3 # importing the pandas library and timeimport pandas as pdimport time# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) start = time.time()print("The last element in the series using iloc is : ", ser.iloc[-1])end = time.time() print("Time taken by iloc : ", end-start) start = time.time()print("The last element in the series using iat is : ", ser.iat[-1])end = time.time() print("Time taken by iat : ", end-start) Output: Method 3: Using tail(1).item() tail(n) is used to access bottom n rows from a series or a data frame and item() returns the element of the given series object as scalar. Program: Python3 # importing the pandas libraryimport pandas as pd# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) # printing the last element using tailprint("The last element in the series using tail is : ", ser.tail(1).item()) Output: Python Pandas-exercise Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisite: Pandas " }, { "code": null, "e": 364, "s": 50, "text": "Pandas series is useful in handling various analytical operations independently or as being a part of pandas data frame. So it is important for us to know how various operations are performed in pandas series. The following article discusses various ways in which last element of a pandas series can be retrieved." }, { "code": null, "e": 390, "s": 364, "text": "Method 1: Naive approach " }, { "code": null, "e": 453, "s": 390, "text": "There are two naive approaches for accessing the last element:" }, { "code": null, "e": 510, "s": 453, "text": "Iterate through the entire series till we reach the end." }, { "code": null, "e": 605, "s": 510, "text": "Find the length of the series. The last element would be length-1 (as indexing starts from 0)." }, { "code": null, "e": 614, "s": 605, "text": "Program:" }, { "code": null, "e": 622, "s": 614, "text": "Python3" }, { "code": "# importing the pandas libraryimport pandas as pd # initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) # iterating the series until the iterator reaches the end of the seriesfor i in range(0, ser.size): if i == ser.size-1: # printing the last element i.e, size of the series-1 print(\"The last element in the series using loop is : \", ser[i]) # calculating the length of the serieslen = ser.size # printing the last element i.e len-1 as indexing starts from 0print(\"The last element in the series by calculating length is : \", ser[len-1])", "e": 1196, "s": 622, "text": null }, { "code": null, "e": 1204, "s": 1196, "text": "Output:" }, { "code": null, "e": 1234, "s": 1204, "text": "Method 2: Using .iloc or .iat" }, { "code": null, "e": 1467, "s": 1234, "text": "Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result. " }, { "code": null, "e": 1726, "s": 1467, "text": "Pandas iat is used to access data of a passed location. iat is comparatively faster than iloc. Also note that ser[-1] will not print the last element of series, as series supports positive indexes only. However, we can use negative indexing in iloc and iat." }, { "code": null, "e": 1735, "s": 1726, "text": "Program:" }, { "code": null, "e": 1743, "s": 1735, "text": "Python3" }, { "code": "# importing the pandas library and timeimport pandas as pdimport time# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) start = time.time()print(\"The last element in the series using iloc is : \", ser.iloc[-1])end = time.time() print(\"Time taken by iloc : \", end-start) start = time.time()print(\"The last element in the series using iat is : \", ser.iat[-1])end = time.time() print(\"Time taken by iat : \", end-start)", "e": 2179, "s": 1743, "text": null }, { "code": null, "e": 2187, "s": 2179, "text": "Output:" }, { "code": null, "e": 2218, "s": 2187, "text": "Method 3: Using tail(1).item()" }, { "code": null, "e": 2357, "s": 2218, "text": "tail(n) is used to access bottom n rows from a series or a data frame and item() returns the element of the given series object as scalar." }, { "code": null, "e": 2366, "s": 2357, "text": "Program:" }, { "code": null, "e": 2374, "s": 2366, "text": "Python3" }, { "code": "# importing the pandas libraryimport pandas as pd# initializing the seriesser = pd.Series(['g', 'e', 'e', 'k', 's']) # printing the last element using tailprint(\"The last element in the series using tail is : \", ser.tail(1).item())", "e": 2607, "s": 2374, "text": null }, { "code": null, "e": 2615, "s": 2607, "text": "Output:" }, { "code": null, "e": 2638, "s": 2615, "text": "Python Pandas-exercise" }, { "code": null, "e": 2659, "s": 2638, "text": "Python pandas-series" }, { "code": null, "e": 2673, "s": 2659, "text": "Python-pandas" }, { "code": null, "e": 2680, "s": 2673, "text": "Python" }, { "code": null, "e": 2778, "s": 2680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2810, "s": 2778, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2837, "s": 2810, "text": "Python Classes and Objects" }, { "code": null, "e": 2858, "s": 2837, "text": "Python OOPs Concepts" }, { "code": null, "e": 2881, "s": 2858, "text": "Introduction To PYTHON" }, { "code": null, "e": 2937, "s": 2881, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2968, "s": 2937, "text": "Python | os.path.join() method" }, { "code": null, "e": 3010, "s": 2968, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3052, "s": 3010, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3091, "s": 3052, "text": "Python | Get unique values from a list" } ]
Find the largest multiple of 3 | Set 1 (Using Queue)
08 Jul, 2022 Given an array of non-negative integers. Find the largest multiple of 3 that can be formed from array elements. For example, if the input array is {8, 1, 9}, the output should be “9 8 1”, and if the input array is {8, 1, 7, 6, 0}, output should be “8 7 6 0”. Method 1 (Brute Force) : The simple & straight forward approach is to generate all the combinations of the elements and keep track of the largest number formed which is divisible by 3. Time Complexity: O(n x 2^n). There will be 2^n combinations of array elements. To compare each combination with the largest number so far may take O(n) time. Auxiliary Space: O(n) // to avoid integer overflow, the largest number is assumed to be stored in the form of array. Method 2 (Tricky) : This problem can be solved efficiently with the help of O(n) extra space. This method is based on the following facts about numbers which are multiple of 3. A number is multiple of 3 if and only if the sum of digits of number is multiple of 3. For example, let us consider 8760, it is a multiple of 3 because sum of digits is 8 + 7+ 6+ 0 = 21, which is a multiple of 3. If a number is multiple of 3, then all permutations of it are also multiple of 3. For example, since 6078 is a multiple of 3, the numbers 8760, 7608, 7068, ..... are also multiples of 3. We get the same remainder when we divide the number and sum of digits of the number. For example, if divide number 151 and sum of it digits 7, by 3, we get the same remainder 1. A number is multiple of 3 if and only if the sum of digits of number is multiple of 3. For example, let us consider 8760, it is a multiple of 3 because sum of digits is 8 + 7+ 6+ 0 = 21, which is a multiple of 3. If a number is multiple of 3, then all permutations of it are also multiple of 3. For example, since 6078 is a multiple of 3, the numbers 8760, 7608, 7068, ..... are also multiples of 3. We get the same remainder when we divide the number and sum of digits of the number. For example, if divide number 151 and sum of it digits 7, by 3, we get the same remainder 1. What is the idea behind above facts? The value of 10%3 and 100%3 is 1. The same is true for all the higher powers of 10, because 3 divides 9, 99, 999, ... etc. Let us consider a 3 digit number n to prove above facts. Let the first, second and third digits of n be ‘a’, ‘b’ and ‘c’ respectively. n can be written as n = 100.a + 10.b + c Since (10^x)%3 is 1 for any x, the above expression gives the same remainder as following expression 1.a + 1.b + c So the remainder obtained by sum of digits and ‘n’ is same. Following is a solution based on the above observation. Sort the array in non-decreasing order.Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2Find the sum of all the digits.Three cases arise: ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array.......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible.......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible.Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array. Sort the array in non-decreasing order. Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2 Find the sum of all the digits. Three cases arise: ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array.......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible.......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible. ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array. ......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible. ......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible. Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array. The below code works only if the input arrays has numbers from 0 to 9. It can be easily extended for any positive integer array. We just have to modify the part where we sort the array in decreasing order, at the end of code. C++ C Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // This function puts all elements of 3 queues in the auxiliary arrayvoid populateAux(int aux[], queue<int> queue0, queue<int> queue1, queue<int> queue2, int* top){ // Put all items of first queue in aux[] while (!queue0.empty()) { aux[(*top)++] = queue0.front(); queue0.pop(); } // Put all items of second queue in aux[] while (!queue1.empty()) { aux[(*top)++] = queue1.front(); queue1.pop(); } // Put all items of third queue in aux[] while (!queue2.empty()) { aux[(*top)++] = queue2.front(); queue2.pop(); }} // The main function that finds the largest possible multiple of// 3 that can be formed by arr[] elementsint findMaxMultupleOf3(int arr[], int size){ // Step 1: sort the array in non-decreasing order sort(arr, arr + size); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively queue<int> queue0, queue1, queue2; // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int i, sum; for (i = 0, sum = 0; i < size; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.push(arr[i]); else if ((arr[i] % 3) == 1) queue1.push(arr[i]); else queue2.push(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!queue1.empty()) queue1.pop(); // or remove two items from queue2 else { if (!queue2.empty()) queue2.pop(); else return 0; if (!queue2.empty()) queue2.pop(); else return 0; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!queue2.empty()) queue2.pop(); // or remove two items from queue1 else { if (!queue1.empty()) queue1.pop(); else return 0; if (!queue1.empty()) queue1.pop(); else return 0; } } int aux[size], top = 0; // Empty all the queues into an auxiliary array. populateAux(aux, queue0, queue1, queue2, &top); // sort the array in non-increasing order sort(aux, aux + top, greater<int>()); // print the result for (int i = 0; i < top; ++i) cout << aux[i] << " "; return top;}int main(){ int arr[] = { 8, 1, 7, 6, 0 }; int size = sizeof(arr) / sizeof(arr[0]); if (findMaxMultupleOf3(arr, size) == 0) cout << "Not Possible"; return 0;} /* A program to find the largest multiple of 3 from an array of elements */#include <stdio.h>#include <stdlib.h> // A queue nodetypedef struct Queue { int front; int rear; int capacity; int* array;} Queue; // A utility function to create a queue with given capacityQueue* createQueue(int capacity){ Queue* queue = (Queue*)malloc(sizeof(Queue)); queue->capacity = capacity; queue->front = queue->rear = -1; queue->array = (int*)malloc(queue->capacity * sizeof(int)); return queue;} // A utility function to check if queue is emptyint isEmpty(Queue* queue){ return queue->front == -1;} // A function to add an item to queuevoid Enqueue(Queue* queue, int item){ queue->array[++queue->rear] = item; if (isEmpty(queue)) ++queue->front;} // A function to remove an item from queueint Dequeue(Queue* queue){ int item = queue->array[queue->front]; if (queue->front == queue->rear) queue->front = queue->rear = -1; else queue->front++; return item;} // A utility function to print array contentsvoid printArr(int* arr, int size){ int i; for (i = 0; i < size; ++i) printf("%d ", arr[i]);} /* Following two functions are needed for library function qsort(). Refer following link for help of qsort() http:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compareAsc(const void* a, const void* b){ return *(int*)a > *(int*)b;}int compareDesc(const void* a, const void* b){ return *(int*)a < *(int*)b;} // This function puts all elements of 3 queues in the auxiliary arrayvoid populateAux(int* aux, Queue* queue0, Queue* queue1, Queue* queue2, int* top){ // Put all items of first queue in aux[] while (!isEmpty(queue0)) aux[(*top)++] = Dequeue(queue0); // Put all items of second queue in aux[] while (!isEmpty(queue1)) aux[(*top)++] = Dequeue(queue1); // Put all items of third queue in aux[] while (!isEmpty(queue2)) aux[(*top)++] = Dequeue(queue2);} // The main function that finds the largest possible multiple of// 3 that can be formed by arr[] elementsint findMaxMultupleOf3(int* arr, int size){ // Step 1: sort the array in non-decreasing order qsort(arr, size, sizeof(int), compareAsc); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue* queue0 = createQueue(size); Queue* queue1 = createQueue(size); Queue* queue2 = createQueue(size); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int i, sum; for (i = 0, sum = 0; i < size; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) Enqueue(queue0, arr[i]); else if ((arr[i] % 3) == 1) Enqueue(queue1, arr[i]); else Enqueue(queue2, arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!isEmpty(queue1)) Dequeue(queue1); // or remove two items from queue2 else { if (!isEmpty(queue2)) Dequeue(queue2); else return 0; if (!isEmpty(queue2)) Dequeue(queue2); else return 0; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!isEmpty(queue2)) Dequeue(queue2); // or remove two items from queue1 else { if (!isEmpty(queue1)) Dequeue(queue1); else return 0; if (!isEmpty(queue1)) Dequeue(queue1); else return 0; } } int aux[size], top = 0; // Empty all the queues into an auxiliary array. populateAux(aux, queue0, queue1, queue2, &top); // sort the array in non-increasing order qsort(aux, top, sizeof(int), compareDesc); // print the result printArr(aux, top); return top;} // Driver program to test above functionsint main(){ int arr[] = { 8, 1, 7, 6, 0 }; int size = sizeof(arr) / sizeof(arr[0]); if (findMaxMultupleOf3(arr, size) == 0) printf("Not Possible"); return 0;} /* Java program to find the largest multipleof 3 that can be formed from an arrayof elements */import java.util.Arrays;import java.util.Queue;import java.util.LinkedList;import java.util.Collections; public class Geeks { // This function puts all elements of 3 queues in the // array auxiliary public static int populateAux(int aux[], Queue<Integer> queue0, Queue<Integer> queue1, Queue<Integer> queue2) { int top=0; // Put all items of first queue in aux[] while(!queue0.isEmpty()) { aux[top++]=queue0.remove(); } // Put all items of second queue in aux[] while(!queue1.isEmpty()) { aux[top++]=queue1.remove(); } // Put all items of third queue in aux[] while(!queue2.isEmpty()) { aux[top++]=queue2.remove(); } //Return number of integer added to aux[] return top; } // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elements public static boolean findMaxMultupleOf3(int arr[]) { // Step 1: sort the array in non-decreasing order Arrays.sort(arr); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue<Integer> queue0=new LinkedList<>(); Queue<Integer> queue1=new LinkedList<>(); Queue<Integer> queue2=new LinkedList<>(); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int sum=0; for (int i = 0; i < arr.length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.add(arr[i]); else if ((arr[i] % 3) == 1) queue1.add(arr[i]); else queue2.add(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!queue1.isEmpty()) queue1.remove(); // or remove two items from queue2 else { if (!queue2.isEmpty()) queue2.remove(); else return false; if (!queue2.isEmpty()) queue2.remove(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!queue2.isEmpty()) queue2.remove(); // or remove two items from queue1 else { if (!queue1.isEmpty()) queue1.remove(); else return false; if (!queue1.isEmpty()) queue1.remove(); else return false; } } int aux[]=new int[arr.length]; // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] int top=populateAux(aux,queue0,queue1,queue2); // sort the array in non-increasing order Arrays.sort(aux,0,top); // print the result for (int i = top-1; i>=0; i--) System.out.print(aux[i]+" ") ; return true; } public static void main(String args[]) { int arr[] = { 8, 1, 7, 6, 0 }; if (!findMaxMultupleOf3(arr)) System.out.println("Not possible") ; }} // This code is contributed by Gaurav Tiwari # Python3 program to find the largest multiple# of 3 that can be formed from an array# of elements aux = [] # This function puts all elements of 3 queues in the# array auxiliarydef populateAux(queue0, queue1, queue2): global aux top = 0 # Put all items of first queue in aux[] while(len(queue0) > 0): aux[top] = queue0.pop(0) top += 1 # Put all items of second queue in aux[] while(len(queue1) != 0): aux[top] = queue1.pop(0) top += 1 # Put all items of third queue in aux[] while(len(queue2) != 0): aux[top] = queue2.pop(0) top += 1 # Return number of integer added to aux[] return top # The main function that finds the largest possible multiple of# 3 that can be formed by arr[] elementsdef findMaxMultupleOf3(arr): global aux # Step 1: sort the array in non-decreasing order arr.sort() # Create 3 queues to store numbers with remainder 0, 1 # and 2 respectively queue0 = [] queue1 = [] queue2 = [] # Step 2 and 3 get the sum of numbers and place them in # corresponding queues sum = 0 for i in range(len(arr)): sum += arr[i] if ((arr[i] % 3) == 0): queue0.append(arr[i]) elif ((arr[i] % 3) == 1): queue1.append(arr[i]) else: queue2.append(arr[i]) # Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1): # either remove one item from queue1 if (len(queue1) != 0): queue1.pop(0) # or remove two items from queue2 else: if (len(queue2) != 0): queue2.pop(0) else: return False if (len(queue2) != 0): queue2.pop(0) else: return False # Step 4.3: The sum produces remainder 2 elif ((sum % 3) == 2): # either remove one item from queue2 if (len(queue2) != 0): queue2.pop(0) # or remove two items from queue1 else: if (len(queue1) != 0): queue1.pop(0) else: return False if (len(queue1) != 0): queue1.pop(0) else: return False aux = [0 for i in range(len(arr))] # Empty all the queues into an auxiliary array # and get the number of integers added to aux[] top = populateAux(queue0, queue1, queue2) # sort the array in non-increasing order aux.sort(reverse=True) # print the result for i in range(0, top): print(aux[i], end=" ") return True # Driver codearr = [8, 1, 7, 6, 0]if (not findMaxMultupleOf3(arr)): print("Not possible") # This code is contributed by phasing17 /* C# program to find the largest multipleof 3 that can be formed from an arrayof elements */using System;using System.Collections.Generic; class Geeks{ // This function puts all elements of 3 queues in the // array auxiliary public static int populateAux(int []aux, Queue<int> queue0, Queue<int> queue1, Queue<int> queue2) { int top = 0; // Put all items of first queue in aux[] while(queue0.Count != 0) { aux[top++] = queue0.Dequeue(); } // Put all items of second queue in aux[] while(queue1.Count != 0) { aux[top++] = queue1.Dequeue(); } // Put all items of third queue in aux[] while(queue2.Count != 0) { aux[top++] = queue2.Dequeue(); } //Return number of integer added to aux[] return top; } // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elements public static bool findMaxMultupleOf3(int []arr) { // Step 1: sort the array in non-decreasing order Array.Sort(arr); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue<int> queue0 = new Queue<int>(); Queue<int> queue1 = new Queue<int>(); Queue<int> queue2 = new Queue<int>(); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int sum=0; for (int i = 0; i < arr.Length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.Enqueue(arr[i]); else if ((arr[i] % 3) == 1) queue1.Enqueue(arr[i]); else queue2.Enqueue(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (queue1.Count != 0) queue1.Dequeue(); // or remove two items from queue2 else { if (queue2.Count != 0) queue2.Dequeue(); else return false; if (queue2.Count != 0) queue2.Dequeue(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (queue2.Count != 0) queue2.Dequeue(); // or remove two items from queue1 else { if (queue1.Count != 0) queue1.Dequeue(); else return false; if (queue1.Count != 0) queue1.Dequeue(); else return false; } } int []aux = new int[arr.Length]; // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] int top = populateAux(aux,queue0,queue1,queue2); // sort the array in non-increasing order Array.Sort(aux,0,top); // print the result for (int i = top-1; i >= 0; i--) Console.Write(aux[i]+" ") ; return true; } // Driver code public static void Main() { int []arr = { 8, 1, 7, 6, 0 }; if (!findMaxMultupleOf3(arr)) Console.WriteLine("Not possible") ; }} /* This code contributed by PrinciRaj1992 */ <script> /* Javascript program to find the largest multipleof 3 that can be formed from an arrayof elements */ // This function puts all elements of 3 queues in the // array auxiliaryfunction populateAux(aux, queue0, queue1, queue2){ let top = 0; // Put all items of first queue in aux[] while(queue0.length != 0) { aux[top++] = queue0.shift(); } // Put all items of second queue in aux[] while(queue1.length != 0) { aux[top++] = queue1.shift(); } // Put all items of third queue in aux[] while(queue2.length != 0) { aux[top++] = queue2.shift(); } //Return number of integer added to aux[] return top;} // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elementsfunction findMaxMultupleOf3(arr){ // Step 1: sort the array in non-decreasing order arr.sort(function(a, b){return a - b;}); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively let queue0 = []; let queue1 = []; let queue2 = []; // Step 2 and 3 get the sum of numbers and place them in // corresponding queues let sum = 0; for (let i = 0; i < arr.length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.push(arr[i]); else if ((arr[i] % 3) == 1) queue1.push(arr[i]); else queue2.push(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (queue1.length != 0) queue1.shift(); // or remove two items from queue2 else { if (queue2.length != 0) queue2.shift(); else return false; if (queue2.length != 0) queue2.shift(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (queue2.length != 0) queue2.shift(); // or remove two items from queue1 else { if (queue1.length != 0) queue1.shift(); else return false; if (queue1.length != 0) queue1.shift(); else return false; } } let aux=new Array(arr.length); // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] let top=populateAux(aux, queue0, queue1, queue2); // sort the array in non-increasing order aux.sort(function(a, b){return a - b;}); // print the result for (let i = top - 1; i >= 0; i--) document.write(aux[i]+" ") ; return true;} // Driver codelet arr = [ 8, 1, 7, 6, 0 ];if (!findMaxMultupleOf3(arr)) document.write("Not possible") ; // This code is contributed by rag2127.</script> 8 7 6 0 The above method can be optimized in following ways. We can use Heap Sort or Merge Sort to make the time complexity O(nLogn). We can avoid extra space for queues. We know at most two items will be removed from the input array. So we can keep track of two items in two variables. At the end, instead of sorting the array again in descending order, we can print the ascending sorted array in reverse order. While printing in reverse order, we can skip the two elements to be removed. We can use Heap Sort or Merge Sort to make the time complexity O(nLogn). We can avoid extra space for queues. We know at most two items will be removed from the input array. So we can keep track of two items in two variables. At the end, instead of sorting the array again in descending order, we can print the ascending sorted array in reverse order. While printing in reverse order, we can skip the two elements to be removed. Time Complexity: O(nLogn), assuming a O(nLogn) algorithm is used for sorting. Find the largest multiple of 3 | Set 2 (In O(n) time and O(1) space) _Gaurav_Tiwari princiraj1992 avanitrachhadiya2155 hardikkoriintern phasing17 cpp-queue divisibility Queue Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 311, "s": 52, "text": "Given an array of non-negative integers. Find the largest multiple of 3 that can be formed from array elements. For example, if the input array is {8, 1, 9}, the output should be “9 8 1”, and if the input array is {8, 1, 7, 6, 0}, output should be “8 7 6 0”." }, { "code": null, "e": 336, "s": 311, "text": "Method 1 (Brute Force) :" }, { "code": null, "e": 771, "s": 336, "text": "The simple & straight forward approach is to generate all the combinations of the elements and keep track of the largest number formed which is divisible by 3. Time Complexity: O(n x 2^n). There will be 2^n combinations of array elements. To compare each combination with the largest number so far may take O(n) time. Auxiliary Space: O(n) // to avoid integer overflow, the largest number is assumed to be stored in the form of array." }, { "code": null, "e": 791, "s": 771, "text": "Method 2 (Tricky) :" }, { "code": null, "e": 948, "s": 791, "text": "This problem can be solved efficiently with the help of O(n) extra space. This method is based on the following facts about numbers which are multiple of 3." }, { "code": null, "e": 1526, "s": 948, "text": "A number is multiple of 3 if and only if the sum of digits of number is multiple of 3. For example, let us consider 8760, it is a multiple of 3 because sum of digits is 8 + 7+ 6+ 0 = 21, which is a multiple of 3. If a number is multiple of 3, then all permutations of it are also multiple of 3. For example, since 6078 is a multiple of 3, the numbers 8760, 7608, 7068, ..... are also multiples of 3. We get the same remainder when we divide the number and sum of digits of the number. For example, if divide number 151 and sum of it digits 7, by 3, we get the same remainder 1." }, { "code": null, "e": 1740, "s": 1526, "text": "A number is multiple of 3 if and only if the sum of digits of number is multiple of 3. For example, let us consider 8760, it is a multiple of 3 because sum of digits is 8 + 7+ 6+ 0 = 21, which is a multiple of 3. " }, { "code": null, "e": 1928, "s": 1740, "text": "If a number is multiple of 3, then all permutations of it are also multiple of 3. For example, since 6078 is a multiple of 3, the numbers 8760, 7608, 7068, ..... are also multiples of 3. " }, { "code": null, "e": 2106, "s": 1928, "text": "We get the same remainder when we divide the number and sum of digits of the number. For example, if divide number 151 and sum of it digits 7, by 3, we get the same remainder 1." }, { "code": null, "e": 2144, "s": 2106, "text": "What is the idea behind above facts? " }, { "code": null, "e": 2423, "s": 2144, "text": "The value of 10%3 and 100%3 is 1. The same is true for all the higher powers of 10, because 3 divides 9, 99, 999, ... etc. Let us consider a 3 digit number n to prove above facts. Let the first, second and third digits of n be ‘a’, ‘b’ and ‘c’ respectively. n can be written as " }, { "code": null, "e": 2445, "s": 2423, "text": "n = 100.a + 10.b + c " }, { "code": null, "e": 2546, "s": 2445, "text": "Since (10^x)%3 is 1 for any x, the above expression gives the same remainder as following expression" }, { "code": null, "e": 2562, "s": 2546, "text": " 1.a + 1.b + c " }, { "code": null, "e": 2622, "s": 2562, "text": "So the remainder obtained by sum of digits and ‘n’ is same." }, { "code": null, "e": 2678, "s": 2622, "text": "Following is a solution based on the above observation." }, { "code": null, "e": 3749, "s": 2678, "text": "Sort the array in non-decreasing order.Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2Find the sum of all the digits.Three cases arise: ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array.......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible.......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible.Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array." }, { "code": null, "e": 3789, "s": 3749, "text": "Sort the array in non-decreasing order." }, { "code": null, "e": 4067, "s": 3789, "text": "Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2" }, { "code": null, "e": 4099, "s": 4067, "text": "Find the sum of all the digits." }, { "code": null, "e": 4692, "s": 4099, "text": "Three cases arise: ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array.......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible.......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible." }, { "code": null, "e": 4838, "s": 4692, "text": "......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array." }, { "code": null, "e": 5053, "s": 4838, "text": "......4.2 The sum of digits produces remainder 1 when divided by 3. Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible." }, { "code": null, "e": 5268, "s": 5053, "text": "......4.3 The sum of digits produces remainder 2 when divided by 3. Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible." }, { "code": null, "e": 5400, "s": 5268, "text": "Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array." }, { "code": null, "e": 5628, "s": 5400, "text": "The below code works only if the input arrays has numbers from 0 to 9. It can be easily extended for any positive integer array. We just have to modify the part where we sort the array in decreasing order, at the end of code. " }, { "code": null, "e": 5632, "s": 5628, "text": "C++" }, { "code": null, "e": 5634, "s": 5632, "text": "C" }, { "code": null, "e": 5639, "s": 5634, "text": "Java" }, { "code": null, "e": 5647, "s": 5639, "text": "Python3" }, { "code": null, "e": 5650, "s": 5647, "text": "C#" }, { "code": null, "e": 5661, "s": 5650, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // This function puts all elements of 3 queues in the auxiliary arrayvoid populateAux(int aux[], queue<int> queue0, queue<int> queue1, queue<int> queue2, int* top){ // Put all items of first queue in aux[] while (!queue0.empty()) { aux[(*top)++] = queue0.front(); queue0.pop(); } // Put all items of second queue in aux[] while (!queue1.empty()) { aux[(*top)++] = queue1.front(); queue1.pop(); } // Put all items of third queue in aux[] while (!queue2.empty()) { aux[(*top)++] = queue2.front(); queue2.pop(); }} // The main function that finds the largest possible multiple of// 3 that can be formed by arr[] elementsint findMaxMultupleOf3(int arr[], int size){ // Step 1: sort the array in non-decreasing order sort(arr, arr + size); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively queue<int> queue0, queue1, queue2; // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int i, sum; for (i = 0, sum = 0; i < size; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.push(arr[i]); else if ((arr[i] % 3) == 1) queue1.push(arr[i]); else queue2.push(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!queue1.empty()) queue1.pop(); // or remove two items from queue2 else { if (!queue2.empty()) queue2.pop(); else return 0; if (!queue2.empty()) queue2.pop(); else return 0; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!queue2.empty()) queue2.pop(); // or remove two items from queue1 else { if (!queue1.empty()) queue1.pop(); else return 0; if (!queue1.empty()) queue1.pop(); else return 0; } } int aux[size], top = 0; // Empty all the queues into an auxiliary array. populateAux(aux, queue0, queue1, queue2, &top); // sort the array in non-increasing order sort(aux, aux + top, greater<int>()); // print the result for (int i = 0; i < top; ++i) cout << aux[i] << \" \"; return top;}int main(){ int arr[] = { 8, 1, 7, 6, 0 }; int size = sizeof(arr) / sizeof(arr[0]); if (findMaxMultupleOf3(arr, size) == 0) cout << \"Not Possible\"; return 0;}", "e": 8442, "s": 5661, "text": null }, { "code": "/* A program to find the largest multiple of 3 from an array of elements */#include <stdio.h>#include <stdlib.h> // A queue nodetypedef struct Queue { int front; int rear; int capacity; int* array;} Queue; // A utility function to create a queue with given capacityQueue* createQueue(int capacity){ Queue* queue = (Queue*)malloc(sizeof(Queue)); queue->capacity = capacity; queue->front = queue->rear = -1; queue->array = (int*)malloc(queue->capacity * sizeof(int)); return queue;} // A utility function to check if queue is emptyint isEmpty(Queue* queue){ return queue->front == -1;} // A function to add an item to queuevoid Enqueue(Queue* queue, int item){ queue->array[++queue->rear] = item; if (isEmpty(queue)) ++queue->front;} // A function to remove an item from queueint Dequeue(Queue* queue){ int item = queue->array[queue->front]; if (queue->front == queue->rear) queue->front = queue->rear = -1; else queue->front++; return item;} // A utility function to print array contentsvoid printArr(int* arr, int size){ int i; for (i = 0; i < size; ++i) printf(\"%d \", arr[i]);} /* Following two functions are needed for library function qsort(). Refer following link for help of qsort() http:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compareAsc(const void* a, const void* b){ return *(int*)a > *(int*)b;}int compareDesc(const void* a, const void* b){ return *(int*)a < *(int*)b;} // This function puts all elements of 3 queues in the auxiliary arrayvoid populateAux(int* aux, Queue* queue0, Queue* queue1, Queue* queue2, int* top){ // Put all items of first queue in aux[] while (!isEmpty(queue0)) aux[(*top)++] = Dequeue(queue0); // Put all items of second queue in aux[] while (!isEmpty(queue1)) aux[(*top)++] = Dequeue(queue1); // Put all items of third queue in aux[] while (!isEmpty(queue2)) aux[(*top)++] = Dequeue(queue2);} // The main function that finds the largest possible multiple of// 3 that can be formed by arr[] elementsint findMaxMultupleOf3(int* arr, int size){ // Step 1: sort the array in non-decreasing order qsort(arr, size, sizeof(int), compareAsc); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue* queue0 = createQueue(size); Queue* queue1 = createQueue(size); Queue* queue2 = createQueue(size); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int i, sum; for (i = 0, sum = 0; i < size; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) Enqueue(queue0, arr[i]); else if ((arr[i] % 3) == 1) Enqueue(queue1, arr[i]); else Enqueue(queue2, arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!isEmpty(queue1)) Dequeue(queue1); // or remove two items from queue2 else { if (!isEmpty(queue2)) Dequeue(queue2); else return 0; if (!isEmpty(queue2)) Dequeue(queue2); else return 0; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!isEmpty(queue2)) Dequeue(queue2); // or remove two items from queue1 else { if (!isEmpty(queue1)) Dequeue(queue1); else return 0; if (!isEmpty(queue1)) Dequeue(queue1); else return 0; } } int aux[size], top = 0; // Empty all the queues into an auxiliary array. populateAux(aux, queue0, queue1, queue2, &top); // sort the array in non-increasing order qsort(aux, top, sizeof(int), compareDesc); // print the result printArr(aux, top); return top;} // Driver program to test above functionsint main(){ int arr[] = { 8, 1, 7, 6, 0 }; int size = sizeof(arr) / sizeof(arr[0]); if (findMaxMultupleOf3(arr, size) == 0) printf(\"Not Possible\"); return 0;}", "e": 12674, "s": 8442, "text": null }, { "code": "/* Java program to find the largest multipleof 3 that can be formed from an arrayof elements */import java.util.Arrays;import java.util.Queue;import java.util.LinkedList;import java.util.Collections; public class Geeks { // This function puts all elements of 3 queues in the // array auxiliary public static int populateAux(int aux[], Queue<Integer> queue0, Queue<Integer> queue1, Queue<Integer> queue2) { int top=0; // Put all items of first queue in aux[] while(!queue0.isEmpty()) { aux[top++]=queue0.remove(); } // Put all items of second queue in aux[] while(!queue1.isEmpty()) { aux[top++]=queue1.remove(); } // Put all items of third queue in aux[] while(!queue2.isEmpty()) { aux[top++]=queue2.remove(); } //Return number of integer added to aux[] return top; } // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elements public static boolean findMaxMultupleOf3(int arr[]) { // Step 1: sort the array in non-decreasing order Arrays.sort(arr); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue<Integer> queue0=new LinkedList<>(); Queue<Integer> queue1=new LinkedList<>(); Queue<Integer> queue2=new LinkedList<>(); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int sum=0; for (int i = 0; i < arr.length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.add(arr[i]); else if ((arr[i] % 3) == 1) queue1.add(arr[i]); else queue2.add(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (!queue1.isEmpty()) queue1.remove(); // or remove two items from queue2 else { if (!queue2.isEmpty()) queue2.remove(); else return false; if (!queue2.isEmpty()) queue2.remove(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (!queue2.isEmpty()) queue2.remove(); // or remove two items from queue1 else { if (!queue1.isEmpty()) queue1.remove(); else return false; if (!queue1.isEmpty()) queue1.remove(); else return false; } } int aux[]=new int[arr.length]; // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] int top=populateAux(aux,queue0,queue1,queue2); // sort the array in non-increasing order Arrays.sort(aux,0,top); // print the result for (int i = top-1; i>=0; i--) System.out.print(aux[i]+\" \") ; return true; } public static void main(String args[]) { int arr[] = { 8, 1, 7, 6, 0 }; if (!findMaxMultupleOf3(arr)) System.out.println(\"Not possible\") ; }} // This code is contributed by Gaurav Tiwari", "e": 16270, "s": 12674, "text": null }, { "code": "# Python3 program to find the largest multiple# of 3 that can be formed from an array# of elements aux = [] # This function puts all elements of 3 queues in the# array auxiliarydef populateAux(queue0, queue1, queue2): global aux top = 0 # Put all items of first queue in aux[] while(len(queue0) > 0): aux[top] = queue0.pop(0) top += 1 # Put all items of second queue in aux[] while(len(queue1) != 0): aux[top] = queue1.pop(0) top += 1 # Put all items of third queue in aux[] while(len(queue2) != 0): aux[top] = queue2.pop(0) top += 1 # Return number of integer added to aux[] return top # The main function that finds the largest possible multiple of# 3 that can be formed by arr[] elementsdef findMaxMultupleOf3(arr): global aux # Step 1: sort the array in non-decreasing order arr.sort() # Create 3 queues to store numbers with remainder 0, 1 # and 2 respectively queue0 = [] queue1 = [] queue2 = [] # Step 2 and 3 get the sum of numbers and place them in # corresponding queues sum = 0 for i in range(len(arr)): sum += arr[i] if ((arr[i] % 3) == 0): queue0.append(arr[i]) elif ((arr[i] % 3) == 1): queue1.append(arr[i]) else: queue2.append(arr[i]) # Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1): # either remove one item from queue1 if (len(queue1) != 0): queue1.pop(0) # or remove two items from queue2 else: if (len(queue2) != 0): queue2.pop(0) else: return False if (len(queue2) != 0): queue2.pop(0) else: return False # Step 4.3: The sum produces remainder 2 elif ((sum % 3) == 2): # either remove one item from queue2 if (len(queue2) != 0): queue2.pop(0) # or remove two items from queue1 else: if (len(queue1) != 0): queue1.pop(0) else: return False if (len(queue1) != 0): queue1.pop(0) else: return False aux = [0 for i in range(len(arr))] # Empty all the queues into an auxiliary array # and get the number of integers added to aux[] top = populateAux(queue0, queue1, queue2) # sort the array in non-increasing order aux.sort(reverse=True) # print the result for i in range(0, top): print(aux[i], end=\" \") return True # Driver codearr = [8, 1, 7, 6, 0]if (not findMaxMultupleOf3(arr)): print(\"Not possible\") # This code is contributed by phasing17", "e": 18969, "s": 16270, "text": null }, { "code": "/* C# program to find the largest multipleof 3 that can be formed from an arrayof elements */using System;using System.Collections.Generic; class Geeks{ // This function puts all elements of 3 queues in the // array auxiliary public static int populateAux(int []aux, Queue<int> queue0, Queue<int> queue1, Queue<int> queue2) { int top = 0; // Put all items of first queue in aux[] while(queue0.Count != 0) { aux[top++] = queue0.Dequeue(); } // Put all items of second queue in aux[] while(queue1.Count != 0) { aux[top++] = queue1.Dequeue(); } // Put all items of third queue in aux[] while(queue2.Count != 0) { aux[top++] = queue2.Dequeue(); } //Return number of integer added to aux[] return top; } // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elements public static bool findMaxMultupleOf3(int []arr) { // Step 1: sort the array in non-decreasing order Array.Sort(arr); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively Queue<int> queue0 = new Queue<int>(); Queue<int> queue1 = new Queue<int>(); Queue<int> queue2 = new Queue<int>(); // Step 2 and 3 get the sum of numbers and place them in // corresponding queues int sum=0; for (int i = 0; i < arr.Length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.Enqueue(arr[i]); else if ((arr[i] % 3) == 1) queue1.Enqueue(arr[i]); else queue2.Enqueue(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (queue1.Count != 0) queue1.Dequeue(); // or remove two items from queue2 else { if (queue2.Count != 0) queue2.Dequeue(); else return false; if (queue2.Count != 0) queue2.Dequeue(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (queue2.Count != 0) queue2.Dequeue(); // or remove two items from queue1 else { if (queue1.Count != 0) queue1.Dequeue(); else return false; if (queue1.Count != 0) queue1.Dequeue(); else return false; } } int []aux = new int[arr.Length]; // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] int top = populateAux(aux,queue0,queue1,queue2); // sort the array in non-increasing order Array.Sort(aux,0,top); // print the result for (int i = top-1; i >= 0; i--) Console.Write(aux[i]+\" \") ; return true; } // Driver code public static void Main() { int []arr = { 8, 1, 7, 6, 0 }; if (!findMaxMultupleOf3(arr)) Console.WriteLine(\"Not possible\") ; }} /* This code contributed by PrinciRaj1992 */", "e": 22513, "s": 18969, "text": null }, { "code": "<script> /* Javascript program to find the largest multipleof 3 that can be formed from an arrayof elements */ // This function puts all elements of 3 queues in the // array auxiliaryfunction populateAux(aux, queue0, queue1, queue2){ let top = 0; // Put all items of first queue in aux[] while(queue0.length != 0) { aux[top++] = queue0.shift(); } // Put all items of second queue in aux[] while(queue1.length != 0) { aux[top++] = queue1.shift(); } // Put all items of third queue in aux[] while(queue2.length != 0) { aux[top++] = queue2.shift(); } //Return number of integer added to aux[] return top;} // The main function that finds the largest possible multiple of // 3 that can be formed by arr[] elementsfunction findMaxMultupleOf3(arr){ // Step 1: sort the array in non-decreasing order arr.sort(function(a, b){return a - b;}); // Create 3 queues to store numbers with remainder 0, 1 // and 2 respectively let queue0 = []; let queue1 = []; let queue2 = []; // Step 2 and 3 get the sum of numbers and place them in // corresponding queues let sum = 0; for (let i = 0; i < arr.length; ++i) { sum += arr[i]; if ((arr[i] % 3) == 0) queue0.push(arr[i]); else if ((arr[i] % 3) == 1) queue1.push(arr[i]); else queue2.push(arr[i]); } // Step 4.2: The sum produces remainder 1 if ((sum % 3) == 1) { // either remove one item from queue1 if (queue1.length != 0) queue1.shift(); // or remove two items from queue2 else { if (queue2.length != 0) queue2.shift(); else return false; if (queue2.length != 0) queue2.shift(); else return false; } } // Step 4.3: The sum produces remainder 2 else if ((sum % 3) == 2) { // either remove one item from queue2 if (queue2.length != 0) queue2.shift(); // or remove two items from queue1 else { if (queue1.length != 0) queue1.shift(); else return false; if (queue1.length != 0) queue1.shift(); else return false; } } let aux=new Array(arr.length); // Empty all the queues into an auxiliary array // and get the number of integers added to aux[] let top=populateAux(aux, queue0, queue1, queue2); // sort the array in non-increasing order aux.sort(function(a, b){return a - b;}); // print the result for (let i = top - 1; i >= 0; i--) document.write(aux[i]+\" \") ; return true;} // Driver codelet arr = [ 8, 1, 7, 6, 0 ];if (!findMaxMultupleOf3(arr)) document.write(\"Not possible\") ; // This code is contributed by rag2127.</script>", "e": 25814, "s": 22513, "text": null }, { "code": null, "e": 25822, "s": 25814, "text": "8 7 6 0" }, { "code": null, "e": 25878, "s": 25824, "text": "The above method can be optimized in following ways. " }, { "code": null, "e": 26307, "s": 25878, "text": "We can use Heap Sort or Merge Sort to make the time complexity O(nLogn). We can avoid extra space for queues. We know at most two items will be removed from the input array. So we can keep track of two items in two variables. At the end, instead of sorting the array again in descending order, we can print the ascending sorted array in reverse order. While printing in reverse order, we can skip the two elements to be removed." }, { "code": null, "e": 26381, "s": 26307, "text": "We can use Heap Sort or Merge Sort to make the time complexity O(nLogn). " }, { "code": null, "e": 26535, "s": 26381, "text": "We can avoid extra space for queues. We know at most two items will be removed from the input array. So we can keep track of two items in two variables. " }, { "code": null, "e": 26738, "s": 26535, "text": "At the end, instead of sorting the array again in descending order, we can print the ascending sorted array in reverse order. While printing in reverse order, we can skip the two elements to be removed." }, { "code": null, "e": 26817, "s": 26738, "text": "Time Complexity: O(nLogn), assuming a O(nLogn) algorithm is used for sorting. " }, { "code": null, "e": 26886, "s": 26817, "text": "Find the largest multiple of 3 | Set 2 (In O(n) time and O(1) space)" }, { "code": null, "e": 26901, "s": 26886, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 26915, "s": 26901, "text": "princiraj1992" }, { "code": null, "e": 26936, "s": 26915, "text": "avanitrachhadiya2155" }, { "code": null, "e": 26953, "s": 26936, "text": "hardikkoriintern" }, { "code": null, "e": 26963, "s": 26953, "text": "phasing17" }, { "code": null, "e": 26973, "s": 26963, "text": "cpp-queue" }, { "code": null, "e": 26986, "s": 26973, "text": "divisibility" }, { "code": null, "e": 26992, "s": 26986, "text": "Queue" }, { "code": null, "e": 26998, "s": 26992, "text": "Queue" } ]
Spring Boot JpaRepository with Example
28 Dec, 2021 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot: It allows avoiding heavy configuration of XML which is present in spring It provides easy maintenance and creation of REST endpoints It includes embedded Tomcat-server Deployment is very easy, war and jar files can be easily deployed in the tomcat server For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use JpaRepository to manage data in a Spring Boot application. JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. Syntax: public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> Where: T: Domain type that repository manages (Generally the Entity/Model class name) ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class) Illustration: public interface DepartmentRepository extends JpaRepository<Department, Long> {} Some of the most important methods that are available inside the JpaRepository are given below Method 1: saveAll(): Saves all given entities. Syntax: <S extends T> List<S> saveAll(Iterable<S> entities) Parameters: Entities, keeping note that they must not be null nor must it contain null. Return Type: the saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument. Exception Thrown: It throws IllegalArgumentException in case the given entities or one of its entities is null. Method 2: getById(): Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is implemented this is very likely to always return an instance and throw an EntityNotFoundException on first access. Some of them will reject invalid identifiers immediately. Syntax: T getById(ID id) Parameters: id – must not be null. Return Type: a reference to the entity with the given identifier. Method 3: flush(): Flushes all pending changes to the database. Syntax: void flush() Method 4: saveAndFlush(): Saves an entity and flushes changes instantly. Syntax: <S extends T> S saveAndFlush(S entity) Parameters: The entity to be saved. Must not be null. Return Type: The saved entity Method 5: deleteAllInBatch(): Deletes the given entities in a batch which means it will create a single query. This kind of operation leaves JPAs first-level cache and the database out of sync. Consider flushing the EntityManager before calling this method. Syntax: void deleteAllInBatch(Iterable<T> entities) Parameters: The entities to be deleted, must not be null. Implementation: Let us consider a Spring Boot application that manages a Department entity with JpaRepository. The data is saved in the H2 database. We use a RESTful controller. Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. Step 2: Add the following dependency Spring Web H2 Database Lombok Spring Data JPA Example: Here is the complete code for the pom.xml file. XML <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project> Step 3: Create 4 packages as listed below and create some classes and interfaces inside these packages as seen in the below image entity repository service controller Note: Green Rounded Icon ‘I’ Buttons are Interface Blue Rounded Icon ‘C’ Buttons are Classes Step 4: Inside the entity package Create a simple POJO class inside the Department.java file. Java // Java Program to Demonstrate Department File // Importing package module to this code fragment package com.amiya.springbootdemoproject.entity; import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; // Importing required classes import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Class public class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;} Step 5: Inside the repository package Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the JpaRepository as we have discussed above. Example: Java // Java Program to Illustrate DepartmentRepository File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interfacepublic interface DepartmentRepository extends JpaRepository<Department, Long> {} Step 6: Inside the service package Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. Example 1-A: Java // Java Program to Demonstrate DepartmentService File // Importing required package to code fragmentpackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);} Example 1-B: Java // Java Program to Illustrate DepartmentServiceImpl File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !"".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !"".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !"".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }} Step 7: Inside the controller package Inside the package create one class named as DepartmentController. Java // Java Program to Demonstrate DepartmentController File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping("/departments") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping("/departments") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping("/departments/{id}") public Department updateDepartment(@RequestBody Department department, @PathVariable("id") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping("/departments/{id}") public String deleteDepartmentById(@PathVariable("id") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return "Deleted Successfully"; }} Step 8: Below is the code for the application.properties file server.port = 8082 # H2 Database spring.h2.console.enabled=true spring.datasource.url=jdbc:h2:mem:dcbapp spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database. Endpoint 1: POST – http://localhost:8082/departments/ Endpoint 2: GET – http://localhost:8082/departments/ Endpoint 3: PUT – http://localhost:8082/departments/1 Endpoint 4: DELETE – http://localhost:8082/departments/1 H2 Database is a follows: Java-Spring-Boot Java MongoDB Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Mongoose | findByIdAndUpdate() Function Upload and Retrieve Image on MongoDB using Mongoose Mongoose Populate() Method Mongoose find() Function MongoDB - db.collection.Find() Method
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Dec, 2021" }, { "code": null, "e": 526, "s": 52, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:" }, { "code": null, "e": 599, "s": 526, "text": "It allows avoiding heavy configuration of XML which is present in spring" }, { "code": null, "e": 659, "s": 599, "text": "It provides easy maintenance and creation of REST endpoints" }, { "code": null, "e": 694, "s": 659, "text": "It includes embedded Tomcat-server" }, { "code": null, "e": 781, "s": 694, "text": "Deployment is very easy, war and jar files can be easily deployed in the tomcat server" }, { "code": null, "e": 972, "s": 781, "text": "For more information please refer to this article: Introduction to Spring Boot. In this article, we are going to discuss how to use JpaRepository to manage data in a Spring Boot application." }, { "code": null, "e": 1213, "s": 972, "text": "JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting." }, { "code": null, "e": 1221, "s": 1213, "text": "Syntax:" }, { "code": null, "e": 1329, "s": 1221, "text": "public interface JpaRepository<T,ID> \nextends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T> " }, { "code": null, "e": 1336, "s": 1329, "text": "Where:" }, { "code": null, "e": 1415, "s": 1336, "text": "T: Domain type that repository manages (Generally the Entity/Model class name)" }, { "code": null, "e": 1560, "s": 1415, "text": "ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)" }, { "code": null, "e": 1574, "s": 1560, "text": "Illustration:" }, { "code": null, "e": 1655, "s": 1574, "text": "public interface DepartmentRepository extends JpaRepository<Department, Long> {}" }, { "code": null, "e": 1750, "s": 1655, "text": "Some of the most important methods that are available inside the JpaRepository are given below" }, { "code": null, "e": 1797, "s": 1750, "text": "Method 1: saveAll(): Saves all given entities." }, { "code": null, "e": 1805, "s": 1797, "text": "Syntax:" }, { "code": null, "e": 1857, "s": 1805, "text": "<S extends T> List<S> saveAll(Iterable<S> entities)" }, { "code": null, "e": 1945, "s": 1857, "text": "Parameters: Entities, keeping note that they must not be null nor must it contain null." }, { "code": null, "e": 2083, "s": 1945, "text": "Return Type: the saved entities; will never be null. The returned Iterable will have the same size as the Iterable passed as an argument." }, { "code": null, "e": 2195, "s": 2083, "text": "Exception Thrown: It throws IllegalArgumentException in case the given entities or one of its entities is null." }, { "code": null, "e": 2499, "s": 2195, "text": "Method 2: getById(): Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is implemented this is very likely to always return an instance and throw an EntityNotFoundException on first access. Some of them will reject invalid identifiers immediately." }, { "code": null, "e": 2508, "s": 2499, "text": "Syntax: " }, { "code": null, "e": 2525, "s": 2508, "text": "T getById(ID id)" }, { "code": null, "e": 2560, "s": 2525, "text": "Parameters: id – must not be null." }, { "code": null, "e": 2626, "s": 2560, "text": "Return Type: a reference to the entity with the given identifier." }, { "code": null, "e": 2690, "s": 2626, "text": "Method 3: flush(): Flushes all pending changes to the database." }, { "code": null, "e": 2698, "s": 2690, "text": "Syntax:" }, { "code": null, "e": 2711, "s": 2698, "text": "void flush()" }, { "code": null, "e": 2784, "s": 2711, "text": "Method 4: saveAndFlush(): Saves an entity and flushes changes instantly." }, { "code": null, "e": 2792, "s": 2784, "text": "Syntax:" }, { "code": null, "e": 2831, "s": 2792, "text": "<S extends T> S saveAndFlush(S entity)" }, { "code": null, "e": 2885, "s": 2831, "text": "Parameters: The entity to be saved. Must not be null." }, { "code": null, "e": 2915, "s": 2885, "text": "Return Type: The saved entity" }, { "code": null, "e": 3173, "s": 2915, "text": "Method 5: deleteAllInBatch(): Deletes the given entities in a batch which means it will create a single query. This kind of operation leaves JPAs first-level cache and the database out of sync. Consider flushing the EntityManager before calling this method." }, { "code": null, "e": 3181, "s": 3173, "text": "Syntax:" }, { "code": null, "e": 3226, "s": 3181, "text": " void deleteAllInBatch(Iterable<T> entities)" }, { "code": null, "e": 3284, "s": 3226, "text": "Parameters: The entities to be deleted, must not be null." }, { "code": null, "e": 3462, "s": 3284, "text": "Implementation: Let us consider a Spring Boot application that manages a Department entity with JpaRepository. The data is saved in the H2 database. We use a RESTful controller." }, { "code": null, "e": 3553, "s": 3462, "text": "Step 1: Create a Spring Boot Project with IntelliJ IDEA and create a Spring Boot project. " }, { "code": null, "e": 3590, "s": 3553, "text": "Step 2: Add the following dependency" }, { "code": null, "e": 3601, "s": 3590, "text": "Spring Web" }, { "code": null, "e": 3613, "s": 3601, "text": "H2 Database" }, { "code": null, "e": 3620, "s": 3613, "text": "Lombok" }, { "code": null, "e": 3636, "s": 3620, "text": "Spring Data JPA" }, { "code": null, "e": 3693, "s": 3636, "text": "Example: Here is the complete code for the pom.xml file." }, { "code": null, "e": 3697, "s": 3693, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.amiya</groupId> <artifactId>Spring-Boot-Demo-Project</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Spring-Boot-Demo-Project</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>", "e": 6162, "s": 3697, "text": null }, { "code": null, "e": 6292, "s": 6162, "text": "Step 3: Create 4 packages as listed below and create some classes and interfaces inside these packages as seen in the below image" }, { "code": null, "e": 6299, "s": 6292, "text": "entity" }, { "code": null, "e": 6310, "s": 6299, "text": "repository" }, { "code": null, "e": 6318, "s": 6310, "text": "service" }, { "code": null, "e": 6329, "s": 6318, "text": "controller" }, { "code": null, "e": 6335, "s": 6329, "text": "Note:" }, { "code": null, "e": 6380, "s": 6335, "text": "Green Rounded Icon ‘I’ Buttons are Interface" }, { "code": null, "e": 6422, "s": 6380, "text": "Blue Rounded Icon ‘C’ Buttons are Classes" }, { "code": null, "e": 6456, "s": 6422, "text": "Step 4: Inside the entity package" }, { "code": null, "e": 6517, "s": 6456, "text": "Create a simple POJO class inside the Department.java file. " }, { "code": null, "e": 6522, "s": 6517, "text": "Java" }, { "code": "// Java Program to Demonstrate Department File // Importing package module to this code fragment package com.amiya.springbootdemoproject.entity; import lombok.AllArgsConstructor;import lombok.Builder;import lombok.Data;import lombok.NoArgsConstructor; // Importing required classes import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; @Entity@Data@NoArgsConstructor@AllArgsConstructor@Builder // Class public class Department { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long departmentId; private String departmentName; private String departmentAddress; private String departmentCode;}", "e": 7244, "s": 6522, "text": null }, { "code": null, "e": 7282, "s": 7244, "text": "Step 5: Inside the repository package" }, { "code": null, "e": 7437, "s": 7282, "text": "Create a simple interface and name the interface as DepartmentRepository. This interface is going to extend the JpaRepository as we have discussed above. " }, { "code": null, "e": 7446, "s": 7437, "text": "Example:" }, { "code": null, "e": 7451, "s": 7446, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentRepository File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.repository; import com.amiya.springbootdemoproject.entity.Department;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; // Annotation@Repository // Interfacepublic interface DepartmentRepository extends JpaRepository<Department, Long> {}", "e": 7896, "s": 7451, "text": null }, { "code": null, "e": 7931, "s": 7896, "text": "Step 6: Inside the service package" }, { "code": null, "e": 8045, "s": 7931, "text": "Inside the package create one interface named as DepartmentService and one class named as DepartmentServiceImpl. " }, { "code": null, "e": 8058, "s": 8045, "text": "Example 1-A:" }, { "code": null, "e": 8063, "s": 8058, "text": "Java" }, { "code": "// Java Program to Demonstrate DepartmentService File // Importing required package to code fragmentpackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;// Importing required classesimport java.util.List; // Interfacepublic interface DepartmentService { // Save operation Department saveDepartment(Department department); // Read operation List<Department> fetchDepartmentList(); // Update operation Department updateDepartment(Department department, Long departmentId); // Delete operation void deleteDepartmentById(Long departmentId);}", "e": 8720, "s": 8063, "text": null }, { "code": null, "e": 8733, "s": 8720, "text": "Example 1-B:" }, { "code": null, "e": 8738, "s": 8733, "text": "Java" }, { "code": "// Java Program to Illustrate DepartmentServiceImpl File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.service; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.repository.DepartmentRepository;// Importing required classesimport java.util.List;import java.util.Objects;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; // Annotation@Service // Classpublic class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentRepository departmentRepository; // Save operation @Override public Department saveDepartment(Department department) { return departmentRepository.save(department); } // Read operation @Override public List<Department> fetchDepartmentList() { return (List<Department>) departmentRepository.findAll(); } // Update operation @Override public Department updateDepartment(Department department, Long departmentId) { Department depDB = departmentRepository.findById(departmentId) .get(); if (Objects.nonNull(department.getDepartmentName()) && !\"\".equalsIgnoreCase( department.getDepartmentName())) { depDB.setDepartmentName( department.getDepartmentName()); } if (Objects.nonNull( department.getDepartmentAddress()) && !\"\".equalsIgnoreCase( department.getDepartmentAddress())) { depDB.setDepartmentAddress( department.getDepartmentAddress()); } if (Objects.nonNull(department.getDepartmentCode()) && !\"\".equalsIgnoreCase( department.getDepartmentCode())) { depDB.setDepartmentCode( department.getDepartmentCode()); } return departmentRepository.save(depDB); } // Delete operation @Override public void deleteDepartmentById(Long departmentId) { departmentRepository.deleteById(departmentId); }}", "e": 10913, "s": 8738, "text": null }, { "code": null, "e": 10951, "s": 10913, "text": "Step 7: Inside the controller package" }, { "code": null, "e": 11019, "s": 10951, "text": "Inside the package create one class named as DepartmentController. " }, { "code": null, "e": 11024, "s": 11019, "text": "Java" }, { "code": "// Java Program to Demonstrate DepartmentController File // Importing package module to code fragmentpackage com.amiya.springbootdemoproject.controller; import com.amiya.springbootdemoproject.entity.Department;import com.amiya.springbootdemoproject.service.DepartmentService;import java.util.List;// Importing required classesimport javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; // Annotation@RestController // Classpublic class DepartmentController { @Autowired private DepartmentService departmentService; // Save operation @PostMapping(\"/departments\") public Department saveDepartment( @Valid @RequestBody Department department) { return departmentService.saveDepartment(department); } // Read operation @GetMapping(\"/departments\") public List<Department> fetchDepartmentList() { return departmentService.fetchDepartmentList(); } // Update operation @PutMapping(\"/departments/{id}\") public Department updateDepartment(@RequestBody Department department, @PathVariable(\"id\") Long departmentId) { return departmentService.updateDepartment( department, departmentId); } // Delete operation @DeleteMapping(\"/departments/{id}\") public String deleteDepartmentById(@PathVariable(\"id\") Long departmentId) { departmentService.deleteDepartmentById( departmentId); return \"Deleted Successfully\"; }}", "e": 12608, "s": 11024, "text": null }, { "code": null, "e": 12670, "s": 12608, "text": "Step 8: Below is the code for the application.properties file" }, { "code": null, "e": 12951, "s": 12670, "text": "server.port = 8082\n\n# H2 Database\nspring.h2.console.enabled=true\nspring.datasource.url=jdbc:h2:mem:dcbapp\nspring.datasource.driverClassName=org.h2.Driver\nspring.datasource.username=sa\nspring.datasource.password=password\nspring.jpa.database-platform=org.hibernate.dialect.H2Dialect" }, { "code": null, "e": 13051, "s": 12951, "text": "Now run your application and let’s test the endpoints in Postman and also refer to our H2 Database." }, { "code": null, "e": 13105, "s": 13051, "text": "Endpoint 1: POST – http://localhost:8082/departments/" }, { "code": null, "e": 13158, "s": 13105, "text": "Endpoint 2: GET – http://localhost:8082/departments/" }, { "code": null, "e": 13212, "s": 13158, "text": "Endpoint 3: PUT – http://localhost:8082/departments/1" }, { "code": null, "e": 13269, "s": 13212, "text": "Endpoint 4: DELETE – http://localhost:8082/departments/1" }, { "code": null, "e": 13295, "s": 13269, "text": "H2 Database is a follows:" }, { "code": null, "e": 13312, "s": 13295, "text": "Java-Spring-Boot" }, { "code": null, "e": 13317, "s": 13312, "text": "Java" }, { "code": null, "e": 13325, "s": 13317, "text": "MongoDB" }, { "code": null, "e": 13330, "s": 13325, "text": "Java" }, { "code": null, "e": 13428, "s": 13330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13443, "s": 13428, "text": "Stream In Java" }, { "code": null, "e": 13464, "s": 13443, "text": "Introduction to Java" }, { "code": null, "e": 13485, "s": 13464, "text": "Constructors in Java" }, { "code": null, "e": 13504, "s": 13485, "text": "Exceptions in Java" }, { "code": null, "e": 13521, "s": 13504, "text": "Generics in Java" }, { "code": null, "e": 13561, "s": 13521, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 13613, "s": 13561, "text": "Upload and Retrieve Image on MongoDB using Mongoose" }, { "code": null, "e": 13640, "s": 13613, "text": "Mongoose Populate() Method" }, { "code": null, "e": 13665, "s": 13640, "text": "Mongoose find() Function" } ]
Navigation with BeautifulSoup
24 Dec, 2021 BeautifulSoup is a Python package used for parsing HTML and XML documents, it creates a parse tree for parsed paged which can be used for web scraping, it pulls data from HTML and XML files and works with your favorite parser to provide the idiomatic way of navigating, searching, and modifying the parse tree. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 Below code snippet is the HTML document which we shall use, to navigate using BeautifulSoup tags with this code snippet as reference. Python3 ht_doc = """ <html><head><title>Geeks For Geeks</title></head> <body> <p class="title"><b>most viewed courses in GFG,its all free</b></p> <p class ="prog">Top 5 Popular Programming Languages</p> <a href="https://www.geeksforgeeks.org/java-programming-examples/" \class="prog" id="link1">Java</a><a href="https://www.geeksforgeeks.org/cc-programs/" class="prog" \id="link2">c/c++</a><a href="https://www.geeksforgeeks.org/python-programming-examples/"\class="prog" id="link3">Python</a><a href="https://https://www.geeksforgeeks.org/introduction-to-javascript/"\class="prog" id="link4">Javascript</a><a href="https://www.geeksforgeeks.org/ruby-programming-language/" \class="prog" id="link5">Ruby</a> <p>according to an online survey. </p> <p class="prog"> Programming Languages</p> </body></html> """ Now let us navigate in all possible ways by applying BeautifulSoup in Python on the above code snippet, the most important component in Html documents are tags which may also contain other tags/strings(tag’s children). BeautifulSoup provides different ways to iterate over these children, let us see all possible cases Example 1: To get Head Tag. Use .head to BeautifulSoup object to get the head tag in HTML document. Syntax : (BeautifulSoup Variable).head Example 2: To get Title Tag Use .title tag to retrieve the title of the HTML document embedded in BeautifulSoup variable Syntax : (BeautifulSoup Variable).title Code: Python3 soup = BeautifulSoup(ht_doc, 'html.parser')print(soup.head)print(soup.title) Output: <head><title>Geeks For Geeks</title></head> <title>Geeks For Geeks</title> Example 3: To get a specific tag. We can retrieve some specific tags like the first <b> tag in the body tag Syntax : (BeautifulSoup Variable).body.b Using tag name as an attribute will get you the first name of that name Syntax: (BeautifulSoup Variable).(tag attribute) By using find_all, we can get all contents associated with the attribute Syntax: (BeautifulSoup Variable).find_all(tag value) Code: Python3 soup = BeautifulSoup(ht_doc, 'html.parser') # retrieving b tag elementprint(soup.body.b) # retrieving a tag element from BeautifulSoup assigned variableprint(soup.a) # retrieving all elements tagged with a in ht_docprint(soup.find_all("a")) Output: <b>most viewed courses in GFG,its all free</b> <a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a> [<a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a>, <a class=”prog” href=”https://www.geeksforgeeks.org/cc-programs/” id=”link2′′>c/c++</a>, <a class=”prog” href=”https://www.geeksforgeeks.org/python-programming-examples/” id=”link3′′>Python</a>, <a class=”prog” href=”https://https://www.geeksforgeeks.org/introduction-to-javascript/” id=”link4′′>Javascript</a>, <a class=”prog” href=”https://www.geeksforgeeks.org/ruby-programming-language/” id=”link5′′>Ruby</a>] Example 4: Contents and .children We can get tags children in a list by using .contents. Syntax: (BeautifulSoup Variable).contents Code: Python3 soup = BeautifulSoup(ht_doc, 'html.parser') # assigning head tag of BeautifulSoup variablehTag = soup.headprint(hTag) # retrieving contents of BeautifulSoup variableprint(hTag.contents) Output: <head><title>Geeks For Geeks</title></head> [<title>Geeks For Geeks</title>] Example 5: .descendants The .descendants attribute allows you to iterate over all of a tag’s children, recursively −its direct children and the children of its direct children and so on... Syntax: (Variable assigned from BeautifulSoup Variable).descendants Code: Python3 # embedding html document inyto BeautifulSoup variablesoup = BeautifulSoup(ht_doc, 'html.parser') # assigning head element of BeautifulSoup-assigned Variablehtag=soup.head # iterating through child in descendants of htag variablefor child in htag.descendants: print(child) Output : <title>Geeks For Geeks</title> Geeks For Geeks Example 6: .string If the tag has only one child, and that child is a NavigableString, the child is made available as .string However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None, we can see this practical working in below code. Python3 soup = BeautifulSoup(ht_doc, 'html.parser')htag = soup.headprint(htag.string) Output: Geeks For Geeks Example 7: .strings and stripped_strings If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator. Python3 soup = BeautifulSoup(ht_doc, 'html.parser')for string in soup.strings : print(repr(string)) Output : '\n' 'Geeks For Geeks' '\n' '\n' 'most viewed courses in GFG,its all free' '\n' 'Top 5 Popular Programming Languages' '\n' 'Java' '\n' 'c/c++' '\n' 'Python' '\n' 'Javascript' '\n' 'Ruby' '\naccording to an online survey. ' '\n' ' Programming Languages' '\n' For removal of extra whitespaces, we use .stripped_strings generator : Python3 # embedding HTML document in BeautifulSoup-assigned variablesoup = BeautifulSoup(ht_doc, 'html.parser') # iterating through string in stripped_strings of# BeautifulSoup assigned variablefor string in soup.stripped_strings : print(repr(string)) Output: 'Geeks For Geeks' 'most viewed courses in GFG,its all free' 'Top 5 Popular Programming Languages' 'Java' 'c/c++' 'Python' 'Javascript' 'Ruby' 'according to an online survey.' 'Programming Languages' If we consider a “family tree” analogy, every tag and every string has a parent: the tag that contains it: Example 1: .parent. .parent tag is used for retrieving the element’s parent element Syntax : (BeautifulSoup Variable).parent Code: Python3 ht_doc = """<html><head><title>Geeks For Geeks</title></head><body><p class="title"><b>most viewed courses in GFG,its all free</b></p> <p class ="prog">Top 5 Popular Programming Languages</p> <a href="https://www.geeksforgeeks.org/java-programming-examples/"\class="prog" id="link1">Java</a><a href="https://www.geeksforgeeks.org/cc-programs/" class="prog" \id="link2">c/c++</a><a href="https://www.geeksforgeeks.org/python-programming-examples/"\class="prog" id="link3">Python</a><a href="https://https://www.geeksforgeeks.org/introduction-to-javascript/"\class="prog" id="link4">Javascript</a><a href="https://www.geeksforgeeks.org/ruby-programming-language/"\class="prog" id="link5">Ruby</a>according to an online survey. </a><p class="prog"> Programming Languages</p> </body></html>"""from bs4 import BeautifulSoupsoup = BeautifulSoup(ht_doc, 'html.parser') # embedding html documentItag = soup.title # assigning title tag of BeautifulSoup-assigned variable# to print parent element in Itag variableprint(Itag.parent)htmlTag = soup.htmlprint(type(htmlTag.parent))print(soup.parent) Output: <head><title>Geeks For Geeks</title></head> <class 'bs4.BeautifulSoup'> None Example 2: .parents For iterating all over the parent elements, .parents tag can be used : Syntax :(BeautifulSoup Variable).parents Python3 # embedding html doc into BeautifulSoupsoup = BeautifulSoup(ht_doc, 'html.parser') # embedding a tag into link variablelink = soup.aprint(link) # iterating through parent in link variablefor parent in link.parents : # printing statement for Parent is empty case if parent is None : print(parent) else : print(parent.name) Output: <a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a> body html [document] .next_sibling and .previous_sibling are the tags that are used for navigating between page elements that are on same level of the parse tree. Syntax: (BeautifulSoup Variable).(tag attribute).next_sibling (BeautifulSoup Variable).(tag attribute).previous_sibling Code: Python3 from bs4 import BeautifulSoupsibling_soup = BeautifulSoup("<a><b>Geeks For Geeks</b><c><strong>The \Biggest Online Tutorials Library, It's all Free</strong></b></a>") # to retrieve next sibling of b tagprint(sibling_soup.b.next_sibling) # for retrieving previous sibling of c tagprint(sibling_soup.c.previous_sibling) Output: <c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c> <b>Geeks For Geeks</b> akshaysingh98088 ruhelaa48 sumitgumber28 sagar0719kumar Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 339, "s": 28, "text": "BeautifulSoup is a Python package used for parsing HTML and XML documents, it creates a parse tree for parsed paged which can be used for web scraping, it pulls data from HTML and XML files and works with your favorite parser to provide the idiomatic way of navigating, searching, and modifying the parse tree." }, { "code": null, "e": 443, "s": 339, "text": "This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 459, "s": 443, "text": "pip install bs4" }, { "code": null, "e": 593, "s": 459, "text": "Below code snippet is the HTML document which we shall use, to navigate using BeautifulSoup tags with this code snippet as reference." }, { "code": null, "e": 601, "s": 593, "text": "Python3" }, { "code": "ht_doc = \"\"\" <html><head><title>Geeks For Geeks</title></head> <body> <p class=\"title\"><b>most viewed courses in GFG,its all free</b></p> <p class =\"prog\">Top 5 Popular Programming Languages</p> <a href=\"https://www.geeksforgeeks.org/java-programming-examples/\" \\class=\"prog\" id=\"link1\">Java</a><a href=\"https://www.geeksforgeeks.org/cc-programs/\" class=\"prog\" \\id=\"link2\">c/c++</a><a href=\"https://www.geeksforgeeks.org/python-programming-examples/\"\\class=\"prog\" id=\"link3\">Python</a><a href=\"https://https://www.geeksforgeeks.org/introduction-to-javascript/\"\\class=\"prog\" id=\"link4\">Javascript</a><a href=\"https://www.geeksforgeeks.org/ruby-programming-language/\" \\class=\"prog\" id=\"link5\">Ruby</a> <p>according to an online survey. </p> <p class=\"prog\"> Programming Languages</p> </body></html> \"\"\"", "e": 1451, "s": 601, "text": null }, { "code": null, "e": 1771, "s": 1451, "text": "Now let us navigate in all possible ways by applying BeautifulSoup in Python on the above code snippet, the most important component in Html documents are tags which may also contain other tags/strings(tag’s children). BeautifulSoup provides different ways to iterate over these children, let us see all possible cases " }, { "code": null, "e": 1799, "s": 1771, "text": "Example 1: To get Head Tag." }, { "code": null, "e": 1871, "s": 1799, "text": "Use .head to BeautifulSoup object to get the head tag in HTML document." }, { "code": null, "e": 1910, "s": 1871, "text": "Syntax : (BeautifulSoup Variable).head" }, { "code": null, "e": 1939, "s": 1910, "text": "Example 2: To get Title Tag " }, { "code": null, "e": 2033, "s": 1939, "text": "Use .title tag to retrieve the title of the HTML document embedded in BeautifulSoup variable " }, { "code": null, "e": 2073, "s": 2033, "text": "Syntax : (BeautifulSoup Variable).title" }, { "code": null, "e": 2080, "s": 2073, "text": "Code: " }, { "code": null, "e": 2088, "s": 2080, "text": "Python3" }, { "code": "soup = BeautifulSoup(ht_doc, 'html.parser')print(soup.head)print(soup.title)", "e": 2165, "s": 2088, "text": null }, { "code": null, "e": 2175, "s": 2165, "text": " Output: " }, { "code": null, "e": 2250, "s": 2175, "text": "<head><title>Geeks For Geeks</title></head>\n<title>Geeks For Geeks</title>" }, { "code": null, "e": 2284, "s": 2250, "text": "Example 3: To get a specific tag." }, { "code": null, "e": 2360, "s": 2284, "text": "We can retrieve some specific tags like the first <b> tag in the body tag " }, { "code": null, "e": 2401, "s": 2360, "text": "Syntax : (BeautifulSoup Variable).body.b" }, { "code": null, "e": 2474, "s": 2401, "text": "Using tag name as an attribute will get you the first name of that name " }, { "code": null, "e": 2523, "s": 2474, "text": "Syntax: (BeautifulSoup Variable).(tag attribute)" }, { "code": null, "e": 2597, "s": 2523, "text": "By using find_all, we can get all contents associated with the attribute " }, { "code": null, "e": 2650, "s": 2597, "text": "Syntax: (BeautifulSoup Variable).find_all(tag value)" }, { "code": null, "e": 2656, "s": 2650, "text": "Code:" }, { "code": null, "e": 2664, "s": 2656, "text": "Python3" }, { "code": "soup = BeautifulSoup(ht_doc, 'html.parser') # retrieving b tag elementprint(soup.body.b) # retrieving a tag element from BeautifulSoup assigned variableprint(soup.a) # retrieving all elements tagged with a in ht_docprint(soup.find_all(\"a\"))", "e": 2905, "s": 2664, "text": null }, { "code": null, "e": 2913, "s": 2905, "text": "Output:" }, { "code": null, "e": 2960, "s": 2913, "text": "<b>most viewed courses in GFG,its all free</b>" }, { "code": null, "e": 3061, "s": 2960, "text": "<a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a>" }, { "code": null, "e": 3164, "s": 3061, "text": "[<a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a>," }, { "code": null, "e": 3254, "s": 3164, "text": "<a class=”prog” href=”https://www.geeksforgeeks.org/cc-programs/” id=”link2′′>c/c++</a>, " }, { "code": null, "e": 3360, "s": 3254, "text": "<a class=”prog” href=”https://www.geeksforgeeks.org/python-programming-examples/” id=”link3′′>Python</a>," }, { "code": null, "e": 3477, "s": 3360, "text": "<a class=”prog” href=”https://https://www.geeksforgeeks.org/introduction-to-javascript/” id=”link4′′>Javascript</a>," }, { "code": null, "e": 3579, "s": 3477, "text": "<a class=”prog” href=”https://www.geeksforgeeks.org/ruby-programming-language/” id=”link5′′>Ruby</a>]" }, { "code": null, "e": 3613, "s": 3579, "text": "Example 4: Contents and .children" }, { "code": null, "e": 3668, "s": 3613, "text": "We can get tags children in a list by using .contents." }, { "code": null, "e": 3710, "s": 3668, "text": "Syntax: (BeautifulSoup Variable).contents" }, { "code": null, "e": 3716, "s": 3710, "text": "Code:" }, { "code": null, "e": 3724, "s": 3716, "text": "Python3" }, { "code": "soup = BeautifulSoup(ht_doc, 'html.parser') # assigning head tag of BeautifulSoup variablehTag = soup.headprint(hTag) # retrieving contents of BeautifulSoup variableprint(hTag.contents)", "e": 3910, "s": 3724, "text": null }, { "code": null, "e": 3918, "s": 3910, "text": "Output:" }, { "code": null, "e": 3995, "s": 3918, "text": "<head><title>Geeks For Geeks</title></head>\n[<title>Geeks For Geeks</title>]" }, { "code": null, "e": 4019, "s": 3995, "text": "Example 5: .descendants" }, { "code": null, "e": 4184, "s": 4019, "text": "The .descendants attribute allows you to iterate over all of a tag’s children, recursively −its direct children and the children of its direct children and so on..." }, { "code": null, "e": 4252, "s": 4184, "text": "Syntax: (Variable assigned from BeautifulSoup Variable).descendants" }, { "code": null, "e": 4258, "s": 4252, "text": "Code:" }, { "code": null, "e": 4266, "s": 4258, "text": "Python3" }, { "code": "# embedding html document inyto BeautifulSoup variablesoup = BeautifulSoup(ht_doc, 'html.parser') # assigning head element of BeautifulSoup-assigned Variablehtag=soup.head # iterating through child in descendants of htag variablefor child in htag.descendants: print(child)", "e": 4542, "s": 4266, "text": null }, { "code": null, "e": 4551, "s": 4542, "text": "Output :" }, { "code": null, "e": 4598, "s": 4551, "text": "<title>Geeks For Geeks</title>\nGeeks For Geeks" }, { "code": null, "e": 4617, "s": 4598, "text": "Example 6: .string" }, { "code": null, "e": 4724, "s": 4617, "text": "If the tag has only one child, and that child is a NavigableString, the child is made available as .string" }, { "code": null, "e": 4902, "s": 4724, "text": "However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None, we can see this practical working in below code." }, { "code": null, "e": 4910, "s": 4902, "text": "Python3" }, { "code": "soup = BeautifulSoup(ht_doc, 'html.parser')htag = soup.headprint(htag.string)", "e": 4988, "s": 4910, "text": null }, { "code": null, "e": 4996, "s": 4988, "text": "Output:" }, { "code": null, "e": 5012, "s": 4996, "text": "Geeks For Geeks" }, { "code": null, "e": 5053, "s": 5012, "text": "Example 7: .strings and stripped_strings" }, { "code": null, "e": 5166, "s": 5053, "text": "If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator." }, { "code": null, "e": 5174, "s": 5166, "text": "Python3" }, { "code": "soup = BeautifulSoup(ht_doc, 'html.parser')for string in soup.strings : print(repr(string))", "e": 5269, "s": 5174, "text": null }, { "code": null, "e": 5278, "s": 5269, "text": "Output :" }, { "code": null, "e": 5536, "s": 5278, "text": "'\\n'\n'Geeks For Geeks'\n'\\n'\n'\\n'\n'most viewed courses in GFG,its all free'\n'\\n'\n'Top 5 Popular Programming Languages'\n'\\n'\n'Java'\n'\\n'\n'c/c++'\n'\\n'\n'Python'\n'\\n'\n'Javascript'\n'\\n'\n'Ruby'\n'\\naccording to an online survey. '\n'\\n'\n' Programming Languages'\n'\\n'" }, { "code": null, "e": 5607, "s": 5536, "text": "For removal of extra whitespaces, we use .stripped_strings generator :" }, { "code": null, "e": 5615, "s": 5607, "text": "Python3" }, { "code": "# embedding HTML document in BeautifulSoup-assigned variablesoup = BeautifulSoup(ht_doc, 'html.parser') # iterating through string in stripped_strings of# BeautifulSoup assigned variablefor string in soup.stripped_strings : print(repr(string))", "e": 5862, "s": 5615, "text": null }, { "code": null, "e": 5870, "s": 5862, "text": "Output:" }, { "code": null, "e": 6069, "s": 5870, "text": "'Geeks For Geeks'\n'most viewed courses in GFG,its all free'\n'Top 5 Popular Programming Languages'\n'Java'\n'c/c++'\n'Python'\n'Javascript'\n'Ruby'\n'according to an online survey.'\n'Programming Languages'" }, { "code": null, "e": 6176, "s": 6069, "text": "If we consider a “family tree” analogy, every tag and every string has a parent: the tag that contains it:" }, { "code": null, "e": 6196, "s": 6176, "text": "Example 1: .parent." }, { "code": null, "e": 6260, "s": 6196, "text": ".parent tag is used for retrieving the element’s parent element" }, { "code": null, "e": 6301, "s": 6260, "text": "Syntax : (BeautifulSoup Variable).parent" }, { "code": null, "e": 6307, "s": 6301, "text": "Code:" }, { "code": null, "e": 6315, "s": 6307, "text": "Python3" }, { "code": "ht_doc = \"\"\"<html><head><title>Geeks For Geeks</title></head><body><p class=\"title\"><b>most viewed courses in GFG,its all free</b></p> <p class =\"prog\">Top 5 Popular Programming Languages</p> <a href=\"https://www.geeksforgeeks.org/java-programming-examples/\"\\class=\"prog\" id=\"link1\">Java</a><a href=\"https://www.geeksforgeeks.org/cc-programs/\" class=\"prog\" \\id=\"link2\">c/c++</a><a href=\"https://www.geeksforgeeks.org/python-programming-examples/\"\\class=\"prog\" id=\"link3\">Python</a><a href=\"https://https://www.geeksforgeeks.org/introduction-to-javascript/\"\\class=\"prog\" id=\"link4\">Javascript</a><a href=\"https://www.geeksforgeeks.org/ruby-programming-language/\"\\class=\"prog\" id=\"link5\">Ruby</a>according to an online survey. </a><p class=\"prog\"> Programming Languages</p> </body></html>\"\"\"from bs4 import BeautifulSoupsoup = BeautifulSoup(ht_doc, 'html.parser') # embedding html documentItag = soup.title # assigning title tag of BeautifulSoup-assigned variable# to print parent element in Itag variableprint(Itag.parent)htmlTag = soup.htmlprint(type(htmlTag.parent))print(soup.parent)", "e": 7413, "s": 6315, "text": null }, { "code": null, "e": 7421, "s": 7413, "text": "Output:" }, { "code": null, "e": 7498, "s": 7421, "text": "<head><title>Geeks For Geeks</title></head>\n<class 'bs4.BeautifulSoup'>\nNone" }, { "code": null, "e": 7518, "s": 7498, "text": "Example 2: .parents" }, { "code": null, "e": 7589, "s": 7518, "text": "For iterating all over the parent elements, .parents tag can be used :" }, { "code": null, "e": 7630, "s": 7589, "text": "Syntax :(BeautifulSoup Variable).parents" }, { "code": null, "e": 7638, "s": 7630, "text": "Python3" }, { "code": "# embedding html doc into BeautifulSoupsoup = BeautifulSoup(ht_doc, 'html.parser') # embedding a tag into link variablelink = soup.aprint(link) # iterating through parent in link variablefor parent in link.parents : # printing statement for Parent is empty case if parent is None : print(parent) else : print(parent.name)", "e": 7988, "s": 7638, "text": null }, { "code": null, "e": 7997, "s": 7988, "text": "Output: " }, { "code": null, "e": 8098, "s": 7997, "text": "<a class=”prog” href=”https://www.geeksforgeeks.org/java-programming-examples/” id=”link1′′>Java</a>" }, { "code": null, "e": 8103, "s": 8098, "text": "body" }, { "code": null, "e": 8108, "s": 8103, "text": "html" }, { "code": null, "e": 8119, "s": 8108, "text": "[document]" }, { "code": null, "e": 8262, "s": 8119, "text": ".next_sibling and .previous_sibling are the tags that are used for navigating between page elements that are on same level of the parse tree. " }, { "code": null, "e": 8270, "s": 8262, "text": "Syntax:" }, { "code": null, "e": 8324, "s": 8270, "text": "(BeautifulSoup Variable).(tag attribute).next_sibling" }, { "code": null, "e": 8382, "s": 8324, "text": "(BeautifulSoup Variable).(tag attribute).previous_sibling" }, { "code": null, "e": 8389, "s": 8382, "text": "Code: " }, { "code": null, "e": 8397, "s": 8389, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupsibling_soup = BeautifulSoup(\"<a><b>Geeks For Geeks</b><c><strong>The \\Biggest Online Tutorials Library, It's all Free</strong></b></a>\") # to retrieve next sibling of b tagprint(sibling_soup.b.next_sibling) # for retrieving previous sibling of c tagprint(sibling_soup.c.previous_sibling)", "e": 8715, "s": 8397, "text": null }, { "code": null, "e": 8723, "s": 8715, "text": "Output:" }, { "code": null, "e": 8822, "s": 8723, "text": "<c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c>\n<b>Geeks For Geeks</b>" }, { "code": null, "e": 8839, "s": 8822, "text": "akshaysingh98088" }, { "code": null, "e": 8849, "s": 8839, "text": "ruhelaa48" }, { "code": null, "e": 8863, "s": 8849, "text": "sumitgumber28" }, { "code": null, "e": 8878, "s": 8863, "text": "sagar0719kumar" }, { "code": null, "e": 8885, "s": 8878, "text": "Picked" }, { "code": null, "e": 8906, "s": 8885, "text": "Python BeautifulSoup" }, { "code": null, "e": 8913, "s": 8906, "text": "Python" } ]
Efficient program to calculate e^x
29 Oct, 2021 The value of Exponential Function e^x can be expressed using following Taylor Series. e^x = 1 + x/1! + x^2/2! + x^3/3! + ...... How to efficiently calculate the sum of above series? The series can be re-written as e^x = 1 + (x/1) (1 + (x/2) (1 + (x/3) (........) ) ) Let the sum needs to be calculated for n terms, we can calculate sum using following loop. for (i = n - 1, sum = 1; i > 0; --i ) sum = 1 + x * sum / i; Following is implementation of the above idea. C++ C Java Python3 C# PHP Javascript // C++ Efficient program to calculate// e raise to the power x#include <bits/stdc++.h>using namespace std; // Returns approximate value of e^x// using sum of first n terms of Taylor Seriesfloat exponential(int n, float x){ float sum = 1.0f; // initialize sum of series for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum;} // Driver codeint main(){ int n = 10; float x = 1.0f; cout << "e^x = " << fixed << setprecision(5) << exponential(n, x); return 0;} // This code is contributed by rathbhupendra // C Efficient program to calculate// e raise to the power x#include <stdio.h> // Returns approximate value of e^x// using sum of first n terms of Taylor Seriesfloat exponential(int n, float x){ float sum = 1.0f; // initialize sum of series for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum;} // Driver program to test above functionint main(){ int n = 10; float x = 1.0f; printf("e^x = %f", exponential(n, x)); return 0;} // Java efficient program to calculate// e raise to the power ximport java.io.*; class GFG{ // Function returns approximate value of e^x // using sum of first n terms of Taylor Series static float exponential(int n, float x) { // initialize sum of series float sum = 1; for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum; } // driver program public static void main (String[] args) { int n = 10; float x = 1; System.out.println("e^x = "+exponential(n,x)); }} // Contributed by Pramod Kumar # Python program to calculate# e raise to the power x # Function to calculate value# using sum of first n terms of# Taylor Seriesdef exponential(n, x): # initialize sum of series sum = 1.0 for i in range(n, 0, -1): sum = 1 + x * sum / i print ("e^x =", sum) # Driver program to test above functionn = 10x = 1.0exponential(n, x) # This code is contributed by Danish Raza // C# efficient program to calculate// e raise to the power xusing System; class GFG{ // Function returns approximate value of e^x // using sum of first n terms of Taylor Series static float exponential(int n, float x) { // initialize sum of series float sum = 1; for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum; } // driver program public static void Main () { int n = 10; float x = 1; Console.Write("e^x = " + exponential(n, x)); }} // This code is contributed by nitin mittal. <?php// PHP Efficient program to calculate// e raise to the power x // Returns approximate value of e^x// using sum of first n terms// of Taylor Seriesfunction exponential($n, $x){ // initialize sum of series $sum = 1.0; for ($i = $n - 1; $i > 0; --$i ) $sum = 1 + $x * $sum / $i; return $sum;} // Driver Code$n = 10;$x = 1.0;echo("e^x = " . exponential($n, $x)); // This code is contributed by Ajit.?> <script>// javascript efficient program to calculate// e raise to the power x // Function returns approximate value of e^x // using sum of first n terms of Taylor Series function exponential(n , x) { // initialize sum of series var sum = 1; for (i = n - 1; i > 0; --i) sum = 1 + x * sum / i; return sum; } // driver program var n = 10; var x = 1; document.write("e^x = " + exponential(n, x).toFixed(6)); // This code contributed by Rajput-Ji </script> Output: e^x = 2.718282 Time Complexity: O(n) Auxiliary Space: O(1) This article is compiled by Rahul and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal jit_t Kirti_Mangal rathbhupendra Rajput-Ji subhammahato348 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Oct, 2021" }, { "code": null, "e": 140, "s": 54, "text": "The value of Exponential Function e^x can be expressed using following Taylor Series." }, { "code": null, "e": 183, "s": 140, "text": "e^x = 1 + x/1! + x^2/2! + x^3/3! + ...... " }, { "code": null, "e": 271, "s": 183, "text": "How to efficiently calculate the sum of above series? The series can be re-written as " }, { "code": null, "e": 325, "s": 271, "text": "e^x = 1 + (x/1) (1 + (x/2) (1 + (x/3) (........) ) ) " }, { "code": null, "e": 416, "s": 325, "text": "Let the sum needs to be calculated for n terms, we can calculate sum using following loop." }, { "code": null, "e": 482, "s": 416, "text": "for (i = n - 1, sum = 1; i > 0; --i )\n sum = 1 + x * sum / i; " }, { "code": null, "e": 531, "s": 482, "text": "Following is implementation of the above idea. " }, { "code": null, "e": 535, "s": 531, "text": "C++" }, { "code": null, "e": 537, "s": 535, "text": "C" }, { "code": null, "e": 542, "s": 537, "text": "Java" }, { "code": null, "e": 550, "s": 542, "text": "Python3" }, { "code": null, "e": 553, "s": 550, "text": "C#" }, { "code": null, "e": 557, "s": 553, "text": "PHP" }, { "code": null, "e": 568, "s": 557, "text": "Javascript" }, { "code": "// C++ Efficient program to calculate// e raise to the power x#include <bits/stdc++.h>using namespace std; // Returns approximate value of e^x// using sum of first n terms of Taylor Seriesfloat exponential(int n, float x){ float sum = 1.0f; // initialize sum of series for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum;} // Driver codeint main(){ int n = 10; float x = 1.0f; cout << \"e^x = \" << fixed << setprecision(5) << exponential(n, x); return 0;} // This code is contributed by rathbhupendra", "e": 1113, "s": 568, "text": null }, { "code": "// C Efficient program to calculate// e raise to the power x#include <stdio.h> // Returns approximate value of e^x// using sum of first n terms of Taylor Seriesfloat exponential(int n, float x){ float sum = 1.0f; // initialize sum of series for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum;} // Driver program to test above functionint main(){ int n = 10; float x = 1.0f; printf(\"e^x = %f\", exponential(n, x)); return 0;}", "e": 1583, "s": 1113, "text": null }, { "code": "// Java efficient program to calculate// e raise to the power ximport java.io.*; class GFG{ // Function returns approximate value of e^x // using sum of first n terms of Taylor Series static float exponential(int n, float x) { // initialize sum of series float sum = 1; for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum; } // driver program public static void main (String[] args) { int n = 10; float x = 1; System.out.println(\"e^x = \"+exponential(n,x)); }} // Contributed by Pramod Kumar", "e": 2185, "s": 1583, "text": null }, { "code": "# Python program to calculate# e raise to the power x # Function to calculate value# using sum of first n terms of# Taylor Seriesdef exponential(n, x): # initialize sum of series sum = 1.0 for i in range(n, 0, -1): sum = 1 + x * sum / i print (\"e^x =\", sum) # Driver program to test above functionn = 10x = 1.0exponential(n, x) # This code is contributed by Danish Raza", "e": 2575, "s": 2185, "text": null }, { "code": "// C# efficient program to calculate// e raise to the power xusing System; class GFG{ // Function returns approximate value of e^x // using sum of first n terms of Taylor Series static float exponential(int n, float x) { // initialize sum of series float sum = 1; for (int i = n - 1; i > 0; --i ) sum = 1 + x * sum / i; return sum; } // driver program public static void Main () { int n = 10; float x = 1; Console.Write(\"e^x = \" + exponential(n, x)); }} // This code is contributed by nitin mittal.", "e": 3168, "s": 2575, "text": null }, { "code": "<?php// PHP Efficient program to calculate// e raise to the power x // Returns approximate value of e^x// using sum of first n terms// of Taylor Seriesfunction exponential($n, $x){ // initialize sum of series $sum = 1.0; for ($i = $n - 1; $i > 0; --$i ) $sum = 1 + $x * $sum / $i; return $sum;} // Driver Code$n = 10;$x = 1.0;echo(\"e^x = \" . exponential($n, $x)); // This code is contributed by Ajit.?>", "e": 3592, "s": 3168, "text": null }, { "code": "<script>// javascript efficient program to calculate// e raise to the power x // Function returns approximate value of e^x // using sum of first n terms of Taylor Series function exponential(n , x) { // initialize sum of series var sum = 1; for (i = n - 1; i > 0; --i) sum = 1 + x * sum / i; return sum; } // driver program var n = 10; var x = 1; document.write(\"e^x = \" + exponential(n, x).toFixed(6)); // This code contributed by Rajput-Ji </script>", "e": 4128, "s": 3592, "text": null }, { "code": null, "e": 4137, "s": 4128, "text": "Output: " }, { "code": null, "e": 4152, "s": 4137, "text": "e^x = 2.718282" }, { "code": null, "e": 4174, "s": 4152, "text": "Time Complexity: O(n)" }, { "code": null, "e": 4196, "s": 4174, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4391, "s": 4196, "text": "This article is compiled by Rahul and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 4404, "s": 4391, "text": "nitin mittal" }, { "code": null, "e": 4410, "s": 4404, "text": "jit_t" }, { "code": null, "e": 4423, "s": 4410, "text": "Kirti_Mangal" }, { "code": null, "e": 4437, "s": 4423, "text": "rathbhupendra" }, { "code": null, "e": 4447, "s": 4437, "text": "Rajput-Ji" }, { "code": null, "e": 4463, "s": 4447, "text": "subhammahato348" }, { "code": null, "e": 4476, "s": 4463, "text": "Mathematical" }, { "code": null, "e": 4489, "s": 4476, "text": "Mathematical" } ]
PHP | imagecreatetruecolor() Function
23 Aug, 2019 The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size. Syntax: resource imagecreatetruecolor( $width, $height ) Parameters: This function accepts two parameters as mentioned above and described below: $width: This parameter is used to set the width of image. $height: This parameter is used to set the height of image. Return Value: This function returns an image resource identifier on success, or False on errors. Below programs illustrate the imagecreatetruecolor() function in PHP: Program 1: <?php // Set the vertices of polygon$values = array( 150, 50, // Point 1 (x, y) 50, 250, // Point 2 (x, y) 250, 250 // Point 3 (x, y) ); // Create the size of image or blank image$image = imagecreatetruecolor(300, 300); // Set the background color of image$background_color = imagecolorallocate($image, 0, 153, 0); // Fill background with above selected colorimagefill($image, 0, 0, $background_color); // Allocate a color for the polygon$image_color = imagecolorallocate($image, 255, 255, 255); // Draw the polygonimagepolygon($image, $values, 3, $image_color); // Output the picture to the browserheader('Content-type: image/png'); imagepng($image);?> output: Program 2: <?php // Create the size of image or blank image.$image = imagecreatetruecolor(500, 300); // Display the height of image.echo imagesy($image); ?> output: 300 Related Articles: PHP | imagecolortransparent() Function PHP | imagepolygon() Function Reference: http://php.net/manual/en/function.imagecreatetruecolor.php Image-Processing PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2019" }, { "code": null, "e": 197, "s": 28, "text": "The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size." }, { "code": null, "e": 205, "s": 197, "text": "Syntax:" }, { "code": null, "e": 254, "s": 205, "text": "resource imagecreatetruecolor( $width, $height )" }, { "code": null, "e": 343, "s": 254, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 401, "s": 343, "text": "$width: This parameter is used to set the width of image." }, { "code": null, "e": 461, "s": 401, "text": "$height: This parameter is used to set the height of image." }, { "code": null, "e": 558, "s": 461, "text": "Return Value: This function returns an image resource identifier on success, or False on errors." }, { "code": null, "e": 628, "s": 558, "text": "Below programs illustrate the imagecreatetruecolor() function in PHP:" }, { "code": null, "e": 639, "s": 628, "text": "Program 1:" }, { "code": "<?php // Set the vertices of polygon$values = array( 150, 50, // Point 1 (x, y) 50, 250, // Point 2 (x, y) 250, 250 // Point 3 (x, y) ); // Create the size of image or blank image$image = imagecreatetruecolor(300, 300); // Set the background color of image$background_color = imagecolorallocate($image, 0, 153, 0); // Fill background with above selected colorimagefill($image, 0, 0, $background_color); // Allocate a color for the polygon$image_color = imagecolorallocate($image, 255, 255, 255); // Draw the polygonimagepolygon($image, $values, 3, $image_color); // Output the picture to the browserheader('Content-type: image/png'); imagepng($image);?>", "e": 1366, "s": 639, "text": null }, { "code": null, "e": 1374, "s": 1366, "text": "output:" }, { "code": null, "e": 1385, "s": 1374, "text": "Program 2:" }, { "code": "<?php // Create the size of image or blank image.$image = imagecreatetruecolor(500, 300); // Display the height of image.echo imagesy($image); ?>", "e": 1537, "s": 1385, "text": null }, { "code": null, "e": 1545, "s": 1537, "text": "output:" }, { "code": null, "e": 1549, "s": 1545, "text": "300" }, { "code": null, "e": 1567, "s": 1549, "text": "Related Articles:" }, { "code": null, "e": 1606, "s": 1567, "text": "PHP | imagecolortransparent() Function" }, { "code": null, "e": 1636, "s": 1606, "text": "PHP | imagepolygon() Function" }, { "code": null, "e": 1706, "s": 1636, "text": "Reference: http://php.net/manual/en/function.imagecreatetruecolor.php" }, { "code": null, "e": 1723, "s": 1706, "text": "Image-Processing" }, { "code": null, "e": 1736, "s": 1723, "text": "PHP-function" }, { "code": null, "e": 1740, "s": 1736, "text": "PHP" }, { "code": null, "e": 1757, "s": 1740, "text": "Web Technologies" }, { "code": null, "e": 1761, "s": 1757, "text": "PHP" }, { "code": null, "e": 1859, "s": 1761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1909, "s": 1859, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1949, "s": 1909, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2010, "s": 1949, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2060, "s": 2010, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2105, "s": 2060, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2167, "s": 2105, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2200, "s": 2167, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2261, "s": 2200, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2311, "s": 2261, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to verify enter number is phone number or not using regex in android?
This example demonstrates how to verify enter number is phone number or not, using regex in android. Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 - Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <EditText android:id = "@+id/enterNumber" android:layout_width = "match_parent" android:hint = "Enter phone number" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/text" android:textSize = "18sp" android:textAlignment = "center" android:text = "click" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken Edit text and text view. when the user clicks on text view, it will take data from edit text and valid the data. Step 3 - Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; TextView text; EditText enterNumber; String pattern = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"; Matcher m; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); text = findViewById(R.id.text); enterNumber = findViewById(R.id.enterNumber); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Pattern r = Pattern.compile(pattern); if (!enterNumber.getText().toString().isEmpty()) { m = r.matcher(enterNumber.getText().toString().trim()); } else { Toast.makeText(MainActivity.this, "Please enter mobile number ", Toast.LENGTH_LONG).show(); } if (m.find()) { Toast.makeText(MainActivity.this, "MATCH", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NO MATCH", Toast.LENGTH_LONG).show(); } } }); } } In the above code, we have taken regex expression to valid edit text data. use the following code to valid edit text data. String pattern = "^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$"; Matcher m; ..... Pattern r = Pattern.compile(pattern); if (!enterNumber.getText().toString().isEmpty()) { m = r.matcher(enterNumber.getText().toString().trim()); } else { Toast.makeText(MainActivity.this, "Please enter mobile number ", Toast.LENGTH_LONG).show(); } if (m.find()) { Toast.makeText(MainActivity.this, "MATCH", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NO MATCH", Toast.LENGTH_LONG).show(); } ......... Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen - In the above code, we have given the correct phone number format. it gives proper validation result as "Match". Now we are giving unknown format in edit text. it going the result as "Not match" as shown below - Click here to download the project code
[ { "code": null, "e": 1288, "s": 1187, "text": "This example demonstrates how to verify enter number is phone number or not, using regex in android." }, { "code": null, "e": 1417, "s": 1288, "text": "Step 1 - Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1482, "s": 1417, "text": "Step 2 - Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2304, "s": 1482, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/enterNumber\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter phone number\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:textAlignment = \"center\"\n android:text = \"click\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2450, "s": 2304, "text": "In the above code, we have taken Edit text and text view. when the user clicks on text view, it will take data from edit text and valid the data." }, { "code": null, "e": 2507, "s": 2450, "text": "Step 3 - Add the following code to src/MainActivity.java" }, { "code": null, "e": 4117, "s": 2507, "text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView text;\n EditText enterNumber;\n String pattern = \"^\\\\s*(?:\\\\+?(\\\\d{1,3}))?[-. (]*(\\\\d{3})[-. )]*(\\\\d{3})[-. ]*(\\\\d{4})(?: *x(\\\\d+))?\\\\s*$\";\n Matcher m;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n text = findViewById(R.id.text);\n enterNumber = findViewById(R.id.enterNumber);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Pattern r = Pattern.compile(pattern);\n if (!enterNumber.getText().toString().isEmpty()) {\n m = r.matcher(enterNumber.getText().toString().trim());\n } else {\n Toast.makeText(MainActivity.this, \"Please enter mobile number \", Toast.LENGTH_LONG).show();\n }\n if (m.find()) {\n Toast.makeText(MainActivity.this, \"MATCH\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NO MATCH\", Toast.LENGTH_LONG).show();\n }\n }\n });\n}\n}" }, { "code": null, "e": 4240, "s": 4117, "text": "In the above code, we have taken regex expression to valid edit text data. use the following code to valid edit text data." }, { "code": null, "e": 4805, "s": 4240, "text": "String pattern = \"^\\\\s*(?:\\\\+?(\\\\d{1,3}))?[-. (]*(\\\\d{3})[-. )]*(\\\\d{3})[-. ]*(\\\\d{4})(?: *x(\\\\d+))?\\\\s*$\";\nMatcher m;\n.....\nPattern r = Pattern.compile(pattern);\nif (!enterNumber.getText().toString().isEmpty()) {\n m = r.matcher(enterNumber.getText().toString().trim());\n} else {\n Toast.makeText(MainActivity.this, \"Please enter mobile number \", Toast.LENGTH_LONG).show();\n}\nif (m.find()) {\n Toast.makeText(MainActivity.this, \"MATCH\", Toast.LENGTH_LONG).show();\n} else {\n Toast.makeText(MainActivity.this, \"NO MATCH\", Toast.LENGTH_LONG).show();\n}\n........." }, { "code": null, "e": 5152, "s": 4805, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -" }, { "code": null, "e": 5363, "s": 5152, "text": "In the above code, we have given the correct phone number format. it gives proper validation result as \"Match\". Now we are giving unknown format in edit text. it going the result as \"Not match\" as shown below -" }, { "code": null, "e": 5403, "s": 5363, "text": "Click here to download the project code" } ]
C program to sort an array using pointers
25 May, 2022 Given an array of size n, the task is to sort this array using pointers in C. Examples: Input: n = 5, arr[] = {0, 23, 14, 12, 9} Output: {0, 9, 12, 14, 23} Input: n = 3, arr[] = {7, 0, 2} Output: {0, 2, 7} Approach: The array can be fetched with the help of pointers with the pointer variable pointing to the base address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format. Below is the implementation of the above approach: C #include <stdio.h> // Function to sort the numbers using pointersvoid sort(int n, int* ptr){ int i, j, t; // Sort the numbers using pointers for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (*(ptr + j) < *(ptr + i)) { t = *(ptr + i); *(ptr + i) = *(ptr + j); *(ptr + j) = t; } } } // print the numbers for (i = 0; i < n; i++) printf("%d ", *(ptr + i));} // Driver codeint main(){ int n = 5; int arr[] = { 0, 23, 14, 12, 9 }; sort(n, arr); return 0;} 0 9 12 14 23 Time Complexity: O(n2), where n represents the size of the given array.Auxiliary Space: O(1), no extra space is required, so it is a constant. singh008nranjan ManasChhabra2 samim2000 Arrays C-Pointers C Language Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C Memory Layout of C Programs
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 140, "s": 52, "text": "Given an array of size n, the task is to sort this array using pointers in C. Examples:" }, { "code": null, "e": 259, "s": 140, "text": "Input: n = 5, arr[] = {0, 23, 14, 12, 9}\nOutput: {0, 9, 12, 14, 23}\n\nInput: n = 3, arr[] = {7, 0, 2}\nOutput: {0, 2, 7}" }, { "code": null, "e": 516, "s": 259, "text": "Approach: The array can be fetched with the help of pointers with the pointer variable pointing to the base address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format. " }, { "code": null, "e": 569, "s": 516, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 571, "s": 569, "text": "C" }, { "code": "#include <stdio.h> // Function to sort the numbers using pointersvoid sort(int n, int* ptr){ int i, j, t; // Sort the numbers using pointers for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (*(ptr + j) < *(ptr + i)) { t = *(ptr + i); *(ptr + i) = *(ptr + j); *(ptr + j) = t; } } } // print the numbers for (i = 0; i < n; i++) printf(\"%d \", *(ptr + i));} // Driver codeint main(){ int n = 5; int arr[] = { 0, 23, 14, 12, 9 }; sort(n, arr); return 0;}", "e": 1156, "s": 571, "text": null }, { "code": null, "e": 1169, "s": 1156, "text": "0 9 12 14 23" }, { "code": null, "e": 1312, "s": 1169, "text": "Time Complexity: O(n2), where n represents the size of the given array.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 1328, "s": 1312, "text": "singh008nranjan" }, { "code": null, "e": 1342, "s": 1328, "text": "ManasChhabra2" }, { "code": null, "e": 1352, "s": 1342, "text": "samim2000" }, { "code": null, "e": 1359, "s": 1352, "text": "Arrays" }, { "code": null, "e": 1370, "s": 1359, "text": "C-Pointers" }, { "code": null, "e": 1381, "s": 1370, "text": "C Language" }, { "code": null, "e": 1388, "s": 1381, "text": "Arrays" }, { "code": null, "e": 1486, "s": 1388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1503, "s": 1486, "text": "Substring in C++" }, { "code": null, "e": 1525, "s": 1503, "text": "Function Pointer in C" }, { "code": null, "e": 1560, "s": 1525, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 1606, "s": 1560, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1651, "s": 1606, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1676, "s": 1651, "text": "std::string class in C++" }, { "code": null, "e": 1724, "s": 1676, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1752, "s": 1724, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 1779, "s": 1752, "text": "Enumeration (or enum) in C" } ]