title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Early Stopping in Practice: an example with Keras and TensorFlow 2.0 | by B. Chen | Towards Data Science
In this article, we will focus on adding and customizing Early Stopping in our machine learning model and look at an example of how we do this in practice with Keras and TensorFlow 2.0. In machine learning, early stopping is one of the most widely used regularization techniques to combat the overfitting issue. Early Stopping monitors the performance of the model for every epoch on a held-out validation set during the training, and terminate the training conditional on the validation performance. From Hands-on ML [1] Early Stopping is a very different way to regularize the machine learning model. The way it does is to stop training as soon as the validation error reaches a minimum. The figure below shows a model being trained. As the epochs go by, the algorithm leans and its error on the training set naturally goes down, and so does its error on the validation set. However, after a while, the validation error stops decreasing and actually starts to go back up. This indicates that the model has started to overfit the training data. With Early Stopping, you just stop training as soon as the validation error reaches the minimum. It is such a simple and efficient regularization technique that Geoffrey Hinton called it a “beautiful free lunch.” [1]. With Stochastic and Mini-batch Gradient Descent, the curves are not so smooth, and it may be hard to know whether you have reached the minimum or not. One solution is to stop only after the validation error has been above the minimum for some time (when you are confident that the model will not do any better), then roll back the model parameters to the point where the validation error was at a minimum. In the following article, we are going to add and customize Early Stopping in our machine learning model. We will be using the same dataset as we did in the model regularization and batch normalization. You can skip this chapter if you are already familiar with it. In order to run this tutorial, you need to install TensorFlow 2, numpy, pandas, sklean, matplotlib They can all be installed directly vis PyPI and I strongly recommend to create a new Virtual Environment. For a tutorial on creating a Python virtual environment Create Virtual Environment using “virtualenv” and add it to Jupyter Notebook Create Virtual Environment using “conda” and add it to Jupyter Notebook This is a step by step tutorial and all instructions are in this article. For source code, please check out my Github machine learning repo. This tutorial uses the Anderson Iris flower (iris) dataset for demonstration. The dataset contains a set of 150 records under five attributes: sepal length, sepal width, petal length, petal width, and class (known as target from sklearn datasets). First, let’s import the libraries and obtain iris dataset from scikit-learn library. You can also download it from the UCI Iris dataset. import tensorflow as tfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitiris = load_iris() For the purpose of exploring data, let’s load data into a DataFrame # Load data into a DataFramedf = pd.DataFrame(iris.data, columns=iris.feature_names)# Convert datatype to floatdf = df.astype(float)# append "target" and name it "label"df['label'] = iris.target# Use string label insteaddf['label'] = df.label.replace(dict(enumerate(iris.target_names))) And the df should look like below: We notice the label column is a categorical feature and will need to convert it to one-hot encoding. Otherwise, our machine learning algorithm won’t be able to directly take in that as input. # label -> one-hot encodinglabel = pd.get_dummies(df['label'], prefix='label')df = pd.concat([df, label], axis=1)# drop old labeldf.drop(['label'], axis=1, inplace=True) Now, the df should look like: Next, let’s create X and y. Keras and TensorFlow 2.0 only take in Numpy array as inputs, so we will have to convert DataFrame back to Numpy array. # Creating X and yX = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']]# Convert DataFrame into np arrayX = np.asarray(X)y = df[['label_setosa', 'label_versicolor', 'label_virginica']]# Convert DataFrame into np arrayy = np.asarray(y) Finally, let’s split the dataset into a training set (80%)and a test set (20%) using train_test_split() from sklearn library. X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20) Great! our data is ready for building a Machine Learning model. There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, let’s use the easiest way: Sequential Model with Sequential(). Let’s go ahead and create a function called create_model() to return a Sequential model. from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densedef create_model(): model = Sequential([ Dense(64, activation='relu', input_shape=(4,)), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(3, activation='softmax') ]) return model Our model has the following specifications: The first layer (also known as the input layer) has the input_shape to set the input size (4,) The input layer has 64 units, followed by 3 dense layers, each with 128 units. Then there are further 3 dense layers, each with 64 units. All these layers use the ReLU activation function. The output Dense layer has 3 units and the softmax activation function. In order to train a model, we first have to configure our model using compile() and pass the following arguments: Use Adam (adam) optimization algorithm as the optimizer Use categorical cross-entropy loss function (categorical_crossentropy) for our multiple-class classification problem For simplicity, use accuracy as our evaluation metrics to evaluate the model during training and testing. model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) After that, we can call model.fit() to fit our model to the training data. history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2) If all runs smoothly, we should get an output like below Train on 84 samples, validate on 28 samplesEpoch 1/20084/84 - 1s - loss: 1.0901 - accuracy: 0.3214 - val_loss: 1.0210 - val_accuracy: 0.7143Epoch 2/20084/84 - 0s - loss: 1.0163 - accuracy: 0.6905 - val_loss: 0.9427 - val_accuracy: 0.7143......Epoch 200/20084/84 - 0s - loss: 0.5269 - accuracy: 0.8690 - val_loss: 0.4781 - val_accuracy: 0.8929 Finally, let’s plot the loss vs. epochs graph on the training and validation sets. It is preferable to create a small function for plotting metrics. Let’s go ahead and create a function plot_metric(). %matplotlib inline%config InlineBackend.figure_format = 'svg'def plot_metric(history, metric): train_metrics = history.history[metric] val_metrics = history.history['val_'+metric] epochs = range(1, len(train_metrics) + 1) plt.plot(epochs, train_metrics) plt.plot(epochs, val_metrics) plt.title('Training and validation '+ metric) plt.xlabel("Epochs") plt.ylabel(metric) plt.legend(["train_"+metric, 'val_'+metric]) plt.show() By running plot_metric(history, 'loss') to get a picture of loss progress. From the above graph, we can see that the model has overfitted the training data, so it outperforms the validation set. The Keras module contains a built-in callback designed for Early Stopping [2]. First, let’s import EarlyStopping callback and create an early stopping object early_stopping . from tensorflow.keras.callbacks import EarlyStoppingearly_stopping = EarlyStopping() EarlyStopping() has a few options and by default: monitor='val_loss': to use validation loss as performance measure to terminate the training. patience=0: is the number of epochs with no improvement. The value 0 means the training is terminated as soon as the performance measure gets worse from one epoch to the next. Next, we just need to pass the callback object to model.fit() method. history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2, callbacks=[early_stopping]) You can see that early_stopping get passed in a list to the callbacks argument. It is a list because in practice we might be passing a number of callbacks for performing different tasks, for example debugging and learning rate scheduler. By executing the statement, you should get an output like below: Note: your output can be different due to the different weight initialization. The training gets terminated at Epoch 6 due to the increase of val_loss value and that is exactly the conditions monitor='val_loss' and patience=0. It’s often more convenient to look at a plot, let’s run plot_metric(history, 'loss') to get a clear picture. In the below graph, validation loss is shown in orange and it’s clear that validation error increases at Epoch 6. Apart from the options monitor and patience we mentioned early, the other 2 options min_delta and mode are likely to be used quite often. monitor='val_loss': to use validation loss as performance measure to terminate the training. patience=0: is the number of epochs with no improvement. The value 0 means the training is terminated as soon as the performance measure gets worse from one epoch to the next. min_delta: Minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than min_delta, will count as no improvement. mode='auto': Should be one of auto, min or max. In 'min' mode, training will stop when the quantity monitored has stopped decreasing; in 'max' mode it will stop when the quantity monitored has stopped increasing; in 'auto' mode, the direction is automatically inferred from the name of the monitored quantity. And here is an example of a customized early stopping: custom_early_stopping = EarlyStopping( monitor='val_accuracy', patience=8, min_delta=0.001, mode='max') monitor='val_accuracy' to use validation accuracy as performance measure to terminate the training. patience=8 means the training is terminated as soon as 8 epochs with no improvement. min_delta=0.001 means the validation accuracy has to improve by at least 0.001 for it to count as an improvement. mode='max' means it will stop when the quantity monitored has stopped increasing. Let’s go ahead and run it with the customized early stopping. history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2, callbacks=[custom_early_stopping]) This time, the training gets terminated at Epoch 9 as there are 8 epochs with no improvement on validation accuracy (It has to be ≥ 0.001 to count as an improvement). For a clear picture, let’s look at a plot representation of accuracy by running plot_metric(history, 'accuracy'). In the below graph, validation accuracy is shown in orange and it’s clear that validation accuracy hasn’t got any improvement. Thanks for reading. Please checkout the notebook on my Github for the source code. Stay tuned if you are interested in the practical aspect of machine learning. [1] Hands-on Machine Learning with scikit-learn, keras, and tensorflow: concepts, tools, and techniques to build intelligent system [2] Keras Official Documentation for Early Stopping
[ { "code": null, "e": 358, "s": 172, "text": "In this article, we will focus on adding and customizing Early Stopping in our machine learning model and look at an example of how we do this in practice with Keras and TensorFlow 2.0." }, { "code": null, "e": 484, "s": 358, "text": "In machine learning, early stopping is one of the most widely used regularization techniques to combat the overfitting issue." }, { "code": null, "e": 673, "s": 484, "text": "Early Stopping monitors the performance of the model for every epoch on a held-out validation set during the training, and terminate the training conditional on the validation performance." }, { "code": null, "e": 694, "s": 673, "text": "From Hands-on ML [1]" }, { "code": null, "e": 908, "s": 694, "text": "Early Stopping is a very different way to regularize the machine learning model. The way it does is to stop training as soon as the validation error reaches a minimum. The figure below shows a model being trained." }, { "code": null, "e": 1315, "s": 908, "text": "As the epochs go by, the algorithm leans and its error on the training set naturally goes down, and so does its error on the validation set. However, after a while, the validation error stops decreasing and actually starts to go back up. This indicates that the model has started to overfit the training data. With Early Stopping, you just stop training as soon as the validation error reaches the minimum." }, { "code": null, "e": 1436, "s": 1315, "text": "It is such a simple and efficient regularization technique that Geoffrey Hinton called it a “beautiful free lunch.” [1]." }, { "code": null, "e": 1842, "s": 1436, "text": "With Stochastic and Mini-batch Gradient Descent, the curves are not so smooth, and it may be hard to know whether you have reached the minimum or not. One solution is to stop only after the validation error has been above the minimum for some time (when you are confident that the model will not do any better), then roll back the model parameters to the point where the validation error was at a minimum." }, { "code": null, "e": 1948, "s": 1842, "text": "In the following article, we are going to add and customize Early Stopping in our machine learning model." }, { "code": null, "e": 2108, "s": 1948, "text": "We will be using the same dataset as we did in the model regularization and batch normalization. You can skip this chapter if you are already familiar with it." }, { "code": null, "e": 2159, "s": 2108, "text": "In order to run this tutorial, you need to install" }, { "code": null, "e": 2207, "s": 2159, "text": "TensorFlow 2, numpy, pandas, sklean, matplotlib" }, { "code": null, "e": 2369, "s": 2207, "text": "They can all be installed directly vis PyPI and I strongly recommend to create a new Virtual Environment. For a tutorial on creating a Python virtual environment" }, { "code": null, "e": 2446, "s": 2369, "text": "Create Virtual Environment using “virtualenv” and add it to Jupyter Notebook" }, { "code": null, "e": 2518, "s": 2446, "text": "Create Virtual Environment using “conda” and add it to Jupyter Notebook" }, { "code": null, "e": 2659, "s": 2518, "text": "This is a step by step tutorial and all instructions are in this article. For source code, please check out my Github machine learning repo." }, { "code": null, "e": 2907, "s": 2659, "text": "This tutorial uses the Anderson Iris flower (iris) dataset for demonstration. The dataset contains a set of 150 records under five attributes: sepal length, sepal width, petal length, petal width, and class (known as target from sklearn datasets)." }, { "code": null, "e": 3044, "s": 2907, "text": "First, let’s import the libraries and obtain iris dataset from scikit-learn library. You can also download it from the UCI Iris dataset." }, { "code": null, "e": 3244, "s": 3044, "text": "import tensorflow as tfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitiris = load_iris()" }, { "code": null, "e": 3312, "s": 3244, "text": "For the purpose of exploring data, let’s load data into a DataFrame" }, { "code": null, "e": 3599, "s": 3312, "text": "# Load data into a DataFramedf = pd.DataFrame(iris.data, columns=iris.feature_names)# Convert datatype to floatdf = df.astype(float)# append \"target\" and name it \"label\"df['label'] = iris.target# Use string label insteaddf['label'] = df.label.replace(dict(enumerate(iris.target_names)))" }, { "code": null, "e": 3634, "s": 3599, "text": "And the df should look like below:" }, { "code": null, "e": 3826, "s": 3634, "text": "We notice the label column is a categorical feature and will need to convert it to one-hot encoding. Otherwise, our machine learning algorithm won’t be able to directly take in that as input." }, { "code": null, "e": 3996, "s": 3826, "text": "# label -> one-hot encodinglabel = pd.get_dummies(df['label'], prefix='label')df = pd.concat([df, label], axis=1)# drop old labeldf.drop(['label'], axis=1, inplace=True)" }, { "code": null, "e": 4026, "s": 3996, "text": "Now, the df should look like:" }, { "code": null, "e": 4173, "s": 4026, "text": "Next, let’s create X and y. Keras and TensorFlow 2.0 only take in Numpy array as inputs, so we will have to convert DataFrame back to Numpy array." }, { "code": null, "e": 4445, "s": 4173, "text": "# Creating X and yX = df[['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']]# Convert DataFrame into np arrayX = np.asarray(X)y = df[['label_setosa', 'label_versicolor', 'label_virginica']]# Convert DataFrame into np arrayy = np.asarray(y)" }, { "code": null, "e": 4571, "s": 4445, "text": "Finally, let’s split the dataset into a training set (80%)and a test set (20%) using train_test_split() from sklearn library." }, { "code": null, "e": 4649, "s": 4571, "text": "X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20)" }, { "code": null, "e": 4713, "s": 4649, "text": "Great! our data is ready for building a Machine Learning model." }, { "code": null, "e": 4941, "s": 4713, "text": "There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, let’s use the easiest way: Sequential Model with Sequential()." }, { "code": null, "e": 5030, "s": 4941, "text": "Let’s go ahead and create a function called create_model() to return a Sequential model." }, { "code": null, "e": 5502, "s": 5030, "text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Densedef create_model(): model = Sequential([ Dense(64, activation='relu', input_shape=(4,)), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(128, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(64, activation='relu'), Dense(3, activation='softmax') ]) return model" }, { "code": null, "e": 5546, "s": 5502, "text": "Our model has the following specifications:" }, { "code": null, "e": 5641, "s": 5546, "text": "The first layer (also known as the input layer) has the input_shape to set the input size (4,)" }, { "code": null, "e": 5830, "s": 5641, "text": "The input layer has 64 units, followed by 3 dense layers, each with 128 units. Then there are further 3 dense layers, each with 64 units. All these layers use the ReLU activation function." }, { "code": null, "e": 5902, "s": 5830, "text": "The output Dense layer has 3 units and the softmax activation function." }, { "code": null, "e": 6016, "s": 5902, "text": "In order to train a model, we first have to configure our model using compile() and pass the following arguments:" }, { "code": null, "e": 6072, "s": 6016, "text": "Use Adam (adam) optimization algorithm as the optimizer" }, { "code": null, "e": 6189, "s": 6072, "text": "Use categorical cross-entropy loss function (categorical_crossentropy) for our multiple-class classification problem" }, { "code": null, "e": 6295, "s": 6189, "text": "For simplicity, use accuracy as our evaluation metrics to evaluate the model during training and testing." }, { "code": null, "e": 6394, "s": 6295, "text": "model.compile( optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 6469, "s": 6394, "text": "After that, we can call model.fit() to fit our model to the training data." }, { "code": null, "e": 6592, "s": 6469, "text": "history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2)" }, { "code": null, "e": 6649, "s": 6592, "text": "If all runs smoothly, we should get an output like below" }, { "code": null, "e": 6992, "s": 6649, "text": "Train on 84 samples, validate on 28 samplesEpoch 1/20084/84 - 1s - loss: 1.0901 - accuracy: 0.3214 - val_loss: 1.0210 - val_accuracy: 0.7143Epoch 2/20084/84 - 0s - loss: 1.0163 - accuracy: 0.6905 - val_loss: 0.9427 - val_accuracy: 0.7143......Epoch 200/20084/84 - 0s - loss: 0.5269 - accuracy: 0.8690 - val_loss: 0.4781 - val_accuracy: 0.8929" }, { "code": null, "e": 7075, "s": 6992, "text": "Finally, let’s plot the loss vs. epochs graph on the training and validation sets." }, { "code": null, "e": 7193, "s": 7075, "text": "It is preferable to create a small function for plotting metrics. Let’s go ahead and create a function plot_metric()." }, { "code": null, "e": 7649, "s": 7193, "text": "%matplotlib inline%config InlineBackend.figure_format = 'svg'def plot_metric(history, metric): train_metrics = history.history[metric] val_metrics = history.history['val_'+metric] epochs = range(1, len(train_metrics) + 1) plt.plot(epochs, train_metrics) plt.plot(epochs, val_metrics) plt.title('Training and validation '+ metric) plt.xlabel(\"Epochs\") plt.ylabel(metric) plt.legend([\"train_\"+metric, 'val_'+metric]) plt.show()" }, { "code": null, "e": 7724, "s": 7649, "text": "By running plot_metric(history, 'loss') to get a picture of loss progress." }, { "code": null, "e": 7844, "s": 7724, "text": "From the above graph, we can see that the model has overfitted the training data, so it outperforms the validation set." }, { "code": null, "e": 7923, "s": 7844, "text": "The Keras module contains a built-in callback designed for Early Stopping [2]." }, { "code": null, "e": 8019, "s": 7923, "text": "First, let’s import EarlyStopping callback and create an early stopping object early_stopping ." }, { "code": null, "e": 8104, "s": 8019, "text": "from tensorflow.keras.callbacks import EarlyStoppingearly_stopping = EarlyStopping()" }, { "code": null, "e": 8154, "s": 8104, "text": "EarlyStopping() has a few options and by default:" }, { "code": null, "e": 8247, "s": 8154, "text": "monitor='val_loss': to use validation loss as performance measure to terminate the training." }, { "code": null, "e": 8423, "s": 8247, "text": "patience=0: is the number of epochs with no improvement. The value 0 means the training is terminated as soon as the performance measure gets worse from one epoch to the next." }, { "code": null, "e": 8493, "s": 8423, "text": "Next, we just need to pass the callback object to model.fit() method." }, { "code": null, "e": 8647, "s": 8493, "text": "history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2, callbacks=[early_stopping])" }, { "code": null, "e": 8885, "s": 8647, "text": "You can see that early_stopping get passed in a list to the callbacks argument. It is a list because in practice we might be passing a number of callbacks for performing different tasks, for example debugging and learning rate scheduler." }, { "code": null, "e": 8950, "s": 8885, "text": "By executing the statement, you should get an output like below:" }, { "code": null, "e": 9029, "s": 8950, "text": "Note: your output can be different due to the different weight initialization." }, { "code": null, "e": 9177, "s": 9029, "text": "The training gets terminated at Epoch 6 due to the increase of val_loss value and that is exactly the conditions monitor='val_loss' and patience=0." }, { "code": null, "e": 9400, "s": 9177, "text": "It’s often more convenient to look at a plot, let’s run plot_metric(history, 'loss') to get a clear picture. In the below graph, validation loss is shown in orange and it’s clear that validation error increases at Epoch 6." }, { "code": null, "e": 9538, "s": 9400, "text": "Apart from the options monitor and patience we mentioned early, the other 2 options min_delta and mode are likely to be used quite often." }, { "code": null, "e": 9631, "s": 9538, "text": "monitor='val_loss': to use validation loss as performance measure to terminate the training." }, { "code": null, "e": 9807, "s": 9631, "text": "patience=0: is the number of epochs with no improvement. The value 0 means the training is terminated as soon as the performance measure gets worse from one epoch to the next." }, { "code": null, "e": 9967, "s": 9807, "text": "min_delta: Minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than min_delta, will count as no improvement." }, { "code": null, "e": 10277, "s": 9967, "text": "mode='auto': Should be one of auto, min or max. In 'min' mode, training will stop when the quantity monitored has stopped decreasing; in 'max' mode it will stop when the quantity monitored has stopped increasing; in 'auto' mode, the direction is automatically inferred from the name of the monitored quantity." }, { "code": null, "e": 10332, "s": 10277, "text": "And here is an example of a customized early stopping:" }, { "code": null, "e": 10451, "s": 10332, "text": "custom_early_stopping = EarlyStopping( monitor='val_accuracy', patience=8, min_delta=0.001, mode='max')" }, { "code": null, "e": 10832, "s": 10451, "text": "monitor='val_accuracy' to use validation accuracy as performance measure to terminate the training. patience=8 means the training is terminated as soon as 8 epochs with no improvement. min_delta=0.001 means the validation accuracy has to improve by at least 0.001 for it to count as an improvement. mode='max' means it will stop when the quantity monitored has stopped increasing." }, { "code": null, "e": 10894, "s": 10832, "text": "Let’s go ahead and run it with the customized early stopping." }, { "code": null, "e": 11055, "s": 10894, "text": "history = model.fit( X_train, y_train, epochs=200, validation_split=0.25, batch_size=40, verbose=2, callbacks=[custom_early_stopping])" }, { "code": null, "e": 11463, "s": 11055, "text": "This time, the training gets terminated at Epoch 9 as there are 8 epochs with no improvement on validation accuracy (It has to be ≥ 0.001 to count as an improvement). For a clear picture, let’s look at a plot representation of accuracy by running plot_metric(history, 'accuracy'). In the below graph, validation accuracy is shown in orange and it’s clear that validation accuracy hasn’t got any improvement." }, { "code": null, "e": 11483, "s": 11463, "text": "Thanks for reading." }, { "code": null, "e": 11546, "s": 11483, "text": "Please checkout the notebook on my Github for the source code." }, { "code": null, "e": 11624, "s": 11546, "text": "Stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 11756, "s": 11624, "text": "[1] Hands-on Machine Learning with scikit-learn, keras, and tensorflow: concepts, tools, and techniques to build intelligent system" } ]
Beginner Explanation for Data Transformation | by Cornellius Yudha Wijaya | Towards Data Science
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here. What is Data Transformation?— I am pretty sure anybody who is learning data and statistics would come across these terms at some point. Data transformation is a concept that refers to the mathematical function applied to each value in the dataset to replace the value into a new value. In a mathematical equation, we could express it in the image below. If I put it in a simpler explanation, data transformation is a process that changes your data into another data via a mathematical equation. Why do we need to do Data Transformation? Is there any benefit to transforming data? From a statistical point of view, the reasons are: Transforming data allowed you to fulfill certain statistical assumptions, e.g., Normality, Homogeneity, Linearity, etc. Data transformation scales the values from different columns to be comparable, e.g., Salary in USD (range from 100–10000) with Weight in Kilograms (range from 20–100). Data transformation is useful to gain new insight and clear noise in your data. However, utilizing the data transformation method required you to understand the transformation effect, implication, and conclusion based on the transformed data. In my opinion, you only do data transformation if it is necessary and you understand your transformation goal. What are the methods for data transformation? According to McCune and Grace (2002) in their Analysis of Ecological Communities Book, the methods are: Monotonic Transfromation Relativizations (Standardization) Probabilistic Transformation (Smoothing) If the terms above sound unfamiliar to you, it’s alright. Let’s explore all these methods deeper! One disclaimer I would make is that you need to be careful when doing Data Transformation because you would end up with a transformed data — which is not your original data anymore. Learn what is the purpose of the data transformation and report any data transformation you have done. What is Monotonic Transformation? It is a data transformation method that applies math function to each of the data values independent of the other data. The word monotonic came from the method procedure, which transforms the data values without changing their rank. In a simpler term, Monotonic transformation changed your data without rely on other data and did not change their rank within the column. An example of the renowned Monotonic Transformation function is Logarithmic Transformation or Log Transformation. Just like the name implies, Log Transformation change your data value into their logarithmic values by applying a log function to each data values. Many variables follow log-normal distributions, meaning that the values would follow a normal distribution after the log transformation. This is one of the benefits of Log Transformation — to follow the assumption of normality, or at least close to. In a mathematical term, Log Transformation is expressed in the equation below. Let’s try the log transformation method with sample data. I would use the data from the Kaggle regarding the Engineering Graduate Salary. First, read the data into the data frame. import numpy as npimport pandas as pdimport seaborn as snsdata = pd.read_csv('Engineering_graduate_salary.csv') There are 33 features in this dataset, but I would not use every available data. This data is to know what affects the salary, so let’s try to visualize the salary data distribution. sns.distplot(data['Salary']) As we can see in the image above, the salary feature is not normally distributed. Let’s apply the log transformation to transform the data into a normal distribution. #Salary Log Transformation with base 10data['log10_Salary'] = data['Salary'].apply(np.log10) With a single line, we have transformed the data into the log base 10 values. Let’s try to visualize it once more. sns.distplot(data['log10_Salary']) The salary data is now closer to the normal distribution. We could try to check the normality by using normality tests such as the Shapiro test, but I would not explain that concept in this article. Another purpose of the data transformation is to acquire a better insight from the data relationship. For example, I am only interested in the relationship between the college GPA and the Engineering graduate's salary. Let’s try to visualize it with the scatterplot. sns.scatterplot(x = 'Salary', y = 'collegeGPA', data = data) I am trying to visualize the relationship between Salary and the college GPA, and I ended up with a data cluster with not much insight. This is one of the moments where we could apply log transformation to rescale the data to get better clarity. sns.scatterplot(x = 'log10_Salary',y = 'collegeGPA', data = data) The Salary and college GPA relationship is much clearer right now, where there is not much relationship between the GPA and the Salary. Although, what we do right now is visualize the relationship between log value with unscaled features. Let’s try to transform the college GPA feature as well and visualize the relationship. data['log10_collegeGPA'] = data['collegeGPA'].apply(np.log10)sns.scatterplot(x = 'log10_Salary',y = 'log10_collegeGPA', data = data) The relationship is perfectly seen right now compared to when we visualized it without any data transformation. This is another benefit why you do a data transformation. It is beneficial, especially when you need to present it to the business user where you want to show the data relationship, but your data is clustered, so that it is hard to get any insight. There are many methods in the Monotonic Transformation. Still, I would not explain them in this article as I planned to make another article to outline the other Monotonic Transformation method. What is important is that you understand what Monotonic Transformation is. Relativizations or Standardization is a Data Transformation method where the column or row standard transforms the data values (e.g., Max, Sum, Mean). It is different from the Monotonic Transformation, where Standardization is not independent and relies on another statistic. You would often need Standardization when you occur attributes with a different unit, and your analysis needs the data to have a similar unit. The analysis example is clustering analysis or dimensionality reduction, where they rely on the data distance. The famous standardization method is Z-score standardization, where the data is transformed by the mean and standard deviation of the feature to scale. The transformed feature mean would ~0 and standard deviation ~1. After the Z-score standardization transformation, the transformed data itself would be called Z-score. In a mathematical notation, it is expressed in the equation below. where x = value in feature, μ = feature mean, and σ = feature standard deviation. One note to remember, even though Z-score standardization transformed your data to follow normal distribution standards, the feature distribution itself isn’t necessarily following the normal distribution. The point of Z-score standardization is to rescale the feature, after all. Let’s try the Z-score standardization with a dataset example. First, we need to import the package we want to use. #Import Z-Score Standard Scaler from the Sklearn packagefrom sklearn.preprocessing import StandardScalerscaler = StandardScaler() Let’s say I want to rescale the Salary data from our previous example. Here is our original data and statistic. data['Salary'].head() data['Salary'].agg(['mean', 'std']) Our data unit is in ten-thousands with the Salary mean shown in the image above. Then, we transformed the data into Z-score using the scaler we import previously but first, we need to fit the scaler (this is the process to acquire the mean and standard deviation of the feature). scaler.fit(np.array(data['Salary']).reshape(-1, 1)) If you want to double-check whether our scaler obtained the correct mean and standard deviation, we could access the value with the code below. print('Salary Mean', scaler.mean_)print('Salary STD', np.sqrt(scaler.var_)) The result is slightly different but almost negligible. Let’s transform our Salary data into Z-score values. data['Z_Salary'] = scaler.transform(np.array(data['Salary']).reshape(-1, 1))data[['Salary', 'Z_Salary']].head() We can see the difference now between the original data and the transformed data. The negative value Z-score is when your data is less than the mean and vice versa. Let’s examine the transformed data statistic. data['Z_Salary'].agg(['mean', 'std']) As you can see, the transformed data mean is close to 0, and the std is close to 1. Every feature that scaled using Z-Score Standardization would follow the same standard. There is another benefit specific to the Z-Score Standardization, and that is an Outlier Detection. I would not explain in detail, but basically, the outlier detection concept is related to the empirical rule. Any Z-score that is more than 3 or less than 3 is considered an outlier. Like Monotonic Transformation, Relativizations or Standardization have many methods within, but it would be another article to talk more about it. Probabilistic Transformation or Smoothing is a Data Transformation process to eliminate any noises in the data to enhance the strongest pattern within the data. The transformation is particularly effective on heterogeneous or noisy data. The smoothing process allowed you to see data patterns that previously were unseen. Although you need to be careful when interpreting the result from the smoothing process — it could show you a trend looks reliable even from random data. The common Smoothing technique used is the Kernel-Density Estimation (KDE) smoothing. This technique basically smoothing the data by estimate the data probabilistic function of the population random variable based on the finite data sample. Let’s try to smooth the data sample to obtain the data pattern. For example, I want to see the distribution of the computer programming data. sns.distplot(data['ComputerProgramming'], kde = False) The binning data pattern is seen there, but we might want to eliminate any noise that might distract us from the real pattern. Let’s use KDE Smoothing to acquire that pattern. sns.distplot(data['ComputerProgramming'], hist = False) With the smoothing technique, we transformed the data into density values using the probabilistic function estimation of the data. As we could see, there are two peaks within our data — one in the 0 and one near the ~500 with the highest peak in the latter. This pattern is only seen if we are smoothing the data. You might ask, the smoothing pattern seems to show a different pattern from the binning pattern. Remember the smoothing purpose? It is to eliminate noises in data and to enhance the strongest pattern. Moreover, the KDE estimates the probabilistic function in the population based on the sample data — which means the smoothing pattern is the estimation of what would happen in the population. There are still many Probabilistic Transformation or Smoothing methods you could learn, but I would leave it for another time. The important point of Smoothing is to transform your data to eliminate any noises and enhance the pattern. Data Transformation is a technique that Data scientists should know because of their benefit. According to McCune and Grace (2002) in their Analysis of Ecological Communities Book, there are 3 methods for Data Transformation. They are: Monotonic TransfromationRelativizations (Standardization)Probabilistic Transformation (Smoothing) Monotonic Transfromation Relativizations (Standardization) Probabilistic Transformation (Smoothing) I hope it helps! Visit me on my LinkedIn or Twitter. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 342, "s": 172, "text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here." }, { "code": null, "e": 696, "s": 342, "text": "What is Data Transformation?— I am pretty sure anybody who is learning data and statistics would come across these terms at some point. Data transformation is a concept that refers to the mathematical function applied to each value in the dataset to replace the value into a new value. In a mathematical equation, we could express it in the image below." }, { "code": null, "e": 837, "s": 696, "text": "If I put it in a simpler explanation, data transformation is a process that changes your data into another data via a mathematical equation." }, { "code": null, "e": 973, "s": 837, "text": "Why do we need to do Data Transformation? Is there any benefit to transforming data? From a statistical point of view, the reasons are:" }, { "code": null, "e": 1093, "s": 973, "text": "Transforming data allowed you to fulfill certain statistical assumptions, e.g., Normality, Homogeneity, Linearity, etc." }, { "code": null, "e": 1261, "s": 1093, "text": "Data transformation scales the values from different columns to be comparable, e.g., Salary in USD (range from 100–10000) with Weight in Kilograms (range from 20–100)." }, { "code": null, "e": 1615, "s": 1261, "text": "Data transformation is useful to gain new insight and clear noise in your data. However, utilizing the data transformation method required you to understand the transformation effect, implication, and conclusion based on the transformed data. In my opinion, you only do data transformation if it is necessary and you understand your transformation goal." }, { "code": null, "e": 1765, "s": 1615, "text": "What are the methods for data transformation? According to McCune and Grace (2002) in their Analysis of Ecological Communities Book, the methods are:" }, { "code": null, "e": 1790, "s": 1765, "text": "Monotonic Transfromation" }, { "code": null, "e": 1824, "s": 1790, "text": "Relativizations (Standardization)" }, { "code": null, "e": 1865, "s": 1824, "text": "Probabilistic Transformation (Smoothing)" }, { "code": null, "e": 1963, "s": 1865, "text": "If the terms above sound unfamiliar to you, it’s alright. Let’s explore all these methods deeper!" }, { "code": null, "e": 2248, "s": 1963, "text": "One disclaimer I would make is that you need to be careful when doing Data Transformation because you would end up with a transformed data — which is not your original data anymore. Learn what is the purpose of the data transformation and report any data transformation you have done." }, { "code": null, "e": 2653, "s": 2248, "text": "What is Monotonic Transformation? It is a data transformation method that applies math function to each of the data values independent of the other data. The word monotonic came from the method procedure, which transforms the data values without changing their rank. In a simpler term, Monotonic transformation changed your data without rely on other data and did not change their rank within the column." }, { "code": null, "e": 3165, "s": 2653, "text": "An example of the renowned Monotonic Transformation function is Logarithmic Transformation or Log Transformation. Just like the name implies, Log Transformation change your data value into their logarithmic values by applying a log function to each data values. Many variables follow log-normal distributions, meaning that the values would follow a normal distribution after the log transformation. This is one of the benefits of Log Transformation — to follow the assumption of normality, or at least close to." }, { "code": null, "e": 3244, "s": 3165, "text": "In a mathematical term, Log Transformation is expressed in the equation below." }, { "code": null, "e": 3424, "s": 3244, "text": "Let’s try the log transformation method with sample data. I would use the data from the Kaggle regarding the Engineering Graduate Salary. First, read the data into the data frame." }, { "code": null, "e": 3536, "s": 3424, "text": "import numpy as npimport pandas as pdimport seaborn as snsdata = pd.read_csv('Engineering_graduate_salary.csv')" }, { "code": null, "e": 3719, "s": 3536, "text": "There are 33 features in this dataset, but I would not use every available data. This data is to know what affects the salary, so let’s try to visualize the salary data distribution." }, { "code": null, "e": 3748, "s": 3719, "text": "sns.distplot(data['Salary'])" }, { "code": null, "e": 3915, "s": 3748, "text": "As we can see in the image above, the salary feature is not normally distributed. Let’s apply the log transformation to transform the data into a normal distribution." }, { "code": null, "e": 4008, "s": 3915, "text": "#Salary Log Transformation with base 10data['log10_Salary'] = data['Salary'].apply(np.log10)" }, { "code": null, "e": 4123, "s": 4008, "text": "With a single line, we have transformed the data into the log base 10 values. Let’s try to visualize it once more." }, { "code": null, "e": 4158, "s": 4123, "text": "sns.distplot(data['log10_Salary'])" }, { "code": null, "e": 4357, "s": 4158, "text": "The salary data is now closer to the normal distribution. We could try to check the normality by using normality tests such as the Shapiro test, but I would not explain that concept in this article." }, { "code": null, "e": 4624, "s": 4357, "text": "Another purpose of the data transformation is to acquire a better insight from the data relationship. For example, I am only interested in the relationship between the college GPA and the Engineering graduate's salary. Let’s try to visualize it with the scatterplot." }, { "code": null, "e": 4685, "s": 4624, "text": "sns.scatterplot(x = 'Salary', y = 'collegeGPA', data = data)" }, { "code": null, "e": 4931, "s": 4685, "text": "I am trying to visualize the relationship between Salary and the college GPA, and I ended up with a data cluster with not much insight. This is one of the moments where we could apply log transformation to rescale the data to get better clarity." }, { "code": null, "e": 4997, "s": 4931, "text": "sns.scatterplot(x = 'log10_Salary',y = 'collegeGPA', data = data)" }, { "code": null, "e": 5323, "s": 4997, "text": "The Salary and college GPA relationship is much clearer right now, where there is not much relationship between the GPA and the Salary. Although, what we do right now is visualize the relationship between log value with unscaled features. Let’s try to transform the college GPA feature as well and visualize the relationship." }, { "code": null, "e": 5456, "s": 5323, "text": "data['log10_collegeGPA'] = data['collegeGPA'].apply(np.log10)sns.scatterplot(x = 'log10_Salary',y = 'log10_collegeGPA', data = data)" }, { "code": null, "e": 5626, "s": 5456, "text": "The relationship is perfectly seen right now compared to when we visualized it without any data transformation. This is another benefit why you do a data transformation." }, { "code": null, "e": 5817, "s": 5626, "text": "It is beneficial, especially when you need to present it to the business user where you want to show the data relationship, but your data is clustered, so that it is hard to get any insight." }, { "code": null, "e": 6087, "s": 5817, "text": "There are many methods in the Monotonic Transformation. Still, I would not explain them in this article as I planned to make another article to outline the other Monotonic Transformation method. What is important is that you understand what Monotonic Transformation is." }, { "code": null, "e": 6363, "s": 6087, "text": "Relativizations or Standardization is a Data Transformation method where the column or row standard transforms the data values (e.g., Max, Sum, Mean). It is different from the Monotonic Transformation, where Standardization is not independent and relies on another statistic." }, { "code": null, "e": 6617, "s": 6363, "text": "You would often need Standardization when you occur attributes with a different unit, and your analysis needs the data to have a similar unit. The analysis example is clustering analysis or dimensionality reduction, where they rely on the data distance." }, { "code": null, "e": 7004, "s": 6617, "text": "The famous standardization method is Z-score standardization, where the data is transformed by the mean and standard deviation of the feature to scale. The transformed feature mean would ~0 and standard deviation ~1. After the Z-score standardization transformation, the transformed data itself would be called Z-score. In a mathematical notation, it is expressed in the equation below." }, { "code": null, "e": 7086, "s": 7004, "text": "where x = value in feature, μ = feature mean, and σ = feature standard deviation." }, { "code": null, "e": 7367, "s": 7086, "text": "One note to remember, even though Z-score standardization transformed your data to follow normal distribution standards, the feature distribution itself isn’t necessarily following the normal distribution. The point of Z-score standardization is to rescale the feature, after all." }, { "code": null, "e": 7482, "s": 7367, "text": "Let’s try the Z-score standardization with a dataset example. First, we need to import the package we want to use." }, { "code": null, "e": 7612, "s": 7482, "text": "#Import Z-Score Standard Scaler from the Sklearn packagefrom sklearn.preprocessing import StandardScalerscaler = StandardScaler()" }, { "code": null, "e": 7724, "s": 7612, "text": "Let’s say I want to rescale the Salary data from our previous example. Here is our original data and statistic." }, { "code": null, "e": 7746, "s": 7724, "text": "data['Salary'].head()" }, { "code": null, "e": 7782, "s": 7746, "text": "data['Salary'].agg(['mean', 'std'])" }, { "code": null, "e": 8062, "s": 7782, "text": "Our data unit is in ten-thousands with the Salary mean shown in the image above. Then, we transformed the data into Z-score using the scaler we import previously but first, we need to fit the scaler (this is the process to acquire the mean and standard deviation of the feature)." }, { "code": null, "e": 8114, "s": 8062, "text": "scaler.fit(np.array(data['Salary']).reshape(-1, 1))" }, { "code": null, "e": 8258, "s": 8114, "text": "If you want to double-check whether our scaler obtained the correct mean and standard deviation, we could access the value with the code below." }, { "code": null, "e": 8334, "s": 8258, "text": "print('Salary Mean', scaler.mean_)print('Salary STD', np.sqrt(scaler.var_))" }, { "code": null, "e": 8443, "s": 8334, "text": "The result is slightly different but almost negligible. Let’s transform our Salary data into Z-score values." }, { "code": null, "e": 8555, "s": 8443, "text": "data['Z_Salary'] = scaler.transform(np.array(data['Salary']).reshape(-1, 1))data[['Salary', 'Z_Salary']].head()" }, { "code": null, "e": 8766, "s": 8555, "text": "We can see the difference now between the original data and the transformed data. The negative value Z-score is when your data is less than the mean and vice versa. Let’s examine the transformed data statistic." }, { "code": null, "e": 8804, "s": 8766, "text": "data['Z_Salary'].agg(['mean', 'std'])" }, { "code": null, "e": 8976, "s": 8804, "text": "As you can see, the transformed data mean is close to 0, and the std is close to 1. Every feature that scaled using Z-Score Standardization would follow the same standard." }, { "code": null, "e": 9259, "s": 8976, "text": "There is another benefit specific to the Z-Score Standardization, and that is an Outlier Detection. I would not explain in detail, but basically, the outlier detection concept is related to the empirical rule. Any Z-score that is more than 3 or less than 3 is considered an outlier." }, { "code": null, "e": 9406, "s": 9259, "text": "Like Monotonic Transformation, Relativizations or Standardization have many methods within, but it would be another article to talk more about it." }, { "code": null, "e": 9567, "s": 9406, "text": "Probabilistic Transformation or Smoothing is a Data Transformation process to eliminate any noises in the data to enhance the strongest pattern within the data." }, { "code": null, "e": 9882, "s": 9567, "text": "The transformation is particularly effective on heterogeneous or noisy data. The smoothing process allowed you to see data patterns that previously were unseen. Although you need to be careful when interpreting the result from the smoothing process — it could show you a trend looks reliable even from random data." }, { "code": null, "e": 10123, "s": 9882, "text": "The common Smoothing technique used is the Kernel-Density Estimation (KDE) smoothing. This technique basically smoothing the data by estimate the data probabilistic function of the population random variable based on the finite data sample." }, { "code": null, "e": 10265, "s": 10123, "text": "Let’s try to smooth the data sample to obtain the data pattern. For example, I want to see the distribution of the computer programming data." }, { "code": null, "e": 10320, "s": 10265, "text": "sns.distplot(data['ComputerProgramming'], kde = False)" }, { "code": null, "e": 10496, "s": 10320, "text": "The binning data pattern is seen there, but we might want to eliminate any noise that might distract us from the real pattern. Let’s use KDE Smoothing to acquire that pattern." }, { "code": null, "e": 10552, "s": 10496, "text": "sns.distplot(data['ComputerProgramming'], hist = False)" }, { "code": null, "e": 10810, "s": 10552, "text": "With the smoothing technique, we transformed the data into density values using the probabilistic function estimation of the data. As we could see, there are two peaks within our data — one in the 0 and one near the ~500 with the highest peak in the latter." }, { "code": null, "e": 11259, "s": 10810, "text": "This pattern is only seen if we are smoothing the data. You might ask, the smoothing pattern seems to show a different pattern from the binning pattern. Remember the smoothing purpose? It is to eliminate noises in data and to enhance the strongest pattern. Moreover, the KDE estimates the probabilistic function in the population based on the sample data — which means the smoothing pattern is the estimation of what would happen in the population." }, { "code": null, "e": 11494, "s": 11259, "text": "There are still many Probabilistic Transformation or Smoothing methods you could learn, but I would leave it for another time. The important point of Smoothing is to transform your data to eliminate any noises and enhance the pattern." }, { "code": null, "e": 11730, "s": 11494, "text": "Data Transformation is a technique that Data scientists should know because of their benefit. According to McCune and Grace (2002) in their Analysis of Ecological Communities Book, there are 3 methods for Data Transformation. They are:" }, { "code": null, "e": 11828, "s": 11730, "text": "Monotonic TransfromationRelativizations (Standardization)Probabilistic Transformation (Smoothing)" }, { "code": null, "e": 11853, "s": 11828, "text": "Monotonic Transfromation" }, { "code": null, "e": 11887, "s": 11853, "text": "Relativizations (Standardization)" }, { "code": null, "e": 11928, "s": 11887, "text": "Probabilistic Transformation (Smoothing)" }, { "code": null, "e": 11945, "s": 11928, "text": "I hope it helps!" }, { "code": null, "e": 11981, "s": 11945, "text": "Visit me on my LinkedIn or Twitter." } ]
Count the number of ways to divide N in k groups incrementally - GeeksforGeeks
26 Nov, 2021 Given two integers N and K, the task is to count the number of ways to divide N into K groups of positive integers such that their sum is N and the number of elements in groups follows a non-decreasing order (i.e group[i] <= group[i+1]).Examples: Input: N = 8, K = 4 Output: 5 Explanation: Their are 5 groups such that their sum is 8 and the number of positive integers in each group is 4. [1, 1, 1, 5], [1, 1, 2, 4], [1, 1, 3, 3], [1, 2, 2, 3], [2, 2, 2, 2]Input: N = 24, K = 5 Output: 164 Explanation: There are 164 such groups such that their sum is 24 and number of positive integers in each group is 5 Different Approaches:1. Naive Approach (Time: O(NK), Space: O(N))2. Memoization (Time: O((N3*K), Space: O(N2*K))3. Bottom-Up Dynamic Programming (Time: O(N*K), Space: O(N*K)) Naive Approach: We can solve this problem using recursion. At each step of recursion put all the values greater than equal to the previously computed value.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsint calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;} // Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.util.*;class GFG{ // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codepublic static void main(String[] args){ int N = 8; int K = 4; System.out.print(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji # Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # Function to count the number# of ways to divide the number N# in groups such that each group# has K number of elementsdef calculate(pos, prev, left, k): # Base Case if (pos == k): if (left == 0): return 1; else: return 0; # If N is divides completely # into less than k groups if (left == 0): return 0; answer = 0; # Put all possible values # greater equal to prev for i in range(prev, left + 1): answer += calculate(pos + 1, i, left - i, k); return answer; # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k): return calculate(0, 1, n, k); # Driver Codeif __name__ == '__main__': N = 8; K = 4; print(countWaystoDivide(N, K)); # This code is contributed by 29AjayKumar // C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System; class GFG{ // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codepublic static void Main(String[] args){ int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsfunction calculate(pos, prev, left, k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; let answer = 0; // put all possible values // greater equal to prev for (let i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k){ return calculate(0, 1, n, k);} // Driver Code let N = 8; let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by Mayank Tyagi </script> 5 Time complexity: O(NK)Auxiliary Space: O(N).Memoization Approach: In the previous approach we can see that we are solving the subproblems repeatedly, i.e. it follows the property of Overlapping Subproblems. So we can memoize the same using the DP table.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // DP Tableint dp[100][100][100]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsint calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsint countWaystoDivide(int n, int k){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return calculate(0, 1, n, k);} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;} // Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.util.*;class GFG{ // DP Tablestatic int [][][]dp = new int[100][100][100]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsstatic int countWaystoDivide(int n, int k){ // Initialize DP Table as -1 for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { for (int l = 0; l < 100; l++) dp[i][j][l] = -1; } } return calculate(0, 1, n, k);} // Driver Codepublic static void main(String[] args){ int N = 8; int K = 4; System.out.print(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji # Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # DP Tabledp = [[[0 for i in range(50)] for j in range(50)] for j in range(50)] # Function to count the number# of ways to divide the number N# in groups such that each group# has K number of elementsdef calculate(pos, prev, left, k): # Base Case if (pos == k): if (left == 0): return 1; else: return 0; # if N is divides completely # into less than k groups if (left == 0): return 0; # If the subproblem has been # solved, use the value if (dp[pos][prev][left] != -1): return dp[pos][prev][left]; answer = 0; # put all possible values # greater equal to prev for i in range(prev,left+1): answer += calculate(pos + 1, i, left - i, k); dp[pos][prev][left] = answer; return dp[pos][prev][left]; # Function to count the number of# ways to divide the number N in groupsdef countWaystoDivide(n, k): # Initialize DP Table as -1 for i in range(50): for j in range(50): for l in range(50): dp[i][j][l] = -1; return calculate(0, 1, n, k); # Driver Codeif __name__ == '__main__': N = 8; K = 4; print(countWaystoDivide(N, K)); # This code is contributed by Rajput-Ji // C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System;class GFG{ // DP Tablestatic int [,,]dp = new int[50, 50, 50]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos, prev, left] != -1) return dp[pos, prev, left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos, prev, left] = answer;} // Function to count the number of// ways to divide the number N in groupsstatic int countWaystoDivide(int n, int k){ // Initialize DP Table as -1 for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { for (int l = 0; l < 50; l++) dp[i, j, l] = -1; } } return calculate(0, 1, n, k);} // Driver Codepublic static void Main(String[] args){ int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K));}} // This code is contributed by gauravrajput1 <script> // JavaScript implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements // DP Tablelet dp = new Array(500);for(let i=0;i<500;i++){ dp[i]=new Array(500); for(let j=0;j<500;j++) { dp[i][j]=new Array(500); for(let k=0;k<500;k++) dp[i][j][k]=0; }} // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsfunction calculate(pos,prev,left,k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; let answer = 0; // put all possible values // greater equal to prev for (let i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsfunction countWaystoDivide(n,k){ // Initialize DP Table as -1 for (let i = 0; i < 500; i++) { for (let j = 0; j < 500; j++) { for (let l = 0; l < 500; l++) dp[i][j][l] = -1; } } return calculate(0, 1, n, k);} // Driver Codelet N = 8;let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by unknown2108 </script> Output: 5 Time complexity: O(N^3 * K) Auxiliary Space: O(N^2 * K). Bottom-Up DP: We are asked to find CountWaystoDivide(n,k) So the recurrence approach and explanation of DP is: CountWaystoDivide( n , k ) = CountWaystoDivide( n-k , k ) + CountWaystoDivide( n-1 , k-1 ) Explanation:Divide CountWaystoDivide( n , k ) into two parts where If first element is 1 then the rest form a total of n-1 divide into k-1 so CountWaystoDivide( n-1 , k-1 )If first element is greater than 1 then, we can subtract 1 from every element and get a valid partition of n-k into k parts, hence CountWaystoDivide( n-1 , k-1 ). If first element is 1 then the rest form a total of n-1 divide into k-1 so CountWaystoDivide( n-1 , k-1 ) If first element is greater than 1 then, we can subtract 1 from every element and get a valid partition of n-k into k parts, hence CountWaystoDivide( n-1 , k-1 ). Mathematical Explanation of DP: As each group must have at least one person, so, give each group one person, then we are left with n-k persons, which can we divided into 1,2,3..or k groups. Thus our dp will be: dp[n][k] = dp[n-k][1] + dp[n-k][2] + dp[n-k][3] + .... + dp[n-k][k].At first look, the previous might give O(N3) vibes, but with a little manipulation we can optimize it: dp[n][k] = dp[(n-1)-(k-1)][1] + dp[(n-1)-(k-1)][2] + ... + dp[(n-1)-(k-1)][k-1] + dp[(n-1)-(k-1)][k]From the recurrence, we can write:dp[n][k] = dp[n-1][k-1] + dp[n-k][k] As each group must have at least one person, so, give each group one person, then we are left with n-k persons, which can we divided into 1,2,3..or k groups. Thus our dp will be: dp[n][k] = dp[n-k][1] + dp[n-k][2] + dp[n-k][3] + .... + dp[n-k][k]. At first look, the previous might give O(N3) vibes, but with a little manipulation we can optimize it: dp[n][k] = dp[(n-1)-(k-1)][1] + dp[(n-1)-(k-1)][2] + ... + dp[(n-1)-(k-1)][k-1] + dp[(n-1)-(k-1)][k]From the recurrence, we can write:dp[n][k] = dp[n-1][k-1] + dp[n-k][k] Steps to solve the problem using DP: Initialize a 2-D array dp[][] of size n+1, k+1 where dp[i][j] will store the optimal solution to divide n into k groups. For each value from i=0 to n, dp[n][1] will be 1 since total ways to divide n into 1 is 1. also dp[0][0] will be 1. DP states are updated as follows: If i>=j then dp[i][j] = dp[i-1][j-1] + dp[i-j][j] otherwise i-j<0 and dp[i-j][j] become zero so dp[i][j] = dp[i-1][j-1] C++ Java Python3 C# Javascript // C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // Function to count the number of// ways to divide the number N in groupsint countWaystoDivide(int n, int k){ if (n < k) return 0; // When n is less than k, No way to divide // into groups vector<vector<int> > dp(n + 1, vector<int>(k + 1)); for (int i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;} // Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.io.*; class GFG { static int countWaystoDivide(int n, int k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups int [][]dp = new int[n+1][k+1]; for (int i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups } // Driver code public static void main (String[] args) { int N = 8; int K = 4; System.out.println(countWaystoDivide(N, K)); }} // This code is contributed by rohitsingh07052. # Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # DP Table# Function to count the number of# ways to divide the number N in groups def countWaystoDivide(n, k): if(n < k): return 0 dp = [[0 for i in range(k+1)] for i in range(n+1)] for i in range(1, n+1): dp[i][1] = 1 dp[0][0] = 1 for i in range(1, n+1): for j in range(2, k+1): if(i >= j): dp[i][j] = dp[i-1][j-1] + dp[i-j][j] else: dp[i][j] = dp[i-1][j-1] return dp[n][k] # Driver Codeif __name__ == '__main__': N = 8 K = 4 print(countWaystoDivide(N, K)) # This code is contributed by Rajput-Ji // C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System;using System.Collections.Generic;class GFG { static int countWaystoDivide(int n, int k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups int[,] dp = new int[n + 1, k + 1]; for (int i = 1; i <= n; i++) dp[i, 1] = 1; // exact one way to divide n to 1 group dp[0, 0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i,j] = dp[i - j,j] + dp[i - 1,j - 1]; else dp[i,j] = dp[i - 1, j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n,k]; // returning number of ways to divide N // in k groups } static void Main() { int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K)); }} // This code is contributed by rameshtravel07. <script> // Javascript implementation to count the // number of ways to divide N in // groups such that each group // has K number of elements // Function to count the number of // ways to divide the number N in groups function countWaystoDivide(n, k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups let dp = new Array(n + 1); for(let i = 0; i < n + 1; i++) { dp[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { dp[i][j] = 0; } } for (let i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (let i = 1; i <= n; i++) { for (let j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups } let N = 8; let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by mukesh07.</script> 5 Time complexity: O(N * K)Auxiliary Space: O(N * K) king_tsar Rajput-Ji GauravRajput1 29AjayKumar mayanktyagi1709 TarunSingh2 unknown2108 saurabh1990aror pankajsharmagfg kapilag akhil14shukla sweetyty prachisoda1234 mukesh07 rohitsingh07052 rameshtravel07 ashutoshsinghgeeksforgeeks Algorithms Competitive Programming Dynamic Programming Mathematical Recursion Dynamic Programming Mathematical Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Recursive Practice Problems with Solutions Quick Sort vs Merge Sort Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 10 Algorithms and Data Structures for Competitive Programming Bits manipulation (Important tactics)
[ { "code": null, "e": 24760, "s": 24732, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25009, "s": 24760, "text": "Given two integers N and K, the task is to count the number of ways to divide N into K groups of positive integers such that their sum is N and the number of elements in groups follows a non-decreasing order (i.e group[i] <= group[i+1]).Examples: " }, { "code": null, "e": 25369, "s": 25009, "text": "Input: N = 8, K = 4 Output: 5 Explanation: Their are 5 groups such that their sum is 8 and the number of positive integers in each group is 4. [1, 1, 1, 5], [1, 1, 2, 4], [1, 1, 3, 3], [1, 2, 2, 3], [2, 2, 2, 2]Input: N = 24, K = 5 Output: 164 Explanation: There are 164 such groups such that their sum is 24 and number of positive integers in each group is 5" }, { "code": null, "e": 25545, "s": 25369, "text": "Different Approaches:1. Naive Approach (Time: O(NK), Space: O(N))2. Memoization (Time: O((N3*K), Space: O(N2*K))3. Bottom-Up Dynamic Programming (Time: O(N*K), Space: O(N*K))" }, { "code": null, "e": 25753, "s": 25545, "text": "Naive Approach: We can solve this problem using recursion. At each step of recursion put all the values greater than equal to the previously computed value.Below is the implementation of the above approach: " }, { "code": null, "e": 25757, "s": 25753, "text": "C++" }, { "code": null, "e": 25762, "s": 25757, "text": "Java" }, { "code": null, "e": 25770, "s": 25762, "text": "Python3" }, { "code": null, "e": 25773, "s": 25770, "text": "C#" }, { "code": null, "e": 25784, "s": 25773, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsint calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nint countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;}", "e": 26825, "s": 25784, "text": null }, { "code": "// Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.util.*;class GFG{ // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codepublic static void main(String[] args){ int N = 8; int K = 4; System.out.print(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji", "e": 27945, "s": 26825, "text": null }, { "code": "# Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # Function to count the number# of ways to divide the number N# in groups such that each group# has K number of elementsdef calculate(pos, prev, left, k): # Base Case if (pos == k): if (left == 0): return 1; else: return 0; # If N is divides completely # into less than k groups if (left == 0): return 0; answer = 0; # Put all possible values # greater equal to prev for i in range(prev, left + 1): answer += calculate(pos + 1, i, left - i, k); return answer; # Function to count the number of# ways to divide the number Ndef countWaystoDivide(n, k): return calculate(0, 1, n, k); # Driver Codeif __name__ == '__main__': N = 8; K = 4; print(countWaystoDivide(N, K)); # This code is contributed by 29AjayKumar", "e": 28916, "s": 27945, "text": null }, { "code": "// C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System; class GFG{ // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // If N is divides completely // into less than k groups if (left == 0) return 0; int answer = 0; // Put all possible values // greater equal to prev for(int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nstatic int countWaystoDivide(int n, int k){ return calculate(0, 1, n, k);} // Driver Codepublic static void Main(String[] args){ int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji", "e": 30026, "s": 28916, "text": null }, { "code": "<script> // Javascript implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsfunction calculate(pos, prev, left, k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; let answer = 0; // put all possible values // greater equal to prev for (let i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return answer;} // Function to count the number of// ways to divide the number Nfunction countWaystoDivide(n, k){ return calculate(0, 1, n, k);} // Driver Code let N = 8; let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by Mayank Tyagi </script>", "e": 31068, "s": 30026, "text": null }, { "code": null, "e": 31070, "s": 31068, "text": "5" }, { "code": null, "e": 31374, "s": 31070, "text": "Time complexity: O(NK)Auxiliary Space: O(N).Memoization Approach: In the previous approach we can see that we are solving the subproblems repeatedly, i.e. it follows the property of Overlapping Subproblems. So we can memoize the same using the DP table.Below is the implementation of the above approach:" }, { "code": null, "e": 31378, "s": 31374, "text": "C++" }, { "code": null, "e": 31383, "s": 31378, "text": "Java" }, { "code": null, "e": 31391, "s": 31383, "text": "Python3" }, { "code": null, "e": 31394, "s": 31391, "text": "C#" }, { "code": null, "e": 31405, "s": 31394, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // DP Tableint dp[100][100][100]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsint calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsint countWaystoDivide(int n, int k){ // Initialize DP Table as -1 memset(dp, -1, sizeof(dp)); return calculate(0, 1, n, k);} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;}", "e": 32702, "s": 31405, "text": null }, { "code": "// Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.util.*;class GFG{ // DP Tablestatic int [][][]dp = new int[100][100][100]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsstatic int countWaystoDivide(int n, int k){ // Initialize DP Table as -1 for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { for (int l = 0; l < 100; l++) dp[i][j][l] = -1; } } return calculate(0, 1, n, k);} // Driver Codepublic static void main(String[] args){ int N = 8; int K = 4; System.out.print(countWaystoDivide(N, K));}} // This code is contributed by Rajput-Ji", "e": 34286, "s": 32702, "text": null }, { "code": "# Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # DP Tabledp = [[[0 for i in range(50)] for j in range(50)] for j in range(50)] # Function to count the number# of ways to divide the number N# in groups such that each group# has K number of elementsdef calculate(pos, prev, left, k): # Base Case if (pos == k): if (left == 0): return 1; else: return 0; # if N is divides completely # into less than k groups if (left == 0): return 0; # If the subproblem has been # solved, use the value if (dp[pos][prev][left] != -1): return dp[pos][prev][left]; answer = 0; # put all possible values # greater equal to prev for i in range(prev,left+1): answer += calculate(pos + 1, i, left - i, k); dp[pos][prev][left] = answer; return dp[pos][prev][left]; # Function to count the number of# ways to divide the number N in groupsdef countWaystoDivide(n, k): # Initialize DP Table as -1 for i in range(50): for j in range(50): for l in range(50): dp[i][j][l] = -1; return calculate(0, 1, n, k); # Driver Codeif __name__ == '__main__': N = 8; K = 4; print(countWaystoDivide(N, K)); # This code is contributed by Rajput-Ji", "e": 35687, "s": 34286, "text": null }, { "code": "// C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System;class GFG{ // DP Tablestatic int [,,]dp = new int[50, 50, 50]; // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsstatic int calculate(int pos, int prev, int left, int k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos, prev, left] != -1) return dp[pos, prev, left]; int answer = 0; // put all possible values // greater equal to prev for (int i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos, prev, left] = answer;} // Function to count the number of// ways to divide the number N in groupsstatic int countWaystoDivide(int n, int k){ // Initialize DP Table as -1 for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { for (int l = 0; l < 50; l++) dp[i, j, l] = -1; } } return calculate(0, 1, n, k);} // Driver Codepublic static void Main(String[] args){ int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K));}} // This code is contributed by gauravrajput1", "e": 37256, "s": 35687, "text": null }, { "code": "<script> // JavaScript implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements // DP Tablelet dp = new Array(500);for(let i=0;i<500;i++){ dp[i]=new Array(500); for(let j=0;j<500;j++) { dp[i][j]=new Array(500); for(let k=0;k<500;k++) dp[i][j][k]=0; }} // Function to count the number// of ways to divide the number N// in groups such that each group// has K number of elementsfunction calculate(pos,prev,left,k){ // Base Case if (pos == k) { if (left == 0) return 1; else return 0; } // if N is divides completely // into less than k groups if (left == 0) return 0; // If the subproblem has been // solved, use the value if (dp[pos][prev][left] != -1) return dp[pos][prev][left]; let answer = 0; // put all possible values // greater equal to prev for (let i = prev; i <= left; i++) { answer += calculate(pos + 1, i, left - i, k); } return dp[pos][prev][left] = answer;} // Function to count the number of// ways to divide the number N in groupsfunction countWaystoDivide(n,k){ // Initialize DP Table as -1 for (let i = 0; i < 500; i++) { for (let j = 0; j < 500; j++) { for (let l = 0; l < 500; l++) dp[i][j][l] = -1; } } return calculate(0, 1, n, k);} // Driver Codelet N = 8;let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by unknown2108 </script>", "e": 38885, "s": 37256, "text": null }, { "code": null, "e": 38893, "s": 38885, "text": "Output:" }, { "code": null, "e": 38895, "s": 38893, "text": "5" }, { "code": null, "e": 38952, "s": 38895, "text": "Time complexity: O(N^3 * K) Auxiliary Space: O(N^2 * K)." }, { "code": null, "e": 39064, "s": 38952, "text": "Bottom-Up DP: We are asked to find CountWaystoDivide(n,k) So the recurrence approach and explanation of DP is:" }, { "code": null, "e": 39156, "s": 39064, "text": "CountWaystoDivide( n , k ) = CountWaystoDivide( n-k , k ) + CountWaystoDivide( n-1 , k-1 ) " }, { "code": null, "e": 39223, "s": 39156, "text": "Explanation:Divide CountWaystoDivide( n , k ) into two parts where" }, { "code": null, "e": 39492, "s": 39223, "text": "If first element is 1 then the rest form a total of n-1 divide into k-1 so CountWaystoDivide( n-1 , k-1 )If first element is greater than 1 then, we can subtract 1 from every element and get a valid partition of n-k into k parts, hence CountWaystoDivide( n-1 , k-1 )." }, { "code": null, "e": 39599, "s": 39492, "text": "If first element is 1 then the rest form a total of n-1 divide into k-1 so CountWaystoDivide( n-1 , k-1 )" }, { "code": null, "e": 39762, "s": 39599, "text": "If first element is greater than 1 then, we can subtract 1 from every element and get a valid partition of n-k into k parts, hence CountWaystoDivide( n-1 , k-1 )." }, { "code": null, "e": 39794, "s": 39762, "text": "Mathematical Explanation of DP:" }, { "code": null, "e": 40315, "s": 39794, "text": "As each group must have at least one person, so, give each group one person, then we are left with n-k persons, which can we divided into 1,2,3..or k groups. Thus our dp will be: dp[n][k] = dp[n-k][1] + dp[n-k][2] + dp[n-k][3] + .... + dp[n-k][k].At first look, the previous might give O(N3) vibes, but with a little manipulation we can optimize it: dp[n][k] = dp[(n-1)-(k-1)][1] + dp[(n-1)-(k-1)][2] + ... + dp[(n-1)-(k-1)][k-1] + dp[(n-1)-(k-1)][k]From the recurrence, we can write:dp[n][k] = dp[n-1][k-1] + dp[n-k][k]" }, { "code": null, "e": 40563, "s": 40315, "text": "As each group must have at least one person, so, give each group one person, then we are left with n-k persons, which can we divided into 1,2,3..or k groups. Thus our dp will be: dp[n][k] = dp[n-k][1] + dp[n-k][2] + dp[n-k][3] + .... + dp[n-k][k]." }, { "code": null, "e": 40837, "s": 40563, "text": "At first look, the previous might give O(N3) vibes, but with a little manipulation we can optimize it: dp[n][k] = dp[(n-1)-(k-1)][1] + dp[(n-1)-(k-1)][2] + ... + dp[(n-1)-(k-1)][k-1] + dp[(n-1)-(k-1)][k]From the recurrence, we can write:dp[n][k] = dp[n-1][k-1] + dp[n-k][k]" }, { "code": null, "e": 40874, "s": 40837, "text": "Steps to solve the problem using DP:" }, { "code": null, "e": 40995, "s": 40874, "text": "Initialize a 2-D array dp[][] of size n+1, k+1 where dp[i][j] will store the optimal solution to divide n into k groups." }, { "code": null, "e": 41111, "s": 40995, "text": "For each value from i=0 to n, dp[n][1] will be 1 since total ways to divide n into 1 is 1. also dp[0][0] will be 1." }, { "code": null, "e": 41151, "s": 41111, "text": " DP states are updated as follows:" }, { "code": null, "e": 41201, "s": 41151, "text": "If i>=j then dp[i][j] = dp[i-1][j-1] + dp[i-j][j]" }, { "code": null, "e": 41272, "s": 41201, "text": "otherwise i-j<0 and dp[i-j][j] become zero so dp[i][j] = dp[i-1][j-1] " }, { "code": null, "e": 41276, "s": 41272, "text": "C++" }, { "code": null, "e": 41281, "s": 41276, "text": "Java" }, { "code": null, "e": 41289, "s": 41281, "text": "Python3" }, { "code": null, "e": 41292, "s": 41289, "text": "C#" }, { "code": null, "e": 41303, "s": 41292, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of ways to divide N in// groups such that each group// has K number of elements #include <bits/stdc++.h> using namespace std; // Function to count the number of// ways to divide the number N in groupsint countWaystoDivide(int n, int k){ if (n < k) return 0; // When n is less than k, No way to divide // into groups vector<vector<int> > dp(n + 1, vector<int>(k + 1)); for (int i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups} // Driver Codeint main(){ int N = 8; int K = 4; cout << countWaystoDivide(N, K); return 0;}", "e": 42392, "s": 41303, "text": null }, { "code": "// Java implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsimport java.io.*; class GFG { static int countWaystoDivide(int n, int k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups int [][]dp = new int[n+1][k+1]; for (int i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups } // Driver code public static void main (String[] args) { int N = 8; int K = 4; System.out.println(countWaystoDivide(N, K)); }} // This code is contributed by rohitsingh07052.", "e": 43362, "s": 42392, "text": null }, { "code": "# Python3 implementation to count the# number of ways to divide N in# groups such that each group# has K number of elements # DP Table# Function to count the number of# ways to divide the number N in groups def countWaystoDivide(n, k): if(n < k): return 0 dp = [[0 for i in range(k+1)] for i in range(n+1)] for i in range(1, n+1): dp[i][1] = 1 dp[0][0] = 1 for i in range(1, n+1): for j in range(2, k+1): if(i >= j): dp[i][j] = dp[i-1][j-1] + dp[i-j][j] else: dp[i][j] = dp[i-1][j-1] return dp[n][k] # Driver Codeif __name__ == '__main__': N = 8 K = 4 print(countWaystoDivide(N, K)) # This code is contributed by Rajput-Ji", "e": 44090, "s": 43362, "text": null }, { "code": "// C# implementation to count the// number of ways to divide N in// groups such that each group// has K number of elementsusing System;using System.Collections.Generic;class GFG { static int countWaystoDivide(int n, int k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups int[,] dp = new int[n + 1, k + 1]; for (int i = 1; i <= n; i++) dp[i, 1] = 1; // exact one way to divide n to 1 group dp[0, 0] = 1; for (int i = 1; i <= n; i++) { for (int j = 2; j <= k; j++) { if (i >= j) dp[i,j] = dp[i - j,j] + dp[i - 1,j - 1]; else dp[i,j] = dp[i - 1, j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n,k]; // returning number of ways to divide N // in k groups } static void Main() { int N = 8; int K = 4; Console.Write(countWaystoDivide(N, K)); }} // This code is contributed by rameshtravel07.", "e": 45035, "s": 44090, "text": null }, { "code": "<script> // Javascript implementation to count the // number of ways to divide N in // groups such that each group // has K number of elements // Function to count the number of // ways to divide the number N in groups function countWaystoDivide(n, k) { if (n < k) return 0; // When n is less than k, No way to divide // into groups let dp = new Array(n + 1); for(let i = 0; i < n + 1; i++) { dp[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { dp[i][j] = 0; } } for (let i = 1; i <= n; i++) dp[i][1] = 1; // exact one way to divide n to 1 group dp[0][0] = 1; for (let i = 1; i <= n; i++) { for (let j = 2; j <= k; j++) { if (i >= j) dp[i][j] = dp[i - j][j] + dp[i - 1][j - 1]; else dp[i][j] = dp[i - 1][j - 1]; // i<j so dp[i-j][j] // becomes zero } } return dp[n][k]; // returning number of ways to divide N // in k groups } let N = 8; let K = 4; document.write(countWaystoDivide(N, K)); // This code is contributed by mukesh07.</script>", "e": 46399, "s": 45035, "text": null }, { "code": null, "e": 46401, "s": 46399, "text": "5" }, { "code": null, "e": 46453, "s": 46401, "text": "Time complexity: O(N * K)Auxiliary Space: O(N * K)" }, { "code": null, "e": 46463, "s": 46453, "text": "king_tsar" }, { "code": null, "e": 46473, "s": 46463, "text": "Rajput-Ji" }, { "code": null, "e": 46487, "s": 46473, "text": "GauravRajput1" }, { "code": null, "e": 46499, "s": 46487, "text": "29AjayKumar" }, { "code": null, "e": 46515, "s": 46499, "text": "mayanktyagi1709" }, { "code": null, "e": 46527, "s": 46515, "text": "TarunSingh2" }, { "code": null, "e": 46539, "s": 46527, "text": "unknown2108" }, { "code": null, "e": 46555, "s": 46539, "text": "saurabh1990aror" }, { "code": null, "e": 46571, "s": 46555, "text": "pankajsharmagfg" }, { "code": null, "e": 46579, "s": 46571, "text": "kapilag" }, { "code": null, "e": 46593, "s": 46579, "text": "akhil14shukla" }, { "code": null, "e": 46602, "s": 46593, "text": "sweetyty" }, { "code": null, "e": 46617, "s": 46602, "text": "prachisoda1234" }, { "code": null, "e": 46626, "s": 46617, "text": "mukesh07" }, { "code": null, "e": 46642, "s": 46626, "text": "rohitsingh07052" }, { "code": null, "e": 46657, "s": 46642, "text": "rameshtravel07" }, { "code": null, "e": 46684, "s": 46657, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 46695, "s": 46684, "text": "Algorithms" }, { "code": null, "e": 46719, "s": 46695, "text": "Competitive Programming" }, { "code": null, "e": 46739, "s": 46719, "text": "Dynamic Programming" }, { "code": null, "e": 46752, "s": 46739, "text": "Mathematical" }, { "code": null, "e": 46762, "s": 46752, "text": "Recursion" }, { "code": null, "e": 46782, "s": 46762, "text": "Dynamic Programming" }, { "code": null, "e": 46795, "s": 46782, "text": "Mathematical" }, { "code": null, "e": 46805, "s": 46795, "text": "Recursion" }, { "code": null, "e": 46816, "s": 46805, "text": "Algorithms" }, { "code": null, "e": 46914, "s": 46816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46963, "s": 46914, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 46988, "s": 46963, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 47015, "s": 46988, "text": "Introduction to Algorithms" }, { "code": null, "e": 47058, "s": 47015, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 47083, "s": 47058, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 47126, "s": 47083, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 47169, "s": 47126, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 47210, "s": 47169, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 47276, "s": 47210, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" } ]
K-Means Clustering — Introduction to Machine Learning Algorithms | by Rohith Gandhi | Towards Data Science
In machine learning, we are not always provided an objective to optimize, we are not always provided a target label to classify the input data points into. The kinds of problems where we are not provided with an objective or label to classify is termed as an unsupervised learning problem in the domain of AI. In an unsupervised learning problem, we try to model the latent structured information present within the data. Clustering is a type of unsupervised learning problem where we try to group similar data based on their underlying structure into cohorts/clusters. K-means algorithm is a famous clustering algorithm that is ubiquitously used. K represents the number of clusters we are going to classify our data points into. ## K-Means Clustering 1. Choose the number of clusters(K) and obtain the data points 2. Place the centroids c_1, c_2, ..... c_k randomly 3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations4. for each data point x_i: - find the nearest centroid(c_1, c_2 .. c_k) - assign the point to that cluster 5. for each cluster j = 1..k - new centroid = mean of all points assigned to that cluster6. End The simulations below would provide a better understanding of the K-means algorithm. There would be some instances where we would not know the number of clusters. Then, how can we choose the value for K??? There is a way called the elbow method. In this method, you choose a different number of clusters and start plotting the within-cluster distance to the centroid. The graph looks as below. From the above graph we can infer that at k=4, the graph reaches an optimum minimum value. Even though the within-cluster distance decreases after 4, we would be doing more computations. Which is just analogous to the law of diminishing returns. Therefore, we choose a value of 4 as the optimum number of clusters. The reason it is named the elbow method is that the optimum number of clusters would represent an elbow joint! Behavioural Segmentation Anomaly Detection Social Network Analysis Market Segmentation There are just a few examples where clustering algorithm like K-means is applied. We will be using the Iris dataset to build our algorithm. Even though the Iris dataset has labels, we will be dropping them and use only the feature points to cluster the data. We know that there are 3 clusters(‘Iris-virginica’, ‘Iris-setosa’, ‘Iris-versicolor’). Therefore, k=3 in our case. We load the dataset and drop the target values. We convert the feature points into a numpy array and split it into training and testing data. We implement the pseudocode shown above and we can find that our algorithm converges after 6 iterations. We can now input a test data point and find the centroid it is closest to and assign that point to the respective cluster. The Scikit-learn library once again saves us from writing so many lines of code by providing an abstract level object which we can just use to implement the algorithm. K-means is an introductory algorithm to clustering techniques and it is the simplest of them. As you would’ve noticed, there is no objective/loss function. Hence, no partial derivates is required and that complicated math is eliminated. K-means is an easy to implement and handy algorithm.
[ { "code": null, "e": 902, "s": 171, "text": "In machine learning, we are not always provided an objective to optimize, we are not always provided a target label to classify the input data points into. The kinds of problems where we are not provided with an objective or label to classify is termed as an unsupervised learning problem in the domain of AI. In an unsupervised learning problem, we try to model the latent structured information present within the data. Clustering is a type of unsupervised learning problem where we try to group similar data based on their underlying structure into cohorts/clusters. K-means algorithm is a famous clustering algorithm that is ubiquitously used. K represents the number of clusters we are going to classify our data points into." }, { "code": null, "e": 1353, "s": 902, "text": "## K-Means Clustering 1. Choose the number of clusters(K) and obtain the data points 2. Place the centroids c_1, c_2, ..... c_k randomly 3. Repeat steps 4 and 5 until convergence or until the end of a fixed number of iterations4. for each data point x_i: - find the nearest centroid(c_1, c_2 .. c_k) - assign the point to that cluster 5. for each cluster j = 1..k - new centroid = mean of all points assigned to that cluster6. End " }, { "code": null, "e": 1438, "s": 1353, "text": "The simulations below would provide a better understanding of the K-means algorithm." }, { "code": null, "e": 1747, "s": 1438, "text": "There would be some instances where we would not know the number of clusters. Then, how can we choose the value for K??? There is a way called the elbow method. In this method, you choose a different number of clusters and start plotting the within-cluster distance to the centroid. The graph looks as below." }, { "code": null, "e": 2173, "s": 1747, "text": "From the above graph we can infer that at k=4, the graph reaches an optimum minimum value. Even though the within-cluster distance decreases after 4, we would be doing more computations. Which is just analogous to the law of diminishing returns. Therefore, we choose a value of 4 as the optimum number of clusters. The reason it is named the elbow method is that the optimum number of clusters would represent an elbow joint!" }, { "code": null, "e": 2198, "s": 2173, "text": "Behavioural Segmentation" }, { "code": null, "e": 2216, "s": 2198, "text": "Anomaly Detection" }, { "code": null, "e": 2240, "s": 2216, "text": "Social Network Analysis" }, { "code": null, "e": 2260, "s": 2240, "text": "Market Segmentation" }, { "code": null, "e": 2342, "s": 2260, "text": "There are just a few examples where clustering algorithm like K-means is applied." }, { "code": null, "e": 2634, "s": 2342, "text": "We will be using the Iris dataset to build our algorithm. Even though the Iris dataset has labels, we will be dropping them and use only the feature points to cluster the data. We know that there are 3 clusters(‘Iris-virginica’, ‘Iris-setosa’, ‘Iris-versicolor’). Therefore, k=3 in our case." }, { "code": null, "e": 2776, "s": 2634, "text": "We load the dataset and drop the target values. We convert the feature points into a numpy array and split it into training and testing data." }, { "code": null, "e": 3004, "s": 2776, "text": "We implement the pseudocode shown above and we can find that our algorithm converges after 6 iterations. We can now input a test data point and find the centroid it is closest to and assign that point to the respective cluster." }, { "code": null, "e": 3172, "s": 3004, "text": "The Scikit-learn library once again saves us from writing so many lines of code by providing an abstract level object which we can just use to implement the algorithm." } ]
Visualizing Missing Values in Python is Shockingly Easy | by Eirik Berge | Towards Data Science
Setting the StageWhat is Missingno?Loading the DataBar ChartsMatrix PlotsHeatmapsWhat have you Learned?Wrapping Up Setting the Stage What is Missingno? Loading the Data Bar Charts Matrix Plots Heatmaps What have you Learned? Wrapping Up Missing values are a fact of life. If you are a data scientist or a data engineer and receives data, then missing values abound. How you should deal with missing values is highly context-dependent: Maybe remove all the rows with missing values? Maybe drop an entire feature that has too many missing values? Maybe fill in the missing values in a clever way? The first step should always be to understand what is missing and why it is missing. To start this discovery, there is nothing better than to obtain a good visualization of the missing values! Which of the two options below are easier to comprehend? 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool It’s definitely the bar chart, right? 😋 Both options give you information about the missing values in the famous Titanic dataset. By a single look at the bar chart, you can see that there are two features (age and deck) where you are missing a serious amount of data. In this blog post, I will show you how to work with the Python library missingno. This library gives you a few utility functions that plot the missing values of a pandas dataframe. If you are more of a visual learner, then I have also made a video on the topic 😃 Missingno is a Python library that helps you to visualize missing values in a pandas dataframe. The authors of the library describe missingno in the following way: Messy datasets? Missing values? missingno provides a small toolset of flexible and easy-to-use missing data visualizations and utilities that allows you to get a quick visual summary of the completeness (or lack thereof) of your dataset. — Missingno Documentation In this blog post, you will use missingno to understand the missing values in the famous Titanic dataset. The dataset comes preinstalled with the library seaborn, so there is no need to download it separately. First of all, let’s install missingno. I will be using Anaconda, and have hence installed missingno with the simple command: conda install -c conda-forge missingno If you are using PIP, then you can use the command: pip install missingno Since I am using Jupyter Notebooks through Anaconda, I already have pandas and seaborn installed. Make sure you have these installed if you want to follow the code in this blog post 😉 You should start by importing the packages: # Package importsimport seaborn as snsimport pandas as pdimport missingno as msno%matplotlib inline Importing missingno with the alias msno is the recommended way. Now you can use seaborn to import the Titanic dataset. This dataset comes preinstalled with seaborn, and you can simply run the command: # Load the Titanic data settitanic = sns.load_dataset("titanic") Now the Titanic dataset is stored in the pandas dataframe titanic. It is difficult to visualize the missing values with pandas. The only thing you can really do is to use the pandas method .info() to get a summary of the missing values: titanic.info()Output: <class 'pandas.core.frame.DataFrame'>RangeIndex: 891 entries, 0 to 890Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category 12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool dtypes: bool(2), category(2), float64(2), int64(4), object(5)memory usage: 80.7+ KB The method .info() is great for checking out the data types of the different features. However, it is not great for getting a visual picture of what is missing for the different features. You will use missingno for this 😍 The most basic plot for visualizing missing values is the bar chart. To get this, you can simply use the function bar in the missingno library: # Gives a bar chart of the missing valuesmsno.bar(titanic) This displays the image: Here you can immediately see that the age and deck features are seriously missing values. A closer look also reveals that the features embarked and embark_town are missing two values each. How you should deal with missing values depends on the context. In this setting, it should be possible to fill in the features age, embarked, and embark_town with appropriate values. However, for the deck feature, there is so much missing that I would consider dropping the feature entirely. Although a bar char is simple, there is no way to see which parts of a feature that is missing. In the next section, I will show you how to see this with missingno’s matrix function. Another utility visualization that missingno provides is the matrix plot. Simply use the matrix() function as follows: # Gives positional information of the missing valuesmsno.matrix(titanic) This displays the image: From the matrix plot, you can see where the missing values are located. For the Titanic dataset, the missing values are located all over the place. However, for other datasets (such as time-series), the missing data is often bundled together (due to e.g. server crashes). The matrix plot reaffirms our initial assumption that it will be hard to save anything regarding the deck features 😟 A final visualization you can use is the heatmap. This is slightly more complicated than the bar chart and the matrix plot. However, it can sometimes reveal interesting connections between missing values of different features. To get a heatmap, you can simply use the function heatmap() in the missingno library: # Gives a heatmap of how missing values are relatedmsno.heatmap(titanic) This displays the image: First of all, notice that there are only four features present in the heatmap. This is because there are only four features that are missing values. All the other features are discarded from the plot. To understand the heatmap, look at the value that corresponds to embarked and embark_town. The value is 1. This means that there is a perfect correspondence between missing values in embarked and missing values in embark_town . You can also see this from the matrix plot you made before. The values in the heatmap range between -1 and 1. A value of -1 indicates a negative correspondence: A missing value in feature A implies that there is not a missing value in feature B. Finally, a value of 0 indicates that there is no obvious correspondence between missing values in feature A and missing values in feature B. This is (more or less) the case for all the remaining features. For the Titanic dataset, the heatmap reveals that there is no obvious correspondence between missing values in the age feature and missing values in the deck feature. From the visualizations you have done, the following conclusions can be drawn. Bar Chart — The Titanic dataset is mostly missing values from the features age and deck. Matrix Plot — The missing values in age and deck are spread out all over the rows. Heatmap — There is no strong correlation between missing values in the age and deck features. This gives you a lot more intuition than you started with. Visualizing the missing data is just the first step in a long process. You have far to go, but at least now you have started the journey 🔥 If you need to learn more about missingno, then check out the missingno Github or my video on missingno. Like my writing? Check out my blog posts Modernize Your Sinful Python Code with Beautiful Type Hints A Quick Guide to Symbolic Mathematics with SymPy 5 Awesome NumPy Functions That Can Save You in a Pinch 5 Expert Tips to Skyrocket Your Dictionary Skills in Python 🚀 for more Python content. If you are interested in data science, programming, or anything in between, then feel free to add me on LinkedIn and say hi ✋
[ { "code": null, "e": 287, "s": 172, "text": "Setting the StageWhat is Missingno?Loading the DataBar ChartsMatrix PlotsHeatmapsWhat have you Learned?Wrapping Up" }, { "code": null, "e": 305, "s": 287, "text": "Setting the Stage" }, { "code": null, "e": 324, "s": 305, "text": "What is Missingno?" }, { "code": null, "e": 341, "s": 324, "text": "Loading the Data" }, { "code": null, "e": 352, "s": 341, "text": "Bar Charts" }, { "code": null, "e": 365, "s": 352, "text": "Matrix Plots" }, { "code": null, "e": 374, "s": 365, "text": "Heatmaps" }, { "code": null, "e": 397, "s": 374, "text": "What have you Learned?" }, { "code": null, "e": 409, "s": 397, "text": "Wrapping Up" }, { "code": null, "e": 607, "s": 409, "text": "Missing values are a fact of life. If you are a data scientist or a data engineer and receives data, then missing values abound. How you should deal with missing values is highly context-dependent:" }, { "code": null, "e": 654, "s": 607, "text": "Maybe remove all the rows with missing values?" }, { "code": null, "e": 717, "s": 654, "text": "Maybe drop an entire feature that has too many missing values?" }, { "code": null, "e": 767, "s": 717, "text": "Maybe fill in the missing values in a clever way?" }, { "code": null, "e": 1017, "s": 767, "text": "The first step should always be to understand what is missing and why it is missing. To start this discovery, there is nothing better than to obtain a good visualization of the missing values! Which of the two options below are easier to comprehend?" }, { "code": null, "e": 1633, "s": 1017, "text": "0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool " }, { "code": null, "e": 1673, "s": 1633, "text": "It’s definitely the bar chart, right? 😋" }, { "code": null, "e": 1901, "s": 1673, "text": "Both options give you information about the missing values in the famous Titanic dataset. By a single look at the bar chart, you can see that there are two features (age and deck) where you are missing a serious amount of data." }, { "code": null, "e": 2164, "s": 1901, "text": "In this blog post, I will show you how to work with the Python library missingno. This library gives you a few utility functions that plot the missing values of a pandas dataframe. If you are more of a visual learner, then I have also made a video on the topic 😃" }, { "code": null, "e": 2328, "s": 2164, "text": "Missingno is a Python library that helps you to visualize missing values in a pandas dataframe. The authors of the library describe missingno in the following way:" }, { "code": null, "e": 2592, "s": 2328, "text": "Messy datasets? Missing values? missingno provides a small toolset of flexible and easy-to-use missing data visualizations and utilities that allows you to get a quick visual summary of the completeness (or lack thereof) of your dataset. — Missingno Documentation" }, { "code": null, "e": 2802, "s": 2592, "text": "In this blog post, you will use missingno to understand the missing values in the famous Titanic dataset. The dataset comes preinstalled with the library seaborn, so there is no need to download it separately." }, { "code": null, "e": 2927, "s": 2802, "text": "First of all, let’s install missingno. I will be using Anaconda, and have hence installed missingno with the simple command:" }, { "code": null, "e": 2966, "s": 2927, "text": "conda install -c conda-forge missingno" }, { "code": null, "e": 3018, "s": 2966, "text": "If you are using PIP, then you can use the command:" }, { "code": null, "e": 3040, "s": 3018, "text": "pip install missingno" }, { "code": null, "e": 3224, "s": 3040, "text": "Since I am using Jupyter Notebooks through Anaconda, I already have pandas and seaborn installed. Make sure you have these installed if you want to follow the code in this blog post 😉" }, { "code": null, "e": 3268, "s": 3224, "text": "You should start by importing the packages:" }, { "code": null, "e": 3368, "s": 3268, "text": "# Package importsimport seaborn as snsimport pandas as pdimport missingno as msno%matplotlib inline" }, { "code": null, "e": 3432, "s": 3368, "text": "Importing missingno with the alias msno is the recommended way." }, { "code": null, "e": 3569, "s": 3432, "text": "Now you can use seaborn to import the Titanic dataset. This dataset comes preinstalled with seaborn, and you can simply run the command:" }, { "code": null, "e": 3634, "s": 3569, "text": "# Load the Titanic data settitanic = sns.load_dataset(\"titanic\")" }, { "code": null, "e": 3701, "s": 3634, "text": "Now the Titanic dataset is stored in the pandas dataframe titanic." }, { "code": null, "e": 3871, "s": 3701, "text": "It is difficult to visualize the missing values with pandas. The only thing you can really do is to use the pandas method .info() to get a summary of the missing values:" }, { "code": null, "e": 4793, "s": 3871, "text": "titanic.info()Output: <class 'pandas.core.frame.DataFrame'>RangeIndex: 891 entries, 0 to 890Data columns (total 15 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 survived 891 non-null int64 1 pclass 891 non-null int64 2 sex 891 non-null object 3 age 714 non-null float64 4 sibsp 891 non-null int64 5 parch 891 non-null int64 6 fare 891 non-null float64 7 embarked 889 non-null object 8 class 891 non-null category 9 who 891 non-null object 10 adult_male 891 non-null bool 11 deck 203 non-null category 12 embark_town 889 non-null object 13 alive 891 non-null object 14 alone 891 non-null bool dtypes: bool(2), category(2), float64(2), int64(4), object(5)memory usage: 80.7+ KB" }, { "code": null, "e": 5015, "s": 4793, "text": "The method .info() is great for checking out the data types of the different features. However, it is not great for getting a visual picture of what is missing for the different features. You will use missingno for this 😍" }, { "code": null, "e": 5159, "s": 5015, "text": "The most basic plot for visualizing missing values is the bar chart. To get this, you can simply use the function bar in the missingno library:" }, { "code": null, "e": 5218, "s": 5159, "text": "# Gives a bar chart of the missing valuesmsno.bar(titanic)" }, { "code": null, "e": 5243, "s": 5218, "text": "This displays the image:" }, { "code": null, "e": 5432, "s": 5243, "text": "Here you can immediately see that the age and deck features are seriously missing values. A closer look also reveals that the features embarked and embark_town are missing two values each." }, { "code": null, "e": 5724, "s": 5432, "text": "How you should deal with missing values depends on the context. In this setting, it should be possible to fill in the features age, embarked, and embark_town with appropriate values. However, for the deck feature, there is so much missing that I would consider dropping the feature entirely." }, { "code": null, "e": 5907, "s": 5724, "text": "Although a bar char is simple, there is no way to see which parts of a feature that is missing. In the next section, I will show you how to see this with missingno’s matrix function." }, { "code": null, "e": 6026, "s": 5907, "text": "Another utility visualization that missingno provides is the matrix plot. Simply use the matrix() function as follows:" }, { "code": null, "e": 6099, "s": 6026, "text": "# Gives positional information of the missing valuesmsno.matrix(titanic)" }, { "code": null, "e": 6124, "s": 6099, "text": "This displays the image:" }, { "code": null, "e": 6396, "s": 6124, "text": "From the matrix plot, you can see where the missing values are located. For the Titanic dataset, the missing values are located all over the place. However, for other datasets (such as time-series), the missing data is often bundled together (due to e.g. server crashes)." }, { "code": null, "e": 6513, "s": 6396, "text": "The matrix plot reaffirms our initial assumption that it will be hard to save anything regarding the deck features 😟" }, { "code": null, "e": 6740, "s": 6513, "text": "A final visualization you can use is the heatmap. This is slightly more complicated than the bar chart and the matrix plot. However, it can sometimes reveal interesting connections between missing values of different features." }, { "code": null, "e": 6826, "s": 6740, "text": "To get a heatmap, you can simply use the function heatmap() in the missingno library:" }, { "code": null, "e": 6899, "s": 6826, "text": "# Gives a heatmap of how missing values are relatedmsno.heatmap(titanic)" }, { "code": null, "e": 6924, "s": 6899, "text": "This displays the image:" }, { "code": null, "e": 7125, "s": 6924, "text": "First of all, notice that there are only four features present in the heatmap. This is because there are only four features that are missing values. All the other features are discarded from the plot." }, { "code": null, "e": 7413, "s": 7125, "text": "To understand the heatmap, look at the value that corresponds to embarked and embark_town. The value is 1. This means that there is a perfect correspondence between missing values in embarked and missing values in embark_town . You can also see this from the matrix plot you made before." }, { "code": null, "e": 7599, "s": 7413, "text": "The values in the heatmap range between -1 and 1. A value of -1 indicates a negative correspondence: A missing value in feature A implies that there is not a missing value in feature B." }, { "code": null, "e": 7804, "s": 7599, "text": "Finally, a value of 0 indicates that there is no obvious correspondence between missing values in feature A and missing values in feature B. This is (more or less) the case for all the remaining features." }, { "code": null, "e": 7971, "s": 7804, "text": "For the Titanic dataset, the heatmap reveals that there is no obvious correspondence between missing values in the age feature and missing values in the deck feature." }, { "code": null, "e": 8050, "s": 7971, "text": "From the visualizations you have done, the following conclusions can be drawn." }, { "code": null, "e": 8139, "s": 8050, "text": "Bar Chart — The Titanic dataset is mostly missing values from the features age and deck." }, { "code": null, "e": 8222, "s": 8139, "text": "Matrix Plot — The missing values in age and deck are spread out all over the rows." }, { "code": null, "e": 8316, "s": 8222, "text": "Heatmap — There is no strong correlation between missing values in the age and deck features." }, { "code": null, "e": 8514, "s": 8316, "text": "This gives you a lot more intuition than you started with. Visualizing the missing data is just the first step in a long process. You have far to go, but at least now you have started the journey 🔥" }, { "code": null, "e": 8619, "s": 8514, "text": "If you need to learn more about missingno, then check out the missingno Github or my video on missingno." }, { "code": null, "e": 8660, "s": 8619, "text": "Like my writing? Check out my blog posts" }, { "code": null, "e": 8720, "s": 8660, "text": "Modernize Your Sinful Python Code with Beautiful Type Hints" }, { "code": null, "e": 8769, "s": 8720, "text": "A Quick Guide to Symbolic Mathematics with SymPy" }, { "code": null, "e": 8824, "s": 8769, "text": "5 Awesome NumPy Functions That Can Save You in a Pinch" }, { "code": null, "e": 8886, "s": 8824, "text": "5 Expert Tips to Skyrocket Your Dictionary Skills in Python 🚀" } ]
Error:selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH using Selenium
We can get the error selenium.common.exceptions.WebDriverException if the path of the chromedriver.exe executable file is not set properly or incorrect within the webdriver.Chrome(). The below image shows such an exception. It can be resolved by the following ways − Verify the path of the chromedriver.exe file set within webdriver.Chrome. Verify the path of the chromedriver.exe file set within webdriver.Chrome. Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code. Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code. Code Implementation with webdriver manager from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager #configure webdriver manager driver = webdriver.Chrome(ChromeDriverManager().install()) driver.implicitly_wait(0.5) #launch URL driver.get("https://www.tutorialspoint.com/index.htm") print("URL is: ") print(driver.current_url) driver.close()
[ { "code": null, "e": 1286, "s": 1062, "text": "We can get the error selenium.common.exceptions.WebDriverException if the path of the chromedriver.exe executable file is not set properly or incorrect within the webdriver.Chrome(). The below image shows such an exception." }, { "code": null, "e": 1329, "s": 1286, "text": "It can be resolved by the following ways −" }, { "code": null, "e": 1403, "s": 1329, "text": "Verify the path of the chromedriver.exe file set within webdriver.Chrome." }, { "code": null, "e": 1477, "s": 1403, "text": "Verify the path of the chromedriver.exe file set within webdriver.Chrome." }, { "code": null, "e": 1649, "s": 1477, "text": "Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code." }, { "code": null, "e": 1821, "s": 1649, "text": "Install the webdriver manager with the command: pip install webdrivermanager. Then add the statement: from webdriver_manager.chrome import ChromeDriverManager in our code." }, { "code": null, "e": 1864, "s": 1821, "text": "Code Implementation with webdriver manager" }, { "code": null, "e": 2194, "s": 1864, "text": "from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\n#configure webdriver manager\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\nprint(\"URL is: \")\nprint(driver.current_url)\ndriver.close()" } ]
Build a basic Text Editor using Tkinter in Python - GeeksforGeeks
29 Dec, 2020 Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but this is the only framework that’s built into the Python standard library. It has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. It is lightweight and relatively painless to use compared to other frameworks. This makes it a compelling choice for building GUI applications in Python, especially for applications where a modern shine is unnecessary, and the top priority is to build something that’s functional and cross-platform quickly. Let’s start quickly working with Tkinter Firstly Tkinter is a module that is available in most IDE’s. So let’s break apart the beginning into points: Importing the Tkinter module.Creating a window in which the program executes. It is also known as the “root window”.Finally, using a function to execute the code which is known as “mainloop()”. Importing the Tkinter module. Creating a window in which the program executes. It is also known as the “root window”. Finally, using a function to execute the code which is known as “mainloop()”. Python3 # import all things from tkinterfrom tkinter import * # create root window root = Tk() # widgets,buttons,etc hereroot.mainloop() Output: “*” implements all features of Tkinter This is how you could build a window in just three simple lines! Note: Please do not spell “tkinter” as with a capital “T”, as this would not import the module and you would most probably encounter an error message!!! This is a simple step! So we will basically use these mains functions:- geometry(“AAAxBBB”)minsize(height = AAA, width = BBB)maxsize(height = AAA, width = BBB)title(“DESIRED TITLE”) geometry(“AAAxBBB”) minsize(height = AAA, width = BBB) maxsize(height = AAA, width = BBB) title(“DESIRED TITLE”) Python3 from tkinter import * # rootroot = Tk() # designroot.geometry("300x300")root.minsize(height=560)root.title("TKINter Program") # executeroot.mainloop() Output: Notepad is one thing used commonly by every person who owns a desktop. It a shortcut tool to save important information in small notes, for temporary purposes, etc. Let’s make our own notepad using Tkinter. First, let’s type the basic code that we discussed earlier. Python3 from tkinter import * # create root windowroot = Tk() # designroot.geometry("300x300")root.minsize(height=560)root.title("Notepad") # running the programroot.mainloop() Okay so let’s think we will need a text function and a scroll bar to scroll through the text if it exceeds the dimensions of the window. Also, we learn about grid() and pack(). They are used to pack the functions in the window, without them the buttons, text, frames would not display in the window. Note: We can either use .grid() or .pack() for our program. However, using both in the same file would not work since Tkinter does not accept this, you obtain an error. You could use .pack() for efficient packing Now let’s add a scrollbar: We shall invent a variable known as scrollbar and equate it to Scrollbar(root). It is important to add root into the brackets to integrate the scrollbar function into main root loop. Now let’s pack the scrollbar: We call the variable name and append it with “.pack(). We use side = RIGHT so that the scrollbar is added to the right of the window and fill = Y or fill = “y” (Use anyone) so that it fill across the whole y-axis. Python3 from tkinter import * root = Tk()root.geometry("300x300")root.minsize(height=560, width=560)root.title("Notepad") # implementing scrollbar functionalityscrollbar = Scrollbar(root) # packing the scrollbar functionscrollbar.pack(side=RIGHT, fill=Y) root.mainloop() Output: Now let’s add the text: We will use the text function and pack it. Also, we will configure the scrollbar for functionality. We will add a command called “yscrollcommand” which will connect the text and scrollbar function together and it would add scrolling option for the text. Python3 from tkinter import * root = Tk()root.geometry("350x250")root.title("Sticky Notes")root.minsize(height=250, width=350)root.maxsize(height=250, width=350) # adding scrollbarscrollbar = Scrollbar(root) # packing scrollbarscrollbar.pack(side=RIGHT, fill=Y) text_info = Text(root, yscrollcommand=scrollbar.set)text_info.pack(fill=BOTH) # configuring the scrollbarscrollbar.config(command=text_info.yview) root.mainloop() Output: Python Tkinter-exercises Python-projects Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n29 Dec, 2020" }, { "code": null, "e": 24899, "s": 24316, "text": "Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but this is the only framework that’s built into the Python standard library. It has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. It is lightweight and relatively painless to use compared to other frameworks. This makes it a compelling choice for building GUI applications in Python, especially for applications where a modern shine is unnecessary, and the top priority is to build something that’s functional and cross-platform quickly. " }, { "code": null, "e": 24942, "s": 24899, "text": "Let’s start quickly working with Tkinter " }, { "code": null, "e": 25057, "s": 24942, "text": " Firstly Tkinter is a module that is available in most IDE’s. So let’s break apart the beginning into points:" }, { "code": null, "e": 25255, "s": 25057, "text": "Importing the Tkinter module.Creating a window in which the program executes. It is also known as the “root window”.Finally, using a function to execute the code which is known as “mainloop()”. " }, { "code": null, "e": 25285, "s": 25255, "text": "Importing the Tkinter module." }, { "code": null, "e": 25373, "s": 25285, "text": "Creating a window in which the program executes. It is also known as the “root window”." }, { "code": null, "e": 25455, "s": 25373, "text": "Finally, using a function to execute the code which is known as “mainloop()”. " }, { "code": null, "e": 25463, "s": 25455, "text": "Python3" }, { "code": "# import all things from tkinterfrom tkinter import * # create root window root = Tk() # widgets,buttons,etc hereroot.mainloop()", "e": 25601, "s": 25463, "text": null }, { "code": null, "e": 25609, "s": 25601, "text": "Output:" }, { "code": null, "e": 25648, "s": 25609, "text": "“*” implements all features of Tkinter" }, { "code": null, "e": 25716, "s": 25648, "text": " This is how you could build a window in just three simple lines!" }, { "code": null, "e": 25869, "s": 25716, "text": "Note: Please do not spell “tkinter” as with a capital “T”, as this would not import the module and you would most probably encounter an error message!!!" }, { "code": null, "e": 25952, "s": 25875, "text": " This is a simple step! So we will basically use these mains functions:-" }, { "code": null, "e": 26062, "s": 25952, "text": "geometry(“AAAxBBB”)minsize(height = AAA, width = BBB)maxsize(height = AAA, width = BBB)title(“DESIRED TITLE”)" }, { "code": null, "e": 26082, "s": 26062, "text": "geometry(“AAAxBBB”)" }, { "code": null, "e": 26117, "s": 26082, "text": "minsize(height = AAA, width = BBB)" }, { "code": null, "e": 26152, "s": 26117, "text": "maxsize(height = AAA, width = BBB)" }, { "code": null, "e": 26175, "s": 26152, "text": "title(“DESIRED TITLE”)" }, { "code": null, "e": 26183, "s": 26175, "text": "Python3" }, { "code": "from tkinter import * # rootroot = Tk() # designroot.geometry(\"300x300\")root.minsize(height=560)root.title(\"TKINter Program\") # executeroot.mainloop()", "e": 26337, "s": 26183, "text": null }, { "code": null, "e": 26345, "s": 26337, "text": "Output:" }, { "code": null, "e": 26552, "s": 26345, "text": "Notepad is one thing used commonly by every person who owns a desktop. It a shortcut tool to save important information in small notes, for temporary purposes, etc. Let’s make our own notepad using Tkinter." }, { "code": null, "e": 26612, "s": 26552, "text": "First, let’s type the basic code that we discussed earlier." }, { "code": null, "e": 26620, "s": 26612, "text": "Python3" }, { "code": "from tkinter import * # create root windowroot = Tk() # designroot.geometry(\"300x300\")root.minsize(height=560)root.title(\"Notepad\") # running the programroot.mainloop()", "e": 26792, "s": 26620, "text": null }, { "code": null, "e": 27092, "s": 26792, "text": "Okay so let’s think we will need a text function and a scroll bar to scroll through the text if it exceeds the dimensions of the window. Also, we learn about grid() and pack(). They are used to pack the functions in the window, without them the buttons, text, frames would not display in the window." }, { "code": null, "e": 27305, "s": 27092, "text": "Note: We can either use .grid() or .pack() for our program. However, using both in the same file would not work since Tkinter does not accept this, you obtain an error. You could use .pack() for efficient packing" }, { "code": null, "e": 27515, "s": 27305, "text": "Now let’s add a scrollbar: We shall invent a variable known as scrollbar and equate it to Scrollbar(root). It is important to add root into the brackets to integrate the scrollbar function into main root loop." }, { "code": null, "e": 27759, "s": 27515, "text": "Now let’s pack the scrollbar: We call the variable name and append it with “.pack(). We use side = RIGHT so that the scrollbar is added to the right of the window and fill = Y or fill = “y” (Use anyone) so that it fill across the whole y-axis." }, { "code": null, "e": 27767, "s": 27759, "text": "Python3" }, { "code": "from tkinter import * root = Tk()root.geometry(\"300x300\")root.minsize(height=560, width=560)root.title(\"Notepad\") # implementing scrollbar functionalityscrollbar = Scrollbar(root) # packing the scrollbar functionscrollbar.pack(side=RIGHT, fill=Y) root.mainloop()", "e": 28064, "s": 27767, "text": null }, { "code": null, "e": 28072, "s": 28064, "text": "Output:" }, { "code": null, "e": 28350, "s": 28072, "text": "Now let’s add the text: We will use the text function and pack it. Also, we will configure the scrollbar for functionality. We will add a command called “yscrollcommand” which will connect the text and scrollbar function together and it would add scrolling option for the text." }, { "code": null, "e": 28358, "s": 28350, "text": "Python3" }, { "code": "from tkinter import * root = Tk()root.geometry(\"350x250\")root.title(\"Sticky Notes\")root.minsize(height=250, width=350)root.maxsize(height=250, width=350) # adding scrollbarscrollbar = Scrollbar(root) # packing scrollbarscrollbar.pack(side=RIGHT, fill=Y) text_info = Text(root, yscrollcommand=scrollbar.set)text_info.pack(fill=BOTH) # configuring the scrollbarscrollbar.config(command=text_info.yview) root.mainloop()", "e": 28815, "s": 28358, "text": null }, { "code": null, "e": 28824, "s": 28815, "text": " Output:" }, { "code": null, "e": 28849, "s": 28824, "text": "Python Tkinter-exercises" }, { "code": null, "e": 28865, "s": 28849, "text": "Python-projects" }, { "code": null, "e": 28880, "s": 28865, "text": "Python-tkinter" }, { "code": null, "e": 28887, "s": 28880, "text": "Python" }, { "code": null, "e": 28985, "s": 28887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29017, "s": 28985, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29059, "s": 29017, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29115, "s": 29059, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29157, "s": 29115, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29179, "s": 29157, "text": "Defaultdict in Python" }, { "code": null, "e": 29210, "s": 29179, "text": "Python | os.path.join() method" }, { "code": null, "e": 29265, "s": 29210, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29304, "s": 29265, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29333, "s": 29304, "text": "Create a directory in Python" } ]
Design a Chess Game - GeeksforGeeks
30 Sep, 2020 Problem Statement: The problem is to design a Chess Game using Object Oriented Principles. Asked In: Adobe, Amazon, Microsoft, etc. Solution:These type of questions are asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all we should think about the classes. The main classes will be: Spot: A spot represents one block of the 8×8 grid and an optional piece.Piece: The basic building block of the system, every piece will be placed on a spot. Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations.Board: Board is an 8×8 set of boxes containing all active chess pieces.Player: Player class represents one of the participants playing the game.Move: Represents a game move, containing the starting and ending spot. The Move class will also keep track of the player who made the move.Game: This class controls the flow of a game. It keeps track of all the game moves, which player has the current turn, and the final result of the game.Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes.Spot: To represent a cell on the chess board:public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }}Piece: An abstract class to represent common functionality of all chess pieces:public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);}King: To represent King as a chess piece:public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }}Knight: To represent Knight as a chess piecepublic class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }}Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc.Board: To represent a chess board:public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception("Index out of bound"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }}Player: An abstract class for player, it can be a human or a computer.public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }}Move: To represent a chess move:public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }}public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION}Game: To represent a chess game:public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }}Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.htmlMy Personal Notes arrow_drop_upSave Spot: A spot represents one block of the 8×8 grid and an optional piece. Piece: The basic building block of the system, every piece will be placed on a spot. Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations. Board: Board is an 8×8 set of boxes containing all active chess pieces. Player: Player class represents one of the participants playing the game. Move: Represents a game move, containing the starting and ending spot. The Move class will also keep track of the player who made the move. Game: This class controls the flow of a game. It keeps track of all the game moves, which player has the current turn, and the final result of the game.Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes.Spot: To represent a cell on the chess board:public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }}Piece: An abstract class to represent common functionality of all chess pieces:public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);}King: To represent King as a chess piece:public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }}Knight: To represent Knight as a chess piecepublic class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }}Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc.Board: To represent a chess board:public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception("Index out of bound"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }}Player: An abstract class for player, it can be a human or a computer.public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }}Move: To represent a chess move:public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }}public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION}Game: To represent a chess game:public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }}Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.htmlMy Personal Notes arrow_drop_upSave Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes. Spot: To represent a cell on the chess board: public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }} Piece: An abstract class to represent common functionality of all chess pieces: public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);} King: To represent King as a chess piece: public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }} Knight: To represent Knight as a chess piece public class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }} Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc. Board: To represent a chess board: public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception("Index out of bound"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }} Player: An abstract class for player, it can be a human or a computer. public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }} Move: To represent a chess move: public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }} public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION} Game: To represent a chess game: public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }} Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.html shutovleonid Java-Object Oriented Marketing Object-Oriented-Design Advanced Data Structure Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Red-Black Tree | Set 3 (Delete) Difference between B tree and B+ tree Splay Tree | Set 1 (Search) Fibonacci Heap | Set 1 (Introduction) Pattern Searching using Suffix Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS A* Search Algorithm
[ { "code": null, "e": 24558, "s": 24530, "text": "\n30 Sep, 2020" }, { "code": null, "e": 24649, "s": 24558, "text": "Problem Statement: The problem is to design a Chess Game using Object Oriented Principles." }, { "code": null, "e": 24690, "s": 24649, "text": "Asked In: Adobe, Amazon, Microsoft, etc." }, { "code": null, "e": 24857, "s": 24690, "text": "Solution:These type of questions are asked in interviews to Judge the Object-Oriented Design skill of a candidate. So, first of all we should think about the classes." }, { "code": null, "e": 24883, "s": 24857, "text": "The main classes will be:" }, { "code": null, "e": 34449, "s": 24883, "text": "Spot: A spot represents one block of the 8×8 grid and an optional piece.Piece: The basic building block of the system, every piece will be placed on a spot. Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations.Board: Board is an 8×8 set of boxes containing all active chess pieces.Player: Player class represents one of the participants playing the game.Move: Represents a game move, containing the starting and ending spot. The Move class will also keep track of the player who made the move.Game: This class controls the flow of a game. It keeps track of all the game moves, which player has the current turn, and the final result of the game.Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes.Spot: To represent a cell on the chess board:public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }}Piece: An abstract class to represent common functionality of all chess pieces:public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);}King: To represent King as a chess piece:public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }}Knight: To represent Knight as a chess piecepublic class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }}Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc.Board: To represent a chess board:public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception(\"Index out of bound\"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }}Player: An abstract class for player, it can be a human or a computer.public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }}Move: To represent a chess move:public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }}public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION}Game: To represent a chess game:public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }}Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34522, "s": 34449, "text": "Spot: A spot represents one block of the 8×8 grid and an optional piece." }, { "code": null, "e": 34742, "s": 34522, "text": "Piece: The basic building block of the system, every piece will be placed on a spot. Piece class is an abstract class. The extended classes (Pawn, King, Queen, Rook, Knight, Bishop) implements the abstracted operations." }, { "code": null, "e": 34814, "s": 34742, "text": "Board: Board is an 8×8 set of boxes containing all active chess pieces." }, { "code": null, "e": 34888, "s": 34814, "text": "Player: Player class represents one of the participants playing the game." }, { "code": null, "e": 35028, "s": 34888, "text": "Move: Represents a game move, containing the starting and ending spot. The Move class will also keep track of the player who made the move." }, { "code": null, "e": 44020, "s": 35028, "text": "Game: This class controls the flow of a game. It keeps track of all the game moves, which player has the current turn, and the final result of the game.Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes.Spot: To represent a cell on the chess board:public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }}Piece: An abstract class to represent common functionality of all chess pieces:public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);}King: To represent King as a chess piece:public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }}Knight: To represent Knight as a chess piecepublic class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }}Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc.Board: To represent a chess board:public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception(\"Index out of bound\"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }}Player: An abstract class for player, it can be a human or a computer.public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }}Move: To represent a chess move:public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }}public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION}Game: To represent a chess game:public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }}Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 44163, "s": 44020, "text": "Let’s look at the details. These codes are self-explanatory. You can have a look at the properties/variables and methods of different classes." }, { "code": null, "e": 44209, "s": 44163, "text": "Spot: To represent a cell on the chess board:" }, { "code": "public class Spot { private Piece piece; private int x; private int y; public Spot(int x, int y, Piece piece) { this.setPiece(piece); this.setX(x); this.setY(y); } public Piece getPiece() { return this.piece; } public void setPiece(Piece p) { this.piece = p; } public int getX() { return this.x; } public void setX(int x) { this.x = x; } public int getY() { return this.y; } public void setY(int y) { this.y = y; }}", "e": 44774, "s": 44209, "text": null }, { "code": null, "e": 44854, "s": 44774, "text": "Piece: An abstract class to represent common functionality of all chess pieces:" }, { "code": "public abstract class Piece { private boolean killed = false; private boolean white = false; public Piece(boolean white) { this.setWhite(white); } public boolean isWhite() { return this.white; } public void setWhite(boolean white) { this.white = white; } public boolean isKilled() { return this.killed; } public void setKilled(boolean killed) { this.killed = killed; } public abstract boolean canMove(Board board, Spot start, Spot end);}", "e": 45428, "s": 44854, "text": null }, { "code": null, "e": 45470, "s": 45428, "text": "King: To represent King as a chess piece:" }, { "code": "public class King extends Piece { private boolean castlingDone = false; public King(boolean white) { super(white); } public boolean isCastlingDone() { return this.castlingDone; } public void setCastlingDone(boolean castlingDone) { this.castlingDone = castlingDone; } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a Spot that // has a piece of the same color if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); if (x + y == 1) { // check if this move will not result in the king // being attacked if so return true return true; } return this.isValidCastling(board, start, end); } private boolean isValidCastling(Board board, Spot start, Spot end) { if (this.isCastlingDone()) { return false; } // Logic for returning true or false } public boolean isCastlingMove(Spot start, Spot end) { // check if the starting and // ending position are correct }}", "e": 46770, "s": 45470, "text": null }, { "code": null, "e": 46815, "s": 46770, "text": "Knight: To represent Knight as a chess piece" }, { "code": "public class Knight extends Piece { public Knight(boolean white) { super(white); } @Override public boolean canMove(Board board, Spot start, Spot end) { // we can't move the piece to a spot that has // a piece of the same colour if (end.getPiece().isWhite() == this.isWhite()) { return false; } int x = Math.abs(start.getX() - end.getX()); int y = Math.abs(start.getY() - end.getY()); return x * y == 2; }}", "e": 47358, "s": 46815, "text": null }, { "code": null, "e": 47447, "s": 47358, "text": "Similarly, we can create classes for other pieces like Queen, Pawns, Rooks, Bishops etc." }, { "code": null, "e": 47482, "s": 47447, "text": "Board: To represent a chess board:" }, { "code": "public class Board { Spot[][] boxes; public Board() { this.resetBoard(); } public Spot getBox(int x, int y) { if (x < 0 || x > 7 || y < 0 || y > 7) { throw new Exception(\"Index out of bound\"); } return boxes[x][y]; } public void resetBoard() { // initialize white pieces boxes[0][0] = new Spot(0, 0, new Rook(true)); boxes[0][1] = new Spot(0, 1, new Knight(true)); boxes[0][2] = new Spot(0, 2, new Bishop(true)); //... boxes[1][0] = new Spot(1, 0, new Pawn(true)); boxes[1][1] = new Spot(1, 1, new Pawn(true)); //... // initialize black pieces boxes[7][0] = new Spot(7, 0, new Rook(false)); boxes[7][1] = new Spot(7, 1, new Knight(false)); boxes[7][2] = new Spot(7, 2, new Bishop(false)); //... boxes[6][0] = new Spot(6, 0, new Pawn(false)); boxes[6][1] = new Spot(6, 1, new Pawn(false)); //... // initialize remaining boxes without any piece for (int i = 2; i < 6; i++) { for (int j = 0; j < 8; j++) { boxes[i][j] = new Spot(i, j, null); } } }}", "e": 48681, "s": 47482, "text": null }, { "code": null, "e": 48752, "s": 48681, "text": "Player: An abstract class for player, it can be a human or a computer." }, { "code": "public abstract class Player { public boolean whiteSide; public boolean humanPlayer; public boolean isWhiteSide() { return this.whiteSide; } public boolean isHumanPlayer() { return this.humanPlayer; }} public class HumanPlayer extends Player { public HumanPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = true; }} public class ComputerPlayer extends Player { public ComputerPlayer(boolean whiteSide) { this.whiteSide = whiteSide; this.humanPlayer = false; }}", "e": 49329, "s": 48752, "text": null }, { "code": null, "e": 49362, "s": 49329, "text": "Move: To represent a chess move:" }, { "code": "public class Move { private Player player; private Spot start; private Spot end; private Piece pieceMoved; private Piece pieceKilled; private boolean castlingMove = false; public Move(Player player, Spot start, Spot end) { this.player = player; this.start = start; this.end = end; this.pieceMoved = start.getPiece(); } public boolean isCastlingMove() { return this.castlingMove; } public void setCastlingMove(boolean castlingMove) { this.castlingMove = castlingMove; }}", "e": 49925, "s": 49362, "text": null }, { "code": "public enum GameStatus { ACTIVE, BLACK_WIN, WHITE_WIN, FORFEIT, STALEMATE, RESIGNATION}", "e": 50031, "s": 49925, "text": null }, { "code": null, "e": 50064, "s": 50031, "text": "Game: To represent a chess game:" }, { "code": "public class Game { private Player[] players; private Board board; private Player currentTurn; private GameStatus status; private List<Move> movesPlayed; private void initialize(Player p1, Player p2) { players[0] = p1; players[1] = p2; board.resetBoard(); if (p1.isWhiteSide()) { this.currentTurn = p1; } else { this.currentTurn = p2; } movesPlayed.clear(); } public boolean isEnd() { return this.getStatus() != GameStatus.ACTIVE; } public boolean getStatus() { return this.status; } public void setStatus(GameStatus status) { this.status = status; } public boolean playerMove(Player player, int startX, int startY, int endX, int endY) { Spot startBox = board.getBox(startX, startY); Spot endBox = board.getBox(startY, endY); Move move = new Move(player, startBox, endBox); return this.makeMove(move, player); } private boolean makeMove(Move move, Player player) { Piece sourcePiece = move.getStart().getPiece(); if (sourcePiece == null) { return false; } // valid player if (player != currentTurn) { return false; } if (sourcePiece.isWhite() != player.isWhiteSide()) { return false; } // valid move? if (!sourcePiece.canMove(board, move.getStart(), move.getEnd())) { return false; } // kill? Piece destPiece = move.getStart().getPiece(); if (destPiece != null) { destPiece.setKilled(true); move.setPieceKilled(destPiece); } // castling? if (sourcePiece != null && sourcePiece instanceof King && sourcePiece.isCastlingMove()) { move.setCastlingMove(true); } // store the move movesPlayed.add(move); // move piece from the stat box to end box move.getEnd().setPiece(move.getStart().getPiece()); move.getStart.setPiece(null); if (destPiece != null && destPiece instanceof King) { if (player.isWhiteSide()) { this.setStatus(GameStatus.WHITE_WIN); } else { this.setStatus(GameStatus.BLACK_WIN); } } // set the current turn to the other player if (this.currentTurn == players[0]) { this.currentTurn = players[1]; } else { this.currentTurn = players[0]; } return true; }}", "e": 52741, "s": 50064, "text": null }, { "code": null, "e": 52844, "s": 52741, "text": "Reference: http://massivetechinterview.blogspot.com/2015/07/design-chess-game-using-oo-principles.html" }, { "code": null, "e": 52857, "s": 52844, "text": "shutovleonid" }, { "code": null, "e": 52878, "s": 52857, "text": "Java-Object Oriented" }, { "code": null, "e": 52888, "s": 52878, "text": "Marketing" }, { "code": null, "e": 52911, "s": 52888, "text": "Object-Oriented-Design" }, { "code": null, "e": 52935, "s": 52911, "text": "Advanced Data Structure" }, { "code": null, "e": 52946, "s": 52935, "text": "Algorithms" }, { "code": null, "e": 52957, "s": 52946, "text": "Algorithms" }, { "code": null, "e": 53055, "s": 52957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53087, "s": 53055, "text": "Red-Black Tree | Set 3 (Delete)" }, { "code": null, "e": 53125, "s": 53087, "text": "Difference between B tree and B+ tree" }, { "code": null, "e": 53153, "s": 53125, "text": "Splay Tree | Set 1 (Search)" }, { "code": null, "e": 53191, "s": 53153, "text": "Fibonacci Heap | Set 1 (Introduction)" }, { "code": null, "e": 53227, "s": 53191, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 53276, "s": 53227, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 53320, "s": 53276, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 53345, "s": 53320, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 53376, "s": 53345, "text": "Difference between BFS and DFS" } ]
Image processing/OpenCV image dilation Java Example.
Erosion and dilation are the two basic morphological operations. As the name implies, morphological operations are the set of operations that process images according to their shapes. During dilation operation additional pixels are added to an image boundary, a total number of pixels added during the dilation process depends on the dimensions of the structuring element used. You can dilate an image using the dilate() method of the Imgproc class, this method three mat objects representing source, destination, and kernel. import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.stage.Stage; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class ImageDilation extends Application { public void start(Stage stage) throws IOException { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading image data String file ="D:\\Images\\lamma2.jpg"; Mat src = Imgcodecs.imread(file); //Creating destination matrix Mat dst = new Mat(src.rows(), src.cols(), src.type()); //Preparing the kernel matrix object Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((2*2) + 1, (2*2)+1)); //Applying dilate on the Image Imgproc.dilate(src, dst, kernel); //Converting matrix to JavaFX writable image Image img = HighGui.toBufferedImage(dst); WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null); //Setting the image view ImageView imageView = new ImageView(writableImage); imageView.setX(10); imageView.setY(10); imageView.setFitWidth(575); imageView.setPreserveRatio(true); //Setting the Scene object Group root = new Group(imageView); Scene scene = new Scene(root, 595, 400); stage.setTitle("Dilation Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } On executing, above example generates the following output −
[ { "code": null, "e": 1246, "s": 1062, "text": "Erosion and dilation are the two basic morphological operations. As the name\nimplies, morphological operations are the set of operations that process images\naccording to their shapes." }, { "code": null, "e": 1440, "s": 1246, "text": "During dilation operation additional pixels are added to an image boundary, a total number of pixels added during the dilation process depends on the dimensions of the structuring element used." }, { "code": null, "e": 1588, "s": 1440, "text": "You can dilate an image using the dilate() method of the Imgproc class, this method three mat objects representing source, destination, and kernel." }, { "code": null, "e": 3424, "s": 1588, "text": "import java.awt.Image;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport javafx.application.Application;\nimport javafx.embed.swing.SwingFXUtils;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.image.WritableImage;\nimport javafx.stage.Stage;\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.Size;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class ImageDilation extends Application {\n public void start(Stage stage) throws IOException {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\lamma2.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Preparing the kernel matrix object\n Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size((2*2) + 1, (2*2)+1));\n //Applying dilate on the Image\n Imgproc.dilate(src, dst, kernel);\n //Converting matrix to JavaFX writable image\n Image img = HighGui.toBufferedImage(dst);\n WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);\n //Setting the image view\n ImageView imageView = new ImageView(writableImage);\n imageView.setX(10);\n imageView.setY(10);\n imageView.setFitWidth(575);\n imageView.setPreserveRatio(true);\n //Setting the Scene object\n Group root = new Group(imageView);\n Scene scene = new Scene(root, 595, 400);\n stage.setTitle(\"Dilation Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 3485, "s": 3424, "text": "On executing, above example generates the following output −" } ]
strictfp keyword in java
26 Sep, 2021 strictfp is a modifier that stands for strict floating-point which was not introduced in the base version of java as it was introduced in Java version 1.2. It is used in java for restricting floating-point calculations and ensuring the same result on every platform while performing operations in the floating-point variable. Floating-point calculations are platform-dependent i.e. different output(floating-point values) is achieved when a class file is run on different platforms(16/32/64 bit processors). To solve this type of issue, strictfp keyword was introduced in JDK 1.2 version by following IEEE 754 standards for floating-point calculations. Note: strictfp modifier is used with classes, interfaces, and methods only but is not applicable to apply with variables as illustrated below: Illustration 1: Keyword usage with classes strictfp class Test { // All concrete methods here are implicitly strictfp. } Illustration 2: Keyword usage with Interfaces strictfp interface Test { // All methods here becomes implicitly // strictfp when used during inheritance. } class Car { // strictfp applied on a concrete method strictfp void calculateSpeed(){} } Illustration 3: Keyword usage with variables strictfp interface Test { double sum(); // Compile-time error here strictfp double mul(); } Some conclusions can be drawn from the above illustrations as follows: When a class or an interface is declared with strictfp modifier, then all methods declared in the class/interface, and all nested types declared in the class, are implicitly strictfp. strictfp cannot be used with abstract methods. However, it can be used with abstract classes/interfaces. Since methods of an interface are implicitly abstract, strictfp cannot be used with any method inside an interface. Example Java // Java program to illustrate strictfp modifier// Usage in Classes // Main classclass GFG { // Method 1 // Calculating sum using strictfp modifier public strictfp double sum() { double num1 = 10e+10; double num2 = 6e+08; // Returning the sum return (num1 + num2); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG t = new GFG(); // Here we have error of putting strictfp and // error is not found public static void main method System.out.println(t.sum()); }} Output: This article is contributed by Gaurav Miglani. 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. sonimihir07 sooda367 Java-keyword Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Sep, 2021" }, { "code": null, "e": 708, "s": 54, "text": "strictfp is a modifier that stands for strict floating-point which was not introduced in the base version of java as it was introduced in Java version 1.2. It is used in java for restricting floating-point calculations and ensuring the same result on every platform while performing operations in the floating-point variable. Floating-point calculations are platform-dependent i.e. different output(floating-point values) is achieved when a class file is run on different platforms(16/32/64 bit processors). To solve this type of issue, strictfp keyword was introduced in JDK 1.2 version by following IEEE 754 standards for floating-point calculations. " }, { "code": null, "e": 851, "s": 708, "text": "Note: strictfp modifier is used with classes, interfaces, and methods only but is not applicable to apply with variables as illustrated below:" }, { "code": null, "e": 895, "s": 851, "text": "Illustration 1: Keyword usage with classes " }, { "code": null, "e": 985, "s": 895, "text": "strictfp class Test {\n \n // All concrete methods here are implicitly strictfp. \n}" }, { "code": null, "e": 1032, "s": 985, "text": "Illustration 2: Keyword usage with Interfaces " }, { "code": null, "e": 1270, "s": 1032, "text": "strictfp interface Test {\n \n // All methods here becomes implicitly \n // strictfp when used during inheritance. \n}\n\nclass Car {\n \n // strictfp applied on a concrete method \n strictfp void calculateSpeed(){}\n} " }, { "code": null, "e": 1315, "s": 1270, "text": "Illustration 3: Keyword usage with variables" }, { "code": null, "e": 1425, "s": 1315, "text": "strictfp interface Test {\n double sum();\n \n // Compile-time error here\n strictfp double mul(); \n}" }, { "code": null, "e": 1496, "s": 1425, "text": "Some conclusions can be drawn from the above illustrations as follows:" }, { "code": null, "e": 1680, "s": 1496, "text": "When a class or an interface is declared with strictfp modifier, then all methods declared in the class/interface, and all nested types declared in the class, are implicitly strictfp." }, { "code": null, "e": 1785, "s": 1680, "text": "strictfp cannot be used with abstract methods. However, it can be used with abstract classes/interfaces." }, { "code": null, "e": 1901, "s": 1785, "text": "Since methods of an interface are implicitly abstract, strictfp cannot be used with any method inside an interface." }, { "code": null, "e": 1910, "s": 1901, "text": "Example " }, { "code": null, "e": 1915, "s": 1910, "text": "Java" }, { "code": "// Java program to illustrate strictfp modifier// Usage in Classes // Main classclass GFG { // Method 1 // Calculating sum using strictfp modifier public strictfp double sum() { double num1 = 10e+10; double num2 = 6e+08; // Returning the sum return (num1 + num2); } // Method 2 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG t = new GFG(); // Here we have error of putting strictfp and // error is not found public static void main method System.out.println(t.sum()); }}", "e": 2550, "s": 1915, "text": null }, { "code": null, "e": 2559, "s": 2550, "text": "Output: " }, { "code": null, "e": 2982, "s": 2559, "text": "This article is contributed by Gaurav Miglani. 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": 2994, "s": 2982, "text": "sonimihir07" }, { "code": null, "e": 3003, "s": 2994, "text": "sooda367" }, { "code": null, "e": 3016, "s": 3003, "text": "Java-keyword" }, { "code": null, "e": 3029, "s": 3016, "text": "Java-Library" }, { "code": null, "e": 3034, "s": 3029, "text": "Java" }, { "code": null, "e": 3039, "s": 3034, "text": "Java" }, { "code": null, "e": 3137, "s": 3039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3188, "s": 3137, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3219, "s": 3188, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3238, "s": 3219, "text": "Interfaces in Java" }, { "code": null, "e": 3268, "s": 3238, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3286, "s": 3268, "text": "ArrayList in Java" }, { "code": null, "e": 3306, "s": 3286, "text": "Collections in Java" }, { "code": null, "e": 3338, "s": 3306, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3362, "s": 3338, "text": "Singleton Class in Java" }, { "code": null, "e": 3374, "s": 3362, "text": "Set in Java" } ]
How to format Phone Numbers in PHP ?
25 May, 2021 In this article, we will learn how to format phone numbers using PHP. When we need to store a phone number then we store the formatting phone number. Using PHP, we can easily format phone numbers. Approach: In this article, we will format the phone number using the preg_match() method. We can use this method to format phone numbers. This function has special characteristics of finding specified patterns from string. PHP code: The following is the complete code to format phone numbers using preg_match(). PHP <?php // Create a formatting functionfunction formatting($phone){ // Pass phone number in preg_match function if(preg_match( '/^\+[0-9]([0-9]{3})([0-9]{3})([0-9]{4})$/', $phone, $value)) { // Store value in format variable $format = $value[1] . '-' . $value[2] . '-' . $value[3]; } else { // If given number is invalid echo "Invalid phone number <br>"; } // Print the given format echo("$format" . "<br>");} // Call the functionformatting("+02025550170"); formatting("+01677942758");?> Output: 202-555-0170 167-794-2758 PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to delete an array element based on key in PHP? How to convert array to string in PHP ? 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": "\n25 May, 2021" }, { "code": null, "e": 225, "s": 28, "text": "In this article, we will learn how to format phone numbers using PHP. When we need to store a phone number then we store the formatting phone number. Using PHP, we can easily format phone numbers." }, { "code": null, "e": 449, "s": 225, "text": "Approach: In this article, we will format the phone number using the preg_match() method. We can use this method to format phone numbers. This function has special characteristics of finding specified patterns from string. " }, { "code": null, "e": 538, "s": 449, "text": "PHP code: The following is the complete code to format phone numbers using preg_match()." }, { "code": null, "e": 542, "s": 538, "text": "PHP" }, { "code": "<?php // Create a formatting functionfunction formatting($phone){ // Pass phone number in preg_match function if(preg_match( '/^\\+[0-9]([0-9]{3})([0-9]{3})([0-9]{4})$/', $phone, $value)) { // Store value in format variable $format = $value[1] . '-' . $value[2] . '-' . $value[3]; } else { // If given number is invalid echo \"Invalid phone number <br>\"; } // Print the given format echo(\"$format\" . \"<br>\");} // Call the functionformatting(\"+02025550170\"); formatting(\"+01677942758\");?>", "e": 1131, "s": 542, "text": null }, { "code": null, "e": 1139, "s": 1131, "text": "Output:" }, { "code": null, "e": 1165, "s": 1139, "text": "202-555-0170\n167-794-2758" }, { "code": null, "e": 1178, "s": 1165, "text": "PHP-function" }, { "code": null, "e": 1192, "s": 1178, "text": "PHP-Questions" }, { "code": null, "e": 1199, "s": 1192, "text": "Picked" }, { "code": null, "e": 1203, "s": 1199, "text": "PHP" }, { "code": null, "e": 1220, "s": 1203, "text": "Web Technologies" }, { "code": null, "e": 1224, "s": 1220, "text": "PHP" }, { "code": null, "e": 1322, "s": 1224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1367, "s": 1322, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 1417, "s": 1367, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1441, "s": 1417, "text": "PHP in_array() Function" }, { "code": null, "e": 1493, "s": 1441, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 1533, "s": 1493, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1595, "s": 1533, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1628, "s": 1595, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1689, "s": 1628, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1739, "s": 1689, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Adding new column to existing DataFrame in Pandas
Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list and series etc. In this article we will see how to add a new column to an existing data frame. So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no. Live Demo import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) print (df) Running the above code gives us the following result: Month_No 0 6 1 8 2 3 3 1 4 12 We can use the insert() function of pandas which will insert the column at the position specified by its index. Below we add No of Days in a month as a column to the existing pandas DataFrame at index position 1. Live Demo import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) # Insert the new column at position 1. df.insert(1,"No_of_days",[30,31,31,31,31],True) print (df) Running the above code gives us the following result − Month_No No_of_days 0 6 30 1 8 31 2 3 31 3 1 31 4 12 31 The assign() function Live Demo import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) # Insert a column at the end df = df.assign(No_of_days = [30,31,31,31,31]) print (df) Running the above code gives us the following result − Month_No No_of_days 0 6 30 1 8 31 2 3 31 3 1 31 4 12 31
[ { "code": null, "e": 1619, "s": 1187, "text": "Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list and series etc. In this article we will see how to add a new column to an existing data frame.\nSo first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no." }, { "code": null, "e": 1630, "s": 1619, "text": " Live Demo" }, { "code": null, "e": 1731, "s": 1630, "text": "import pandas as pd\ns = pd.Series([6,8,3,1,12])\ndf = pd.DataFrame(s,columns=['Month_No'])\nprint (df)" }, { "code": null, "e": 1785, "s": 1731, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 1848, "s": 1785, "text": " Month_No\n0 6\n1 8\n2 3\n3 1\n4 12" }, { "code": null, "e": 2061, "s": 1848, "text": "We can use the insert() function of pandas which will insert the column at the position specified by its index. Below we add No of Days in a month as a column to the existing pandas DataFrame at index position 1." }, { "code": null, "e": 2072, "s": 2061, "text": " Live Demo" }, { "code": null, "e": 2261, "s": 2072, "text": "import pandas as pd\ns = pd.Series([6,8,3,1,12])\ndf = pd.DataFrame(s,columns=['Month_No'])\n\n# Insert the new column at position 1.\ndf.insert(1,\"No_of_days\",[30,31,31,31,31],True)\nprint (df)" }, { "code": null, "e": 2316, "s": 2261, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2434, "s": 2316, "text": " Month_No No_of_days\n0 6 30\n1 8 31\n2 3 31\n3 1 31\n4 12 31" }, { "code": null, "e": 2456, "s": 2434, "text": "The assign() function" }, { "code": null, "e": 2467, "s": 2456, "text": " Live Demo" }, { "code": null, "e": 2645, "s": 2467, "text": "import pandas as pd\ns = pd.Series([6,8,3,1,12])\ndf = pd.DataFrame(s,columns=['Month_No'])\n\n# Insert a column at the end\ndf = df.assign(No_of_days = [30,31,31,31,31])\n\nprint (df)" }, { "code": null, "e": 2700, "s": 2645, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2818, "s": 2700, "text": " Month_No No_of_days\n0 6 30\n1 8 31\n2 3 31\n3 1 31\n4 12 31" } ]
Minimum rooms for m events of n batches with given schedule
01 Jun, 2021 There are n student groups at the school. On each day in school, there are m time slots. A student group may or may not be free during a time slot. We are given n binary string where each binary string is of length m. A character at j-th position in i-th string is 0 if i-th group is free in j-th slot and 1 if i-th group is busy. Our task is to determine the minimum number of rooms needed to hold classes for all groups on a single study day. Note that one room can hold at most one group class in a single time slot.Examples: Input : n = 2, m = 7, slots[] = {“0101010”, “1010101”} Output : 1 Explanation : Both group can hold their classes in a single room as they have alternative classes.Input : n = 3, m = 7, slots[] = {“0101011”, “0011001”, “0110111”} Output : 3 Approach used: Here we traverse through each character of strings we have and while traversing maintaining a count of the number of 1’s at each position of the strings and hence we know the number of coinciding classes at each particular time slot. Then we just need to find the maximum number of coinciding classes amongst all time slots. C++ Java Python3 C# PHP Javascript // CPP program to find minimum number of rooms// required#include <bits/stdc++.h>using namespace std; // Returns minimum number of rooms required// to perform classes of n groups in m slots// with given schedule.int findMinRooms(string slots[], int n, int m){ // Store count of classes happening in // every slot. int counts[m] = { 0 }; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. return *max_element(counts, counts+m); } // Driver Codeint main(){ int n = 3, m = 7; string slots[n] = { "0101011", "0011001", "0110111" }; cout << findMinRooms(slots, n, m); return 0;} // java program to find the minimum number// of rooms requiredclass GFG { // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. static int findMinRooms(String slots[], int n, int m) { // Store number of class happening in //empty slot int counts[] = new int[m]; //initialize all values to zero for (int i = 0; i < m; i++) counts[i] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i].charAt(j) == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. int max = -1; // find the max element for (int i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // Driver Code public static void main(String args[]) { int n = 3, m = 7; String slots[] = { "0101011", "0011001", "0110111" }; System.out.println( findMinRooms(slots, n, m)); }} // This code is contributed by Arnab Kundu. # Python3 program to find minimum# number of rooms required # Returns minimum number of# rooms required to perform# classes of n groups in m# slots with given schedule.def findMinRooms(slots, n, m): # Store count of classes # happening in every slot. counts = [0] * m; for i in range(n): for j in range(m): if (slots[i][j] == '1'): counts[j] += 1; # Number of rooms required is # equal to maximum classes # happening in a particular slot. return max(counts); # Driver Coden = 3;m = 7;slots = ["0101011", "0011001", "0110111"];print(findMinRooms(slots, n, m)); # This code is contributed by mits // C# program to find the minimum number// of rooms requiredusing System;class GFG { // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. static int findMinRooms(string []slots, int n, int m) { // Store number of class happening in //empty slot int []counts = new int[m]; //initialize all values to zero for (int i = 0; i < m; i++) counts[i] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. int max = -1; // find the max element for (int i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // Driver Code public static void Main() { int n = 3, m = 7; String []slots = { "0101011", "0011001", "0110111" }; Console.Write( findMinRooms(slots, n, m)); }} // This code is contributed by nitin mittal <?php// PHP program to find minimum// number of rooms required // Returns minimum number of// rooms required to perform// classes of n groups in m// slots with given schedule.function findMinRooms($slots, $n, $m){ // Store count of classes // happening in every slot. $counts = array_fill(0, $m, 0); for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) if ($slots[$i][$j] == '1') $counts[$j]++; // Number of rooms required is // equal to maximum classes // happening in a particular slot. return max($counts); } // Driver Code$n = 3;$m = 7;$slots = array("0101011", "0011001", "0110111");echo findMinRooms($slots, $n, $m); // This code is contributed by mits?> <script> // Javascript program to find the minimum number// of rooms required // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. function findMinRooms(slots, n, m) { // Store number of class happening in //empty slot let counts = Array(m).fill(0); //initialize all values to zero for (let i = 0; i < m; i++) counts[i] = 0; for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. let max = -1; // find the max element for (let i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // driver code let n = 3, m = 7; let slots = [ "0101011", "0011001", "0110111" ]; document.write( findMinRooms(slots, n, m)); </script> 3 Time Complexity: O(m * n) Auxiliary Space: O(m) andrew1234 nitin mittal Mithun Kumar avijitmondal1998 arorakashish0911 binary-string Arrays Greedy Strings Arrays Strings Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Program for array rotation Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Minimum Number of Platforms Required for a Railway/Bus Station
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Jun, 2021" }, { "code": null, "e": 584, "s": 53, "text": "There are n student groups at the school. On each day in school, there are m time slots. A student group may or may not be free during a time slot. We are given n binary string where each binary string is of length m. A character at j-th position in i-th string is 0 if i-th group is free in j-th slot and 1 if i-th group is busy. Our task is to determine the minimum number of rooms needed to hold classes for all groups on a single study day. Note that one room can hold at most one group class in a single time slot.Examples: " }, { "code": null, "e": 827, "s": 584, "text": "Input : n = 2, m = 7, slots[] = {“0101010”, “1010101”} Output : 1 Explanation : Both group can hold their classes in a single room as they have alternative classes.Input : n = 3, m = 7, slots[] = {“0101011”, “0011001”, “0110111”} Output : 3 " }, { "code": null, "e": 1170, "s": 829, "text": "Approach used: Here we traverse through each character of strings we have and while traversing maintaining a count of the number of 1’s at each position of the strings and hence we know the number of coinciding classes at each particular time slot. Then we just need to find the maximum number of coinciding classes amongst all time slots. " }, { "code": null, "e": 1174, "s": 1170, "text": "C++" }, { "code": null, "e": 1179, "s": 1174, "text": "Java" }, { "code": null, "e": 1187, "s": 1179, "text": "Python3" }, { "code": null, "e": 1190, "s": 1187, "text": "C#" }, { "code": null, "e": 1194, "s": 1190, "text": "PHP" }, { "code": null, "e": 1205, "s": 1194, "text": "Javascript" }, { "code": "// CPP program to find minimum number of rooms// required#include <bits/stdc++.h>using namespace std; // Returns minimum number of rooms required// to perform classes of n groups in m slots// with given schedule.int findMinRooms(string slots[], int n, int m){ // Store count of classes happening in // every slot. int counts[m] = { 0 }; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. return *max_element(counts, counts+m); } // Driver Codeint main(){ int n = 3, m = 7; string slots[n] = { \"0101011\", \"0011001\", \"0110111\" }; cout << findMinRooms(slots, n, m); return 0;}", "e": 2051, "s": 1205, "text": null }, { "code": "// java program to find the minimum number// of rooms requiredclass GFG { // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. static int findMinRooms(String slots[], int n, int m) { // Store number of class happening in //empty slot int counts[] = new int[m]; //initialize all values to zero for (int i = 0; i < m; i++) counts[i] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i].charAt(j) == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. int max = -1; // find the max element for (int i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // Driver Code public static void main(String args[]) { int n = 3, m = 7; String slots[] = { \"0101011\", \"0011001\", \"0110111\" }; System.out.println( findMinRooms(slots, n, m)); }} // This code is contributed by Arnab Kundu.", "e": 3363, "s": 2051, "text": null }, { "code": "# Python3 program to find minimum# number of rooms required # Returns minimum number of# rooms required to perform# classes of n groups in m# slots with given schedule.def findMinRooms(slots, n, m): # Store count of classes # happening in every slot. counts = [0] * m; for i in range(n): for j in range(m): if (slots[i][j] == '1'): counts[j] += 1; # Number of rooms required is # equal to maximum classes # happening in a particular slot. return max(counts); # Driver Coden = 3;m = 7;slots = [\"0101011\", \"0011001\", \"0110111\"];print(findMinRooms(slots, n, m)); # This code is contributed by mits", "e": 4021, "s": 3363, "text": null }, { "code": "// C# program to find the minimum number// of rooms requiredusing System;class GFG { // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. static int findMinRooms(string []slots, int n, int m) { // Store number of class happening in //empty slot int []counts = new int[m]; //initialize all values to zero for (int i = 0; i < m; i++) counts[i] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. int max = -1; // find the max element for (int i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // Driver Code public static void Main() { int n = 3, m = 7; String []slots = { \"0101011\", \"0011001\", \"0110111\" }; Console.Write( findMinRooms(slots, n, m)); }} // This code is contributed by nitin mittal", "e": 5328, "s": 4021, "text": null }, { "code": "<?php// PHP program to find minimum// number of rooms required // Returns minimum number of// rooms required to perform// classes of n groups in m// slots with given schedule.function findMinRooms($slots, $n, $m){ // Store count of classes // happening in every slot. $counts = array_fill(0, $m, 0); for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) if ($slots[$i][$j] == '1') $counts[$j]++; // Number of rooms required is // equal to maximum classes // happening in a particular slot. return max($counts); } // Driver Code$n = 3;$m = 7;$slots = array(\"0101011\", \"0011001\", \"0110111\");echo findMinRooms($slots, $n, $m); // This code is contributed by mits?>", "e": 6086, "s": 5328, "text": null }, { "code": "<script> // Javascript program to find the minimum number// of rooms required // Returns minimum number of rooms required // to perform classes of n groups in m slots // with given schedule. function findMinRooms(slots, n, m) { // Store number of class happening in //empty slot let counts = Array(m).fill(0); //initialize all values to zero for (let i = 0; i < m; i++) counts[i] = 0; for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) if (slots[i][j] == '1') counts[j]++; // Number of rooms required is equal to // maximum classes happening in a // particular slot. let max = -1; // find the max element for (let i = 0; i < m; i++) if(max < counts[i]) max = counts[i]; return max; } // driver code let n = 3, m = 7; let slots = [ \"0101011\", \"0011001\", \"0110111\" ]; document.write( findMinRooms(slots, n, m)); </script>", "e": 7264, "s": 6086, "text": null }, { "code": null, "e": 7266, "s": 7264, "text": "3" }, { "code": null, "e": 7317, "s": 7268, "text": "Time Complexity: O(m * n) Auxiliary Space: O(m) " }, { "code": null, "e": 7328, "s": 7317, "text": "andrew1234" }, { "code": null, "e": 7341, "s": 7328, "text": "nitin mittal" }, { "code": null, "e": 7354, "s": 7341, "text": "Mithun Kumar" }, { "code": null, "e": 7371, "s": 7354, "text": "avijitmondal1998" }, { "code": null, "e": 7388, "s": 7371, "text": "arorakashish0911" }, { "code": null, "e": 7402, "s": 7388, "text": "binary-string" }, { "code": null, "e": 7409, "s": 7402, "text": "Arrays" }, { "code": null, "e": 7416, "s": 7409, "text": "Greedy" }, { "code": null, "e": 7424, "s": 7416, "text": "Strings" }, { "code": null, "e": 7431, "s": 7424, "text": "Arrays" }, { "code": null, "e": 7439, "s": 7431, "text": "Strings" }, { "code": null, "e": 7446, "s": 7439, "text": "Greedy" }, { "code": null, "e": 7544, "s": 7446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7559, "s": 7544, "text": "Arrays in Java" }, { "code": null, "e": 7605, "s": 7559, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7673, "s": 7605, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7717, "s": 7673, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7749, "s": 7717, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 7776, "s": 7749, "text": "Program for array rotation" }, { "code": null, "e": 7836, "s": 7776, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7855, "s": 7836, "text": "Coin Change | DP-7" }, { "code": null, "e": 7936, "s": 7855, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" } ]
cupsd command in Linux with examples
15 May, 2019 cupsd is a type of scheduler for CUPS (Common Unit Printing System). It implements the printing system on the basis of the Internet Printing Protocol(Version 2.1). If no options is being specified on the command-line then the default configuration file /etc/cups/cupsd.conf will be automatically be used. Installation:To install the CUPS in your Linux machine, simply use the sudo command with the apt. A complete CUPS package installation has many package dependencies, but they can all be specified on the same command line. Enter the following command on the terminal: sudo apt install cups Once authenticated with your username and password, the packages must be downloaded and installed without error. As the conclusion of the installation, the CUPS server will be going to start automatically by default. Syntax: cupsd [ -c config-file ] [ -f ] [ -F ] [ -h ] [ -l ] [ -t ] Options: cupsd -c config-file: This option uses the named configuration file. cupsd -f: This option runs cupsd in the foreground. The default is to run in the background as a “daemon”. cupsd -F: This option runs cupsd in the foreground but detaches the process from the controlling terminal and also from the current directory. This is very useful for running cupsd from init. cupsd -h: This option shows the program usage. cupsd -l config-file: This option passed to cupsd when it is being run from launchd or systemd command. cupsd -t: This option tests the configuration file for syntax errors. cupsd command with help option: It will print the general syntax of the command along with the various options that can be used with the cupsd command as well as gives a brief description about each option.Example: Example: Web Interface: CUPS can be easily configured and can be monitored using a web interface, which is by default available at http://localhost:631/admin. The web interface can be used to perform all the printer management tasks. In order to perform the administrative tasks through the web interface, you must either have the root account enabled on your server, or you need to authenticate as a user in the lpadmin group. For security reasons, CUPS by default won’t authenticate a user that doesn’t have a password. To add a user to the lpadmin group, run at the following command in your terminal prompt: sudo usermod -aG lpadmin username Examples: Run the cupsd in the background with all the default configuration file:cupsd cupsd Test a configuration file known to be test.conf:cupsd -t -c test.conf cupsd -t -c test.conf Run cupsd command in the foreground with a test configuration file known to be test.conf:cupsd -f -c test.conf cupsd -f -c test.conf linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2019" }, { "code": null, "e": 333, "s": 28, "text": "cupsd is a type of scheduler for CUPS (Common Unit Printing System). It implements the printing system on the basis of the Internet Printing Protocol(Version 2.1). If no options is being specified on the command-line then the default configuration file /etc/cups/cupsd.conf will be automatically be used." }, { "code": null, "e": 600, "s": 333, "text": "Installation:To install the CUPS in your Linux machine, simply use the sudo command with the apt. A complete CUPS package installation has many package dependencies, but they can all be specified on the same command line. Enter the following command on the terminal:" }, { "code": null, "e": 623, "s": 600, "text": "sudo apt install cups " }, { "code": null, "e": 840, "s": 623, "text": "Once authenticated with your username and password, the packages must be downloaded and installed without error. As the conclusion of the installation, the CUPS server will be going to start automatically by default." }, { "code": null, "e": 848, "s": 840, "text": "Syntax:" }, { "code": null, "e": 908, "s": 848, "text": "cupsd [ -c config-file ] [ -f ] [ -F ] [ -h ] [ -l ] [ -t ]" }, { "code": null, "e": 917, "s": 908, "text": "Options:" }, { "code": null, "e": 986, "s": 917, "text": "cupsd -c config-file: This option uses the named configuration file." }, { "code": null, "e": 1093, "s": 986, "text": "cupsd -f: This option runs cupsd in the foreground. The default is to run in the background as a “daemon”." }, { "code": null, "e": 1285, "s": 1093, "text": "cupsd -F: This option runs cupsd in the foreground but detaches the process from the controlling terminal and also from the current directory. This is very useful for running cupsd from init." }, { "code": null, "e": 1332, "s": 1285, "text": "cupsd -h: This option shows the program usage." }, { "code": null, "e": 1436, "s": 1332, "text": "cupsd -l config-file: This option passed to cupsd when it is being run from launchd or systemd command." }, { "code": null, "e": 1506, "s": 1436, "text": "cupsd -t: This option tests the configuration file for syntax errors." }, { "code": null, "e": 1721, "s": 1506, "text": "cupsd command with help option: It will print the general syntax of the command along with the various options that can be used with the cupsd command as well as gives a brief description about each option.Example:" }, { "code": null, "e": 1730, "s": 1721, "text": "Example:" }, { "code": null, "e": 1955, "s": 1730, "text": "Web Interface: CUPS can be easily configured and can be monitored using a web interface, which is by default available at http://localhost:631/admin. The web interface can be used to perform all the printer management tasks." }, { "code": null, "e": 2243, "s": 1955, "text": "In order to perform the administrative tasks through the web interface, you must either have the root account enabled on your server, or you need to authenticate as a user in the lpadmin group. For security reasons, CUPS by default won’t authenticate a user that doesn’t have a password." }, { "code": null, "e": 2333, "s": 2243, "text": "To add a user to the lpadmin group, run at the following command in your terminal prompt:" }, { "code": null, "e": 2367, "s": 2333, "text": "sudo usermod -aG lpadmin username" }, { "code": null, "e": 2377, "s": 2367, "text": "Examples:" }, { "code": null, "e": 2455, "s": 2377, "text": "Run the cupsd in the background with all the default configuration file:cupsd" }, { "code": null, "e": 2461, "s": 2455, "text": "cupsd" }, { "code": null, "e": 2531, "s": 2461, "text": "Test a configuration file known to be test.conf:cupsd -t -c test.conf" }, { "code": null, "e": 2553, "s": 2531, "text": "cupsd -t -c test.conf" }, { "code": null, "e": 2664, "s": 2553, "text": "Run cupsd command in the foreground with a test configuration file known to be test.conf:cupsd -f -c test.conf" }, { "code": null, "e": 2686, "s": 2664, "text": "cupsd -f -c test.conf" }, { "code": null, "e": 2700, "s": 2686, "text": "linux-command" }, { "code": null, "e": 2720, "s": 2700, "text": "Linux-misc-commands" }, { "code": null, "e": 2727, "s": 2720, "text": "Picked" }, { "code": null, "e": 2738, "s": 2727, "text": "Linux-Unix" } ]
Nested switch case
24 Jan, 2022 Switch-case statements:These are a substitute for long if statements that compare a variable to several integral values The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Switch is a control statement that allows a value to change control of execution. Points to remember while using Switch Case The expression used in a switch statement must have an integral or character type, or be of a class type in which the class has a single conversion function to an integral or character type. There can be any number of case statements within a switch. Each case is followed by the value to be compared to and after that a colon. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached i.e. all the case statements will get executed as soon as compiler finds a comparison to be true. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. Syntax: switch (n) { case 1: // code to be executed if n = 1; break; case 2: // code to be executed if n = 2; break; default: // code to be executed if // n doesn't match any cases } Nested-Switch Statement:Nested-Switch statements refers to Switch statements inside of another Switch Statements.Syntax: switch(n) { // code to be executed if n = 1; case 1: // Nested switch switch(num) { // code to be executed if num = 10 case 10: statement 1; break; // code to be executed if num = 20 case 20: statement 2; break; // code to be executed if num = 30 case 30: statement 3; break; // code to be executed if num // doesn't match any cases default: } break; // code to be executed if n = 2; case 2: statement 2; break; // code to be executed if n = 3; case 3: statement 3; break; // code to be executed if n doesn't match any cases default: } Example: C++ C Java Python3 C# Javascript // Following is a simple program to demonstrate// syntax of Nested Switch Statements.#include <iostream>using namespace std; int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: cout << "Choice is 2"; break; // If y == 3 case 3: cout << "Choice is 3"; break; } break; // If x == 4 case 4: cout << "Choice is 4"; break; // If x == 5 case 5: cout << "Choice is 5"; break; default: cout << "Choice is other than 1, 2 3, 4, or 5"; break; } return 0;} // This code is contributed by Shubham Singh // Following is a simple program to demonstrate// syntax of Nested Switch Statements.#include <stdio.h> int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: printf( "Choice is 2"); break; // If y == 3 case 3: printf( "Choice is 3"); break; } break; // If x == 4 case 4: printf( "Choice is 4"); break; // If x == 5 case 5: printf( "Choice is 5"); break; default: printf( "Choice is other than 1, 2 3, 4, or 5"); break; } return 0;} // Following is a simple program to demonstrate// syntax of Nested Switch Statements.import java.io.*; class GFG { public static void main (String[] args) { int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: System.out.println("Choice is 2"); break; // If y == 3 case 3: System.out.println("Choice is 3"); break; } break; // If x == 4 case 4: System.out.println("Choice is 4"); break; // If x == 5 case 5: System.out.println("Choice is 5"); break; default: System.out.println("Choice is other than 1, 2 3, 4, or 5"); break; } }} // This code is contributed by Shubham Singh # Following is a simple program to demonstrate# syntax of Nested Switch Statements. x = 1y = 2 # Outer Switchdef switch_x(x): switcher = { 1: switch_y(y), 4: "Choice is 4", 5: "Choice is 5", } return switcher.get(x, "Choice is other than 1, 2 3, 4, or 5") def switch_y(y): switcher = { 2: "Choice is 2", 3: "Choice is 3", } return switcher.get(y, "")print(switch_x(x)) # This code is contributed by Shubham Singh // Following is a simple program to demonstrate// syntax of Nested Switch Statements.using System; public class GFG{ static public void Main () { int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: Console.WriteLine("Choice is 2"); break; // If y == 3 case 3: Console.WriteLine("Choice is 3"); break; } break; // If x == 4 case 4: Console.WriteLine("Choice is 4"); break; // If x == 5 case 5: Console.WriteLine("Choice is 5"); break; default: Console.WriteLine("Choice is other than 1, 2 3, 4, or 5"); break; } }} // This code is contributed by Shubham Singh <script>// Following is a simple program to demonstrate// syntax of Nested Switch Statements.var x = 1, y = 2; // Outer Switchswitch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: document.write("Choice is 2"); break; // If y == 3 case 3: document.write("Choice is 3"); break; } break; // If x == 4 case 4: document.write("Choice is 4"); break; // If x == 5 case 5: document.write("Choice is 5"); break; default: document.write("Choice is other than 1, 2 3, 4, or 5"); break;} // This code is contributed by Shubham Singh</script> Choice is 2 shohamziner shubhamsingh84100 SHUBHAMSINGH10 Technical Scripter 2018 C Language Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library What is the purpose of a function prototype? Operators in C / C++ Exception Handling in C++ Smart Pointers in C++ and How to Use Them TCP Server-Client implementation in C 'this' pointer in C++ Ways to copy a vector in C++ Understanding "extern" keyword in C Storage Classes in C
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jan, 2022" }, { "code": null, "e": 174, "s": 52, "text": "Switch-case statements:These are a substitute for long if statements that compare a variable to several integral values " }, { "code": null, "e": 338, "s": 174, "text": "The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression." }, { "code": null, "e": 420, "s": 338, "text": "Switch is a control statement that allows a value to change control of execution." }, { "code": null, "e": 467, "s": 422, "text": "Points to remember while using Switch Case " }, { "code": null, "e": 658, "s": 467, "text": "The expression used in a switch statement must have an integral or character type, or be of a class type in which the class has a single conversion function to an integral or character type." }, { "code": null, "e": 795, "s": 658, "text": "There can be any number of case statements within a switch. Each case is followed by the value to be compared to and after that a colon." }, { "code": null, "e": 935, "s": 795, "text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached." }, { "code": null, "e": 1072, "s": 935, "text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement." }, { "code": null, "e": 1315, "s": 1072, "text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached i.e. all the case statements will get executed as soon as compiler finds a comparison to be true." }, { "code": null, "e": 1536, "s": 1315, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 1546, "s": 1536, "text": "Syntax: " }, { "code": null, "e": 1744, "s": 1546, "text": "switch (n)\n{\n case 1: // code to be executed if n = 1;\n break;\n case 2: // code to be executed if n = 2;\n break;\n default: // code to be executed if \n // n doesn't match any cases\n}" }, { "code": null, "e": 1867, "s": 1744, "text": "Nested-Switch Statement:Nested-Switch statements refers to Switch statements inside of another Switch Statements.Syntax: " }, { "code": null, "e": 2577, "s": 1867, "text": "switch(n)\n{\n // code to be executed if n = 1;\n case 1: \n \n // Nested switch\n switch(num) \n {\n // code to be executed if num = 10\n case 10: \n statement 1;\n break;\n \n // code to be executed if num = 20\n case 20: \n statement 2;\n break;\n \n // code to be executed if num = 30\n case 30: \n statement 3;\n break;\n \n // code to be executed if num \n // doesn't match any cases\n default: \n }\n \n \n break;\n \n // code to be executed if n = 2;\n case 2:\n statement 2;\n break;\n \n // code to be executed if n = 3;\n case 3: \n statement 3;\n break;\n \n // code to be executed if n doesn't match any cases\n default: \n}" }, { "code": null, "e": 2587, "s": 2577, "text": "Example: " }, { "code": null, "e": 2591, "s": 2587, "text": "C++" }, { "code": null, "e": 2593, "s": 2591, "text": "C" }, { "code": null, "e": 2598, "s": 2593, "text": "Java" }, { "code": null, "e": 2606, "s": 2598, "text": "Python3" }, { "code": null, "e": 2609, "s": 2606, "text": "C#" }, { "code": null, "e": 2620, "s": 2609, "text": "Javascript" }, { "code": "// Following is a simple program to demonstrate// syntax of Nested Switch Statements.#include <iostream>using namespace std; int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: cout << \"Choice is 2\"; break; // If y == 3 case 3: cout << \"Choice is 3\"; break; } break; // If x == 4 case 4: cout << \"Choice is 4\"; break; // If x == 5 case 5: cout << \"Choice is 5\"; break; default: cout << \"Choice is other than 1, 2 3, 4, or 5\"; break; } return 0;} // This code is contributed by Shubham Singh", "e": 3382, "s": 2620, "text": null }, { "code": "// Following is a simple program to demonstrate// syntax of Nested Switch Statements.#include <stdio.h> int main(){ int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: printf( \"Choice is 2\"); break; // If y == 3 case 3: printf( \"Choice is 3\"); break; } break; // If x == 4 case 4: printf( \"Choice is 4\"); break; // If x == 5 case 5: printf( \"Choice is 5\"); break; default: printf( \"Choice is other than 1, 2 3, 4, or 5\"); break; } return 0;}", "e": 4078, "s": 3382, "text": null }, { "code": "// Following is a simple program to demonstrate// syntax of Nested Switch Statements.import java.io.*; class GFG { public static void main (String[] args) { int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: System.out.println(\"Choice is 2\"); break; // If y == 3 case 3: System.out.println(\"Choice is 3\"); break; } break; // If x == 4 case 4: System.out.println(\"Choice is 4\"); break; // If x == 5 case 5: System.out.println(\"Choice is 5\"); break; default: System.out.println(\"Choice is other than 1, 2 3, 4, or 5\"); break; } }} // This code is contributed by Shubham Singh", "e": 5066, "s": 4078, "text": null }, { "code": "# Following is a simple program to demonstrate# syntax of Nested Switch Statements. x = 1y = 2 # Outer Switchdef switch_x(x): switcher = { 1: switch_y(y), 4: \"Choice is 4\", 5: \"Choice is 5\", } return switcher.get(x, \"Choice is other than 1, 2 3, 4, or 5\") def switch_y(y): switcher = { 2: \"Choice is 2\", 3: \"Choice is 3\", } return switcher.get(y, \"\")print(switch_x(x)) # This code is contributed by Shubham Singh", "e": 5532, "s": 5066, "text": null }, { "code": "// Following is a simple program to demonstrate// syntax of Nested Switch Statements.using System; public class GFG{ static public void Main () { int x = 1, y = 2; // Outer Switch switch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: Console.WriteLine(\"Choice is 2\"); break; // If y == 3 case 3: Console.WriteLine(\"Choice is 3\"); break; } break; // If x == 4 case 4: Console.WriteLine(\"Choice is 4\"); break; // If x == 5 case 5: Console.WriteLine(\"Choice is 5\"); break; default: Console.WriteLine(\"Choice is other than 1, 2 3, 4, or 5\"); break; } }} // This code is contributed by Shubham Singh", "e": 6504, "s": 5532, "text": null }, { "code": "<script>// Following is a simple program to demonstrate// syntax of Nested Switch Statements.var x = 1, y = 2; // Outer Switchswitch (x) { // If x == 1 case 1: // Nested Switch switch (y) { // If y == 2 case 2: document.write(\"Choice is 2\"); break; // If y == 3 case 3: document.write(\"Choice is 3\"); break; } break; // If x == 4 case 4: document.write(\"Choice is 4\"); break; // If x == 5 case 5: document.write(\"Choice is 5\"); break; default: document.write(\"Choice is other than 1, 2 3, 4, or 5\"); break;} // This code is contributed by Shubham Singh</script>", "e": 7270, "s": 6504, "text": null }, { "code": null, "e": 7282, "s": 7270, "text": "Choice is 2" }, { "code": null, "e": 7296, "s": 7284, "text": "shohamziner" }, { "code": null, "e": 7314, "s": 7296, "text": "shubhamsingh84100" }, { "code": null, "e": 7329, "s": 7314, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7353, "s": 7329, "text": "Technical Scripter 2018" }, { "code": null, "e": 7364, "s": 7353, "text": "C Language" }, { "code": null, "e": 7383, "s": 7364, "text": "Technical Scripter" }, { "code": null, "e": 7481, "s": 7383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7529, "s": 7481, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 7574, "s": 7529, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 7595, "s": 7574, "text": "Operators in C / C++" }, { "code": null, "e": 7621, "s": 7595, "text": "Exception Handling in C++" }, { "code": null, "e": 7663, "s": 7621, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 7701, "s": 7663, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 7723, "s": 7701, "text": "'this' pointer in C++" }, { "code": null, "e": 7752, "s": 7723, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 7788, "s": 7752, "text": "Understanding \"extern\" keyword in C" } ]
Numpy count_nonzero method | Python
22 Apr, 2020 numpy.count_nonzero() function counts the number of non-zero values in the array arr. Syntax : numpy.count_nonzero(arr, axis=None) Parameters :arr : [array_like] The array for which to count non-zeros.axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr. Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned. Code #1 : # Python program explaining# numpy.count_nonzero() function # importing numpy as geek import numpy as geek arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]] gfg = geek.count_nonzero(arr) print (gfg) Output : 6 Code #2 : # Python program explaining# numpy.count_nonzero() function # importing numpy as geek import numpy as geek arr = [[0, 1, 2, 3, 4], [5, 0, 6, 0, 7]] gfg = geek.count_nonzero(arr, axis = 0) print (gfg) Output : 7 Python-numpy 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": 114, "s": 28, "text": "numpy.count_nonzero() function counts the number of non-zero values in the array arr." }, { "code": null, "e": 159, "s": 114, "text": "Syntax : numpy.count_nonzero(arr, axis=None)" }, { "code": null, "e": 405, "s": 159, "text": "Parameters :arr : [array_like] The array for which to count non-zeros.axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr." }, { "code": null, "e": 568, "s": 405, "text": "Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned." }, { "code": null, "e": 578, "s": 568, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.count_nonzero() function # importing numpy as geek import numpy as geek arr = [[0, 1, 2, 3, 0], [0, 5, 6, 0, 7]] gfg = geek.count_nonzero(arr) print (gfg) ", "e": 773, "s": 578, "text": null }, { "code": null, "e": 782, "s": 773, "text": "Output :" }, { "code": null, "e": 785, "s": 782, "text": "6\n" }, { "code": null, "e": 796, "s": 785, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.count_nonzero() function # importing numpy as geek import numpy as geek arr = [[0, 1, 2, 3, 4], [5, 0, 6, 0, 7]] gfg = geek.count_nonzero(arr, axis = 0) print (gfg) ", "e": 1001, "s": 796, "text": null }, { "code": null, "e": 1010, "s": 1001, "text": "Output :" }, { "code": null, "e": 1013, "s": 1010, "text": "7\n" }, { "code": null, "e": 1026, "s": 1013, "text": "Python-numpy" }, { "code": null, "e": 1033, "s": 1026, "text": "Python" } ]
Print the element at a given index in a Set in C++
12 Jan, 2022 Given a Set of integers sett and an integer index, the task is to find the element in the set which is present at index. If the index is beyond limits, then print “Invalid index”.Examples: Input: sett = {11, 44, 66, 72, 88, 99}, index = 2 Output: The element at index 2 is : 66 Explaination: The element 66 is present in the set and it is present at index 2.Input: sett = {11, 44, 66, 72, 88, 99}, index = 6 Output: Invalid index Approach: Define a template getNthElement which find the index of particular element by using next() function. next() function returns an iterator pointing to the element after being advanced by certain number of positions. It is defined inside the header file. Using the next() function, getNthElement return a pair of boolean and integer values. The boolean value denotes if index is found the set or not. The integer value contains the integer stored at index in the set. If the boolean value is set true, which indicates index to be a valid index, print the integer value stored in the pair. Otherwise print “Invalid index”. Below is the implementation of the above approach: C++ // C++ program to access a// set element by its index #include <bits/stdc++.h>using namespace std; // Generic templatetemplate <typename T>pair<T, bool> getNthElement(set<T>& searchSet, int index){ pair<T, bool> result; // Check if index is valid or not if (searchSet.size() > index) { result.first = *(std::next( searchSet.begin(), index)); result.second = true; } else result.second = false; // Return the pair return result;} // Driver Programint main(){ set<int> sett = { 11, 44, 66, 72, 88, 99 }; int index = 2; pair<int, bool> result = getNthElement( sett, index); if (result.second) cout << "The element at index " << index << " is " << result.first; else cout << "Invalid index"; return 0;} The element at index 2 is 66 Time Complexity: O(N) Auxiliary Space: O(1) as5853535 C++-Templates cpp-set C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Different ways to print elements of vector Dynamic _Cast in C++ string::npos in C++ with Examples Why it is important to write "using namespace std" in C++ program? How to convert a Vector to Set in C++ Maximum value of long long int in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jan, 2022" }, { "code": null, "e": 243, "s": 52, "text": "Given a Set of integers sett and an integer index, the task is to find the element in the set which is present at index. If the index is beyond limits, then print “Invalid index”.Examples: " }, { "code": null, "e": 486, "s": 243, "text": "Input: sett = {11, 44, 66, 72, 88, 99}, index = 2 Output: The element at index 2 is : 66 Explaination: The element 66 is present in the set and it is present at index 2.Input: sett = {11, 44, 66, 72, 88, 99}, index = 6 Output: Invalid index " }, { "code": null, "e": 499, "s": 488, "text": "Approach: " }, { "code": null, "e": 601, "s": 499, "text": "Define a template getNthElement which find the index of particular element by using next() function. " }, { "code": null, "e": 752, "s": 601, "text": "next() function returns an iterator pointing to the element after being advanced by certain number of positions. It is defined inside the header file." }, { "code": null, "e": 965, "s": 752, "text": "Using the next() function, getNthElement return a pair of boolean and integer values. The boolean value denotes if index is found the set or not. The integer value contains the integer stored at index in the set." }, { "code": null, "e": 1119, "s": 965, "text": "If the boolean value is set true, which indicates index to be a valid index, print the integer value stored in the pair. Otherwise print “Invalid index”." }, { "code": null, "e": 1172, "s": 1119, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1176, "s": 1172, "text": "C++" }, { "code": "// C++ program to access a// set element by its index #include <bits/stdc++.h>using namespace std; // Generic templatetemplate <typename T>pair<T, bool> getNthElement(set<T>& searchSet, int index){ pair<T, bool> result; // Check if index is valid or not if (searchSet.size() > index) { result.first = *(std::next( searchSet.begin(), index)); result.second = true; } else result.second = false; // Return the pair return result;} // Driver Programint main(){ set<int> sett = { 11, 44, 66, 72, 88, 99 }; int index = 2; pair<int, bool> result = getNthElement( sett, index); if (result.second) cout << \"The element at index \" << index << \" is \" << result.first; else cout << \"Invalid index\"; return 0;}", "e": 2085, "s": 1176, "text": null }, { "code": null, "e": 2114, "s": 2085, "text": "The element at index 2 is 66" }, { "code": null, "e": 2161, "s": 2116, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 2171, "s": 2161, "text": "as5853535" }, { "code": null, "e": 2185, "s": 2171, "text": "C++-Templates" }, { "code": null, "e": 2193, "s": 2185, "text": "cpp-set" }, { "code": null, "e": 2206, "s": 2193, "text": "C++ Programs" }, { "code": null, "e": 2304, "s": 2206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2345, "s": 2304, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 2366, "s": 2345, "text": "Const keyword in C++" }, { "code": null, "e": 2378, "s": 2366, "text": "cout in C++" }, { "code": null, "e": 2437, "s": 2378, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 2480, "s": 2437, "text": "Different ways to print elements of vector" }, { "code": null, "e": 2501, "s": 2480, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 2535, "s": 2501, "text": "string::npos in C++ with Examples" }, { "code": null, "e": 2602, "s": 2535, "text": "Why it is important to write \"using namespace std\" in C++ program?" }, { "code": null, "e": 2640, "s": 2602, "text": "How to convert a Vector to Set in C++" } ]
Difference between split() and explode() functions for String manipulation in PHP
27 Oct, 2021 In this article, we will see the differences between split() and explode() functions for String manipulation in PHP. The split() and explode() functions are available in base PHP and are used to perform string manipulations as well as conversions. split() Function: The split() function in PHP is used to segregate the input string into different elements. The elements are divided based on the occurrence of patterns in the string. The optional parameter depicts the number of elements to divide the array. It begins from the left to the right of the string. The method returns an array. array split (string pattern, string string [, int limit]) Parameters: pattern – The separator to break the string. string – The string to split into parts. PHP <?php$str = "Geeks_for_geeks_is_fun!";$arr = split("\_", $str);print("String components : ");print_r($arr);?> Output String components : Array ( [0] => Geeks [1] => for [2] => geeks [3] => is [4] => fun! ) explode() Function: The explode() function in PHP is used to divide the string into array components depending on the separator specified. The limit parameter indicates the number of parts into which to divide the array into. This method returns an indexed array with indexes mapped to array elements. explode(separator, string, limit) Parameters: separator – The separator break the string. string – The string to split into parts. limit – Indicator of the number of array elements to divide the array into parts. More than 0 – Returns an array with a maximum of limit element(s)Less than 0 – Returns an array except for the last –limit elements()Equal to 0 – Returns an array with one element More than 0 – Returns an array with a maximum of limit element(s) Less than 0 – Returns an array except for the last –limit elements() Equal to 0 – Returns an array with one element PHP <?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str);print("String components : ");print_r($arr); ?> String components : Array ( [0] => Geeks [1] => for [2] => geeks [3] => is [4] => fun! ) The following code snippet divides the string into a single array component: PHP <?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str, 0);print("String components : ");print_r($arr);?> String components : Array ( [0] => Geeks for geeks is fun! ) The following code snippet indicates the usage of the last parameter less than 1: PHP <?php$str = "Geeks for geeks is fun!";$arr = explode(" ", $str, -1);print("String components : ");print_r($arr);?> String components : Array ( [0] => Geeks [1] => for [2] => geeks [3] => is ) split() Function explode() Function PHP-function PHP-Questions Picked Difference Between PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Oct, 2021" }, { "code": null, "e": 276, "s": 28, "text": "In this article, we will see the differences between split() and explode() functions for String manipulation in PHP. The split() and explode() functions are available in base PHP and are used to perform string manipulations as well as conversions." }, { "code": null, "e": 618, "s": 276, "text": "split() Function: The split() function in PHP is used to segregate the input string into different elements. The elements are divided based on the occurrence of patterns in the string. The optional parameter depicts the number of elements to divide the array. It begins from the left to the right of the string. The method returns an array. " }, { "code": null, "e": 676, "s": 618, "text": "array split (string pattern, string string [, int limit])" }, { "code": null, "e": 689, "s": 676, "text": "Parameters: " }, { "code": null, "e": 734, "s": 689, "text": "pattern – The separator to break the string." }, { "code": null, "e": 775, "s": 734, "text": "string – The string to split into parts." }, { "code": null, "e": 779, "s": 775, "text": "PHP" }, { "code": "<?php$str = \"Geeks_for_geeks_is_fun!\";$arr = split(\"\\_\", $str);print(\"String components : \");print_r($arr);?>", "e": 889, "s": 779, "text": null }, { "code": null, "e": 896, "s": 889, "text": "Output" }, { "code": null, "e": 1011, "s": 896, "text": "String components : Array ( \n [0] => Geeks \n [1] => for \n [2] => geeks \n [3] => is \n [4] => fun! \n)" }, { "code": null, "e": 1314, "s": 1011, "text": "explode() Function: The explode() function in PHP is used to divide the string into array components depending on the separator specified. The limit parameter indicates the number of parts into which to divide the array into. This method returns an indexed array with indexes mapped to array elements. " }, { "code": null, "e": 1348, "s": 1314, "text": "explode(separator, string, limit)" }, { "code": null, "e": 1361, "s": 1348, "text": "Parameters: " }, { "code": null, "e": 1405, "s": 1361, "text": "separator – The separator break the string." }, { "code": null, "e": 1446, "s": 1405, "text": "string – The string to split into parts." }, { "code": null, "e": 1708, "s": 1446, "text": "limit – Indicator of the number of array elements to divide the array into parts. More than 0 – Returns an array with a maximum of limit element(s)Less than 0 – Returns an array except for the last –limit elements()Equal to 0 – Returns an array with one element" }, { "code": null, "e": 1774, "s": 1708, "text": "More than 0 – Returns an array with a maximum of limit element(s)" }, { "code": null, "e": 1843, "s": 1774, "text": "Less than 0 – Returns an array except for the last –limit elements()" }, { "code": null, "e": 1890, "s": 1843, "text": "Equal to 0 – Returns an array with one element" }, { "code": null, "e": 1894, "s": 1890, "text": "PHP" }, { "code": "<?php$str = \"Geeks for geeks is fun!\";$arr = explode(\" \", $str);print(\"String components : \");print_r($arr); ?>", "e": 2007, "s": 1894, "text": null }, { "code": null, "e": 2117, "s": 2007, "text": "String components : Array\n(\n [0] => Geeks\n [1] => for\n [2] => geeks\n [3] => is\n [4] => fun!\n)\n" }, { "code": null, "e": 2195, "s": 2117, "text": "The following code snippet divides the string into a single array component: " }, { "code": null, "e": 2199, "s": 2195, "text": "PHP" }, { "code": "<?php$str = \"Geeks for geeks is fun!\";$arr = explode(\" \", $str, 0);print(\"String components : \");print_r($arr);?>", "e": 2313, "s": 2199, "text": null }, { "code": null, "e": 2379, "s": 2313, "text": "String components : Array\n(\n [0] => Geeks for geeks is fun!\n)\n" }, { "code": null, "e": 2462, "s": 2379, "text": "The following code snippet indicates the usage of the last parameter less than 1: " }, { "code": null, "e": 2466, "s": 2462, "text": "PHP" }, { "code": "<?php$str = \"Geeks for geeks is fun!\";$arr = explode(\" \", $str, -1);print(\"String components : \");print_r($arr);?>", "e": 2581, "s": 2466, "text": null }, { "code": null, "e": 2675, "s": 2581, "text": "String components : Array\n(\n [0] => Geeks\n [1] => for\n [2] => geeks\n [3] => is\n)\n" }, { "code": null, "e": 2692, "s": 2675, "text": "split() Function" }, { "code": null, "e": 2711, "s": 2692, "text": "explode() Function" }, { "code": null, "e": 2724, "s": 2711, "text": "PHP-function" }, { "code": null, "e": 2738, "s": 2724, "text": "PHP-Questions" }, { "code": null, "e": 2745, "s": 2738, "text": "Picked" }, { "code": null, "e": 2764, "s": 2745, "text": "Difference Between" }, { "code": null, "e": 2768, "s": 2764, "text": "PHP" }, { "code": null, "e": 2785, "s": 2768, "text": "Web Technologies" }, { "code": null, "e": 2789, "s": 2785, "text": "PHP" } ]
How to create an Expandable CardView in Android
18 Feb, 2021 Expandable Cardview provides to create expansion panels without too much hassle and without writing boilerplate code. An expandable card-view becomes quite useful when it comes to an efficient and systematic presentation of data or information on the screen. It is used in a variety of apps, for example, the Contacts app or the Gallery app. Here, in this tutorial, we’ll create a simple Expandable CardView in Android using Java. Step 1: Create a New Project in Android Studio Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Java.Select the minimum SDK as per your need. Click on File, then New => New Project. Choose “Empty Activity” for the project template. Select language as Java. Select the minimum SDK as per your need. Step 2: Add the CardView Dependency To be able to use the CardView element, you’ll first have to add it’s dependency in the project. In the build.gradle (Module: app) file add the following dependency and click on Sync now to synchronize the changes made. implementation ‘androidx.cardView:cardView:1.0.0’ Step 3: Add all the Required Drawable Resources in the Drawable Folder Choose the drawable resources as per the requirement. Here, in the CardView, use two images of the GeeksforGeeks icons and 2 other icons to indicate either of the ‘expand more’ or ‘expand less’ options. The following are the geeksforgeeks icons used: The image below shows the use of expansion icons: The expansion icons used here are imported as a vector asset from the Android Studio itself. The steps for the same are as follows: Right-click on the drawable resource folder.Go to new.Click on Vector Asset.The following box pops up. Click on the icon next to Clip Art.From the variety of icons shown, choose the following two icons:ic_baseline_expand_more_24 ic_baseline_expand_less_24 The following files get added to the drawable folder:ic_baseline_expand_more_24ic_baseline_expand_less_24ic_baseline_expand_more_24<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z"/></vector>ic_baseline_expand_less_24<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z"/></vector> Right-click on the drawable resource folder. Go to new. Click on Vector Asset. The following box pops up. Click on the icon next to Clip Art. From the variety of icons shown, choose the following two icons:ic_baseline_expand_more_24 ic_baseline_expand_less_24 The following files get added to the drawable folder:ic_baseline_expand_more_24ic_baseline_expand_less_24ic_baseline_expand_more_24<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z"/></vector>ic_baseline_expand_less_24<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z"/></vector> ic_baseline_expand_more_24 ic_baseline_expand_less_24 The following files get added to the drawable folder: ic_baseline_expand_more_24 ic_baseline_expand_less_24 <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z"/></vector> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="?attr/colorControlNormal"><path android:fillColor="@android:color/white" android:pathData="M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z"/></vector> Step 4: Modify the XML Layout In the XML file, create the entire layout along with the portion that you want to be displayed after the CardView is expanded. The basic idea here is to set the visibility of the expandable element to ‘gone’ or ‘visible’. Note: Set the visibility to ‘gone’ and not ‘invisible’ because ‘gone’ removes that particular element completely as if it was never there. However, ‘invisible’ only makes the element disappears while it still exists in the layout. In the below layout, expanded the CardView to display a list of three subjects. The following is the code for activity_main.xml file. <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#E4E3E3" tools:context=".MainActivity"> <!--Base CardView--> <androidx.cardview.widget.CardView android:id="@+id/base_cardview" style="@style/Base.CardView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.473" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.021"> <!--This is a ConstraintLayout for the entire CardView including the expandable portion--> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="@+id/base_cardview" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.511" tools:layout_editor_absoluteX="-55dp"> <!--This is a ConstraintLayout for the fixed portion of the CardView. The elements that lie within the fixed portion of the CardView can be constrained to this layout.--> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/fixed_layout" android:layout_width="match_parent" android:layout_height="150dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0"> <ImageView android:id="@+id/icon" android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/icon_one" app:layout_constraintBottom_toBottomOf="@+id/fixed_layout" app:layout_constraintEnd_toEndOf="@+id/fixed_layout" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="@+id/fixed_layout" app:layout_constraintTop_toTopOf="@+id/fixed_layout" app:layout_constraintVertical_bias="1.0" /> <TextView android:id="@+id/heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textColor="#006600" android:textSize="25dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/fixed_layout" app:layout_constraintEnd_toEndOf="@+id/fixed_layout" app:layout_constraintHorizontal_bias="0.926" app:layout_constraintStart_toStartOf="@+id/fixed_layout" app:layout_constraintTop_toTopOf="@+id/fixed_layout" app:layout_constraintVertical_bias="0.198" /> <TextView android:id="@+id/list_of_subjects" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginBottom="58dp" android:text="List of subjects" android:textSize="20dp" app:layout_constraintBottom_toBottomOf="@+id/fixed_layout" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.878" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/heading" app:layout_constraintVertical_bias="0.0" /> <!--This is ImageButton for the expansion icon.--> <ImageButton android:id="@+id/arrow_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_baseline_expand_more_24" app:layout_constraintBottom_toBottomOf="@id/fixed_layout" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.802" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/list_of_subjects" app:layout_constraintVertical_bias="0.0" /> </androidx.constraintlayout.widget.ConstraintLayout> <!--The following is the expandable portion whose visibility is initially set to 'gone'. The parent LinearLayout contains 3 child LinearLayouts that hold a subject name and an icon each.--> <LinearLayout android:id="@+id/hidden_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:visibility="gone" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/fixed_layout"> <!--Child LinearLayout 1--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:src="@drawable/gfg_icon_black" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:text="Database Management" android:textColor="#000000" android:textSize="20dp" /> </LinearLayout> <!--Child LinearLayout 2--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:src="@drawable/gfg_icon_black" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:text="Data Structures" android:textColor="#000000" android:textSize="20dp" /> </LinearLayout> <!--Child LinearLayout 3--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_marginStart="20dp" android:layout_marginTop="10dp" android:layout_marginEnd="10dp" android:layout_marginBottom="10dp" android:src="@drawable/gfg_icon_black" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:text="Operating Systems" android:textColor="#000000" android:textSize="20dp" /> </LinearLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout> Step 5: Modify the Java File In the MainActivity.java, using the if-else statements, specify the conditions to manipulate the visibility of the expandable element. package com.example.android.expandable_cardview; import android.os.Bundle;import android.transition.AutoTransition;import android.transition.TransitionManager;import android.view.View;import android.widget.ImageButton;import android.widget.LinearLayout;import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; public class MainActivity extends AppCompatActivity { ImageButton arrow; LinearLayout hiddenView; CardView cardView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cardView = findViewById(R.id.base_cardview); arrow = findViewById(R.id.arrow_button); hiddenView = findViewById(R.id.hidden_view); arrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // If the CardView is already expanded, set its visibility // to gone and change the expand less icon to expand more. if (hiddenView.getVisibility() == View.VISIBLE) { // The transition of the hiddenView is carried out // by the TransitionManager class. // Here we use an object of the AutoTransition // Class to create a default transition. TransitionManager.beginDelayedTransition(cardView, new AutoTransition()); hiddenView.setVisibility(View.GONE); arrow.setImageResource(R.drawable.ic_baseline_expand_more_24); } // If the CardView is not expanded, set its visibility // to visible and change the expand more icon to expand less. else { TransitionManager.beginDelayedTransition(cardView, new AutoTransition()); hiddenView.setVisibility(View.VISIBLE); arrow.setImageResource(R.drawable.ic_baseline_expand_less_24); } } }); }} android Android-View Android How To 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 RecyclerView in Kotlin Android SDK and it's Components Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to filter object array based on attributes?
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Feb, 2021" }, { "code": null, "e": 484, "s": 53, "text": "Expandable Cardview provides to create expansion panels without too much hassle and without writing boilerplate code. An expandable card-view becomes quite useful when it comes to an efficient and systematic presentation of data or information on the screen. It is used in a variety of apps, for example, the Contacts app or the Gallery app. Here, in this tutorial, we’ll create a simple Expandable CardView in Android using Java." }, { "code": null, "e": 531, "s": 484, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 684, "s": 531, "text": "Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Java.Select the minimum SDK as per your need." }, { "code": null, "e": 724, "s": 684, "text": "Click on File, then New => New Project." }, { "code": null, "e": 774, "s": 724, "text": "Choose “Empty Activity” for the project template." }, { "code": null, "e": 799, "s": 774, "text": "Select language as Java." }, { "code": null, "e": 840, "s": 799, "text": "Select the minimum SDK as per your need." }, { "code": null, "e": 876, "s": 840, "text": "Step 2: Add the CardView Dependency" }, { "code": null, "e": 1096, "s": 876, "text": "To be able to use the CardView element, you’ll first have to add it’s dependency in the project. In the build.gradle (Module: app) file add the following dependency and click on Sync now to synchronize the changes made." }, { "code": null, "e": 1146, "s": 1096, "text": "implementation ‘androidx.cardView:cardView:1.0.0’" }, { "code": null, "e": 1217, "s": 1146, "text": "Step 3: Add all the Required Drawable Resources in the Drawable Folder" }, { "code": null, "e": 1468, "s": 1217, "text": "Choose the drawable resources as per the requirement. Here, in the CardView, use two images of the GeeksforGeeks icons and 2 other icons to indicate either of the ‘expand more’ or ‘expand less’ options. The following are the geeksforgeeks icons used:" }, { "code": null, "e": 1518, "s": 1468, "text": "The image below shows the use of expansion icons:" }, { "code": null, "e": 1650, "s": 1518, "text": "The expansion icons used here are imported as a vector asset from the Android Studio itself. The steps for the same are as follows:" }, { "code": null, "e": 2818, "s": 1650, "text": "Right-click on the drawable resource folder.Go to new.Click on Vector Asset.The following box pops up. Click on the icon next to Clip Art.From the variety of icons shown, choose the following two icons:ic_baseline_expand_more_24\nic_baseline_expand_less_24\nThe following files get added to the drawable folder:ic_baseline_expand_more_24ic_baseline_expand_less_24ic_baseline_expand_more_24<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z\"/></vector>ic_baseline_expand_less_24<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z\"/></vector>" }, { "code": null, "e": 2863, "s": 2818, "text": "Right-click on the drawable resource folder." }, { "code": null, "e": 2874, "s": 2863, "text": "Go to new." }, { "code": null, "e": 2897, "s": 2874, "text": "Click on Vector Asset." }, { "code": null, "e": 2960, "s": 2897, "text": "The following box pops up. Click on the icon next to Clip Art." }, { "code": null, "e": 3990, "s": 2960, "text": "From the variety of icons shown, choose the following two icons:ic_baseline_expand_more_24\nic_baseline_expand_less_24\nThe following files get added to the drawable folder:ic_baseline_expand_more_24ic_baseline_expand_less_24ic_baseline_expand_more_24<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z\"/></vector>ic_baseline_expand_less_24<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z\"/></vector>" }, { "code": null, "e": 4045, "s": 3990, "text": "ic_baseline_expand_more_24\nic_baseline_expand_less_24\n" }, { "code": null, "e": 4099, "s": 4045, "text": "The following files get added to the drawable folder:" }, { "code": null, "e": 4126, "s": 4099, "text": "ic_baseline_expand_more_24" }, { "code": null, "e": 4153, "s": 4126, "text": "ic_baseline_expand_less_24" }, { "code": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M16.59, 8.59L12, 13.17 7.41, 8.59 6, 10l6, 6 6, -6z\"/></vector>", "e": 4531, "s": 4153, "text": null }, { "code": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"24dp\" android:height=\"24dp\" android:viewportWidth=\"24\" android:viewportHeight=\"24\" android:tint=\"?attr/colorControlNormal\"><path android:fillColor=\"@android:color/white\" android:pathData=\"M12, 8l-6, 6 1.41, 1.41L12, 10.83l4.59, 4.58L18, 14z\"/></vector>", "e": 4909, "s": 4531, "text": null }, { "code": null, "e": 4939, "s": 4909, "text": "Step 4: Modify the XML Layout" }, { "code": null, "e": 5161, "s": 4939, "text": "In the XML file, create the entire layout along with the portion that you want to be displayed after the CardView is expanded. The basic idea here is to set the visibility of the expandable element to ‘gone’ or ‘visible’." }, { "code": null, "e": 5392, "s": 5161, "text": "Note: Set the visibility to ‘gone’ and not ‘invisible’ because ‘gone’ removes that particular element completely as if it was never there. However, ‘invisible’ only makes the element disappears while it still exists in the layout." }, { "code": null, "e": 5526, "s": 5392, "text": "In the below layout, expanded the CardView to display a list of three subjects. The following is the code for activity_main.xml file." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#E4E3E3\" tools:context=\".MainActivity\"> <!--Base CardView--> <androidx.cardview.widget.CardView android:id=\"@+id/base_cardview\" style=\"@style/Base.CardView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.473\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.021\"> <!--This is a ConstraintLayout for the entire CardView including the expandable portion--> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"@+id/base_cardview\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.511\" tools:layout_editor_absoluteX=\"-55dp\"> <!--This is a ConstraintLayout for the fixed portion of the CardView. The elements that lie within the fixed portion of the CardView can be constrained to this layout.--> <androidx.constraintlayout.widget.ConstraintLayout android:id=\"@+id/fixed_layout\" android:layout_width=\"match_parent\" android:layout_height=\"150dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.0\"> <ImageView android:id=\"@+id/icon\" android:layout_width=\"150dp\" android:layout_height=\"150dp\" android:src=\"@drawable/icon_one\" app:layout_constraintBottom_toBottomOf=\"@+id/fixed_layout\" app:layout_constraintEnd_toEndOf=\"@+id/fixed_layout\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"@+id/fixed_layout\" app:layout_constraintTop_toTopOf=\"@+id/fixed_layout\" app:layout_constraintVertical_bias=\"1.0\" /> <TextView android:id=\"@+id/heading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textColor=\"#006600\" android:textSize=\"25dp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"@+id/fixed_layout\" app:layout_constraintEnd_toEndOf=\"@+id/fixed_layout\" app:layout_constraintHorizontal_bias=\"0.926\" app:layout_constraintStart_toStartOf=\"@+id/fixed_layout\" app:layout_constraintTop_toTopOf=\"@+id/fixed_layout\" app:layout_constraintVertical_bias=\"0.198\" /> <TextView android:id=\"@+id/list_of_subjects\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"58dp\" android:text=\"List of subjects\" android:textSize=\"20dp\" app:layout_constraintBottom_toBottomOf=\"@+id/fixed_layout\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.878\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/heading\" app:layout_constraintVertical_bias=\"0.0\" /> <!--This is ImageButton for the expansion icon.--> <ImageButton android:id=\"@+id/arrow_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:src=\"@drawable/ic_baseline_expand_more_24\" app:layout_constraintBottom_toBottomOf=\"@id/fixed_layout\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.802\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/list_of_subjects\" app:layout_constraintVertical_bias=\"0.0\" /> </androidx.constraintlayout.widget.ConstraintLayout> <!--The following is the expandable portion whose visibility is initially set to 'gone'. The parent LinearLayout contains 3 child LinearLayouts that hold a subject name and an icon each.--> <LinearLayout android:id=\"@+id/hidden_view\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:visibility=\"gone\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/fixed_layout\"> <!--Child LinearLayout 1--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:src=\"@drawable/gfg_icon_black\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:text=\"Database Management\" android:textColor=\"#000000\" android:textSize=\"20dp\" /> </LinearLayout> <!--Child LinearLayout 2--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:src=\"@drawable/gfg_icon_black\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:text=\"Data Structures\" android:textColor=\"#000000\" android:textSize=\"20dp\" /> </LinearLayout> <!--Child LinearLayout 3--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <ImageView android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"10dp\" android:layout_marginEnd=\"10dp\" android:layout_marginBottom=\"10dp\" android:src=\"@drawable/gfg_icon_black\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:text=\"Operating Systems\" android:textColor=\"#000000\" android:textSize=\"20dp\" /> </LinearLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 15100, "s": 5526, "text": null }, { "code": null, "e": 15129, "s": 15100, "text": "Step 5: Modify the Java File" }, { "code": null, "e": 15264, "s": 15129, "text": "In the MainActivity.java, using the if-else statements, specify the conditions to manipulate the visibility of the expandable element." }, { "code": "package com.example.android.expandable_cardview; import android.os.Bundle;import android.transition.AutoTransition;import android.transition.TransitionManager;import android.view.View;import android.widget.ImageButton;import android.widget.LinearLayout;import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; public class MainActivity extends AppCompatActivity { ImageButton arrow; LinearLayout hiddenView; CardView cardView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cardView = findViewById(R.id.base_cardview); arrow = findViewById(R.id.arrow_button); hiddenView = findViewById(R.id.hidden_view); arrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // If the CardView is already expanded, set its visibility // to gone and change the expand less icon to expand more. if (hiddenView.getVisibility() == View.VISIBLE) { // The transition of the hiddenView is carried out // by the TransitionManager class. // Here we use an object of the AutoTransition // Class to create a default transition. TransitionManager.beginDelayedTransition(cardView, new AutoTransition()); hiddenView.setVisibility(View.GONE); arrow.setImageResource(R.drawable.ic_baseline_expand_more_24); } // If the CardView is not expanded, set its visibility // to visible and change the expand more icon to expand less. else { TransitionManager.beginDelayedTransition(cardView, new AutoTransition()); hiddenView.setVisibility(View.VISIBLE); arrow.setImageResource(R.drawable.ic_baseline_expand_less_24); } } }); }}", "e": 17450, "s": 15264, "text": null }, { "code": null, "e": 17458, "s": 17450, "text": "android" }, { "code": null, "e": 17471, "s": 17458, "text": "Android-View" }, { "code": null, "e": 17479, "s": 17471, "text": "Android" }, { "code": null, "e": 17486, "s": 17479, "text": "How To" }, { "code": null, "e": 17491, "s": 17486, "text": "Java" }, { "code": null, "e": 17496, "s": 17491, "text": "Java" }, { "code": null, "e": 17504, "s": 17496, "text": "Android" }, { "code": null, "e": 17602, "s": 17504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17671, "s": 17602, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 17702, "s": 17671, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 17734, "s": 17702, "text": "Android SDK and it's Components" }, { "code": null, "e": 17777, "s": 17734, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 17826, "s": 17777, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 17858, "s": 17826, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 17911, "s": 17858, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 17955, "s": 17911, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 17969, "s": 17955, "text": "Java Tutorial" } ]
FIFO (First-In-First-Out) approach in Programming
21 Jun, 2022 FIFO is an abbreviation for first in, first out. It is a method for handling data structures where the first element is processed first and the newest element is processed last.Real life example: In this example, following things are to be considered: There is a ticket counter where people come, take tickets and go. People enter a line (queue) to get to the Ticket Counter in an organized manner. The person to enter the queue first, will get the ticket first and leave the queue. The person entering the queue next will get the ticket after the person in front of him In this way, the person entering the queue last will the tickets last Therefore, the First person to enter the queue gets the ticket first and the Last person to enter the queue gets the ticket last. This is known as First-In-First-Out approach or FIFO.Where is FIFO used: Data StructuresCertain data structures like Queue and other variants of Queue uses FIFO approach for processing data. Disk schedulingDisk controllers can use the FIFO as a disk scheduling algorithm to determine the order in which to service disk I/O requests. Communications and networkingCommunication network bridges, switches and routers used in computer networks use FIFOs to hold data packets en route to their next destination. Data StructuresCertain data structures like Queue and other variants of Queue uses FIFO approach for processing data. Disk schedulingDisk controllers can use the FIFO as a disk scheduling algorithm to determine the order in which to service disk I/O requests. Communications and networkingCommunication network bridges, switches and routers used in computer networks use FIFOs to hold data packets en route to their next destination. Program Examples for FIFOProgram 1: Queue C++ Java Python3 C# Javascript // C++ program to demonstrate// working of FIFO// using Queue interface in C++ #include<bits/stdc++.h>using namespace std; // print the elements of queuevoid print_queue(queue<int> q){ while (!q.empty()) { cout << q.front() << " "; q.pop(); } cout << endl;} // Driver codeint main(){ queue<int> q ; // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.push(i); // Display contents of the queue. cout << "Elements of queue-"; print_queue(q); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.front(); q.pop(); cout << "removed element-" << removedele << endl; print_queue(q); // To view the head of queue int head = q.front(); cout << "head of queue-" << head << endl; // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.size(); cout << "Size of queue-" << size; return 0;} // This code is contributed by Arnab Kundu // Java program to demonstrate// working of FIFO// using Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println("Elements of queue-" + q); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.remove(); System.out.println("removed element-" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.size(); System.out.println("Size of queue-" + size); }} # Python program to demonstrate# working of FIFO# using Queue interface in Java q = [] # Adds elements {0, 1, 2, 3, 4} to queuefor i in range(5): q.append(i) # Display contents of the queue.print("Elements of queue-" , q) # To remove the head of queue.# In this the oldest element '0' will be removedremovedele = q.pop(0)print("removed element-" , removedele) print(q) # To view the head of queuehead = q[0]print("head of queue-" , head) # Rest all methods of collection interface,# Like size and contains can be used with this# implementation.size = len(q)print("Size of queue-" , size) # This code is contributed by patel2127. // C# program to demonstrate// working of FIFOusing System;using System.Collections.Generic; public class QueueExample{ public static void Main(String[] args) { Queue<int> q = new Queue<int>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.Enqueue(i); // Display contents of the queue. Console.Write("Elements of queue-"); foreach(int s in q) Console.Write(s + " "); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.Dequeue(); Console.Write("\nremoved element-" + removedele + "\n"); foreach(int s in q) Console.Write(s + " "); // To view the head of queue int head = q.Peek(); Console.Write("\nhead of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.Count; Console.WriteLine("\nSize of queue-" + size); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to demonstrate// working of FIFO// using Queue interface in Java let q = [];// Adds elements {0, 1, 2, 3, 4} to queuefor (let i = 0; i < 5; i++) q.push(i); // Display contents of the queue.document.write("Elements of queue-[" + q.join(", ")+"]<br>"); // To remove the head of queue.// In this the oldest element '0' will be removedlet removedele = q.shift();document.write("removed element-" + removedele+"<br>"); document.write("["+q.join(", ")+"]<br>"); // To view the head of queuelet head = q[0];document.write("head of queue-" + head+"<br>"); // Rest all methods of collection interface,// Like size and contains can be used with this// implementation.let size = q.length;document.write("Size of queue-" + size+"<br>"); // This code is contributed by avanitrachhadiya2155 </script> Output: Elements of queue-[0, 1, 2, 3, 4] removed element-0 [1, 2, 3, 4] head of queue-1 Size of queue-4 Time Complexity: O(N)Space Complexity: O(N) 29AjayKumar andrew1234 avanitrachhadiya2155 patel2127 geekygirl2001 Data Structures Queue Data Structures Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Jun, 2022" }, { "code": null, "e": 250, "s": 53, "text": "FIFO is an abbreviation for first in, first out. It is a method for handling data structures where the first element is processed first and the newest element is processed last.Real life example: " }, { "code": null, "e": 308, "s": 250, "text": "In this example, following things are to be considered: " }, { "code": null, "e": 374, "s": 308, "text": "There is a ticket counter where people come, take tickets and go." }, { "code": null, "e": 455, "s": 374, "text": "People enter a line (queue) to get to the Ticket Counter in an organized manner." }, { "code": null, "e": 539, "s": 455, "text": "The person to enter the queue first, will get the ticket first and leave the queue." }, { "code": null, "e": 627, "s": 539, "text": "The person entering the queue next will get the ticket after the person in front of him" }, { "code": null, "e": 697, "s": 627, "text": "In this way, the person entering the queue last will the tickets last" }, { "code": null, "e": 827, "s": 697, "text": "Therefore, the First person to enter the queue gets the ticket first and the Last person to enter the queue gets the ticket last." }, { "code": null, "e": 901, "s": 827, "text": "This is known as First-In-First-Out approach or FIFO.Where is FIFO used: " }, { "code": null, "e": 1337, "s": 901, "text": "Data StructuresCertain data structures like Queue and other variants of Queue uses FIFO approach for processing data. Disk schedulingDisk controllers can use the FIFO as a disk scheduling algorithm to determine the order in which to service disk I/O requests. Communications and networkingCommunication network bridges, switches and routers used in computer networks use FIFOs to hold data packets en route to their next destination." }, { "code": null, "e": 1457, "s": 1337, "text": "Data StructuresCertain data structures like Queue and other variants of Queue uses FIFO approach for processing data. " }, { "code": null, "e": 1601, "s": 1457, "text": "Disk schedulingDisk controllers can use the FIFO as a disk scheduling algorithm to determine the order in which to service disk I/O requests. " }, { "code": null, "e": 1775, "s": 1601, "text": "Communications and networkingCommunication network bridges, switches and routers used in computer networks use FIFOs to hold data packets en route to their next destination." }, { "code": null, "e": 1819, "s": 1775, "text": "Program Examples for FIFOProgram 1: Queue " }, { "code": null, "e": 1823, "s": 1819, "text": "C++" }, { "code": null, "e": 1828, "s": 1823, "text": "Java" }, { "code": null, "e": 1836, "s": 1828, "text": "Python3" }, { "code": null, "e": 1839, "s": 1836, "text": "C#" }, { "code": null, "e": 1850, "s": 1839, "text": "Javascript" }, { "code": "// C++ program to demonstrate// working of FIFO// using Queue interface in C++ #include<bits/stdc++.h>using namespace std; // print the elements of queuevoid print_queue(queue<int> q){ while (!q.empty()) { cout << q.front() << \" \"; q.pop(); } cout << endl;} // Driver codeint main(){ queue<int> q ; // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.push(i); // Display contents of the queue. cout << \"Elements of queue-\"; print_queue(q); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.front(); q.pop(); cout << \"removed element-\" << removedele << endl; print_queue(q); // To view the head of queue int head = q.front(); cout << \"head of queue-\" << head << endl; // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.size(); cout << \"Size of queue-\" << size; return 0;} // This code is contributed by Arnab Kundu", "e": 2929, "s": 1850, "text": null }, { "code": "// Java program to demonstrate// working of FIFO// using Queue interface in Java import java.util.LinkedList;import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.add(i); // Display contents of the queue. System.out.println(\"Elements of queue-\" + q); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.remove(); System.out.println(\"removed element-\" + removedele); System.out.println(q); // To view the head of queue int head = q.peek(); System.out.println(\"head of queue-\" + head); // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.size(); System.out.println(\"Size of queue-\" + size); }}", "e": 3945, "s": 2929, "text": null }, { "code": "# Python program to demonstrate# working of FIFO# using Queue interface in Java q = [] # Adds elements {0, 1, 2, 3, 4} to queuefor i in range(5): q.append(i) # Display contents of the queue.print(\"Elements of queue-\" , q) # To remove the head of queue.# In this the oldest element '0' will be removedremovedele = q.pop(0)print(\"removed element-\" , removedele) print(q) # To view the head of queuehead = q[0]print(\"head of queue-\" , head) # Rest all methods of collection interface,# Like size and contains can be used with this# implementation.size = len(q)print(\"Size of queue-\" , size) # This code is contributed by patel2127.", "e": 4577, "s": 3945, "text": null }, { "code": "// C# program to demonstrate// working of FIFOusing System;using System.Collections.Generic; public class QueueExample{ public static void Main(String[] args) { Queue<int> q = new Queue<int>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i = 0; i < 5; i++) q.Enqueue(i); // Display contents of the queue. Console.Write(\"Elements of queue-\"); foreach(int s in q) Console.Write(s + \" \"); // To remove the head of queue. // In this the oldest element '0' will be removed int removedele = q.Dequeue(); Console.Write(\"\\nremoved element-\" + removedele + \"\\n\"); foreach(int s in q) Console.Write(s + \" \"); // To view the head of queue int head = q.Peek(); Console.Write(\"\\nhead of queue-\" + head); // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = q.Count; Console.WriteLine(\"\\nSize of queue-\" + size); }} // This code has been contributed by 29AjayKumar", "e": 5693, "s": 4577, "text": null }, { "code": "<script> // JavaScript program to demonstrate// working of FIFO// using Queue interface in Java let q = [];// Adds elements {0, 1, 2, 3, 4} to queuefor (let i = 0; i < 5; i++) q.push(i); // Display contents of the queue.document.write(\"Elements of queue-[\" + q.join(\", \")+\"]<br>\"); // To remove the head of queue.// In this the oldest element '0' will be removedlet removedele = q.shift();document.write(\"removed element-\" + removedele+\"<br>\"); document.write(\"[\"+q.join(\", \")+\"]<br>\"); // To view the head of queuelet head = q[0];document.write(\"head of queue-\" + head+\"<br>\"); // Rest all methods of collection interface,// Like size and contains can be used with this// implementation.let size = q.length;document.write(\"Size of queue-\" + size+\"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 6515, "s": 5693, "text": null }, { "code": null, "e": 6525, "s": 6515, "text": "Output: " }, { "code": null, "e": 6622, "s": 6525, "text": "Elements of queue-[0, 1, 2, 3, 4]\nremoved element-0\n[1, 2, 3, 4]\nhead of queue-1\nSize of queue-4" }, { "code": null, "e": 6667, "s": 6622, "text": "Time Complexity: O(N)Space Complexity: O(N) " }, { "code": null, "e": 6679, "s": 6667, "text": "29AjayKumar" }, { "code": null, "e": 6690, "s": 6679, "text": "andrew1234" }, { "code": null, "e": 6711, "s": 6690, "text": "avanitrachhadiya2155" }, { "code": null, "e": 6721, "s": 6711, "text": "patel2127" }, { "code": null, "e": 6735, "s": 6721, "text": "geekygirl2001" }, { "code": null, "e": 6751, "s": 6735, "text": "Data Structures" }, { "code": null, "e": 6757, "s": 6751, "text": "Queue" }, { "code": null, "e": 6773, "s": 6757, "text": "Data Structures" }, { "code": null, "e": 6779, "s": 6773, "text": "Queue" } ]
MD5 hash in Python
21 Apr, 2020 Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases.There are many hash functions defined in the “hashlib” library in python.This article deals with explanation and working of MD5 hash. This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has security issues. Functions associated : encode() : Converts the string into bytes to be acceptable by hash function. digest() : Returns the encoded data in byte format. hexdigest() : Returns the encoded data in hexadecimal format. The below code demonstrates the working of MD5 hash accepting bytes and output as bytes. # Python 3 code to demonstrate the # working of MD5 (byte - byte) import hashlib # encoding GeeksforGeeks using md5 hash# function result = hashlib.md5(b'GeeksforGeeks') # printing the equivalent byte value.print("The byte equivalent of hash is : ", end ="")print(result.digest()) Output: The byte equivalent of hash is : b'\xf1\xe0ix~\xcetS\x1d\x11%Y\x94\\hq' Explanation : The above code takes byte and can be accepted by the hash function. The md5 hash function encodes it and then using digest(), byte equivalent encoded string is printed. Below code demonstrated how to take string as input and output hexadecimal equivalent of the encoded value. # Python 3 code to demonstrate the # working of MD5 (string - hexadecimal) import hashlib # initializing stringstr2hash = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to md5()result = hashlib.md5(str2hash.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of hash is : ", end ="")print(result.hexdigest()) Output: The hexadecimal equivalent of hash is : f1e069787ece74531d112559945c6871 Explanation : The above code takes string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The md5 hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed. andecker91 cryptography Python cryptography 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 Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Apr, 2020" }, { "code": null, "e": 510, "s": 54, "text": "Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases.There are many hash functions defined in the “hashlib” library in python.This article deals with explanation and working of MD5 hash." }, { "code": null, "e": 649, "s": 510, "text": "This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has security issues." }, { "code": null, "e": 672, "s": 649, "text": "Functions associated :" }, { "code": null, "e": 749, "s": 672, "text": "encode() : Converts the string into bytes to be acceptable by hash function." }, { "code": null, "e": 801, "s": 749, "text": "digest() : Returns the encoded data in byte format." }, { "code": null, "e": 863, "s": 801, "text": "hexdigest() : Returns the encoded data in hexadecimal format." }, { "code": null, "e": 952, "s": 863, "text": "The below code demonstrates the working of MD5 hash accepting bytes and output as bytes." }, { "code": "# Python 3 code to demonstrate the # working of MD5 (byte - byte) import hashlib # encoding GeeksforGeeks using md5 hash# function result = hashlib.md5(b'GeeksforGeeks') # printing the equivalent byte value.print(\"The byte equivalent of hash is : \", end =\"\")print(result.digest())", "e": 1236, "s": 952, "text": null }, { "code": null, "e": 1244, "s": 1236, "text": "Output:" }, { "code": null, "e": 1317, "s": 1244, "text": "The byte equivalent of hash is : b'\\xf1\\xe0ix~\\xcetS\\x1d\\x11%Y\\x94\\\\hq'\n" }, { "code": null, "e": 1500, "s": 1317, "text": "Explanation : The above code takes byte and can be accepted by the hash function. The md5 hash function encodes it and then using digest(), byte equivalent encoded string is printed." }, { "code": null, "e": 1608, "s": 1500, "text": "Below code demonstrated how to take string as input and output hexadecimal equivalent of the encoded value." }, { "code": "# Python 3 code to demonstrate the # working of MD5 (string - hexadecimal) import hashlib # initializing stringstr2hash = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to md5()result = hashlib.md5(str2hash.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of hash is : \", end =\"\")print(result.hexdigest())", "e": 1980, "s": 1608, "text": null }, { "code": null, "e": 1988, "s": 1980, "text": "Output:" }, { "code": null, "e": 2062, "s": 1988, "text": "The hexadecimal equivalent of hash is : f1e069787ece74531d112559945c6871\n" }, { "code": null, "e": 2320, "s": 2062, "text": "Explanation : The above code takes string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The md5 hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed." }, { "code": null, "e": 2331, "s": 2320, "text": "andecker91" }, { "code": null, "e": 2344, "s": 2331, "text": "cryptography" }, { "code": null, "e": 2351, "s": 2344, "text": "Python" }, { "code": null, "e": 2364, "s": 2351, "text": "cryptography" }, { "code": null, "e": 2462, "s": 2364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2480, "s": 2462, "text": "Python Dictionary" }, { "code": null, "e": 2522, "s": 2480, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2544, "s": 2522, "text": "Enumerate() in Python" }, { "code": null, "e": 2570, "s": 2544, "text": "Python String | replace()" }, { "code": null, "e": 2602, "s": 2570, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2631, "s": 2602, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2658, "s": 2631, "text": "Python Classes and Objects" }, { "code": null, "e": 2694, "s": 2658, "text": "Convert integer to string in Python" }, { "code": null, "e": 2725, "s": 2694, "text": "Python | os.path.join() method" } ]
Python | Dictionary with index as value
29 Apr, 2019 The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index where element occurs. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using dictionary comprehension + enumerate() This problem can be solved easily using the combination of above functions, dictionary comprehension can perform the task of constructing the dictionary and enumerate function can be used to access the index value along with the element. # Python3 code to demonstrate# Dictionary with index as value# using Dictionary comprehension + enumerate() # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] # printing original listprint("The original list : " + str(test_list)) # using Dictionary comprehension + enumerate()# Dictionary with index as valueres = {val : idx + 1 for idx, val in enumerate(test_list)} # print resultprint("The Dictionary after index keys : " + str(res)) The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] The Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3} Method #2 : Using dict() + zip() This problem can also be solved using the combination of above 2 functions, the dict method can be used to convert to dictionary and zip function can be used to map the indices with the keys. # Python3 code to demonstrate# Dictionary with index as value# using dict() + zip() # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] # printing original listprint("The original list : " + str(test_list)) # using dict() + zip()# Dictionary with index as valueres = dict(zip(test_list, range(1, len(test_list)+1))) # print resultprint("The Dictionary after index keys : " + str(res)) The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] The Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3} Python dictionary-programs Python list-programs Python Python Programs 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 program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2019" }, { "code": null, "e": 396, "s": 28, "text": "The interconversion between the datatypes is very popular and hence many articles have been written to demonstrate different kind of problems with their solutions. This article deals with yet another similar type problem of converting a list to dictionary, with values as the index where element occurs. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 453, "s": 396, "text": "Method #1 : Using dictionary comprehension + enumerate()" }, { "code": null, "e": 691, "s": 453, "text": "This problem can be solved easily using the combination of above functions, dictionary comprehension can perform the task of constructing the dictionary and enumerate function can be used to access the index value along with the element." }, { "code": "# Python3 code to demonstrate# Dictionary with index as value# using Dictionary comprehension + enumerate() # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] # printing original listprint(\"The original list : \" + str(test_list)) # using Dictionary comprehension + enumerate()# Dictionary with index as valueres = {val : idx + 1 for idx, val in enumerate(test_list)} # print resultprint(\"The Dictionary after index keys : \" + str(res))", "e": 1152, "s": 691, "text": null }, { "code": null, "e": 1301, "s": 1152, "text": "The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']\nThe Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3}\n" }, { "code": null, "e": 1336, "s": 1303, "text": "Method #2 : Using dict() + zip()" }, { "code": null, "e": 1528, "s": 1336, "text": "This problem can also be solved using the combination of above 2 functions, the dict method can be used to convert to dictionary and zip function can be used to map the indices with the keys." }, { "code": "# Python3 code to demonstrate# Dictionary with index as value# using dict() + zip() # initializing listtest_list = ['Nikhil', 'Akshat', 'Akash', 'Manjeet'] # printing original listprint(\"The original list : \" + str(test_list)) # using dict() + zip()# Dictionary with index as valueres = dict(zip(test_list, range(1, len(test_list)+1))) # print resultprint(\"The Dictionary after index keys : \" + str(res))", "e": 1937, "s": 1528, "text": null }, { "code": null, "e": 2086, "s": 1937, "text": "The original list : ['Nikhil', 'Akshat', 'Akash', 'Manjeet']\nThe Dictionary after index keys : {'Akshat': 2, 'Nikhil': 1, 'Manjeet': 4, 'Akash': 3}\n" }, { "code": null, "e": 2113, "s": 2086, "text": "Python dictionary-programs" }, { "code": null, "e": 2134, "s": 2113, "text": "Python list-programs" }, { "code": null, "e": 2141, "s": 2134, "text": "Python" }, { "code": null, "e": 2157, "s": 2141, "text": "Python Programs" }, { "code": null, "e": 2255, "s": 2157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2297, "s": 2255, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2319, "s": 2297, "text": "Enumerate() in Python" }, { "code": null, "e": 2345, "s": 2319, "text": "Python String | replace()" }, { "code": null, "e": 2377, "s": 2345, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2406, "s": 2377, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2449, "s": 2406, "text": "Python program to convert a list to string" }, { "code": null, "e": 2471, "s": 2449, "text": "Defaultdict in Python" }, { "code": null, "e": 2510, "s": 2471, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2548, "s": 2510, "text": "Python | Convert a list to dictionary" } ]
Maximum number of squares that can fit in a right angle isosceles triangle
16 Jun, 2022 You are given an isosceles (a triangle with at-least two equal sides) right angle triangle with base b, we need to find the maximum number of squares of side m, which can be fitted into given triangle.Examples: Input : b = 6, m = 2 Output : 3 Input : b = 4, m = 1 Output : 6 Let’s consider a right angle triangle XYZ, where YZ is the base of triangle. Suppose length of the base is b. If we consider the position of first square with the vertex Y, we will have (b / m-1) squares in the base, and we will be left with another isosceles right angle triangle having base length (b – m).Illustration : Let f(b, m) = Number of squares which can be fitted in triangle having base length b. then f(b, m) = (b / m – 1) + f(b – m, m) We can calculate f(b) using above recursion, and with use of memoization. Later we can answer each query in O(1) time. We can do it for even and odd numbers separately with the base case if (b < 2 * m) f(b, m) = 0.The given recursion can be solved as :f(b, m) = b / m – 1 + f(b – m, m) = b / m – 1 + (b – m) / m – 1 + f(b – 2m, m) f(b, m) = b / m – 1 + b / m – 2 + f(b – 3m, m) +...+ f(b – (b / m)m, m) f(b) = b / m – 1 + b / m – 2 + b / m – 3 +.....+ 1 + 0 With conditions, if (b < 2 * m) f(b, m) = 0 f(b) = sum of first (b / m – 1) natural numbers = (b / m – 1) * (b / m) / 2 This formula can be used to reduce the time complexity upto O(1). C++ Java Python3 C# PHP Javascript // CPP program for finding maximum squares// that can fit in right angle isosceles// triangle#include<bits/stdc++.h>using namespace std; // function for finding max squaresint maxSquare(int b, int m){ // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2;} // driver programint main(){ int b = 10, m = 2; cout << maxSquare (b,m); return 0;} // Java program for finding maximum squares// that can fit in right angle isosceles// trianglepublic class GFG{ // function for finding max squares static int maxSquare(int b, int m) { // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; } // driver program public static void main(String args[]) { int b = 10, m = 2; System.out.println(maxSquare (b,m)); }} // This code is contribute by Sumit Ghosh # Python3 program for# finding maximum squares# that can fit in# right angle isosceles# triangle # function for finding max squaresdef maxSquare(b, m): # return in O(1) with derived # formula return (b / m - 1) * (b / m) / 2 # driver programb = 10m = 2print(int(maxSquare (b,m))) # This code is contributed by# Smitha Dinesh Semwal // C# program for finding maximum squares// that can fit in right angle isosceles// triangleusing System; public class GFG{ // function for finding max squares static int maxSquare(int b, int m) { // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; } // driver program public static void Main() { int b = 10, m = 2; Console.WriteLine(maxSquare (b, m)); }} // This code is contribute by vt_m <?php// PHP program for finding// maximum squares that can// fit in right angle isosceles// triangle // function for finding// max squaresfunction maxSquare($b, $m){ // return in O(1) with // derived formula return ($b / $m - 1) * ($b / $m) / 2;} // Driver Code $b = 10; $m = 2; echo maxSquare($b,$m);// This code is contribute by vt_m?> <script> // Javascript program for finding maximum squares// that can fit in right angle isosceles// triangle // function for finding max squaresfunction maxSquare(b, m){ // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; a} // Driver program let b = 10, m = 2; document.write(maxSquare (b,m)); // This code is contributed by Mayank Tyagi</script> Output: 10 Time complexity: O(1) Auxiliary Space: O(1)This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m mayanktyagi1709 hasani triangle Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 267, "s": 54, "text": "You are given an isosceles (a triangle with at-least two equal sides) right angle triangle with base b, we need to find the maximum number of squares of side m, which can be fitted into given triangle.Examples: " }, { "code": null, "e": 332, "s": 267, "text": "Input : b = 6, m = 2\nOutput : 3\n\nInput : b = 4, m = 1\nOutput : 6" }, { "code": null, "e": 659, "s": 334, "text": "Let’s consider a right angle triangle XYZ, where YZ is the base of triangle. Suppose length of the base is b. If we consider the position of first square with the vertex Y, we will have (b / m-1) squares in the base, and we will be left with another isosceles right angle triangle having base length (b – m).Illustration : " }, { "code": null, "e": 1431, "s": 659, "text": "Let f(b, m) = Number of squares which can be fitted in triangle having base length b. then f(b, m) = (b / m – 1) + f(b – m, m) We can calculate f(b) using above recursion, and with use of memoization. Later we can answer each query in O(1) time. We can do it for even and odd numbers separately with the base case if (b < 2 * m) f(b, m) = 0.The given recursion can be solved as :f(b, m) = b / m – 1 + f(b – m, m) = b / m – 1 + (b – m) / m – 1 + f(b – 2m, m) f(b, m) = b / m – 1 + b / m – 2 + f(b – 3m, m) +...+ f(b – (b / m)m, m) f(b) = b / m – 1 + b / m – 2 + b / m – 3 +.....+ 1 + 0 With conditions, if (b < 2 * m) f(b, m) = 0 f(b) = sum of first (b / m – 1) natural numbers = (b / m – 1) * (b / m) / 2 This formula can be used to reduce the time complexity upto O(1). " }, { "code": null, "e": 1435, "s": 1431, "text": "C++" }, { "code": null, "e": 1440, "s": 1435, "text": "Java" }, { "code": null, "e": 1448, "s": 1440, "text": "Python3" }, { "code": null, "e": 1451, "s": 1448, "text": "C#" }, { "code": null, "e": 1455, "s": 1451, "text": "PHP" }, { "code": null, "e": 1466, "s": 1455, "text": "Javascript" }, { "code": "// CPP program for finding maximum squares// that can fit in right angle isosceles// triangle#include<bits/stdc++.h>using namespace std; // function for finding max squaresint maxSquare(int b, int m){ // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2;} // driver programint main(){ int b = 10, m = 2; cout << maxSquare (b,m); return 0;}", "e": 1846, "s": 1466, "text": null }, { "code": "// Java program for finding maximum squares// that can fit in right angle isosceles// trianglepublic class GFG{ // function for finding max squares static int maxSquare(int b, int m) { // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; } // driver program public static void main(String args[]) { int b = 10, m = 2; System.out.println(maxSquare (b,m)); }} // This code is contribute by Sumit Ghosh", "e": 2338, "s": 1846, "text": null }, { "code": "# Python3 program for# finding maximum squares# that can fit in# right angle isosceles# triangle # function for finding max squaresdef maxSquare(b, m): # return in O(1) with derived # formula return (b / m - 1) * (b / m) / 2 # driver programb = 10m = 2print(int(maxSquare (b,m))) # This code is contributed by# Smitha Dinesh Semwal", "e": 2683, "s": 2338, "text": null }, { "code": "// C# program for finding maximum squares// that can fit in right angle isosceles// triangleusing System; public class GFG{ // function for finding max squares static int maxSquare(int b, int m) { // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; } // driver program public static void Main() { int b = 10, m = 2; Console.WriteLine(maxSquare (b, m)); }} // This code is contribute by vt_m", "e": 3162, "s": 2683, "text": null }, { "code": "<?php// PHP program for finding// maximum squares that can// fit in right angle isosceles// triangle // function for finding// max squaresfunction maxSquare($b, $m){ // return in O(1) with // derived formula return ($b / $m - 1) * ($b / $m) / 2;} // Driver Code $b = 10; $m = 2; echo maxSquare($b,$m);// This code is contribute by vt_m?>", "e": 3535, "s": 3162, "text": null }, { "code": "<script> // Javascript program for finding maximum squares// that can fit in right angle isosceles// triangle // function for finding max squaresfunction maxSquare(b, m){ // return in O(1) with derived // formula return (b / m - 1) * (b / m) / 2; a} // Driver program let b = 10, m = 2; document.write(maxSquare (b,m)); // This code is contributed by Mayank Tyagi</script>", "e": 3930, "s": 3535, "text": null }, { "code": null, "e": 3940, "s": 3930, "text": "Output: " }, { "code": null, "e": 3943, "s": 3940, "text": "10" }, { "code": null, "e": 3965, "s": 3943, "text": "Time complexity: O(1)" }, { "code": null, "e": 4422, "s": 3965, "text": "Auxiliary Space: O(1)This article is contributed by Shivam Pradhan (anuj_charm). 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": 4427, "s": 4422, "text": "vt_m" }, { "code": null, "e": 4443, "s": 4427, "text": "mayanktyagi1709" }, { "code": null, "e": 4450, "s": 4443, "text": "hasani" }, { "code": null, "e": 4459, "s": 4450, "text": "triangle" }, { "code": null, "e": 4469, "s": 4459, "text": "Geometric" }, { "code": null, "e": 4479, "s": 4469, "text": "Geometric" } ]
Python | Inverse Fast Fourier Transformation
20 Jul, 2021 Inverse Fast Fourier transform (IDFT) is an algorithm to undoes the process of DFT. It is also known as backward Fourier transform. It converts a space or time signal to a signal of the frequency domain. The DFT signal is generated by the distribution of value sequences to different frequency components. Working directly to convert on Fourier transform is computationally too expensive. So, Fast Fourier transform is used as it rapidly computes by factorizing the DFT matrix as the product of sparse factors. As a result, it reduces the DFT computation complexity from O(N2) to O(N log N). And this is a huge difference when working on a large dataset. Also, FFT algorithms are very accurate as compared to the DFT definition directly, in the presence of round-off error. This transformation is a translation from the configuration space to frequency space and this is very important in terms of exploring both transformations of certain problems for more efficient computation and in exploring the power spectrum of a signal. This translation can be from xn to Xk. It is converting spatial or temporal data into the frequency domain data. sympy.discrete.transforms.ifft() :It can perform Inverse Discrete Fourier Transform (DFT) in the complex domain.Automatically the sequence is padded with zero to the right because the radix-2 FFT requires the sample point number as a power of 2. For short sequences use this method with default arguments only as with the size of the sequence, the complexity of expressions increases. Parameters : -> seq : [iterable] sequence on which Inverse DFT is to be applied. -> dps : [Integer] number of decimal digits for precision. Returns : Fast Fourier Transform Example 1: # import sympy from sympy import ifft # sequence seq = [15, 21, 13, 44] # ffttransform = ifft(seq)print ("Inverse FFT : ", transform) Output: Inverse FFT : [93/4, 1/2 + 23*I/4, -37/4, 1/2 - 23*I/4] Example 2: # import sympy from sympy import ifft # sequence seq = [15, 21, 13, 44] decimal_point = 4 # ffttransform = ifft(seq, decimal_point )print ("Inverse FFT : ", transform) Output: Inverse FFT : [23.25, 0.5 + 5.75*I, -9.250, 0.5 - 5.75*I] Maths Mathematical Python Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jul, 2021" }, { "code": null, "e": 828, "s": 54, "text": "Inverse Fast Fourier transform (IDFT) is an algorithm to undoes the process of DFT. It is also known as backward Fourier transform. It converts a space or time signal to a signal of the frequency domain. The DFT signal is generated by the distribution of value sequences to different frequency components. Working directly to convert on Fourier transform is computationally too expensive. So, Fast Fourier transform is used as it rapidly computes by factorizing the DFT matrix as the product of sparse factors. As a result, it reduces the DFT computation complexity from O(N2) to O(N log N). And this is a huge difference when working on a large dataset. Also, FFT algorithms are very accurate as compared to the DFT definition directly, in the presence of round-off error." }, { "code": null, "e": 1196, "s": 828, "text": "This transformation is a translation from the configuration space to frequency space and this is very important in terms of exploring both transformations of certain problems for more efficient computation and in exploring the power spectrum of a signal. This translation can be from xn to Xk. It is converting spatial or temporal data into the frequency domain data." }, { "code": null, "e": 1581, "s": 1196, "text": "sympy.discrete.transforms.ifft() :It can perform Inverse Discrete Fourier Transform (DFT) in the complex domain.Automatically the sequence is padded with zero to the right because the radix-2 FFT requires the sample point number as a power of 2. For short sequences use this method with default arguments only as with the size of the sequence, the complexity of expressions increases." }, { "code": null, "e": 1760, "s": 1581, "text": " Parameters : \n\n-> seq : [iterable] sequence on which Inverse DFT is to be applied.\n-> dps : [Integer] number of decimal digits for precision.\n\nReturns : \nFast Fourier Transform\n" }, { "code": null, "e": 1771, "s": 1760, "text": "Example 1:" }, { "code": "# import sympy from sympy import ifft # sequence seq = [15, 21, 13, 44] # ffttransform = ifft(seq)print (\"Inverse FFT : \", transform)", "e": 1907, "s": 1771, "text": null }, { "code": null, "e": 1915, "s": 1907, "text": "Output:" }, { "code": null, "e": 1972, "s": 1915, "text": "Inverse FFT : [93/4, 1/2 + 23*I/4, -37/4, 1/2 - 23*I/4]" }, { "code": null, "e": 1983, "s": 1972, "text": "Example 2:" }, { "code": "# import sympy from sympy import ifft # sequence seq = [15, 21, 13, 44] decimal_point = 4 # ffttransform = ifft(seq, decimal_point )print (\"Inverse FFT : \", transform)", "e": 2154, "s": 1983, "text": null }, { "code": null, "e": 2162, "s": 2154, "text": "Output:" }, { "code": null, "e": 2222, "s": 2162, "text": "Inverse FFT : [23.25, 0.5 + 5.75*I, -9.250, 0.5 - 5.75*I]\n" }, { "code": null, "e": 2228, "s": 2222, "text": "Maths" }, { "code": null, "e": 2241, "s": 2228, "text": "Mathematical" }, { "code": null, "e": 2248, "s": 2241, "text": "Python" }, { "code": null, "e": 2261, "s": 2248, "text": "Mathematical" } ]
Node.js console.count() Method
26 Jun, 2020 The console.count() method is an inbuilt application programming interface of the console module which is used to count label passed to it as a parameter, by maintaining an internal counter for that specific label. Syntax: console.count(label) Parameters: This method has one parameter as mentioned above and described below: label: It is an optional parameter specifies the label to be counted. Default value is “default”. Return Value: This method outputs the count of this function called with the specified label to the stdout. Below examples illustrate the use of console.count() method in Node.js: Example 1: // Node.js program to demonstrate the // console.count() Method // Accessing console moduleconst console = require('console'); // Calling console.count() console.count("a");console.count("b");console.count("a");console.count("a");console.count("a");console.count("b");console.count("b");console.count("b"); Output: a: 1 b: 1 a: 2 a: 3 a: 4 b: 2 b: 3 b: 4 Example 2: // Node.js program to demonstrate the // console.count() Method // Accessing console moduleconst console = require('console'); // Calling console.count() method// with no parameter to count// default labelconsole.count();console.count("a");console.count("b");console.count("a");console.count("a");console.count();console.count();console.count();console.count("b"); Output: default: 1 a: 1 b: 1 a: 2 a: 3 default: 2 default: 3 default: 4 b: 2 Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/console.html#console_console_count_label Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js 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": 28, "s": 0, "text": "\n26 Jun, 2020" }, { "code": null, "e": 243, "s": 28, "text": "The console.count() method is an inbuilt application programming interface of the console module which is used to count label passed to it as a parameter, by maintaining an internal counter for that specific label." }, { "code": null, "e": 251, "s": 243, "text": "Syntax:" }, { "code": null, "e": 272, "s": 251, "text": "console.count(label)" }, { "code": null, "e": 354, "s": 272, "text": "Parameters: This method has one parameter as mentioned above and described below:" }, { "code": null, "e": 452, "s": 354, "text": "label: It is an optional parameter specifies the label to be counted. Default value is “default”." }, { "code": null, "e": 560, "s": 452, "text": "Return Value: This method outputs the count of this function called with the specified label to the stdout." }, { "code": null, "e": 632, "s": 560, "text": "Below examples illustrate the use of console.count() method in Node.js:" }, { "code": null, "e": 643, "s": 632, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // console.count() Method // Accessing console moduleconst console = require('console'); // Calling console.count() console.count(\"a\");console.count(\"b\");console.count(\"a\");console.count(\"a\");console.count(\"a\");console.count(\"b\");console.count(\"b\");console.count(\"b\");", "e": 954, "s": 643, "text": null }, { "code": null, "e": 962, "s": 954, "text": "Output:" }, { "code": null, "e": 1003, "s": 962, "text": "a: 1\nb: 1\na: 2\na: 3\na: 4\nb: 2\nb: 3\nb: 4\n" }, { "code": null, "e": 1014, "s": 1003, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // console.count() Method // Accessing console moduleconst console = require('console'); // Calling console.count() method// with no parameter to count// default labelconsole.count();console.count(\"a\");console.count(\"b\");console.count(\"a\");console.count(\"a\");console.count();console.count();console.count();console.count(\"b\");", "e": 1383, "s": 1014, "text": null }, { "code": null, "e": 1391, "s": 1383, "text": "Output:" }, { "code": null, "e": 1461, "s": 1391, "text": "default: 1\na: 1\nb: 1\na: 2\na: 3\ndefault: 2\ndefault: 3\ndefault: 4\nb: 2\n" }, { "code": null, "e": 1545, "s": 1461, "text": "Note: The above program will compile and run by using the node filename.js command." }, { "code": null, "e": 1620, "s": 1545, "text": "Reference: https://nodejs.org/api/console.html#console_console_count_label" }, { "code": null, "e": 1636, "s": 1620, "text": "Node.js-Methods" }, { "code": null, "e": 1644, "s": 1636, "text": "Node.js" }, { "code": null, "e": 1661, "s": 1644, "text": "Web Technologies" }, { "code": null, "e": 1759, "s": 1661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1807, "s": 1759, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1840, "s": 1807, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1870, "s": 1840, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1890, "s": 1870, "text": "How to update NPM ?" }, { "code": null, "e": 1944, "s": 1890, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 2006, "s": 1944, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2067, "s": 2006, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2117, "s": 2067, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2160, "s": 2117, "text": "How to fetch data from an API in ReactJS ?" } ]
Lexicographically first palindromic string
07 Jul, 2022 Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message “no palindromic string”. Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach:1. Sort the string characters in alphabetical(ascending) order.2. One be one find lexicographically next permutation of the given string.3. The first permutation which is palindrome is the answer. Efficient Approach: Properties for palindromic string:1. If length of string is even, then the frequency of each character in the string must be even.2. If the length is odd then there should be one character whose frequency is odd and all other chars must have even frequency and at-least one occurrence of the odd character must be present in the middle of the string. Algorithm1. Store frequency of each character in the given string2. Check whether a palindromic string can be formed or not using the properties of palindromic string mentioned above.3. If palindromic string cannot be formed, return “No Palindromic String”.4. Else we create three strings and then return front_str + odd_str + rear_str. odd_str : It is empty if there is no character with odd frequency. Else it contains all occurrences of odd character. front_str : Contains half occurrences of all even occurring characters of string in increasing order. rear_str Contains half occurrences of all even occurring characters of string in reverse order of front_str. Below is implementation of above steps. C++ Java Python3 C# PHP // C++ program to find first palindromic permutation// of given string#include <bits/stdc++.h>using namespace std; const char MAX_CHAR = 26; // Function to count frequency of each char in the// string. freq[0] for 'a',...., freq[25] for 'z'void countFreq(string str, int freq[], int len){ for (int i=0; i<len; i++) freq[str.at(i) - 'a']++;} // Cases to check whether a palindr0mic// string can be formed or notbool canMakePalindrome(int freq[], int len){ // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i=0; i<MAX_CHAR; i++) if (freq[i]%2 != 0) count_odd++; // For even length string // no odd freq character if (len%2 == 0) { if (count_odd > 0) return false; else return true; } // For odd length string // one odd freq character if (count_odd != 1) return false; return true;} // Function to find odd freq char and// reducing its freq by 1returns "" if odd freq// char is not presentstring findOddAndRemoveItsFreq(int freq[]){ string odd_str = ""; for (int i=0; i<MAX_CHAR; i++) { if (freq[i]%2 != 0) { freq[i]--; odd_str = odd_str + (char)(i+'a'); return odd_str; } } return odd_str;} // To find lexicographically first palindromic// string.string findPalindromicString(string str){ int len = str.length(); int freq[MAX_CHAR] = {0}; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) return "No Palindromic String"; // Assigning odd freq character if present // else empty string. string odd_str = findOddAndRemoveItsFreq(freq); string front_str = "", rear_str = " "; // Traverse characters in increasing order for (int i=0; i<MAX_CHAR; i++) { string temp = ""; if (freq[i] != 0) { char ch = (char)(i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j=1; j<=freq[i]/2; j++) temp = temp + ch; // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str);} // Driver programint main(){ string str = "malayalam"; cout << findPalindromicString(str); return 0;} // Java program to find first palindromic permutation// of given string class GFG { static char MAX_CHAR = 26; // Function to count frequency of each char in the // string. freq[0] for 'a',...., freq[25] for 'z' static void countFreq(String str, int freq[], int len) { for (int i = 0; i < len; i++) { freq[str.charAt(i) - 'a']++; } } // Cases to check whether a palindr0mic // string can be formed or not static boolean canMakePalindrome(int freq[], int len) { // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { count_odd++; } } // For even length string // no odd freq character if (len % 2 == 0) { if (count_odd > 0) { return false; } else { return true; } } // For odd length string // one odd freq character if (count_odd != 1) { return false; } return true; } // Function to find odd freq char and // reducing its freq by 1returns "" if odd freq // char is not present static String findOddAndRemoveItsFreq(int freq[]) { String odd_str = ""; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { freq[i]--; odd_str = odd_str + (char) (i + 'a'); return odd_str; } } return odd_str; } // To find lexicographically first palindromic // string. static String findPalindromicString(String str) { int len = str.length(); int freq[] = new int[MAX_CHAR]; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) { return "No Palindromic String"; } // Assigning odd freq character if present // else empty string. String odd_str = findOddAndRemoveItsFreq(freq); String front_str = "", rear_str = " "; // Traverse characters in increasing order for (int i = 0; i < MAX_CHAR; i++) { String temp = ""; if (freq[i] != 0) { char ch = (char) (i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j = 1; j <= freq[i] / 2; j++) { temp = temp + ch; } // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str); } // Driver program public static void main(String[] args) { String str = "malayalam"; System.out.println(findPalindromicString(str)); }} // This code is contributed by Rajput-Ji # Python3 program to find first palindromic permutation# of given stringMAX_CHAR = 26; # Function to count frequency of each char in the# string. freq[0] for 'a',...., freq[25] for 'z'def countFreq(str1, freq, len1): for i in range(len1): freq[ord(str1[i]) - ord('a')] += 1; # Cases to check whether a palindr0mic# string can be formed or notdef canMakePalindrome(freq, len1): # count_odd to count no of # chars with odd frequency count_odd = 0; for i in range(MAX_CHAR): if (freq[i] % 2 != 0): count_odd += 1; # For even length string # no odd freq character if (len1 % 2 == 0): if (count_odd > 0): return False; else: return True; # For odd length string # one odd freq character if (count_odd != 1): return False; return True; # Function to find odd freq char and# reducing its freq by 1returns "" if odd freq# char is not presentdef findOddAndRemoveItsFreq(freq): odd_str = ""; for i in range(MAX_CHAR): if (freq[i]%2 != 0): freq[i]-=1; odd_str += chr(i+ord('a')); return odd_str; return odd_str; # To find lexicographically first palindromic# string.def findPalindromicString(str1): len1 = len(str1); freq=[0]*MAX_CHAR; countFreq(str1, freq, len1); if (canMakePalindrome(freq, len1) == False): return "No Palindromic String"; # Assigning odd freq character if present # else empty string. odd_str = findOddAndRemoveItsFreq(freq); front_str = ""; rear_str = " "; # Traverse characters in increasing order for i in range(MAX_CHAR): temp = ""; if (freq[i] != 0): ch = chr(i + ord('a')); # Divide all occurrences into two # halves. Note that odd character # is removed by findOddAndRemoveItsFreq() for j in range(1,int(freq[i]/2)+1): temp += ch; # creating front string front_str += temp; # creating rear string rear_str = temp+rear_str; # Final palindromic string which is # lexicographically first return (front_str + odd_str+rear_str); # Driver code str1 = "malayalam";print(findPalindromicString(str1)); # This code is contributed by mits // C# program to find first palindromic permutation// of given string using System;class GFG { static int MAX_CHAR = 26; // Function to count frequency of each char in the // string. freq[0] for 'a',...., freq[25] for 'z' static void countFreq(string str, int[] freq, int len) { for (int i = 0; i < len; i++) { freq[str[i] - 'a']++; } } // Cases to check whether a palindr0mic // string can be formed or not static bool canMakePalindrome(int[] freq, int len) { // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { count_odd++; } } // For even length string // no odd freq character if (len % 2 == 0) { if (count_odd > 0) { return false; } else { return true; } } // For odd length string // one odd freq character if (count_odd != 1) { return false; } return true; } // Function to find odd freq char and // reducing its freq by 1returns "" if odd freq // char is not present static string findOddAndRemoveItsFreq(int[] freq) { string odd_str = ""; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { freq[i]--; odd_str = odd_str + (char) (i + 'a'); return odd_str; } } return odd_str; } // To find lexicographically first // palindromic string. static string findPalindromicString(string str) { int len = str.Length; int[] freq = new int[MAX_CHAR]; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) { return "No Palindromic String"; } // Assigning odd freq character if present // else empty string. string odd_str = findOddAndRemoveItsFreq(freq); string front_str = "", rear_str = " "; // Traverse characters in increasing order for (int i = 0; i < MAX_CHAR; i++) { String temp = ""; if (freq[i] != 0) { char ch = (char) (i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j = 1; j <= freq[i] / 2; j++) { temp = temp + ch; } // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str); } // Driver code public static void Main() { string str = "malayalam"; Console.Write(findPalindromicString(str)); }} // This code is contributed by Ita_c. <?php// PHP program to find first palindromic permutation// of given string$MAX_CHAR = 26; // Function to count frequency of each char in the// string. freq[0] for 'a',...., freq[25] for 'z'function countFreq($str, &$freq, $len){ for ($i = 0; $i < $len; $i++) $freq[ord($str[$i]) - ord('a')]++;} // Cases to check whether a palindr0mic// string can be formed or notfunction canMakePalindrome($freq, $len){ global $MAX_CHAR; // count_odd to count no of // chars with odd frequency $count_odd = 0; for ($i = 0; $i < $MAX_CHAR; $i++) if ($freq[$i] % 2 != 0) $count_odd++; // For even length string // no odd freq character if ($len % 2 == 0) { if ($count_odd > 0) return false; else return true; } // For odd length string // one odd freq character if ($count_odd != 1) return false; return true;} // Function to find odd freq char and// reducing its freq by 1returns "" if odd freq// char is not presentfunction findOddAndRemoveItsFreq($freq){ global $MAX_CHAR; $odd_str = ""; for ($i = 0; $i < $MAX_CHAR; $i++) { if ($freq[$i] % 2 != 0) { $freq[$i]--; $odd_str .= chr($i+ord('a')); return $odd_str; } } return $odd_str;} // To find lexicographically first palindromic// string.function findPalindromicString($str){ global $MAX_CHAR; $len = strlen($str); $freq=array_fill(0, $MAX_CHAR, 0); countFreq($str, $freq, $len); if (!canMakePalindrome($freq, $len)) return "No Palindromic String"; // Assigning odd freq character if present // else empty string. $odd_str = findOddAndRemoveItsFreq($freq); $front_str = ""; $rear_str = " "; // Traverse characters in increasing order for ($i = 0; $i < $MAX_CHAR; $i++) { $temp = ""; if ($freq[$i] != 0) { $ch = chr($i + ord('a')); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for ($j = 1; $j <= (int)($freq[$i]/2); $j++) $temp .= $ch; // creating front string $front_str .= $temp; // creating rear string $rear_str = $temp.$rear_str; } } // Final palindromic string which is // lexicographically first return ($front_str.$odd_str.$rear_str);} // Driver code$str = "malayalam";echo findPalindromicString($str); // This code is contributed by mits?> Output: aalmymlaa Time Complexity : O(n) where n is length of input string. Assuming that size of string alphabet is constant. This article is contributed by Ayush Jauhari. 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. Rajput-Ji ukasp Mithun Kumar lexicographic-ordering palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Convert string to char array in C++ Check whether two strings are anagram of each other Reverse words in a given string
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 217, "s": 52, "text": "Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message “no palindromic string”." }, { "code": null, "e": 227, "s": 217, "text": "Examples:" }, { "code": null, "e": 311, "s": 227, "text": "Input : malayalam\nOutput : aalmymlaa\n\nInput : apple\nOutput : no palindromic string\n" }, { "code": null, "e": 524, "s": 311, "text": "Simple Approach:1. Sort the string characters in alphabetical(ascending) order.2. One be one find lexicographically next permutation of the given string.3. The first permutation which is palindrome is the answer." }, { "code": null, "e": 895, "s": 524, "text": "Efficient Approach: Properties for palindromic string:1. If length of string is even, then the frequency of each character in the string must be even.2. If the length is odd then there should be one character whose frequency is odd and all other chars must have even frequency and at-least one occurrence of the odd character must be present in the middle of the string." }, { "code": null, "e": 1232, "s": 895, "text": "Algorithm1. Store frequency of each character in the given string2. Check whether a palindromic string can be formed or not using the properties of palindromic string mentioned above.3. If palindromic string cannot be formed, return “No Palindromic String”.4. Else we create three strings and then return front_str + odd_str + rear_str." }, { "code": null, "e": 1350, "s": 1232, "text": "odd_str : It is empty if there is no character with odd frequency. Else it contains all occurrences of odd character." }, { "code": null, "e": 1452, "s": 1350, "text": "front_str : Contains half occurrences of all even occurring characters of string in increasing order." }, { "code": null, "e": 1561, "s": 1452, "text": "rear_str Contains half occurrences of all even occurring characters of string in reverse order of front_str." }, { "code": null, "e": 1601, "s": 1561, "text": "Below is implementation of above steps." }, { "code": null, "e": 1605, "s": 1601, "text": "C++" }, { "code": null, "e": 1610, "s": 1605, "text": "Java" }, { "code": null, "e": 1618, "s": 1610, "text": "Python3" }, { "code": null, "e": 1621, "s": 1618, "text": "C#" }, { "code": null, "e": 1625, "s": 1621, "text": "PHP" }, { "code": "// C++ program to find first palindromic permutation// of given string#include <bits/stdc++.h>using namespace std; const char MAX_CHAR = 26; // Function to count frequency of each char in the// string. freq[0] for 'a',...., freq[25] for 'z'void countFreq(string str, int freq[], int len){ for (int i=0; i<len; i++) freq[str.at(i) - 'a']++;} // Cases to check whether a palindr0mic// string can be formed or notbool canMakePalindrome(int freq[], int len){ // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i=0; i<MAX_CHAR; i++) if (freq[i]%2 != 0) count_odd++; // For even length string // no odd freq character if (len%2 == 0) { if (count_odd > 0) return false; else return true; } // For odd length string // one odd freq character if (count_odd != 1) return false; return true;} // Function to find odd freq char and// reducing its freq by 1returns \"\" if odd freq// char is not presentstring findOddAndRemoveItsFreq(int freq[]){ string odd_str = \"\"; for (int i=0; i<MAX_CHAR; i++) { if (freq[i]%2 != 0) { freq[i]--; odd_str = odd_str + (char)(i+'a'); return odd_str; } } return odd_str;} // To find lexicographically first palindromic// string.string findPalindromicString(string str){ int len = str.length(); int freq[MAX_CHAR] = {0}; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) return \"No Palindromic String\"; // Assigning odd freq character if present // else empty string. string odd_str = findOddAndRemoveItsFreq(freq); string front_str = \"\", rear_str = \" \"; // Traverse characters in increasing order for (int i=0; i<MAX_CHAR; i++) { string temp = \"\"; if (freq[i] != 0) { char ch = (char)(i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j=1; j<=freq[i]/2; j++) temp = temp + ch; // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str);} // Driver programint main(){ string str = \"malayalam\"; cout << findPalindromicString(str); return 0;}", "e": 4179, "s": 1625, "text": null }, { "code": "// Java program to find first palindromic permutation// of given string class GFG { static char MAX_CHAR = 26; // Function to count frequency of each char in the // string. freq[0] for 'a',...., freq[25] for 'z' static void countFreq(String str, int freq[], int len) { for (int i = 0; i < len; i++) { freq[str.charAt(i) - 'a']++; } } // Cases to check whether a palindr0mic // string can be formed or not static boolean canMakePalindrome(int freq[], int len) { // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { count_odd++; } } // For even length string // no odd freq character if (len % 2 == 0) { if (count_odd > 0) { return false; } else { return true; } } // For odd length string // one odd freq character if (count_odd != 1) { return false; } return true; } // Function to find odd freq char and // reducing its freq by 1returns \"\" if odd freq // char is not present static String findOddAndRemoveItsFreq(int freq[]) { String odd_str = \"\"; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { freq[i]--; odd_str = odd_str + (char) (i + 'a'); return odd_str; } } return odd_str; } // To find lexicographically first palindromic // string. static String findPalindromicString(String str) { int len = str.length(); int freq[] = new int[MAX_CHAR]; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) { return \"No Palindromic String\"; } // Assigning odd freq character if present // else empty string. String odd_str = findOddAndRemoveItsFreq(freq); String front_str = \"\", rear_str = \" \"; // Traverse characters in increasing order for (int i = 0; i < MAX_CHAR; i++) { String temp = \"\"; if (freq[i] != 0) { char ch = (char) (i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j = 1; j <= freq[i] / 2; j++) { temp = temp + ch; } // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str); } // Driver program public static void main(String[] args) { String str = \"malayalam\"; System.out.println(findPalindromicString(str)); }} // This code is contributed by Rajput-Ji", "e": 7402, "s": 4179, "text": null }, { "code": "# Python3 program to find first palindromic permutation# of given stringMAX_CHAR = 26; # Function to count frequency of each char in the# string. freq[0] for 'a',...., freq[25] for 'z'def countFreq(str1, freq, len1): for i in range(len1): freq[ord(str1[i]) - ord('a')] += 1; # Cases to check whether a palindr0mic# string can be formed or notdef canMakePalindrome(freq, len1): # count_odd to count no of # chars with odd frequency count_odd = 0; for i in range(MAX_CHAR): if (freq[i] % 2 != 0): count_odd += 1; # For even length string # no odd freq character if (len1 % 2 == 0): if (count_odd > 0): return False; else: return True; # For odd length string # one odd freq character if (count_odd != 1): return False; return True; # Function to find odd freq char and# reducing its freq by 1returns \"\" if odd freq# char is not presentdef findOddAndRemoveItsFreq(freq): odd_str = \"\"; for i in range(MAX_CHAR): if (freq[i]%2 != 0): freq[i]-=1; odd_str += chr(i+ord('a')); return odd_str; return odd_str; # To find lexicographically first palindromic# string.def findPalindromicString(str1): len1 = len(str1); freq=[0]*MAX_CHAR; countFreq(str1, freq, len1); if (canMakePalindrome(freq, len1) == False): return \"No Palindromic String\"; # Assigning odd freq character if present # else empty string. odd_str = findOddAndRemoveItsFreq(freq); front_str = \"\"; rear_str = \" \"; # Traverse characters in increasing order for i in range(MAX_CHAR): temp = \"\"; if (freq[i] != 0): ch = chr(i + ord('a')); # Divide all occurrences into two # halves. Note that odd character # is removed by findOddAndRemoveItsFreq() for j in range(1,int(freq[i]/2)+1): temp += ch; # creating front string front_str += temp; # creating rear string rear_str = temp+rear_str; # Final palindromic string which is # lexicographically first return (front_str + odd_str+rear_str); # Driver code str1 = \"malayalam\";print(findPalindromicString(str1)); # This code is contributed by mits", "e": 9717, "s": 7402, "text": null }, { "code": "// C# program to find first palindromic permutation// of given string using System;class GFG { static int MAX_CHAR = 26; // Function to count frequency of each char in the // string. freq[0] for 'a',...., freq[25] for 'z' static void countFreq(string str, int[] freq, int len) { for (int i = 0; i < len; i++) { freq[str[i] - 'a']++; } } // Cases to check whether a palindr0mic // string can be formed or not static bool canMakePalindrome(int[] freq, int len) { // count_odd to count no of // chars with odd frequency int count_odd = 0; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { count_odd++; } } // For even length string // no odd freq character if (len % 2 == 0) { if (count_odd > 0) { return false; } else { return true; } } // For odd length string // one odd freq character if (count_odd != 1) { return false; } return true; } // Function to find odd freq char and // reducing its freq by 1returns \"\" if odd freq // char is not present static string findOddAndRemoveItsFreq(int[] freq) { string odd_str = \"\"; for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] % 2 != 0) { freq[i]--; odd_str = odd_str + (char) (i + 'a'); return odd_str; } } return odd_str; } // To find lexicographically first // palindromic string. static string findPalindromicString(string str) { int len = str.Length; int[] freq = new int[MAX_CHAR]; countFreq(str, freq, len); if (!canMakePalindrome(freq, len)) { return \"No Palindromic String\"; } // Assigning odd freq character if present // else empty string. string odd_str = findOddAndRemoveItsFreq(freq); string front_str = \"\", rear_str = \" \"; // Traverse characters in increasing order for (int i = 0; i < MAX_CHAR; i++) { String temp = \"\"; if (freq[i] != 0) { char ch = (char) (i + 'a'); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for (int j = 1; j <= freq[i] / 2; j++) { temp = temp + ch; } // creating front string front_str = front_str + temp; // creating rear string rear_str = temp + rear_str; } } // Final palindromic string which is // lexicographically first return (front_str + odd_str + rear_str); } // Driver code public static void Main() { string str = \"malayalam\"; Console.Write(findPalindromicString(str)); }} // This code is contributed by Ita_c.", "e": 12915, "s": 9717, "text": null }, { "code": "<?php// PHP program to find first palindromic permutation// of given string$MAX_CHAR = 26; // Function to count frequency of each char in the// string. freq[0] for 'a',...., freq[25] for 'z'function countFreq($str, &$freq, $len){ for ($i = 0; $i < $len; $i++) $freq[ord($str[$i]) - ord('a')]++;} // Cases to check whether a palindr0mic// string can be formed or notfunction canMakePalindrome($freq, $len){ global $MAX_CHAR; // count_odd to count no of // chars with odd frequency $count_odd = 0; for ($i = 0; $i < $MAX_CHAR; $i++) if ($freq[$i] % 2 != 0) $count_odd++; // For even length string // no odd freq character if ($len % 2 == 0) { if ($count_odd > 0) return false; else return true; } // For odd length string // one odd freq character if ($count_odd != 1) return false; return true;} // Function to find odd freq char and// reducing its freq by 1returns \"\" if odd freq// char is not presentfunction findOddAndRemoveItsFreq($freq){ global $MAX_CHAR; $odd_str = \"\"; for ($i = 0; $i < $MAX_CHAR; $i++) { if ($freq[$i] % 2 != 0) { $freq[$i]--; $odd_str .= chr($i+ord('a')); return $odd_str; } } return $odd_str;} // To find lexicographically first palindromic// string.function findPalindromicString($str){ global $MAX_CHAR; $len = strlen($str); $freq=array_fill(0, $MAX_CHAR, 0); countFreq($str, $freq, $len); if (!canMakePalindrome($freq, $len)) return \"No Palindromic String\"; // Assigning odd freq character if present // else empty string. $odd_str = findOddAndRemoveItsFreq($freq); $front_str = \"\"; $rear_str = \" \"; // Traverse characters in increasing order for ($i = 0; $i < $MAX_CHAR; $i++) { $temp = \"\"; if ($freq[$i] != 0) { $ch = chr($i + ord('a')); // Divide all occurrences into two // halves. Note that odd character // is removed by findOddAndRemoveItsFreq() for ($j = 1; $j <= (int)($freq[$i]/2); $j++) $temp .= $ch; // creating front string $front_str .= $temp; // creating rear string $rear_str = $temp.$rear_str; } } // Final palindromic string which is // lexicographically first return ($front_str.$odd_str.$rear_str);} // Driver code$str = \"malayalam\";echo findPalindromicString($str); // This code is contributed by mits?>", "e": 15490, "s": 12915, "text": null }, { "code": null, "e": 15498, "s": 15490, "text": "Output:" }, { "code": null, "e": 15509, "s": 15498, "text": "aalmymlaa\n" }, { "code": null, "e": 15618, "s": 15509, "text": "Time Complexity : O(n) where n is length of input string. Assuming that size of string alphabet is constant." }, { "code": null, "e": 15915, "s": 15618, "text": "This article is contributed by Ayush Jauhari. 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": 16040, "s": 15915, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 16050, "s": 16040, "text": "Rajput-Ji" }, { "code": null, "e": 16056, "s": 16050, "text": "ukasp" }, { "code": null, "e": 16069, "s": 16056, "text": "Mithun Kumar" }, { "code": null, "e": 16092, "s": 16069, "text": "lexicographic-ordering" }, { "code": null, "e": 16103, "s": 16092, "text": "palindrome" }, { "code": null, "e": 16111, "s": 16103, "text": "Strings" }, { "code": null, "e": 16119, "s": 16111, "text": "Strings" }, { "code": null, "e": 16130, "s": 16119, "text": "palindrome" }, { "code": null, "e": 16228, "s": 16130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16273, "s": 16228, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 16330, "s": 16273, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 16405, "s": 16330, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 16441, "s": 16405, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 16479, "s": 16441, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 16540, "s": 16479, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 16585, "s": 16540, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 16621, "s": 16585, "text": "Convert string to char array in C++" }, { "code": null, "e": 16673, "s": 16621, "text": "Check whether two strings are anagram of each other" } ]
How to Encrypt and Decrypt a PHP String ?
31 Jul, 2021 In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt. openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data. Syntax: string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 ) Parameters: $data: It holds the string or data which need to be encrypted. $method: The cipher method is adopted using openssl_get_cipher_methods() function. $key: It holds the encryption key. $options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING. $iv: It holds the initialization vector which is not NULL. $tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM). $aad: It holds the additional authentication data. $tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode. Return Value: It returns the encrypted string on success or FALSE on failure. openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data. Syntax: string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad) Parameters: $data: It holds the string or data which need to be encrypted. $method: The cipher method is adopted using openssl_get_cipher_methods() function. $key: It holds the encryption key. $options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING. $iv: It holds the initialization vector which is not NULL. $tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE. $aad: It holds the additional authentication data. Return Value: It returns the decrypted string on success or FALSE on failure. Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string. Example 1: This example illustrates the encryption and decryption of string. <?php // Store a string into the variable which// need to be Encrypted$simple_string = "Welcome to GeeksforGeeks\n"; // Display the original stringecho "Original String: " . $simple_string; // Store the cipher method$ciphering = "AES-128-CTR"; // Use OpenSSl Encryption method$iv_length = openssl_cipher_iv_length($ciphering);$options = 0; // Non-NULL Initialization Vector for encryption$encryption_iv = '1234567891011121'; // Store the encryption key$encryption_key = "GeeksforGeeks"; // Use openssl_encrypt() function to encrypt the data$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv); // Display the encrypted stringecho "Encrypted String: " . $encryption . "\n"; // Non-NULL Initialization Vector for decryption$decryption_iv = '1234567891011121'; // Store the decryption key$decryption_key = "GeeksforGeeks"; // Use openssl_decrypt() function to decrypt the data$decryption=openssl_decrypt ($encryption, $ciphering, $decryption_key, $options, $decryption_iv); // Display the decrypted stringecho "Decrypted String: " . $decryption; ?> Output: Original String: Welcome to GeeksforGeeks Encrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA== Decrypted String: Welcome to GeeksforGeeks Example 2: Below example illustrate the encryption and decryption of string. Here string to be encrypted and decrypted string will be same but the encrypted string is randomly changed respectively. <?php // Store a string into the variable which// need to be Encrypted$simple_string = "Welcome to GeeksforGeeks"; // Display the original stringecho "Original String: " . $simple_string . "\n"; // Store cipher method$ciphering = "BF-CBC"; // Use OpenSSl encryption method$iv_length = openssl_cipher_iv_length($ciphering);$options = 0; // Use random_bytes() function which gives// randomly 16 digit values$encryption_iv = random_bytes($iv_length); // Alternatively, we can use any 16 digit// characters or numeric for iv$encryption_key = openssl_digest(php_uname(), 'MD5', TRUE); // Encryption of string process starts$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv); // Display the encrypted stringecho "Encrypted String: " . $encryption . "\n"; // Decryption of string process starts// Used random_bytes() which gives randomly// 16 digit values$decryption_iv = random_bytes($iv_length); // Store the decryption key$decryption_key = openssl_digest(php_uname(), 'MD5', TRUE); // Descrypt the string$decryption = openssl_decrypt ($encryption, $ciphering, $decryption_key, $options, $encryption_iv); // Display the decrypted stringecho "Decrypted String: " . $decryption; ?> Output: Original String: Welcome to GeeksforGeeks Encrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA== Decrypted String: Welcome to GeeksforGeeks References: https://www.php.net/manual/en/function.openssl-encrypt.php https://www.php.net/manual/en/function.openssl-decrypt.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. PHP-basics Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to execute PHP code using command line ? How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jul, 2021" }, { "code": null, "e": 202, "s": 54, "text": "In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt." }, { "code": null, "e": 290, "s": 202, "text": "openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data." }, { "code": null, "e": 298, "s": 290, "text": "Syntax:" }, { "code": null, "e": 496, "s": 298, "text": "string openssl_encrypt( string $data, string $method, string $key,\n $options = 0, string $iv, string $tag= NULL,\n string $aad, int $tag_length = 16 )\n" }, { "code": null, "e": 508, "s": 496, "text": "Parameters:" }, { "code": null, "e": 571, "s": 508, "text": "$data: It holds the string or data which need to be encrypted." }, { "code": null, "e": 654, "s": 571, "text": "$method: The cipher method is adopted using openssl_get_cipher_methods() function." }, { "code": null, "e": 689, "s": 654, "text": "$key: It holds the encryption key." }, { "code": null, "e": 788, "s": 689, "text": "$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING." }, { "code": null, "e": 847, "s": 788, "text": "$iv: It holds the initialization vector which is not NULL." }, { "code": null, "e": 956, "s": 847, "text": "$tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM)." }, { "code": null, "e": 1007, "s": 956, "text": "$aad: It holds the additional authentication data." }, { "code": null, "e": 1135, "s": 1007, "text": "$tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode." }, { "code": null, "e": 1213, "s": 1135, "text": "Return Value: It returns the encrypted string on success or FALSE on failure." }, { "code": null, "e": 1300, "s": 1213, "text": "openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data." }, { "code": null, "e": 1308, "s": 1300, "text": "Syntax:" }, { "code": null, "e": 1445, "s": 1308, "text": "string openssl_decrypt( string $data, string $method, string $key,\n int $options = 0, string $iv, string $tag, string $aad)\n" }, { "code": null, "e": 1457, "s": 1445, "text": "Parameters:" }, { "code": null, "e": 1520, "s": 1457, "text": "$data: It holds the string or data which need to be encrypted." }, { "code": null, "e": 1603, "s": 1520, "text": "$method: The cipher method is adopted using openssl_get_cipher_methods() function." }, { "code": null, "e": 1638, "s": 1603, "text": "$key: It holds the encryption key." }, { "code": null, "e": 1737, "s": 1638, "text": "$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING." }, { "code": null, "e": 1796, "s": 1737, "text": "$iv: It holds the initialization vector which is not NULL." }, { "code": null, "e": 1930, "s": 1796, "text": "$tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE." }, { "code": null, "e": 1981, "s": 1930, "text": "$aad: It holds the additional authentication data." }, { "code": null, "e": 2059, "s": 1981, "text": "Return Value: It returns the decrypted string on success or FALSE on failure." }, { "code": null, "e": 2247, "s": 2059, "text": "Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string." }, { "code": null, "e": 2324, "s": 2247, "text": "Example 1: This example illustrates the encryption and decryption of string." }, { "code": "<?php // Store a string into the variable which// need to be Encrypted$simple_string = \"Welcome to GeeksforGeeks\\n\"; // Display the original stringecho \"Original String: \" . $simple_string; // Store the cipher method$ciphering = \"AES-128-CTR\"; // Use OpenSSl Encryption method$iv_length = openssl_cipher_iv_length($ciphering);$options = 0; // Non-NULL Initialization Vector for encryption$encryption_iv = '1234567891011121'; // Store the encryption key$encryption_key = \"GeeksforGeeks\"; // Use openssl_encrypt() function to encrypt the data$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv); // Display the encrypted stringecho \"Encrypted String: \" . $encryption . \"\\n\"; // Non-NULL Initialization Vector for decryption$decryption_iv = '1234567891011121'; // Store the decryption key$decryption_key = \"GeeksforGeeks\"; // Use openssl_decrypt() function to decrypt the data$decryption=openssl_decrypt ($encryption, $ciphering, $decryption_key, $options, $decryption_iv); // Display the decrypted stringecho \"Decrypted String: \" . $decryption; ?>", "e": 3450, "s": 2324, "text": null }, { "code": null, "e": 3458, "s": 3450, "text": "Output:" }, { "code": null, "e": 3599, "s": 3458, "text": "Original String: Welcome to GeeksforGeeks\nEncrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA==\nDecrypted String: Welcome to GeeksforGeeks\n" }, { "code": null, "e": 3797, "s": 3599, "text": "Example 2: Below example illustrate the encryption and decryption of string. Here string to be encrypted and decrypted string will be same but the encrypted string is randomly changed respectively." }, { "code": "<?php // Store a string into the variable which// need to be Encrypted$simple_string = \"Welcome to GeeksforGeeks\"; // Display the original stringecho \"Original String: \" . $simple_string . \"\\n\"; // Store cipher method$ciphering = \"BF-CBC\"; // Use OpenSSl encryption method$iv_length = openssl_cipher_iv_length($ciphering);$options = 0; // Use random_bytes() function which gives// randomly 16 digit values$encryption_iv = random_bytes($iv_length); // Alternatively, we can use any 16 digit// characters or numeric for iv$encryption_key = openssl_digest(php_uname(), 'MD5', TRUE); // Encryption of string process starts$encryption = openssl_encrypt($simple_string, $ciphering, $encryption_key, $options, $encryption_iv); // Display the encrypted stringecho \"Encrypted String: \" . $encryption . \"\\n\"; // Decryption of string process starts// Used random_bytes() which gives randomly// 16 digit values$decryption_iv = random_bytes($iv_length); // Store the decryption key$decryption_key = openssl_digest(php_uname(), 'MD5', TRUE); // Descrypt the string$decryption = openssl_decrypt ($encryption, $ciphering, $decryption_key, $options, $encryption_iv); // Display the decrypted stringecho \"Decrypted String: \" . $decryption; ?>", "e": 5053, "s": 3797, "text": null }, { "code": null, "e": 5061, "s": 5053, "text": "Output:" }, { "code": null, "e": 5202, "s": 5061, "text": "Original String: Welcome to GeeksforGeeks\nEncrypted String: hwB1K5NkfcIzkLTWQeQfHLNg5FlyX3PNUA==\nDecrypted String: Welcome to GeeksforGeeks\n" }, { "code": null, "e": 5214, "s": 5202, "text": "References:" }, { "code": null, "e": 5273, "s": 5214, "text": "https://www.php.net/manual/en/function.openssl-encrypt.php" }, { "code": null, "e": 5332, "s": 5273, "text": "https://www.php.net/manual/en/function.openssl-decrypt.php" }, { "code": null, "e": 5501, "s": 5332, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 5512, "s": 5501, "text": "PHP-basics" }, { "code": null, "e": 5519, "s": 5512, "text": "Picked" }, { "code": null, "e": 5523, "s": 5519, "text": "PHP" }, { "code": null, "e": 5536, "s": 5523, "text": "PHP Programs" }, { "code": null, "e": 5553, "s": 5536, "text": "Web Technologies" }, { "code": null, "e": 5580, "s": 5553, "text": "Web technologies Questions" }, { "code": null, "e": 5584, "s": 5580, "text": "PHP" }, { "code": null, "e": 5682, "s": 5584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5727, "s": 5682, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 5751, "s": 5727, "text": "PHP in_array() Function" }, { "code": null, "e": 5803, "s": 5751, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 5853, "s": 5803, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5893, "s": 5853, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 5938, "s": 5893, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 5990, "s": 5938, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 6040, "s": 5990, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 6080, "s": 6040, "text": "How to convert array to string in PHP ?" } ]
How to reload activity in Android?
In some situations, we need to recall activity again from onCreate(). This example demonstrates how to reload activity 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"> <TextView android:id = "@+id/text" android:textSize = "28sp" android:textAlignment = "center" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, We have taken text view, when a user clicks on text view, it will call Main Activity again. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Intent; 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.TextView; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; TextView textview; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); textview = findViewById(R.id.text); textview.setText("Click here to recall activity"); textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, MainActivity.class); finish(); overridePendingTransition(0, 0); startActivity(i); overridePendingTransition(0, 0); } }); } } In the above code, we have used Intent to recreate an activity as shown below - Intent i = new Intent(MainActivity.this, MainActivity.class); finish(); overridePendingTransition(0, 0); startActivity(i); overridePendingTransition(0, 0); In the above code, we have used overridePendingTransition(), it is used to remove activity create animation while re-creating activity. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, it has shown default screen when you click on text view, it will re-create Main Activity from onCreate() as shown below - Click here to download the project code
[ { "code": null, "e": 1318, "s": 1187, "text": "In some situations, we need to recall activity again from onCreate(). This example demonstrates how to reload activity in Android." }, { "code": null, "e": 1447, "s": 1318, "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": 1512, "s": 1447, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2120, "s": 1512, "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 <TextView\n android:id = \"@+id/text\"\n android:textSize = \"28sp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2231, "s": 2120, "text": "In the above code, We have taken text view, when a user clicks on text view, it will call Main Activity again." }, { "code": null, "e": 2288, "s": 2231, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3335, "s": 2288, "text": "package com.example.andy.myapplication;\nimport android.content.Intent;\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.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textview;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textview = findViewById(R.id.text);\n textview.setText(\"Click here to recall activity\");\n textview.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent i = new Intent(MainActivity.this, MainActivity.class);\n finish();\n overridePendingTransition(0, 0);\n startActivity(i);\n overridePendingTransition(0, 0);\n }\n });\n }\n}" }, { "code": null, "e": 3415, "s": 3335, "text": "In the above code, we have used Intent to recreate an activity as shown below -" }, { "code": null, "e": 3571, "s": 3415, "text": "Intent i = new Intent(MainActivity.this, MainActivity.class);\nfinish();\noverridePendingTransition(0, 0);\nstartActivity(i);\noverridePendingTransition(0, 0);" }, { "code": null, "e": 3707, "s": 3571, "text": "In the above code, we have used overridePendingTransition(), it is used to remove activity create animation while re-creating activity." }, { "code": null, "e": 4054, "s": 3707, "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": 4197, "s": 4054, "text": "In the above result, it has shown default screen when you click on text view, it will re-create Main Activity from onCreate() as shown below -" }, { "code": null, "e": 4237, "s": 4197, "text": "Click here to download the project code" } ]
MongoDB - Analyzing Queries
Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries. The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized. In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query − >db.users.createIndex({gender:1,user_name:1}) { "numIndexesBefore" : 2, "numIndexesAfter" : 2, "note" : "all indexes already exist", "ok" : 1 } We will now use $explain on the following query − >db.users.find({gender:"M"},{user_name:1,_id:0}).explain() The above explain() query returns the following analyzed result − { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "mydb.users", "indexFilterSet" : false, "parsedQuery" : { "gender" : { "$eq" : "M" } }, "queryHash" : "B4037D3C", "planCacheKey" : "DEAAE17C", "winningPlan" : { "stage" : "PROJECTION_COVERED", "transformBy" : { "user_name" : 1, "_id" : 0 }, "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "gender" : 1, "user_name" : 1 }, "indexName" : "gender_1_user_name_1", "isMultiKey" : false, "multiKeyPaths" : { "gender" : [ ], "user_name" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "gender" : [ "[\"M\", \"M\"]" ], "user_name" : [ "[MinKey, MaxKey]" ] } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "Krishna", "port" : 27017, "version" : "4.2.1", "gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e" }, "ok" : 1 } We will now look at the fields in this result set − The true value of indexOnly indicates that this query has used indexing. The true value of indexOnly indicates that this query has used indexing. The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes. The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes. n indicates the number of documents matching returned. n indicates the number of documents matching returned. nscannedObjects indicates the total number of documents scanned. nscannedObjects indicates the total number of documents scanned. nscanned indicates the total number of documents or index entries scanned. nscanned indicates the total number of documents or index entries scanned. The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query − >db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}) { "user_name" : "tombenzamin" } To analyze the above query using $explain − >db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain() Which gives you the following result − { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "mydb.users", "indexFilterSet" : false, "parsedQuery" : { "gender" : { "$eq" : "M" } }, "queryHash" : "B4037D3C", "planCacheKey" : "DEAAE17C", "winningPlan" : { "stage" : "PROJECTION_COVERED", "transformBy" : { "user_name" : 1, "_id" : 0 }, "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "gender" : 1, "user_name" : 1 }, "indexName" : "gender_1_user_name_1", "isMultiKey" : false, "multiKeyPaths" : { "gender" : [ ], "user_name" : [ ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "gender" : [ "[\"M\", \"M\"]" ], "user_name" : [ "[MinKey, MaxKey]" ] } } }, "rejectedPlans" : [ ] }, "serverInfo" : { "host" : "Krishna", "port" : 27017, "version" : "4.2.1", 109 "gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e" }, "ok" : 1 } 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2730, "s": 2553, "text": "Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries." }, { "code": null, "e": 2903, "s": 2730, "text": "The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized." }, { "code": null, "e": 3040, "s": 2903, "text": "In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query −" }, { "code": null, "e": 3188, "s": 3040, "text": ">db.users.createIndex({gender:1,user_name:1})\n{\n\t\"numIndexesBefore\" : 2,\n\t\"numIndexesAfter\" : 2,\n\t\"note\" : \"all indexes already exist\",\n\t\"ok\" : 1\n}" }, { "code": null, "e": 3238, "s": 3188, "text": "We will now use $explain on the following query −" }, { "code": null, "e": 3297, "s": 3238, "text": ">db.users.find({gender:\"M\"},{user_name:1,_id:0}).explain()" }, { "code": null, "e": 3363, "s": 3297, "text": "The above explain() query returns the following analyzed result −" }, { "code": null, "e": 4412, "s": 3363, "text": "{\n\t\"queryPlanner\" : {\n\t\t\"plannerVersion\" : 1,\n\t\t\"namespace\" : \"mydb.users\",\n\t\t\"indexFilterSet\" : false,\n\t\t\"parsedQuery\" : {\n\t\t\t\"gender\" : {\n\t\t\t\t\"$eq\" : \"M\"\n\t\t\t}\n\t\t},\n\t\t\"queryHash\" : \"B4037D3C\",\n\t\t\"planCacheKey\" : \"DEAAE17C\",\n\t\t\"winningPlan\" : {\n\t\t\t\"stage\" : \"PROJECTION_COVERED\",\n\t\t\t\"transformBy\" : {\n\t\t\t\t\"user_name\" : 1,\n\t\t\t\t\"_id\" : 0\n\t\t\t},\n\t\t\t\"inputStage\" : {\n\t\t\t\t\"stage\" : \"IXSCAN\",\n\t\t\t\t\"keyPattern\" : {\n\t\t\t\t\t\"gender\" : 1,\n\t\t\t\t\t\"user_name\" : 1\n\t\t\t\t},\n\t\t\t\t\"indexName\" : \"gender_1_user_name_1\",\n\t\t\t\t\"isMultiKey\" : false,\n\t\t\t\t\"multiKeyPaths\" : {\n\t\t\t\t\t\"gender\" : [ ],\n\t\t\t\t\t\"user_name\" : [ ]\n\t\t\t\t},\n\t\t\t\t\"isUnique\" : false,\n\t\t\t\t\"isSparse\" : false,\n\t\t\t\t\"isPartial\" : false,\n\t\t\t\t\"indexVersion\" : 2,\n\t\t\t\t\"direction\" : \"forward\",\n\t\t\t\t\"indexBounds\" : {\n\t\t\t\t\t\"gender\" : [\n\t\t\t\t\t\t\"[\\\"M\\\", \\\"M\\\"]\"\n\t\t\t\t\t],\n\t\t\t\t\t\"user_name\" : [\n\t\t\t\t\t\t\"[MinKey, MaxKey]\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"rejectedPlans\" : [ ]\n\t},\n\t\"serverInfo\" : {\n\t\t\"host\" : \"Krishna\",\n\t\t\"port\" : 27017,\n\t\t\"version\" : \"4.2.1\",\n\t\t\"gitVersion\" : \"edf6d45851c0b9ee15548f0f847df141764a317e\"\n\t},\n\t\"ok\" : 1\n}\n" }, { "code": null, "e": 4464, "s": 4412, "text": "We will now look at the fields in this result set −" }, { "code": null, "e": 4537, "s": 4464, "text": "The true value of indexOnly indicates that this query has used indexing." }, { "code": null, "e": 4610, "s": 4537, "text": "The true value of indexOnly indicates that this query has used indexing." }, { "code": null, "e": 4830, "s": 4610, "text": "The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes." }, { "code": null, "e": 5050, "s": 4830, "text": "The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes." }, { "code": null, "e": 5105, "s": 5050, "text": "n indicates the number of documents matching returned." }, { "code": null, "e": 5160, "s": 5105, "text": "n indicates the number of documents matching returned." }, { "code": null, "e": 5225, "s": 5160, "text": "nscannedObjects indicates the total number of documents scanned." }, { "code": null, "e": 5290, "s": 5225, "text": "nscannedObjects indicates the total number of documents scanned." }, { "code": null, "e": 5365, "s": 5290, "text": "nscanned indicates the total number of documents or index entries scanned." }, { "code": null, "e": 5440, "s": 5365, "text": "nscanned indicates the total number of documents or index entries scanned." }, { "code": null, "e": 5738, "s": 5440, "text": "The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query −" }, { "code": null, "e": 5848, "s": 5738, "text": ">db.users.find({gender:\"M\"},{user_name:1,_id:0}).hint({gender:1,user_name:1})\n{ \"user_name\" : \"tombenzamin\" }" }, { "code": null, "e": 5892, "s": 5848, "text": "To analyze the above query using $explain −" }, { "code": null, "e": 5980, "s": 5892, "text": ">db.users.find({gender:\"M\"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()" }, { "code": null, "e": 6019, "s": 5980, "text": "Which gives you the following result −" }, { "code": null, "e": 7073, "s": 6019, "text": "{\n\t\"queryPlanner\" : {\n\t\t\"plannerVersion\" : 1,\n\t\t\"namespace\" : \"mydb.users\",\n\t\t\"indexFilterSet\" : false,\n\t\t\"parsedQuery\" : {\n\t\t\t\"gender\" : {\n\t\t\t\t\"$eq\" : \"M\"\n\t\t\t}\n\t\t},\n\t\t\"queryHash\" : \"B4037D3C\",\n\t\t\"planCacheKey\" : \"DEAAE17C\",\n\t\t\"winningPlan\" : {\n\t\t\t\"stage\" : \"PROJECTION_COVERED\",\n\t\t\t\"transformBy\" : {\n\t\t\t\t\"user_name\" : 1,\n\t\t\t\t\"_id\" : 0\n\t\t\t},\n\t\t\t\"inputStage\" : {\n\t\t\t\t\"stage\" : \"IXSCAN\",\n\t\t\t\t\"keyPattern\" : {\n\t\t\t\t\t\"gender\" : 1,\n\t\t\t\t\t\"user_name\" : 1\n\t\t\t\t},\n\t\t\t\t\"indexName\" : \"gender_1_user_name_1\",\n\t\t\t\t\"isMultiKey\" : false,\n\t\t\t\t\"multiKeyPaths\" : {\n\t\t\t\t\t\"gender\" : [ ],\n\t\t\t\t\t\"user_name\" : [ ]\n\t\t\t\t},\n\t\t\t\t\"isUnique\" : false,\n\t\t\t\t\"isSparse\" : false,\n\t\t\t\t\"isPartial\" : false,\n\t\t\t\t\"indexVersion\" : 2,\n\t\t\t\t\"direction\" : \"forward\",\n\t\t\t\t\"indexBounds\" : {\n\t\t\t\t\t\"gender\" : [\n\t\t\t\t\t\t\"[\\\"M\\\", \\\"M\\\"]\"\n\t\t\t\t\t],\n\t\t\t\t\t\"user_name\" : [\n\t\t\t\t\t\t\"[MinKey, MaxKey]\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"rejectedPlans\" : [ ]\n\t},\n\t\"serverInfo\" : {\n\t\t\"host\" : \"Krishna\",\n\t\t\"port\" : 27017,\n\t\t\"version\" : \"4.2.1\",\n\t\t109\n\t\t\"gitVersion\" : \"edf6d45851c0b9ee15548f0f847df141764a317e\"\n\t},\n\t\"ok\" : 1\n}" }, { "code": null, "e": 7106, "s": 7073, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 7125, "s": 7106, "text": " Arnab Chakraborty" }, { "code": null, "e": 7160, "s": 7125, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7188, "s": 7160, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7223, "s": 7188, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7246, "s": 7223, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7281, "s": 7246, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7298, "s": 7281, "text": " University Code" }, { "code": null, "e": 7331, "s": 7298, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 7350, "s": 7331, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 7385, "s": 7350, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7405, "s": 7385, "text": " Skillbakerystudios" }, { "code": null, "e": 7412, "s": 7405, "text": " Print" }, { "code": null, "e": 7423, "s": 7412, "text": " Add Notes" } ]
Accessing variables in a constructor function using a prototype method with JavaScript?
For this, use a “prototype”. JavaScript objects inherit properties and methods from a prototype. For accessing variables, we have also used the “this” in JavaScript. function Customer(fullName){ this.fullName=fullName; } Customer.prototype.setFullName = function(newFullName){ this.fullName=newFullName; } var customer=new Customer("John Smith"); console.log("Using Simple Method = "+ customer.fullName); customer.setFullName("David Miller"); console.log("Using Prototype Method = "+customer.fullName); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo79.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo79.js Using Simple Method = John Smith Using Prototype Method = David Miller
[ { "code": null, "e": 1228, "s": 1062, "text": "For this, use a “prototype”. JavaScript objects inherit properties and methods from a prototype.\nFor accessing variables, we have also used the “this” in JavaScript." }, { "code": null, "e": 1571, "s": 1228, "text": "function Customer(fullName){\n this.fullName=fullName;\n}\nCustomer.prototype.setFullName = function(newFullName){\n this.fullName=newFullName;\n}\nvar customer=new Customer(\"John Smith\");\nconsole.log(\"Using Simple Method = \"+ customer.fullName);\ncustomer.setFullName(\"David Miller\");\nconsole.log(\"Using Prototype Method = \"+customer.fullName);" }, { "code": null, "e": 1637, "s": 1571, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1655, "s": 1637, "text": "node fileName.js." }, { "code": null, "e": 1688, "s": 1655, "text": "Here, my file name is demo79.js." }, { "code": null, "e": 1729, "s": 1688, "text": "This will produce the following output −" }, { "code": null, "e": 1849, "s": 1729, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo79.js\nUsing Simple Method = John Smith\nUsing Prototype Method = David Miller" } ]
Program to find number of steps to solve 8-puzzle in python
Suppose we have a 3x3 board of where all numbers are in range 0 to 8 and no repeating numbers are there. Now, we can swap the 0 with one of its 4 neighbors, and we are trying to solve it to get all arranged sequence, we have to find minimum number of steps required to reach the goal. So, if the input is like then the output will be 4 To solve this, we will follow these steps − Define a function find_next() . This will take node moves := a map defining moves as a list corresponding to each value {0: [1, 3],1: [0, 2, 4],2: [1, 5],3: [0, 4, 6],4: [1, 3, 5, 7],5: [2, 4, 8],6: [3, 7],7: [4, 6, 8],8: [5, 7],} results := a new list pos_0 := first value of node for each move in moves[pos_0], donew_node := a new list from nodeswap new_node[move] and new_node[pos_0]insert a new tuple from new_node at the end of results new_node := a new list from node swap new_node[move] and new_node[pos_0] insert a new tuple from new_node at the end of results return results Define a function get_paths() . This will take dict cnt := 0 Do the following infinitely, docurrent_nodes := a list where value is same as cntif size of current_nodes is same as 0, thenreturn -1for each node in current_nodes, donext_moves := find_next(node)for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1 current_nodes := a list where value is same as cnt if size of current_nodes is same as 0, thenreturn -1 return -1 for each node in current_nodes, donext_moves := find_next(node)for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1 next_moves := find_next(node) for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1 if move is not present in dict, thendict[move] := cnt + 1 dict[move] := cnt + 1 if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1 return cnt + 1 cnt := cnt + 1 From the main method do the following: dict := a new map, flatten := a new list for i in range 0 to row count of board, doflatten := flatten + board[i] flatten := flatten + board[i] flatten := a copy of flatten dict[flatten] := 0 if flatten is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn 0 return 0 return get_paths(dict) Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, board): dict = {} flatten = [] for i in range(len(board)): flatten += board[i] flatten = tuple(flatten) dict[flatten] = 0 if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8): return 0 return self.get_paths(dict) def get_paths(self, dict): cnt = 0 while True: current_nodes = [x for x in dict if dict[x] == cnt] if len(current_nodes) == 0: return -1 for node in current_nodes: next_moves = self.find_next(node) for move in next_moves: if move not in dict: dict[move] = cnt + 1 if move == (0, 1, 2, 3, 4, 5, 6, 7, 8): return cnt + 1 cnt += 1 def find_next(self, node): moves = { 0: [1, 3], 1: [0, 2, 4], 2: [1, 5], 3: [0, 4, 6], 4: [1, 3, 5, 7], 5: [2, 4, 8], 6: [3, 7], 7: [4, 6, 8], 8: [5, 7], } results = [] pos_0 = node.index(0) for move in moves[pos_0]: new_node = list(node) new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move] results.append(tuple(new_node)) return results ob = Solution() matrix = [ [3, 1, 2], [4, 7, 5], [6, 8, 0] ] print(ob.solve(matrix)) matrix = [ [3, 1, 2], [4, 7, 5], [6, 8, 0] ] 4
[ { "code": null, "e": 1347, "s": 1062, "text": "Suppose we have a 3x3 board of where all numbers are in range 0 to 8 and no repeating numbers are there. Now, we can swap the 0 with one of its 4 neighbors, and we are trying to solve it to get all arranged sequence, we have to find minimum number of steps required to reach the goal." }, { "code": null, "e": 1372, "s": 1347, "text": "So, if the input is like" }, { "code": null, "e": 1398, "s": 1372, "text": "then the output will be 4" }, { "code": null, "e": 1442, "s": 1398, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1494, "s": 1442, "text": "Define a function find_next() . This will take node" }, { "code": null, "e": 1673, "s": 1494, "text": "moves := a map defining moves as a list corresponding to each value {0: [1, 3],1: [0, 2, 4],2: [1, 5],3: [0, 4, 6],4: [1, 3, 5, 7],5: [2, 4, 8],6: [3, 7],7: [4, 6, 8],8: [5, 7],}" }, { "code": null, "e": 1695, "s": 1673, "text": "results := a new list" }, { "code": null, "e": 1724, "s": 1695, "text": "pos_0 := first value of node" }, { "code": null, "e": 1883, "s": 1724, "text": "for each move in moves[pos_0], donew_node := a new list from nodeswap new_node[move] and new_node[pos_0]insert a new tuple from new_node at the end of results" }, { "code": null, "e": 1916, "s": 1883, "text": "new_node := a new list from node" }, { "code": null, "e": 1956, "s": 1916, "text": "swap new_node[move] and new_node[pos_0]" }, { "code": null, "e": 2011, "s": 1956, "text": "insert a new tuple from new_node at the end of results" }, { "code": null, "e": 2026, "s": 2011, "text": "return results" }, { "code": null, "e": 2078, "s": 2026, "text": "Define a function get_paths() . This will take dict" }, { "code": null, "e": 2087, "s": 2078, "text": "cnt := 0" }, { "code": null, "e": 2453, "s": 2087, "text": "Do the following infinitely, docurrent_nodes := a list where value is same as cntif size of current_nodes is same as 0, thenreturn -1for each node in current_nodes, donext_moves := find_next(node)for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1" }, { "code": null, "e": 2504, "s": 2453, "text": "current_nodes := a list where value is same as cnt" }, { "code": null, "e": 2557, "s": 2504, "text": "if size of current_nodes is same as 0, thenreturn -1" }, { "code": null, "e": 2567, "s": 2557, "text": "return -1" }, { "code": null, "e": 2800, "s": 2567, "text": "for each node in current_nodes, donext_moves := find_next(node)for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1" }, { "code": null, "e": 2830, "s": 2800, "text": "next_moves := find_next(node)" }, { "code": null, "e": 3000, "s": 2830, "text": "for each move in next_moves, doif move is not present in dict, thendict[move] := cnt + 1if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1cnt := cnt + 1" }, { "code": null, "e": 3058, "s": 3000, "text": "if move is not present in dict, thendict[move] := cnt + 1" }, { "code": null, "e": 3080, "s": 3058, "text": "dict[move] := cnt + 1" }, { "code": null, "e": 3148, "s": 3080, "text": "if move is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn cnt + 1" }, { "code": null, "e": 3163, "s": 3148, "text": "return cnt + 1" }, { "code": null, "e": 3178, "s": 3163, "text": "cnt := cnt + 1" }, { "code": null, "e": 3217, "s": 3178, "text": "From the main method do the following:" }, { "code": null, "e": 3258, "s": 3217, "text": "dict := a new map, flatten := a new list" }, { "code": null, "e": 3330, "s": 3258, "text": "for i in range 0 to row count of board, doflatten := flatten + board[i]" }, { "code": null, "e": 3360, "s": 3330, "text": "flatten := flatten + board[i]" }, { "code": null, "e": 3389, "s": 3360, "text": "flatten := a copy of flatten" }, { "code": null, "e": 3408, "s": 3389, "text": "dict[flatten] := 0" }, { "code": null, "e": 3473, "s": 3408, "text": "if flatten is same as (0, 1, 2, 3, 4, 5, 6, 7, 8) , thenreturn 0" }, { "code": null, "e": 3482, "s": 3473, "text": "return 0" }, { "code": null, "e": 3505, "s": 3482, "text": "return get_paths(dict)" }, { "code": null, "e": 3575, "s": 3505, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3585, "s": 3575, "text": "Live Demo" }, { "code": null, "e": 4964, "s": 3585, "text": "class Solution:\n def solve(self, board):\n dict = {}\n flatten = []\n for i in range(len(board)):\n flatten += board[i]\n flatten = tuple(flatten)\n\n dict[flatten] = 0\n\n if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):\n return 0\n\n return self.get_paths(dict)\n\n def get_paths(self, dict):\n cnt = 0\n while True:\n current_nodes = [x for x in dict if dict[x] == cnt]\n if len(current_nodes) == 0:\n return -1\n\n for node in current_nodes:\n next_moves = self.find_next(node)\n for move in next_moves:\n if move not in dict:\n dict[move] = cnt + 1\n if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):\n return cnt + 1\n cnt += 1\n\n def find_next(self, node):\n moves = {\n 0: [1, 3],\n 1: [0, 2, 4],\n 2: [1, 5],\n 3: [0, 4, 6],\n 4: [1, 3, 5, 7],\n 5: [2, 4, 8],\n 6: [3, 7],\n 7: [4, 6, 8],\n 8: [5, 7],\n }\n\n results = []\n pos_0 = node.index(0)\n for move in moves[pos_0]:\n new_node = list(node)\n new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]\n results.append(tuple(new_node))\n\n return results\nob = Solution()\nmatrix = [\n [3, 1, 2],\n [4, 7, 5],\n [6, 8, 0]\n]\nprint(ob.solve(matrix))" }, { "code": null, "e": 5015, "s": 4964, "text": "matrix = [ \n[3, 1, 2], \n[4, 7, 5], \n[6, 8, 0] ]" }, { "code": null, "e": 5017, "s": 5015, "text": "4" } ]
Array elements that appear more than once - GeeksforGeeks
11 Aug, 2021 Given an integer array, print all repeating elements (Elements that appear more than once) in the array. The output should contain elements according to their first occurrences. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 10 45 Input: arr[] = {1, 2, 3, 4, 2, 5} Output: 2 Input: arr[] = {1, 1, 1, 1, 1} Output: 1 The idea is to use Hashing to solve this in O(n) time on average. We store elements and their counts in a hash table. After storing counts, we traverse input array again and print those elements whose counts are more than once. To make sure that every output element is printed only once, we set count as 0 after printing the element. C++ Java Python3 C# Javascript // C++ program to print all repeating elements#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int n){ // Store elements and their counts in // hash table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Since we want elements in same order, // we traverse array again and print // those elements that appear more than // once. for (int i = 0; i < n; i++) { if (mp[arr[i]] > 1) { cout << arr[i] << " "; // This is tricky, this is done // to make sure that the current // element is not printed again mp[arr[i]] = 0; } }} // Driver codeint main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, n); return 0;} // Java program to print all repeating elements import java.util.*;import java.util.Map.Entry;import java.io.*;import java.lang.*; public class GFG { static void printRepeating(int arr[], int n) { // Store elements and their counts in // hash table Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { try { map.put(arr[i], map.get(arr[i]) + 1); } catch (Exception e) { map.put(arr[i], 1); } } // Since we want elements in the same order, // we traverse array again and print // those elements that appear more than once. for (Entry<Integer, Integer> e : map.entrySet()) { if (e.getValue() > 1) { System.out.print(e.getKey() + " "); } } } // Driver code public static void main(String[] args) throws IOException { int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.length; printRepeating(arr, n); }} // This code is contributed by Wrick # Python3 program to print# all repeating elementsdef printRepeating(arr, n): # Store elements and # their counts in # hash table mp = [0] * 100 for i in range(0, n): mp[arr[i]] += 1 # Since we want elements # in same order, we # traverse array again # and print those elements # that appear more than once. for i in range(0, n): if (mp[arr[i]] > 1): print(arr[i], end = " ") # This is tricky, this # is done to make sure # that the current element # is not printed again mp[arr[i]] = 0 # Driver codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)printRepeating(arr, n) # This code is contributed# by Smita // C# program to print all repeating elementsusing System;using System.Collections.Generic; class GFG{static void printRepeating(int []arr, int n){ // Store elements and their counts in // hash table Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = 0 ; i < n; i++) { if(map.ContainsKey(arr[i])) { var val = map[arr[i]]; map.Remove(arr[i]); map.Add(arr[i], val + 1); } else { map.Add(arr[i], 1); } } // Since we want elements in the same order, // we traverse array again and print // those elements that appear more than once. foreach(KeyValuePair<int, int> e in map) { if (e.Value > 1) { Console.Write(e.Key + " "); } }} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.Length; printRepeating(arr, n);}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to print all// repeating elements function printRepeating(arr, n){ // Store elements and their counts in // hash table var mp = new Map(); for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } // Since we want elements in same order, // we traverse array again and print // those elements that appear more than // once. for (var i = 0; i < n; i++) { if (mp.get(arr[i]) > 1) { document.write( arr[i] + " "); // This is tricky, this is done // to make sure that the current // element is not printed again mp.set(arr[i], 0); } }} // Driver codevar arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];var n = arr.length;printRepeating(arr, n); </script> 10 45 Time Complexity: O(n) under the assumption that hash insert and search functions work in O(1) time. Count all the frequencies of all elements using Counter() function. Traverse in this frequency dictionary and print all keys whose value is greater than 1. Below is the implementation of above approach: Python3 # Python3 program to print# all repeating elementsfrom collections import Counter def printRepeating(arr, n): # Counting frequencies freq = Counter(arr) # Traverse the freq dictionary and # print all the keys whose value # is greater than 1 for i in freq: if(freq[i] > 1): print(i, end=" ") # Driver codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)printRepeating(arr, n) # This code is contributed by vikkycirus Output: 10 45 Smitha Dinesh Semwal Wrick princiraj1992 vikkycirus itsok simranarora5sos Amazon cpp-unordered_map Arrays Hash Amazon Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Building Heap from Array Program to find sum of elements in a given array Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24820, "s": 24792, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24998, "s": 24820, "text": "Given an integer array, print all repeating elements (Elements that appear more than once) in the array. The output should contain elements according to their first occurrences." }, { "code": null, "e": 25009, "s": 24998, "text": "Examples: " }, { "code": null, "e": 25156, "s": 25009, "text": "Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}\nOutput: 10 45\n\nInput: arr[] = {1, 2, 3, 4, 2, 5}\nOutput: 2\n\nInput: arr[] = {1, 1, 1, 1, 1}\nOutput: 1" }, { "code": null, "e": 25493, "s": 25156, "text": "The idea is to use Hashing to solve this in O(n) time on average. We store elements and their counts in a hash table. After storing counts, we traverse input array again and print those elements whose counts are more than once. To make sure that every output element is printed only once, we set count as 0 after printing the element. " }, { "code": null, "e": 25497, "s": 25493, "text": "C++" }, { "code": null, "e": 25502, "s": 25497, "text": "Java" }, { "code": null, "e": 25510, "s": 25502, "text": "Python3" }, { "code": null, "e": 25513, "s": 25510, "text": "C#" }, { "code": null, "e": 25524, "s": 25513, "text": "Javascript" }, { "code": "// C++ program to print all repeating elements#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int n){ // Store elements and their counts in // hash table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Since we want elements in same order, // we traverse array again and print // those elements that appear more than // once. for (int i = 0; i < n; i++) { if (mp[arr[i]] > 1) { cout << arr[i] << \" \"; // This is tricky, this is done // to make sure that the current // element is not printed again mp[arr[i]] = 0; } }} // Driver codeint main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, n); return 0;}", "e": 26361, "s": 25524, "text": null }, { "code": "// Java program to print all repeating elements import java.util.*;import java.util.Map.Entry;import java.io.*;import java.lang.*; public class GFG { static void printRepeating(int arr[], int n) { // Store elements and their counts in // hash table Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { try { map.put(arr[i], map.get(arr[i]) + 1); } catch (Exception e) { map.put(arr[i], 1); } } // Since we want elements in the same order, // we traverse array again and print // those elements that appear more than once. for (Entry<Integer, Integer> e : map.entrySet()) { if (e.getValue() > 1) { System.out.print(e.getKey() + \" \"); } } } // Driver code public static void main(String[] args) throws IOException { int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.length; printRepeating(arr, n); }} // This code is contributed by Wrick", "e": 27488, "s": 26361, "text": null }, { "code": "# Python3 program to print# all repeating elementsdef printRepeating(arr, n): # Store elements and # their counts in # hash table mp = [0] * 100 for i in range(0, n): mp[arr[i]] += 1 # Since we want elements # in same order, we # traverse array again # and print those elements # that appear more than once. for i in range(0, n): if (mp[arr[i]] > 1): print(arr[i], end = \" \") # This is tricky, this # is done to make sure # that the current element # is not printed again mp[arr[i]] = 0 # Driver codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)printRepeating(arr, n) # This code is contributed# by Smita", "e": 28234, "s": 27488, "text": null }, { "code": "// C# program to print all repeating elementsusing System;using System.Collections.Generic; class GFG{static void printRepeating(int []arr, int n){ // Store elements and their counts in // hash table Dictionary<int, int> map = new Dictionary<int, int>(); for (int i = 0 ; i < n; i++) { if(map.ContainsKey(arr[i])) { var val = map[arr[i]]; map.Remove(arr[i]); map.Add(arr[i], val + 1); } else { map.Add(arr[i], 1); } } // Since we want elements in the same order, // we traverse array again and print // those elements that appear more than once. foreach(KeyValuePair<int, int> e in map) { if (e.Value > 1) { Console.Write(e.Key + \" \"); } }} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.Length; printRepeating(arr, n);}} // This code is contributed by PrinciRaj1992", "e": 29285, "s": 28234, "text": null }, { "code": "<script> // JavaScript program to print all// repeating elements function printRepeating(arr, n){ // Store elements and their counts in // hash table var mp = new Map(); for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } // Since we want elements in same order, // we traverse array again and print // those elements that appear more than // once. for (var i = 0; i < n; i++) { if (mp.get(arr[i]) > 1) { document.write( arr[i] + \" \"); // This is tricky, this is done // to make sure that the current // element is not printed again mp.set(arr[i], 0); } }} // Driver codevar arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];var n = arr.length;printRepeating(arr, n); </script>", "e": 30155, "s": 29285, "text": null }, { "code": null, "e": 30161, "s": 30155, "text": "10 45" }, { "code": null, "e": 30264, "s": 30163, "text": "Time Complexity: O(n) under the assumption that hash insert and search functions work in O(1) time. " }, { "code": null, "e": 30332, "s": 30264, "text": "Count all the frequencies of all elements using Counter() function." }, { "code": null, "e": 30420, "s": 30332, "text": "Traverse in this frequency dictionary and print all keys whose value is greater than 1." }, { "code": null, "e": 30467, "s": 30420, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 30475, "s": 30467, "text": "Python3" }, { "code": "# Python3 program to print# all repeating elementsfrom collections import Counter def printRepeating(arr, n): # Counting frequencies freq = Counter(arr) # Traverse the freq dictionary and # print all the keys whose value # is greater than 1 for i in freq: if(freq[i] > 1): print(i, end=\" \") # Driver codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)printRepeating(arr, n) # This code is contributed by vikkycirus", "e": 30942, "s": 30475, "text": null }, { "code": null, "e": 30950, "s": 30942, "text": "Output:" }, { "code": null, "e": 30956, "s": 30950, "text": "10 45" }, { "code": null, "e": 30977, "s": 30956, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 30983, "s": 30977, "text": "Wrick" }, { "code": null, "e": 30997, "s": 30983, "text": "princiraj1992" }, { "code": null, "e": 31008, "s": 30997, "text": "vikkycirus" }, { "code": null, "e": 31014, "s": 31008, "text": "itsok" }, { "code": null, "e": 31030, "s": 31014, "text": "simranarora5sos" }, { "code": null, "e": 31037, "s": 31030, "text": "Amazon" }, { "code": null, "e": 31055, "s": 31037, "text": "cpp-unordered_map" }, { "code": null, "e": 31062, "s": 31055, "text": "Arrays" }, { "code": null, "e": 31067, "s": 31062, "text": "Hash" }, { "code": null, "e": 31074, "s": 31067, "text": "Amazon" }, { "code": null, "e": 31081, "s": 31074, "text": "Arrays" }, { "code": null, "e": 31086, "s": 31081, "text": "Hash" }, { "code": null, "e": 31184, "s": 31086, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31209, "s": 31184, "text": "Window Sliding Technique" }, { "code": null, "e": 31229, "s": 31209, "text": "Trapping Rain Water" }, { "code": null, "e": 31267, "s": 31229, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31292, "s": 31267, "text": "Building Heap from Array" }, { "code": null, "e": 31341, "s": 31292, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31377, "s": 31341, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 31408, "s": 31377, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 31442, "s": 31408, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 31469, "s": 31442, "text": "Count pairs with given sum" } ]
Ways to read input from console in Java
Let us see some ways to read input from console in Java − import java.util.Scanner; public class Demo{ public static void main(String args[]){ Scanner my_scan = new Scanner(System.in); String my_str = my_scan.nextLine(); System.out.println("The string is "+my_str); int my_val = my_scan.nextInt(); System.out.println("The integer is "+my_val); float my_float = my_scan.nextFloat(); System.out.println("The float value is "+my_float); } } The string is Joe The integer is 56 The float value is 78.99 A class named Demo contains the main function. An instance of the Scanner class is created and the ‘nextLine’ function is used to read every line of a string input. An integer value is defined and it is read from the standard input console using ‘nextInt’. Similarly, ‘nextFloat’ function is used to read float type input from the standard input console. They are displayed on the console. Live Demo import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Demo{ public static void main(String[] args) throws IOException{ BufferedReader my_reader = new BufferedReader(new InputStreamReader(System.in)); String my_name = my_reader.readLine(); System.out.println("The name is "); System.out.println(my_name); } } The name is Joe A class named Demo contains the main function. Here, an instance of the buffered reader is created. A string type of data is defined and every line of the string is read using the ‘readLine’ function. The input is given from the standard input, and relevant message is displayed on the console.
[ { "code": null, "e": 1120, "s": 1062, "text": "Let us see some ways to read input from console in Java −" }, { "code": null, "e": 1548, "s": 1120, "text": "import java.util.Scanner;\npublic class Demo{\n public static void main(String args[]){\n Scanner my_scan = new Scanner(System.in);\n String my_str = my_scan.nextLine();\n System.out.println(\"The string is \"+my_str);\n int my_val = my_scan.nextInt();\n System.out.println(\"The integer is \"+my_val);\n float my_float = my_scan.nextFloat();\n System.out.println(\"The float value is \"+my_float);\n }\n}" }, { "code": null, "e": 1609, "s": 1548, "text": "The string is Joe\nThe integer is 56\nThe float value is 78.99" }, { "code": null, "e": 1999, "s": 1609, "text": "A class named Demo contains the main function. An instance of the Scanner class is created and the ‘nextLine’ function is used to read every line of a string input. An integer value is defined and it is read from the standard input console using ‘nextInt’. Similarly, ‘nextFloat’ function is used to read float type input from the standard input console. They are displayed on the console." }, { "code": null, "e": 2010, "s": 1999, "text": " Live Demo" }, { "code": null, "e": 2400, "s": 2010, "text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\npublic class Demo{\n public static void main(String[] args) throws IOException{\n BufferedReader my_reader = new BufferedReader(new InputStreamReader(System.in));\n String my_name = my_reader.readLine();\n System.out.println(\"The name is \");\n System.out.println(my_name);\n }\n}" }, { "code": null, "e": 2416, "s": 2400, "text": "The name is\nJoe" }, { "code": null, "e": 2711, "s": 2416, "text": "A class named Demo contains the main function. Here, an instance of the buffered reader is created. A string type of data is defined and every line of the string is read using the ‘readLine’ function. The input is given from the standard input, and relevant message is displayed on the console." } ]
C++ Program to Implement Sparse Matrix
A sparse matrix is a matrix in which majority of the elements are 0. An example for this is given as follows. The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix. 5 0 0 3 0 1 0 0 9 A program to implement a sparse matrix is as follows. Live Demo #include<iostream> using namespace std; int main () { int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} }; int i, j, count = 0; int row = 3, col = 3; for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j){ if (a[i][j] == 0) count++; } } cout<<"The matrix is:"<<endl; for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } cout<<"The number of zeros in the matrix are "<< count <<endl; if (count > ((row * col)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl; return 0; } The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet. for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { if (a[i][j] == 0) count++; } } After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below. cout<<"The matrix is:"<<endl; for (i = 0; i < row; ++i) { for (j = 0; j < col; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix. cout<<"The number of zeros in the matrix are "<< count <<endl; if (count > ((row * col)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl;
[ { "code": null, "e": 1172, "s": 1062, "text": "A sparse matrix is a matrix in which majority of the elements are 0. An example for this is given as follows." }, { "code": null, "e": 1310, "s": 1172, "text": "The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix." }, { "code": null, "e": 1328, "s": 1310, "text": "5 0 0\n3 0 1\n0 0 9" }, { "code": null, "e": 1382, "s": 1328, "text": "A program to implement a sparse matrix is as follows." }, { "code": null, "e": 1393, "s": 1382, "text": " Live Demo" }, { "code": null, "e": 2044, "s": 1393, "text": "#include<iostream>\nusing namespace std;\nint main () {\n int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} };\n int i, j, count = 0;\n int row = 3, col = 3;\n for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j){\n if (a[i][j] == 0)\n count++;\n }\n }\n cout<<\"The matrix is:\"<<endl;\n for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j) {\n cout<<a[i][j]<<\" \";\n }\n cout<<endl;\n }\n cout<<\"The number of zeros in the matrix are \"<< count <<endl;\n if (count > ((row * col)/ 2))\n cout<<\"This is a sparse matrix\"<<endl;\n else\n cout<<\"This is not a sparse matrix\"<<endl;\n return 0;\n}" }, { "code": null, "e": 2141, "s": 2044, "text": "The matrix is:\n0 0 9\n5 0 8\n7 0 0\nThe number of zeros in the matrix are 5\nThis is a sparse matrix" }, { "code": null, "e": 2288, "s": 2141, "text": "In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet." }, { "code": null, "e": 2393, "s": 2288, "text": "for (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j) {\n if (a[i][j] == 0)\n count++;\n }\n}" }, { "code": null, "e": 2498, "s": 2393, "text": "After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below." }, { "code": null, "e": 2635, "s": 2498, "text": "cout<<\"The matrix is:\"<<endl;\nfor (i = 0; i < row; ++i) {\n for (j = 0; j < col; ++j) {\n cout<<a[i][j]<<\" \";\n }\n cout<<endl;\n}" }, { "code": null, "e": 2849, "s": 2635, "text": "Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix." }, { "code": null, "e": 3029, "s": 2849, "text": "cout<<\"The number of zeros in the matrix are \"<< count <<endl;\nif (count > ((row * col)/ 2))\ncout<<\"This is a sparse matrix\"<<endl;\nelse\ncout<<\"This is not a sparse matrix\"<<endl;" } ]
Set removeAll() method in Java with Examples - GeeksforGeeks
30 Sep, 2019 The removeAll() method of java.util.Set interface is used to remove from this set all of its elements that are contained in the specified collection. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this set. Returns Value: This method returns true if this set changed as a result of the call. Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null. Below are the examples to illustrate the removeAll() method. Example 1: // Java program to demonstrate// removeAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> set1 = new HashSet<Integer>(); // Populating set1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println("Set before removeAll() operation : " + set1); // Creating another object of Set Set<Integer> set2 = new HashSet<Integer>(); set2.add(1); set2.add(2); set2.add(3); // print set2 System.out.println("Collection Elements to be removed : " + set2); // Removing elements from set // specified in set2 // using removeAll() method set1.removeAll(set2); // print set1 System.out.println("Set after removeAll() operation : " + set1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} Set before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : [1, 2, 3] Set after removeAll() operation : [4, 5] Example 2: For NullPointerException. // Java program to demonstrate// removeAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> set1 = new HashSet<Integer>(); // Populating set1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println("Set before removeAll() operation : " + set1); // Creating another object of Set<Integer> Set<Integer> set2 = null; // print set2 System.out.println("Collection Elements to be removed : " + set2); System.out.println("\nTrying to pass " + "null as a specified element\n"); // Removing elements from set // specified in set2 // using removeAll() method set1.removeAll(set2); // print set1 System.out.println("Set after removeAll() operation : " + set1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} Set before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : null Trying to pass null as a specified element Exception thrown : java.lang.NullPointerException Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#removeAll(java.util.Collection) nidhi_biet Java-Collections Java-Functions java-set Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 26385, "s": 26357, "text": "\n30 Sep, 2019" }, { "code": null, "e": 26535, "s": 26385, "text": "The removeAll() method of java.util.Set interface is used to remove from this set all of its elements that are contained in the specified collection." }, { "code": null, "e": 26543, "s": 26535, "text": "Syntax:" }, { "code": null, "e": 26582, "s": 26543, "text": "public boolean removeAll(Collection c)" }, { "code": null, "e": 26689, "s": 26582, "text": "Parameters: This method takes collection c as a parameter containing elements to be removed from this set." }, { "code": null, "e": 26774, "s": 26689, "text": "Returns Value: This method returns true if this set changed as a result of the call." }, { "code": null, "e": 26972, "s": 26774, "text": "Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null." }, { "code": null, "e": 27033, "s": 26972, "text": "Below are the examples to illustrate the removeAll() method." }, { "code": null, "e": 27044, "s": 27033, "text": "Example 1:" }, { "code": "// Java program to demonstrate// removeAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> set1 = new HashSet<Integer>(); // Populating set1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println(\"Set before removeAll() operation : \" + set1); // Creating another object of Set Set<Integer> set2 = new HashSet<Integer>(); set2.add(1); set2.add(2); set2.add(3); // print set2 System.out.println(\"Collection Elements to be removed : \" + set2); // Removing elements from set // specified in set2 // using removeAll() method set1.removeAll(set2); // print set1 System.out.println(\"Set after removeAll() operation : \" + set1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 28326, "s": 27044, "text": null }, { "code": null, "e": 28465, "s": 28326, "text": "Set before removeAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be removed : [1, 2, 3]\nSet after removeAll() operation : [4, 5]\n" }, { "code": null, "e": 28502, "s": 28465, "text": "Example 2: For NullPointerException." }, { "code": "// Java program to demonstrate// removeAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> set1 = new HashSet<Integer>(); // Populating set1 set1.add(1); set1.add(2); set1.add(3); set1.add(4); set1.add(5); // print set1 System.out.println(\"Set before removeAll() operation : \" + set1); // Creating another object of Set<Integer> Set<Integer> set2 = null; // print set2 System.out.println(\"Collection Elements to be removed : \" + set2); System.out.println(\"\\nTrying to pass \" + \"null as a specified element\\n\"); // Removing elements from set // specified in set2 // using removeAll() method set1.removeAll(set2); // print set1 System.out.println(\"Set after removeAll() operation : \" + set1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 29821, "s": 28502, "text": null }, { "code": null, "e": 30009, "s": 29821, "text": "Set before removeAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be removed : null\n\nTrying to pass null as a specified element\n\nException thrown : java.lang.NullPointerException\n" }, { "code": null, "e": 30113, "s": 30009, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#removeAll(java.util.Collection)" }, { "code": null, "e": 30124, "s": 30113, "text": "nidhi_biet" }, { "code": null, "e": 30141, "s": 30124, "text": "Java-Collections" }, { "code": null, "e": 30156, "s": 30141, "text": "Java-Functions" }, { "code": null, "e": 30165, "s": 30156, "text": "java-set" }, { "code": null, "e": 30170, "s": 30165, "text": "Java" }, { "code": null, "e": 30175, "s": 30170, "text": "Java" }, { "code": null, "e": 30192, "s": 30175, "text": "Java-Collections" }, { "code": null, "e": 30290, "s": 30192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30305, "s": 30290, "text": "Stream In Java" }, { "code": null, "e": 30356, "s": 30305, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30386, "s": 30356, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30405, "s": 30386, "text": "Interfaces in Java" }, { "code": null, "e": 30436, "s": 30405, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30454, "s": 30436, "text": "ArrayList in Java" }, { "code": null, "e": 30486, "s": 30454, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30506, "s": 30486, "text": "Stack Class in Java" }, { "code": null, "e": 30530, "s": 30506, "text": "Singleton Class in Java" } ]
Find the last remaining element after repeated removal of odd and even indexed elements alternately - GeeksforGeeks
31 May, 2021 Given a positive integer N, the task is to print the last remaining element from a sequence [1, N] after repeatedly performing the following operations in the given order alternately: Remove all the odd-indexed elements from the sequence.Remove all the even-indexed elements from the sequence. Remove all the odd-indexed elements from the sequence. Remove all the even-indexed elements from the sequence. Examples: Input: N = 9Output: 6Explanation: Sequence = {1, 2, 3, 4, 5, 6, 7, 8, 9}Step 1: Removing odd-indexed elements modifies sequence to {2, 4, 6, 8}Step 2: Removing even-indexed elements modifies sequence to {2, 6}Step 3: Removing odd-indexed elements modifies sequence to {6}Therefore, the last remaining element is 6. Input: N = 5Output: 2Explanation: Sequence = {1, 2, 3, 4, 5}Step 1: Removing odd-indexed elements modifies sequence to {2, 4}Step 2: Removing even-indexed elements modifies sequence to {2}Therefore, the last remaining element is 2. Naive Approach: The simplest approach is to store all the elements from 1 to N sequentially in an array. For every operation, remove elements from the array and shift the remaining elements towards the left. After reducing the array to a single element, print that remaining element as the required answer. Time Complexity: O(N2*log N)Auxiliary Space: O(N) Efficient Approach: The above approach can be optimized using Dynamic Programming. The recurrence relation is as follows: where, i is in the range [1, N]dp[i] stores the answer when the array elements are from 1 to i. Follow the steps below to solve the problem: Initialize an array dp[] where dp[i] stores the remaining element or the sequence [1, i].For the base condition of i = 1, print 1 as the required answer.Calculate the value of dp[N] using the aforementioned recurrence relation and use the already computed subproblems to avoid recomputation of overlapping subproblems.After completing the above steps, print the value of dp[N] as the result. Initialize an array dp[] where dp[i] stores the remaining element or the sequence [1, i]. For the base condition of i = 1, print 1 as the required answer. Calculate the value of dp[N] using the aforementioned recurrence relation and use the already computed subproblems to avoid recomputation of overlapping subproblems. After completing the above steps, print the value of dp[N] as the result. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++14 program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the last// remaining element from the sequenceint lastRemaining(int n, map<int, int> &dp){ // If dp[n] is already calculated if (dp.find(n) != dp.end()) return dp[n]; // Base Case: if (n == 1) return 1; // Recursive call else dp[n] = 2 * (1 + n / 2 - lastRemaining(n / 2, dp)); // Return the value of dp[n] return dp[n];} // Driver Codeint main(){ // Given N int N = 5; // Stores the map<int, int> dp; // Function call cout << lastRemaining(N, dp); return 0;} // This code is contributed by mohit kumar 29 // Java program for// the above approachimport java.util.*;class GFG{ // Function to calculate the last// remaining element from the sequencestatic int lastRemaining(int n, HashMap<Integer, Integer> dp){ // If dp[n] is already calculated if (dp.containsKey(n)) return dp.get(n); // Base Case: if (n == 1) return 1; // Recursive call else dp.put(n, 2 * (1 + n / 2 - lastRemaining(n / 2, dp))); // Return the value of dp[n] return dp.get(n);} // Driver Codepublic static void main(String[] args){ // Given N int N = 5; // Stores the HashMap<Integer, Integer> dp = new HashMap<Integer, Integer>(); // Function call System.out.print(lastRemaining(N, dp));}} // This code is contributed by Princi Singh # Python program for the above approach # Function to calculate the last# remaining element from the sequencedef lastRemaining(n, dp): # If dp[n] is already calculated if n in dp: return dp[n] # Base Case: if n == 1: return 1 # Recursive Call else: dp[n] = 2*(1 + n//2 - lastRemaining(n//2, dp)) # Return the value of dp[n] return dp[n] # Driver Code # Given NN = 5 # Stores thedp = {} # Function Callprint(lastRemaining(N, dp)) // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to calculate the last// remaining element from the sequencestatic int lastRemaining(int n, Dictionary<int, int> dp){ // If dp[n] is already calculated if (dp.ContainsKey(n)) return dp[n]; // Base Case: if (n == 1) return 1; // Recursive call else dp.Add(n, 2 * (1 + n / 2 - lastRemaining(n / 2, dp))); // Return the value of dp[n] return dp[n];} // Driver Codepublic static void Main(String[] args){ // Given N int N = 5; // Stores the Dictionary<int, int> dp = new Dictionary<int, int>(); // Function call Console.Write(lastRemaining(N, dp));}} // This code is contributed by Princi Singh <script> // JavaScript program for the above approach // Function to calculate the last // remaining element from the sequence function lastRemaining(n, dp) { // If dp[n] is already calculated if (dp.hasOwnProperty(n)) return dp[n]; // Base Case: if (n === 1) return 1; // Recursive call else dp[n] = 2 * (1 + parseInt(n / 2) - lastRemaining(parseInt(n / 2), dp)); // Return the value of dp[n] return dp[n]; } // Driver Code // Given N var N = 5; // Stores the var dp = {}; // Function call document.write(lastRemaining(N, dp));</script> 2 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 princi singh rdtank array-rearrange Memoization Arrays Dynamic Programming Mathematical Recursion Arrays Dynamic Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26771, "s": 26743, "text": "\n31 May, 2021" }, { "code": null, "e": 26955, "s": 26771, "text": "Given a positive integer N, the task is to print the last remaining element from a sequence [1, N] after repeatedly performing the following operations in the given order alternately:" }, { "code": null, "e": 27065, "s": 26955, "text": "Remove all the odd-indexed elements from the sequence.Remove all the even-indexed elements from the sequence." }, { "code": null, "e": 27120, "s": 27065, "text": "Remove all the odd-indexed elements from the sequence." }, { "code": null, "e": 27176, "s": 27120, "text": "Remove all the even-indexed elements from the sequence." }, { "code": null, "e": 27186, "s": 27176, "text": "Examples:" }, { "code": null, "e": 27501, "s": 27186, "text": "Input: N = 9Output: 6Explanation: Sequence = {1, 2, 3, 4, 5, 6, 7, 8, 9}Step 1: Removing odd-indexed elements modifies sequence to {2, 4, 6, 8}Step 2: Removing even-indexed elements modifies sequence to {2, 6}Step 3: Removing odd-indexed elements modifies sequence to {6}Therefore, the last remaining element is 6." }, { "code": null, "e": 27733, "s": 27501, "text": "Input: N = 5Output: 2Explanation: Sequence = {1, 2, 3, 4, 5}Step 1: Removing odd-indexed elements modifies sequence to {2, 4}Step 2: Removing even-indexed elements modifies sequence to {2}Therefore, the last remaining element is 2." }, { "code": null, "e": 28041, "s": 27733, "text": "Naive Approach: The simplest approach is to store all the elements from 1 to N sequentially in an array. For every operation, remove elements from the array and shift the remaining elements towards the left. After reducing the array to a single element, print that remaining element as the required answer. " }, { "code": null, "e": 28091, "s": 28041, "text": "Time Complexity: O(N2*log N)Auxiliary Space: O(N)" }, { "code": null, "e": 28213, "s": 28091, "text": "Efficient Approach: The above approach can be optimized using Dynamic Programming. The recurrence relation is as follows:" }, { "code": null, "e": 28311, "s": 28215, "text": "where, i is in the range [1, N]dp[i] stores the answer when the array elements are from 1 to i." }, { "code": null, "e": 28356, "s": 28311, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28748, "s": 28356, "text": "Initialize an array dp[] where dp[i] stores the remaining element or the sequence [1, i].For the base condition of i = 1, print 1 as the required answer.Calculate the value of dp[N] using the aforementioned recurrence relation and use the already computed subproblems to avoid recomputation of overlapping subproblems.After completing the above steps, print the value of dp[N] as the result." }, { "code": null, "e": 28838, "s": 28748, "text": "Initialize an array dp[] where dp[i] stores the remaining element or the sequence [1, i]." }, { "code": null, "e": 28903, "s": 28838, "text": "For the base condition of i = 1, print 1 as the required answer." }, { "code": null, "e": 29069, "s": 28903, "text": "Calculate the value of dp[N] using the aforementioned recurrence relation and use the already computed subproblems to avoid recomputation of overlapping subproblems." }, { "code": null, "e": 29143, "s": 29069, "text": "After completing the above steps, print the value of dp[N] as the result." }, { "code": null, "e": 29194, "s": 29143, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29200, "s": 29194, "text": "C++14" }, { "code": null, "e": 29205, "s": 29200, "text": "Java" }, { "code": null, "e": 29213, "s": 29205, "text": "Python3" }, { "code": null, "e": 29216, "s": 29213, "text": "C#" }, { "code": null, "e": 29227, "s": 29216, "text": "Javascript" }, { "code": "// C++14 program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate the last// remaining element from the sequenceint lastRemaining(int n, map<int, int> &dp){ // If dp[n] is already calculated if (dp.find(n) != dp.end()) return dp[n]; // Base Case: if (n == 1) return 1; // Recursive call else dp[n] = 2 * (1 + n / 2 - lastRemaining(n / 2, dp)); // Return the value of dp[n] return dp[n];} // Driver Codeint main(){ // Given N int N = 5; // Stores the map<int, int> dp; // Function call cout << lastRemaining(N, dp); return 0;} // This code is contributed by mohit kumar 29", "e": 29950, "s": 29227, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to calculate the last// remaining element from the sequencestatic int lastRemaining(int n, HashMap<Integer, Integer> dp){ // If dp[n] is already calculated if (dp.containsKey(n)) return dp.get(n); // Base Case: if (n == 1) return 1; // Recursive call else dp.put(n, 2 * (1 + n / 2 - lastRemaining(n / 2, dp))); // Return the value of dp[n] return dp.get(n);} // Driver Codepublic static void main(String[] args){ // Given N int N = 5; // Stores the HashMap<Integer, Integer> dp = new HashMap<Integer, Integer>(); // Function call System.out.print(lastRemaining(N, dp));}} // This code is contributed by Princi Singh", "e": 30772, "s": 29950, "text": null }, { "code": "# Python program for the above approach # Function to calculate the last# remaining element from the sequencedef lastRemaining(n, dp): # If dp[n] is already calculated if n in dp: return dp[n] # Base Case: if n == 1: return 1 # Recursive Call else: dp[n] = 2*(1 + n//2 - lastRemaining(n//2, dp)) # Return the value of dp[n] return dp[n] # Driver Code # Given NN = 5 # Stores thedp = {} # Function Callprint(lastRemaining(N, dp))", "e": 31256, "s": 30772, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to calculate the last// remaining element from the sequencestatic int lastRemaining(int n, Dictionary<int, int> dp){ // If dp[n] is already calculated if (dp.ContainsKey(n)) return dp[n]; // Base Case: if (n == 1) return 1; // Recursive call else dp.Add(n, 2 * (1 + n / 2 - lastRemaining(n / 2, dp))); // Return the value of dp[n] return dp[n];} // Driver Codepublic static void Main(String[] args){ // Given N int N = 5; // Stores the Dictionary<int, int> dp = new Dictionary<int, int>(); // Function call Console.Write(lastRemaining(N, dp));}} // This code is contributed by Princi Singh", "e": 32158, "s": 31256, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to calculate the last // remaining element from the sequence function lastRemaining(n, dp) { // If dp[n] is already calculated if (dp.hasOwnProperty(n)) return dp[n]; // Base Case: if (n === 1) return 1; // Recursive call else dp[n] = 2 * (1 + parseInt(n / 2) - lastRemaining(parseInt(n / 2), dp)); // Return the value of dp[n] return dp[n]; } // Driver Code // Given N var N = 5; // Stores the var dp = {}; // Function call document.write(lastRemaining(N, dp));</script>", "e": 32870, "s": 32158, "text": null }, { "code": null, "e": 32872, "s": 32870, "text": "2" }, { "code": null, "e": 32917, "s": 32874, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 32932, "s": 32917, "text": "mohit kumar 29" }, { "code": null, "e": 32945, "s": 32932, "text": "princi singh" }, { "code": null, "e": 32952, "s": 32945, "text": "rdtank" }, { "code": null, "e": 32968, "s": 32952, "text": "array-rearrange" }, { "code": null, "e": 32980, "s": 32968, "text": "Memoization" }, { "code": null, "e": 32987, "s": 32980, "text": "Arrays" }, { "code": null, "e": 33007, "s": 32987, "text": "Dynamic Programming" }, { "code": null, "e": 33020, "s": 33007, "text": "Mathematical" }, { "code": null, "e": 33030, "s": 33020, "text": "Recursion" }, { "code": null, "e": 33037, "s": 33030, "text": "Arrays" }, { "code": null, "e": 33057, "s": 33037, "text": "Dynamic Programming" }, { "code": null, "e": 33070, "s": 33057, "text": "Mathematical" }, { "code": null, "e": 33080, "s": 33070, "text": "Recursion" }, { "code": null, "e": 33178, "s": 33080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33201, "s": 33178, "text": "Introduction to Arrays" }, { "code": null, "e": 33233, "s": 33201, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33247, "s": 33233, "text": "Linear Search" }, { "code": null, "e": 33268, "s": 33247, "text": "Linked List vs Array" }, { "code": null, "e": 33353, "s": 33268, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33382, "s": 33353, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 33412, "s": 33382, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33446, "s": 33412, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33477, "s": 33446, "text": "Bellman–Ford Algorithm | DP-23" } ]
Game theory — Minimax. This article will be a bit different... | by NerdzLab | Towards Data Science
This article will be a bit different from previous ones which are based on some new technologies to use in your projects. Interesting? I will describe Minimax algorithm from the perspective of Game theory. Just letting you know what you are to expect : 1. So what’s Minimax algorithm? 2. Plan and code 3. Algorithm description 4. Optimizations 4.1. Deepness optimization 4.2. Alpha-Beta optimization 5. Advice6. Conclusion For coding, we will use language Objective-C.Don’t worry though, there will be more theory than just code. The direction is set, let’s go. So what’s Minimax algorithm? Minimax — is a decision rule used in decision theory, game theory, statistics and philosophy for minimizing the possible loss for a worst case (maximum loss) scenario. Originally formulated for two-player zero-sum game theory, covering both the cases where players take alternate moves and those where they make simultaneous moves, it has also been extended to more complex games and to general decision-making in the presence of uncertainty. Coooooooooool!Now that we have the definition, what logic is embedded in it? Let’s suggest that you are playing a game against your friend. And then each step you take you, want to maximize your win and your friend also wants to minimize his loss. Eventually, it’s the same definition for both of you. Your next decision should be maximizing your current win position knowing that your friend in the next step will minimize his loss position and knowing that the next step you will also maximize your win position... Catching this recursion smell? So the main idea of this algorithm is to make the best decision knowing that your opponent will do the same. Plan and code We will build this algorithm using tree representation. Each new generation of children is possible the next step of another player. For example, the first generation is your possible steps, each step will lead to some list of the opponent’s possible steps. In this situation, your step is the “father vertex” and possible next steps of your opponent are it’s “children vertexes”. Here is the final algorithm code with all optimizations. #pragma mark - Public- (NSUInteger)startAlgorithmWithAITurn:(BOOL)aiTurn; { return [self alphabetaAlgorithm:_searchingDeapth alpha:NSIntegerMin beta:NSIntegerMax maximizing:aiTurn];}#pragma mark - Private- (NSInteger)alphabetaAlgorithm:(NSInteger)depth alpha:(NSInteger)alpha beta:(NSInteger)beta maximizing:(BOOL)maximizing { self.currentCheckingDepth = _searchingDeapth - depth; if (self.datasource == nil || self.delegate == nil) { return 0; } if (depth == 0 || [self.datasource checkStopConditionForAlgorithm:self onAITurn:maximizing]) { return [self.datasource evaluateForAlgorithm:self onAITurn:maximizing]; } NSArray *nextStates = [self.datasource possibleNextStatesForAlgorithm:self onAITurn:maximizing]; for (id state in nextStates) { [self.delegate performActionForAlgorithm:self andState:state onAITurn:maximizing]; if (maximizing) { alpha = MAX(alpha, [self alphabetaAlgorithm:depth - 1 alpha:alpha beta:beta maximizing:NO]); } else { beta = MIN(beta, [self alphabetaAlgorithm:depth - 1 alpha:alpha beta:beta maximizing:YES]); } [self.delegate undoActionForAlgorithm:self andState:state onAITurn:maximizing]; if (beta <= alpha) { break; } } return (maximizing ? alpha : beta);} Algorithm description Let’s close our eyes on optimizations and start with the initial things that we need. First of all, we need an algorithm that will give back the list of possible next steps based on a made step. We use this to produce other children vertexes as described previously. Secondly, we need an algorithm that will calculate evaluation of the game result at the end of the game. Each vertex(made step) will have assigned value with the evaluated result using this algorithm. How it will be assigned will be described later. So how does this work using a tree and these algorithms? Logically algorithm is divided into two parts: 1. Our turn 2. Opponents turn On “our turn” as next vertex, we choose one of our children that have the best evaluation value. Then as next chosen step generates possible opponents steps with its evaluation, he will choose worst evaluation value(worst for us means best for him). This simply means that we will take the maximum evaluated step from possible opponents steps and the opponent will take the minimum evaluated step from our possible next steps. The Next question is — when will we evaluate step? The first thing that comes to mind — just when it’s created. But hold on a minute, how can we calculate it immediately if it depends on the next generation, or in other words on another player’s step? It means that our step value will be maximum from the next generation step value, which is an opponent step. From another point of view, opponents step value will be minimum from the next generation step values, which is mine. Following this rule, we can say that evaluation will be made when the game ends, as it’s final generation of steps. After that, it will unwind in back direction marking all vertexes with previously described calculated value until it gets to the root. Recursive generation ends if: We get a winnerIt’s not possible to have the next move, we get a draw Evaluation of game state can be calculated in a next way: If we win, then evaluated value should be bigger than some positive value If we lose, then it should be lower than some negative value If we have a draw then it should be in between this values It means that the better position we have, the bigger value it should be. This evaluation may depend on different things. Let’s take for example that for evaluation, we give it a situation where we are winners. Then it may evaluate depending on next values:1. How much steps I took to get the win 2. How close was your opponent to the win etc... This function is one of the most important parts of the algorithm. The better organized it is, the better results you get. A function that depends only on one characteristic will not be as accurate as a function that depends on ten. Also, characteristics you choose for evaluation should have logical meaning. If you will treat that evaluation value is bigger because the player is a woman other than a man, it makes some sense for the sexists but not for the algorithm. As a result, you will receive wrong results. And everything is because you’re a sexist. Great!, now we generally understand the algorithm and what idea lays under it. Sound cool, but still, it’s not as good when it comes to execution time. Why? Optimizations For usage, for example, let’s select “four in a row” game. If you don’t know what it is, here is a short description: “It is the goal of the game to connect four of your tokens in a line. All directions (vertical, horizontal, diagonal) are allowed. Players take turns putting one of their tokens into one of the seven slots. A token falls down as far as possible within a slot. The player with the red tokens begins. The game ends immediately when the first player connects four stones.” Let’s think how our algorithm will work in this case. The field has 7*6=42 steps. At the beginning, each user can make 7 different steps. What does this data give to us? These values are worst ever. To make them more real, let’s say, for instance, that game will end in 30 steps and averagely user will have a possibility to select 5 rows. Using our algorithm we will get next approximate data. The first user can produce 5 steps; each step will produce 5 own steps. Now we’re having 5 + 25. These 25 steps, each can produce 5 new steps and that’s equal to 125. Which means on the third step of calculation we will have about155 steps. Each next step will produce more and more possible steps to follow. You can count them using the next function:51 + 52 + 53 + ... + 530. This value is huge and a computer will take a lot of time to calculate so many steps. Thankfully there are ready optimizations for Minimax algorithm, that will lower this value. We will talk about the two of them shortly. Deepness optimization Once upon a time, a very wise man said “why should we count it till the end? Can we make a decision somewhere in the middle?”. Yes, we can. Of course, in the end, accuracy will be much better than somewhere in the middle, but with a good algorithm for evaluation, we can lower this problem. So then what should we do, just add one more rule for "algorithm stops". This rule is, to stop if current step deepness is on critical value. This value you can select on your own after some testing. I think with a bunch of tests you will find those that are matching your special situation. When we start evaluation based on this rule, we’re treating it as a draw. This rule was not as hard, and can really optimize our algorithms. However still, it’s lowering our accuracy, and to make it work, we just can’t use super low deepness otherwise it will give us wrong, and non-accurate values. I will tell you next, we selected that deepness 8 is fine for us. Even though it was taking a lot of time to get its final result. Next optimization has no influence on accuracy and reduces algorithm time really good. Its name is Alpha Beta and it's this thing that breaks my mind out. Alpha-Beta optimization It’s meaning is simple. The idea is next — no need to count next branches if we know that already founded branch will have a better result. It’s just a waste of resources. The idea is simple, what about implementation? To count that, we need two other variables to be passed to the recursive algorithm. 1. Alpha — it’s representing evaluation value on maximizing part 2. Beta — it’s representing evaluation value on minimizing part From previous parts, we understood that we have to go to the end of our tree and only then after can we evaluate our results. So the first evaluation will be made on the last vertex if we would always choose left vertex. After that evaluation process will start for its immediate vertex and will go on for all left vertexes till one of the possible ones end and so on and so forth. Why am I telling you this? It’s all because of understanding how evaluating vertexes is crucial for this optimization. To make it easier for us to imagine, let’s suppose that we’re on the maximizing turn. To us, it means that we’re counting Alpha value. This value is counted as a maximum of all evaluation values of his offsprings. At the same time when we’re counting Alpha(we’re on the maximizing process) we have a Beta value. Here, it represents a current Beta value of his parent. Great!, now we know what Alpha and Beta means in a specific time. To avoid misunderstanding, alpha is our current evaluation value and beta is current further evaluation value. The last thing is optimization check. If Beta is lower or equal the Alpha we’re stopping evaluation for all next child. The last thing is optimization check. If Beta is lower or equals to the Alpha we’re stopping evaluation for all next offsprings. Why does it work? Because Beta already is smaller than Alpha — value of its offspring, at the same time Alpha is counted as a maximum of possible offspring values. It means that now evaluation value for our step can’t become lower than the current value. From another point of view, the Beta that we have now is a current evaluation value of our parent. From the idea that currently, we’re maximizing, we may understand that our Parent is minimizing which means that it will select a minimum of its current value and its offsprings calculated value. Putting all of these together — because we know that our calculated value is higher than the parent value, we make a decision that it will not select us as its next possible step(it has a better offspring and that gives him lower value if it selects them). From that point of view doing the next calculation is ridiculous, because they will not change the final result. So we, as the parent-offspring, we stop all calculations and return the current value. Using this, our parent will compare us and the current best choice. By previously described logic it will select its current value. Using this optimization, we may cut huge branches and save a lot of work that would do nothing to the final result. Advice Great!, now that we know two optimizations that will make our algorithm work faster, I would like to give you one advice. Usually, when a machine makes a choice, the real user need some time to decide what to do next. We can use this time to prepare for next the decision. So when we make our choice, let’s continue to work for all possible user choices. What does this give to us?1. Bunch of them are already calculated from previous user iteration. 2. By the time user will select his choice, we will go far ahead with our calculation. It will increase a deepness of our tree, in other words — accuracy. In the end, when the user makes a choice, we can simply cut off all other branches that were not selected and only continue with selected one. It’s great, but then let’s make a global conclusion on what I suppose — do not start your algorithm each time it’s your turn. Make it run once during the game and when a user selects some step, get calculated data for it and continue our calculation until the end. Someone will say, that it’s has a heavy memory issue. Yes, it does, but this’s just an advice, you can combine two solutions to find what best fits your time, memory, and accuracy for your particular situation. Also, I would recommend performing calculations for each possible step in a new thread, but it’s quite a different story. Conclusion Where should you use this information? Anywhere you have to make or do decision-based on user action. Most often it might be games, but then, you can use your fantasy to integrate it in a place where you would have to reflect on any performed action. The only thing you need to understand is the algorithm for two parts that are “playing” against each other.
[ { "code": null, "e": 293, "s": 171, "text": "This article will be a bit different from previous ones which are based on some new technologies to use in your projects." }, { "code": null, "e": 424, "s": 293, "text": "Interesting? I will describe Minimax algorithm from the perspective of Game theory. Just letting you know what you are to expect :" }, { "code": null, "e": 596, "s": 424, "text": "1. So what’s Minimax algorithm? 2. Plan and code 3. Algorithm description 4. Optimizations 4.1. Deepness optimization 4.2. Alpha-Beta optimization 5. Advice6. Conclusion" }, { "code": null, "e": 703, "s": 596, "text": "For coding, we will use language Objective-C.Don’t worry though, there will be more theory than just code." }, { "code": null, "e": 735, "s": 703, "text": "The direction is set, let’s go." }, { "code": null, "e": 1207, "s": 735, "text": "So what’s Minimax algorithm? Minimax — is a decision rule used in decision theory, game theory, statistics and philosophy for minimizing the possible loss for a worst case (maximum loss) scenario. Originally formulated for two-player zero-sum game theory, covering both the cases where players take alternate moves and those where they make simultaneous moves, it has also been extended to more complex games and to general decision-making in the presence of uncertainty." }, { "code": null, "e": 1724, "s": 1207, "text": "Coooooooooool!Now that we have the definition, what logic is embedded in it? Let’s suggest that you are playing a game against your friend. And then each step you take you, want to maximize your win and your friend also wants to minimize his loss. Eventually, it’s the same definition for both of you. Your next decision should be maximizing your current win position knowing that your friend in the next step will minimize his loss position and knowing that the next step you will also maximize your win position..." }, { "code": null, "e": 1864, "s": 1724, "text": "Catching this recursion smell? So the main idea of this algorithm is to make the best decision knowing that your opponent will do the same." }, { "code": null, "e": 1878, "s": 1864, "text": "Plan and code" }, { "code": null, "e": 2316, "s": 1878, "text": "We will build this algorithm using tree representation. Each new generation of children is possible the next step of another player. For example, the first generation is your possible steps, each step will lead to some list of the opponent’s possible steps. In this situation, your step is the “father vertex” and possible next steps of your opponent are it’s “children vertexes”. Here is the final algorithm code with all optimizations." }, { "code": null, "e": 3638, "s": 2316, "text": "#pragma mark - Public- (NSUInteger)startAlgorithmWithAITurn:(BOOL)aiTurn; { return [self alphabetaAlgorithm:_searchingDeapth alpha:NSIntegerMin beta:NSIntegerMax maximizing:aiTurn];}#pragma mark - Private- (NSInteger)alphabetaAlgorithm:(NSInteger)depth alpha:(NSInteger)alpha beta:(NSInteger)beta maximizing:(BOOL)maximizing { self.currentCheckingDepth = _searchingDeapth - depth; if (self.datasource == nil || self.delegate == nil) { return 0; } if (depth == 0 || [self.datasource checkStopConditionForAlgorithm:self onAITurn:maximizing]) { return [self.datasource evaluateForAlgorithm:self onAITurn:maximizing]; } NSArray *nextStates = [self.datasource possibleNextStatesForAlgorithm:self onAITurn:maximizing]; for (id state in nextStates) { [self.delegate performActionForAlgorithm:self andState:state onAITurn:maximizing]; if (maximizing) { alpha = MAX(alpha, [self alphabetaAlgorithm:depth - 1 alpha:alpha beta:beta maximizing:NO]); } else { beta = MIN(beta, [self alphabetaAlgorithm:depth - 1 alpha:alpha beta:beta maximizing:YES]); } [self.delegate undoActionForAlgorithm:self andState:state onAITurn:maximizing]; if (beta <= alpha) { break; } } return (maximizing ? alpha : beta);}" }, { "code": null, "e": 3660, "s": 3638, "text": "Algorithm description" }, { "code": null, "e": 3927, "s": 3660, "text": "Let’s close our eyes on optimizations and start with the initial things that we need. First of all, we need an algorithm that will give back the list of possible next steps based on a made step. We use this to produce other children vertexes as described previously." }, { "code": null, "e": 4177, "s": 3927, "text": "Secondly, we need an algorithm that will calculate evaluation of the game result at the end of the game. Each vertex(made step) will have assigned value with the evaluated result using this algorithm. How it will be assigned will be described later." }, { "code": null, "e": 4311, "s": 4177, "text": "So how does this work using a tree and these algorithms? Logically algorithm is divided into two parts: 1. Our turn 2. Opponents turn" }, { "code": null, "e": 4561, "s": 4311, "text": "On “our turn” as next vertex, we choose one of our children that have the best evaluation value. Then as next chosen step generates possible opponents steps with its evaluation, he will choose worst evaluation value(worst for us means best for him)." }, { "code": null, "e": 4738, "s": 4561, "text": "This simply means that we will take the maximum evaluated step from possible opponents steps and the opponent will take the minimum evaluated step from our possible next steps." }, { "code": null, "e": 5469, "s": 4738, "text": "The Next question is — when will we evaluate step? The first thing that comes to mind — just when it’s created. But hold on a minute, how can we calculate it immediately if it depends on the next generation, or in other words on another player’s step? It means that our step value will be maximum from the next generation step value, which is an opponent step. From another point of view, opponents step value will be minimum from the next generation step values, which is mine. Following this rule, we can say that evaluation will be made when the game ends, as it’s final generation of steps. After that, it will unwind in back direction marking all vertexes with previously described calculated value until it gets to the root." }, { "code": null, "e": 5569, "s": 5469, "text": "Recursive generation ends if: We get a winnerIt’s not possible to have the next move, we get a draw" }, { "code": null, "e": 5895, "s": 5569, "text": "Evaluation of game state can be calculated in a next way: If we win, then evaluated value should be bigger than some positive value If we lose, then it should be lower than some negative value If we have a draw then it should be in between this values It means that the better position we have, the bigger value it should be." }, { "code": null, "e": 6167, "s": 5895, "text": "This evaluation may depend on different things. Let’s take for example that for evaluation, we give it a situation where we are winners. Then it may evaluate depending on next values:1. How much steps I took to get the win 2. How close was your opponent to the win etc..." }, { "code": null, "e": 6726, "s": 6167, "text": "This function is one of the most important parts of the algorithm. The better organized it is, the better results you get. A function that depends only on one characteristic will not be as accurate as a function that depends on ten. Also, characteristics you choose for evaluation should have logical meaning. If you will treat that evaluation value is bigger because the player is a woman other than a man, it makes some sense for the sexists but not for the algorithm. As a result, you will receive wrong results. And everything is because you’re a sexist." }, { "code": null, "e": 6883, "s": 6726, "text": "Great!, now we generally understand the algorithm and what idea lays under it. Sound cool, but still, it’s not as good when it comes to execution time. Why?" }, { "code": null, "e": 6897, "s": 6883, "text": "Optimizations" }, { "code": null, "e": 7015, "s": 6897, "text": "For usage, for example, let’s select “four in a row” game. If you don’t know what it is, here is a short description:" }, { "code": null, "e": 7385, "s": 7015, "text": "“It is the goal of the game to connect four of your tokens in a line. All directions (vertical, horizontal, diagonal) are allowed. Players take turns putting one of their tokens into one of the seven slots. A token falls down as far as possible within a slot. The player with the red tokens begins. The game ends immediately when the first player connects four stones.”" }, { "code": null, "e": 8244, "s": 7385, "text": "Let’s think how our algorithm will work in this case. The field has 7*6=42 steps. At the beginning, each user can make 7 different steps. What does this data give to us? These values are worst ever. To make them more real, let’s say, for instance, that game will end in 30 steps and averagely user will have a possibility to select 5 rows. Using our algorithm we will get next approximate data. The first user can produce 5 steps; each step will produce 5 own steps. Now we’re having 5 + 25. These 25 steps, each can produce 5 new steps and that’s equal to 125. Which means on the third step of calculation we will have about155 steps. Each next step will produce more and more possible steps to follow. You can count them using the next function:51 + 52 + 53 + ... + 530. This value is huge and a computer will take a lot of time to calculate so many steps." }, { "code": null, "e": 8380, "s": 8244, "text": "Thankfully there are ready optimizations for Minimax algorithm, that will lower this value. We will talk about the two of them shortly." }, { "code": null, "e": 8402, "s": 8380, "text": "Deepness optimization" }, { "code": null, "e": 9059, "s": 8402, "text": "Once upon a time, a very wise man said “why should we count it till the end? Can we make a decision somewhere in the middle?”. Yes, we can. Of course, in the end, accuracy will be much better than somewhere in the middle, but with a good algorithm for evaluation, we can lower this problem. So then what should we do, just add one more rule for \"algorithm stops\". This rule is, to stop if current step deepness is on critical value. This value you can select on your own after some testing. I think with a bunch of tests you will find those that are matching your special situation. When we start evaluation based on this rule, we’re treating it as a draw." }, { "code": null, "e": 9571, "s": 9059, "text": "This rule was not as hard, and can really optimize our algorithms. However still, it’s lowering our accuracy, and to make it work, we just can’t use super low deepness otherwise it will give us wrong, and non-accurate values. I will tell you next, we selected that deepness 8 is fine for us. Even though it was taking a lot of time to get its final result. Next optimization has no influence on accuracy and reduces algorithm time really good. Its name is Alpha Beta and it's this thing that breaks my mind out." }, { "code": null, "e": 9595, "s": 9571, "text": "Alpha-Beta optimization" }, { "code": null, "e": 9814, "s": 9595, "text": "It’s meaning is simple. The idea is next — no need to count next branches if we know that already founded branch will have a better result. It’s just a waste of resources. The idea is simple, what about implementation?" }, { "code": null, "e": 10027, "s": 9814, "text": "To count that, we need two other variables to be passed to the recursive algorithm. 1. Alpha — it’s representing evaluation value on maximizing part 2. Beta — it’s representing evaluation value on minimizing part" }, { "code": null, "e": 10409, "s": 10027, "text": "From previous parts, we understood that we have to go to the end of our tree and only then after can we evaluate our results. So the first evaluation will be made on the last vertex if we would always choose left vertex. After that evaluation process will start for its immediate vertex and will go on for all left vertexes till one of the possible ones end and so on and so forth." }, { "code": null, "e": 10528, "s": 10409, "text": "Why am I telling you this? It’s all because of understanding how evaluating vertexes is crucial for this optimization." }, { "code": null, "e": 11073, "s": 10528, "text": "To make it easier for us to imagine, let’s suppose that we’re on the maximizing turn. To us, it means that we’re counting Alpha value. This value is counted as a maximum of all evaluation values of his offsprings. At the same time when we’re counting Alpha(we’re on the maximizing process) we have a Beta value. Here, it represents a current Beta value of his parent. Great!, now we know what Alpha and Beta means in a specific time. To avoid misunderstanding, alpha is our current evaluation value and beta is current further evaluation value." }, { "code": null, "e": 11193, "s": 11073, "text": "The last thing is optimization check. If Beta is lower or equal the Alpha we’re stopping evaluation for all next child." }, { "code": null, "e": 11322, "s": 11193, "text": "The last thing is optimization check. If Beta is lower or equals to the Alpha we’re stopping evaluation for all next offsprings." }, { "code": null, "e": 11872, "s": 11322, "text": "Why does it work? Because Beta already is smaller than Alpha — value of its offspring, at the same time Alpha is counted as a maximum of possible offspring values. It means that now evaluation value for our step can’t become lower than the current value. From another point of view, the Beta that we have now is a current evaluation value of our parent. From the idea that currently, we’re maximizing, we may understand that our Parent is minimizing which means that it will select a minimum of its current value and its offsprings calculated value." }, { "code": null, "e": 12461, "s": 11872, "text": "Putting all of these together — because we know that our calculated value is higher than the parent value, we make a decision that it will not select us as its next possible step(it has a better offspring and that gives him lower value if it selects them). From that point of view doing the next calculation is ridiculous, because they will not change the final result. So we, as the parent-offspring, we stop all calculations and return the current value. Using this, our parent will compare us and the current best choice. By previously described logic it will select its current value." }, { "code": null, "e": 12577, "s": 12461, "text": "Using this optimization, we may cut huge branches and save a lot of work that would do nothing to the final result." }, { "code": null, "e": 12584, "s": 12577, "text": "Advice" }, { "code": null, "e": 12857, "s": 12584, "text": "Great!, now that we know two optimizations that will make our algorithm work faster, I would like to give you one advice. Usually, when a machine makes a choice, the real user need some time to decide what to do next. We can use this time to prepare for next the decision." }, { "code": null, "e": 13190, "s": 12857, "text": "So when we make our choice, let’s continue to work for all possible user choices. What does this give to us?1. Bunch of them are already calculated from previous user iteration. 2. By the time user will select his choice, we will go far ahead with our calculation. It will increase a deepness of our tree, in other words — accuracy." }, { "code": null, "e": 13598, "s": 13190, "text": "In the end, when the user makes a choice, we can simply cut off all other branches that were not selected and only continue with selected one. It’s great, but then let’s make a global conclusion on what I suppose — do not start your algorithm each time it’s your turn. Make it run once during the game and when a user selects some step, get calculated data for it and continue our calculation until the end." }, { "code": null, "e": 13809, "s": 13598, "text": "Someone will say, that it’s has a heavy memory issue. Yes, it does, but this’s just an advice, you can combine two solutions to find what best fits your time, memory, and accuracy for your particular situation." }, { "code": null, "e": 13931, "s": 13809, "text": "Also, I would recommend performing calculations for each possible step in a new thread, but it’s quite a different story." }, { "code": null, "e": 13942, "s": 13931, "text": "Conclusion" } ]
Make HTML5 input type=“number” accepting dashes
To allow HTML5 input type = ”number” to accept dashes, use a regular expression. Add the regular expression in the pattern attribute as shown below. [ 0 - 9 ] + ([ - \, ] [0 - 9] + ) ? " Add it to the code now: input type = "text" pattern = "[0-9]+([-\,][0-9]+)?" name = "my-num" title = "dashes or comma"/> The above will allow you to add dashes in number. However, above you need to use input type text for the solution to work.
[ { "code": null, "e": 1143, "s": 1062, "text": "To allow HTML5 input type = ”number” to accept dashes, use a regular expression." }, { "code": null, "e": 1211, "s": 1143, "text": "Add the regular expression in the pattern attribute as shown below." }, { "code": null, "e": 1249, "s": 1211, "text": "[ 0 - 9 ] + ([ - \\, ] [0 - 9] + ) ? \"" }, { "code": null, "e": 1273, "s": 1249, "text": "Add it to the code now:" }, { "code": null, "e": 1370, "s": 1273, "text": "input type = \"text\" pattern = \"[0-9]+([-\\,][0-9]+)?\" name = \"my-num\" title = \"dashes or comma\"/>" }, { "code": null, "e": 1493, "s": 1370, "text": "The above will allow you to add dashes in number. However, above you need to use input type text for the solution to work." } ]
Lambda Expressions in Python. How to write anonymous functions in... | by Luay Matalka | Towards Data Science
Imagine we are coding and need to write a simple function. However, we are only going to be using this function once and thus it seems unnecessary to create an entire function with the def keyword for that one task. Well, that’s where lambda expressions come in. Lambda expressions are used to create anonymous functions, or functions without a name. They are useful when we need to create a function that will only need to be used once (a throw-away function) and can be written in one line. Lambda functions can have any number of parameters but can only have one expression. They generally have this format which yields a function object: lambda parameters: expression Let’s say we want to write a function that takes in a number as an input and returns that number squared. We can do so by using the def keyword: We used the def keyword to define this function. We named this function square. This function has one parameter, num, and it returns that number squared using the ** operator. Let’s now write this function as a lambda expression: And that’s it! We first start with the lambda keyword, then the parameter num, a colon, and what you want that function to return, which is num**2. Note that this function is anonymous, or does not have a name. So we cannot invoke the function at a later point. In addition, we did not write return. Everything after the colon is part of the expression that will be returned. If we want to assign a lambda function to a variable so that it can be invoked later, we can do so by using an assignment operator: We can then invoke or call this function the same way we would with a function that was defined with the def keyword. For example: square(3) # will return 9 as the output towardsdatascience.com Let’s make a lambda function that has two parameters instead of just one. First, we will use the def keyword to create a function that returns the sum of two numbers, and then we will write it as a lambda expression: As we can see, if we want our function to have multiple parameters in a lambda expression, we would just separate those parameters by a comma. Just like with expressions created using the def keyword, a lambda expression does not need to have any parameters. For example, if we want a lambda expression that takes in no arguments and always returns True, we can write it as follows: We can also include if else statements in lambda expressions. We would just need to make sure that it is all on one line. For example, let’s create a function that takes in two numbers and returns the greater of those numbers: Our lambda expression takes in two numbers, num1 and num2, and returns num1 if num1 is greater than num2, else, it returns num2. Obviously this function doesn’t take into account if the numbers are equal, as it will just return num2 in that case, however, we are just illustrating how we can use conditional statements within a lambda expression. towardsdatascience.com Technically we cannot use an elif statement in a lambda expression. However, we can nest if else statements within an else statement to achieve the same result as an elif statement. For example, if we also want to check if num1 is greater than num2, if num2 is greater than num1, or else (meaning if they are equal), we can use the following lambda expression: So if our lambda expression finds that num1 > num2, it will return num1. If this condition is false, it’ll move on to the else statement. Within this else statement (within the parenthesis), it’ll first check if num1 < num2 is true. If that condition is true, it will return num2. If that condition is false, it will return whatever is after the else statement which in this case is the string ‘They are equal’. Lambda expressions are extremely useful to use in functions that take in another function as an argument. For example, in the map, filter, and reduce functions, we can pass in a lambda expression as the function. Detailed overview of the map, filter, and reduce functions: towardsdatascience.com towardsdatascience.com In this tutorial, we learned what lambda expressions are, how to write them with zero parameters, one parameter, and multiple parameters. We also learned how to use if else statements within a lambda expression.
[ { "code": null, "e": 435, "s": 172, "text": "Imagine we are coding and need to write a simple function. However, we are only going to be using this function once and thus it seems unnecessary to create an entire function with the def keyword for that one task. Well, that’s where lambda expressions come in." }, { "code": null, "e": 814, "s": 435, "text": "Lambda expressions are used to create anonymous functions, or functions without a name. They are useful when we need to create a function that will only need to be used once (a throw-away function) and can be written in one line. Lambda functions can have any number of parameters but can only have one expression. They generally have this format which yields a function object:" }, { "code": null, "e": 844, "s": 814, "text": "lambda parameters: expression" }, { "code": null, "e": 989, "s": 844, "text": "Let’s say we want to write a function that takes in a number as an input and returns that number squared. We can do so by using the def keyword:" }, { "code": null, "e": 1165, "s": 989, "text": "We used the def keyword to define this function. We named this function square. This function has one parameter, num, and it returns that number squared using the ** operator." }, { "code": null, "e": 1219, "s": 1165, "text": "Let’s now write this function as a lambda expression:" }, { "code": null, "e": 1367, "s": 1219, "text": "And that’s it! We first start with the lambda keyword, then the parameter num, a colon, and what you want that function to return, which is num**2." }, { "code": null, "e": 1595, "s": 1367, "text": "Note that this function is anonymous, or does not have a name. So we cannot invoke the function at a later point. In addition, we did not write return. Everything after the colon is part of the expression that will be returned." }, { "code": null, "e": 1727, "s": 1595, "text": "If we want to assign a lambda function to a variable so that it can be invoked later, we can do so by using an assignment operator:" }, { "code": null, "e": 1858, "s": 1727, "text": "We can then invoke or call this function the same way we would with a function that was defined with the def keyword. For example:" }, { "code": null, "e": 1898, "s": 1858, "text": "square(3) # will return 9 as the output" }, { "code": null, "e": 1921, "s": 1898, "text": "towardsdatascience.com" }, { "code": null, "e": 2138, "s": 1921, "text": "Let’s make a lambda function that has two parameters instead of just one. First, we will use the def keyword to create a function that returns the sum of two numbers, and then we will write it as a lambda expression:" }, { "code": null, "e": 2281, "s": 2138, "text": "As we can see, if we want our function to have multiple parameters in a lambda expression, we would just separate those parameters by a comma." }, { "code": null, "e": 2521, "s": 2281, "text": "Just like with expressions created using the def keyword, a lambda expression does not need to have any parameters. For example, if we want a lambda expression that takes in no arguments and always returns True, we can write it as follows:" }, { "code": null, "e": 2748, "s": 2521, "text": "We can also include if else statements in lambda expressions. We would just need to make sure that it is all on one line. For example, let’s create a function that takes in two numbers and returns the greater of those numbers:" }, { "code": null, "e": 3095, "s": 2748, "text": "Our lambda expression takes in two numbers, num1 and num2, and returns num1 if num1 is greater than num2, else, it returns num2. Obviously this function doesn’t take into account if the numbers are equal, as it will just return num2 in that case, however, we are just illustrating how we can use conditional statements within a lambda expression." }, { "code": null, "e": 3118, "s": 3095, "text": "towardsdatascience.com" }, { "code": null, "e": 3479, "s": 3118, "text": "Technically we cannot use an elif statement in a lambda expression. However, we can nest if else statements within an else statement to achieve the same result as an elif statement. For example, if we also want to check if num1 is greater than num2, if num2 is greater than num1, or else (meaning if they are equal), we can use the following lambda expression:" }, { "code": null, "e": 3891, "s": 3479, "text": "So if our lambda expression finds that num1 > num2, it will return num1. If this condition is false, it’ll move on to the else statement. Within this else statement (within the parenthesis), it’ll first check if num1 < num2 is true. If that condition is true, it will return num2. If that condition is false, it will return whatever is after the else statement which in this case is the string ‘They are equal’." }, { "code": null, "e": 4104, "s": 3891, "text": "Lambda expressions are extremely useful to use in functions that take in another function as an argument. For example, in the map, filter, and reduce functions, we can pass in a lambda expression as the function." }, { "code": null, "e": 4164, "s": 4104, "text": "Detailed overview of the map, filter, and reduce functions:" }, { "code": null, "e": 4187, "s": 4164, "text": "towardsdatascience.com" }, { "code": null, "e": 4210, "s": 4187, "text": "towardsdatascience.com" } ]
Redis - Benchmarks
Redis benchmark is the utility to check the performance of Redis by running n commands simultaneously. Following is the basic syntax of Redis benchmark. redis-benchmark [option] [option value] Following example checks Redis by calling 100000 commands. redis-benchmark -n 100000 PING_INLINE: 141043.72 requests per second PING_BULK: 142857.14 requests per second SET: 141442.72 requests per second GET: 145348.83 requests per second INCR: 137362.64 requests per second LPUSH: 145348.83 requests per second LPOP: 146198.83 requests per second SADD: 146198.83 requests per second SPOP: 149253.73 requests per second LPUSH (needed to benchmark LRANGE): 148588.42 requests per second LRANGE_100 (first 100 elements): 58411.21 requests per second LRANGE_300 (first 300 elements): 21195.42 requests per second LRANGE_500 (first 450 elements): 14539.11 requests per second LRANGE_600 (first 600 elements): 10504.20 requests per second MSET (10 keys): 93283.58 requests per second Following is a list of available options in Redis benchmark. Following example shows the multiple usage options in Redis benchmark utility. redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 100000 -q SET: 146198.83 requests per second LPUSH: 145560.41 requests per second 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2148, "s": 2045, "text": "Redis benchmark is the utility to check the performance of Redis by running n commands simultaneously." }, { "code": null, "e": 2198, "s": 2148, "text": "Following is the basic syntax of Redis benchmark." }, { "code": null, "e": 2240, "s": 2198, "text": "redis-benchmark [option] [option value] \n" }, { "code": null, "e": 2299, "s": 2240, "text": "Following example checks Redis by calling 100000 commands." }, { "code": null, "e": 3038, "s": 2299, "text": "redis-benchmark -n 100000 \n\nPING_INLINE: 141043.72 requests per second \nPING_BULK: 142857.14 requests per second \nSET: 141442.72 requests per second \nGET: 145348.83 requests per second \nINCR: 137362.64 requests per second \nLPUSH: 145348.83 requests per second \nLPOP: 146198.83 requests per second \nSADD: 146198.83 requests per second \nSPOP: 149253.73 requests per second \nLPUSH (needed to benchmark LRANGE): 148588.42 requests per second \nLRANGE_100 (first 100 elements): 58411.21 requests per second \nLRANGE_300 (first 300 elements): 21195.42 requests per second \nLRANGE_500 (first 450 elements): 14539.11 requests per second \nLRANGE_600 (first 600 elements): 10504.20 requests per second \nMSET (10 keys): 93283.58 requests per second \n" }, { "code": null, "e": 3099, "s": 3038, "text": "Following is a list of available options in Redis benchmark." }, { "code": null, "e": 3178, "s": 3099, "text": "Following example shows the multiple usage options in Redis benchmark utility." }, { "code": null, "e": 3319, "s": 3178, "text": "redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 100000 -q \n\nSET: 146198.83 requests per second \nLPUSH: 145560.41 requests per second \n" }, { "code": null, "e": 3351, "s": 3319, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 3371, "s": 3351, "text": " Skillbakerystudios" }, { "code": null, "e": 3378, "s": 3371, "text": " Print" }, { "code": null, "e": 3389, "s": 3378, "text": " Add Notes" } ]
Building a Custom Semantic Segmentation Model | by Sam Watts | Towards Data Science
Following on from my previous post here, I wanted to see how feasible it would be to reliably detect and segment a Futoshiki puzzle grid from an image without using a clunky capture grid. It works surprisingly well even when trained on a tiny dataset! Semantic Segmentation is a step up in complexity versus the more common computer vision tasks such as classification and object detection. The goal is to produce a pixel-level prediction for one or more classes. This prediction is referred to as an image ‘mask’. The example here shows 3 overlaid masks for person, sheep, and dog represented by the different foreground colours. For my task, the setup is somewhat simpler as there is only one class to predict - the puzzle grid. To train the model, we need pairs of images and masks. The images we are using are full colour, so as an array will have the shape (H, W, 3). The masks on the other hand only have a single value per pixel (1 or 0), so will have shape (H, W, 1). How do we get the image masks I’ve just talked about? VIA is a great tool for image labelling — it’s open source and runs in a browser from a standalone HTML file. VIA lets you export labels for multiple images as a csv, with the coordinates of each polygon in json format: {"name":"polygon","all_points_x":[1973,2576,2579,1964],"all_points_y":[2792,2816,3423,3398]} I then wrote a custom pytorch dataloader, which converts the polygon json into a single channel image mask. The training image and the target mask are then passed on to the model. In total I labelled 43 images, which I split 75:25 into training and validation sets. I later added an extra 7 images to serve as a test set. This might not seem like much data to be training a large neural network on - but fortunately there are some techniques we can use to get the most out of this small set of images! As this is a prototype, I wanted to see if the approach would achieve decent results without building the whole thing myself from scratch and potentially wasting a lot of effort. With that in mind, I used the awesome segmentation-models-pytorch library. The power of this library hinges on transfer learning, which means we can avoid having to train the entire network from a standing start. U-Net consists of a coupled encoder and decoder structure, which builds high level abstractions of input images before expanding out these abstractions to provide a pixel-level prediction. The grey arrows signify residual connections between the encoder and decoder pathways. This means that at every upwards step of the decoder, the encoder matrices of the same dimensions are concatenated together with the decoder matrices. The benefits of this are twofold: At each level of the decoder - which would otherwise only contain high level abstraction information of the image - the network is able to combine it’s learning about high and low level features, increasing the fidelity of predictions.Residual connections allow backpropagation during training to skip past layers, making optimisation easier. This is also crucial when training deeper models to avoid issues with vanishing gradients. At each level of the decoder - which would otherwise only contain high level abstraction information of the image - the network is able to combine it’s learning about high and low level features, increasing the fidelity of predictions. Residual connections allow backpropagation during training to skip past layers, making optimisation easier. This is also crucial when training deeper models to avoid issues with vanishing gradients. The beauty of this architecture is also that we can use a pre-trained model that has been used for a classification task - on a dataset such as ImageNet - as our encoder. Once we remove the final classification layer from this model, this can be connected to a decoder with untrained weights, and skip-connections are added to reflect the U-Net structure. This saves a lot of compute time, as our pre-trained encoder already has good parameters for building high levels abstractions of images. segmentation-models-pytorch provides pre-trained weights for a number of different encoder architectures. Google AI published their EfficientNet paper in 2019 with new thinking behind how to scale up convolutional neural networks. Alongside this, the paper proposed a range of models of increasing complexity that achieve state of the art performance. As a trade off between size and performance, I chose the B3 variant to use in my model. Specifying these architecture choices with segmentation-models-pytorch is a breeze: As the training dataset only contains 36 images, overfitting is a serious concern. If we train for multiple epochs over this small dataset, we might worry that our model will start fitting to the noise in this small dataset, leading to poor performance on out of sample examples. This problem can be somewhat mitigated by data augmentation. As each training image and mask pair is read into memory to pass to the model, we apply several layers of non-deterministic image processing, as shown below. It’s useful to look at example image to see the individual effects of each of these layers. This is the first image from our training set: As you can see below, most of the augmentations by themselves only provide a subtle change - however when stacked up, they add enough novelty to our training data to stop the model fitting to the noise of the base dataset The most commonly used loss function is pixel wise Cross-Entropy Loss - similar to what is used in general classification tasks. Here, we instead use Dice Loss, which was introduced to address the issue of class imbalance in semantic segmentation: Dice Loss = 2|A ∩ B| / |A| + |B| In practice, the intersection term of this equation is approximated by calculating the element-wise product of the prediction and target mask matrices: We also use Intersection-over-Union (IoU) as a scoring metric. This essentially looks at the overlapping over total area of both predicted and ground truth masks, which is a similar concept to Dice Loss. Training regime: Trained for 40 epochs, initial learning rate = 5x10e-4 After the 30th epoch, learning rate = 5x10e-5 I tested the trained model on 7 held out images from my labelled dataset, and the model achieved a IOU Score = 0.94 for these images, including some with puzzles at odd angles and as a smaller part of the image. I also ran the model over a short video to see the results more visually, which was also pretty good - it also deals well with an object covering the puzzle! The enhanced version of the code base I discussed in my prior post can be found here. This version of the model shows some slight activation on background features, which is perhaps the sign of some overfitting. To conclude, this approach showed some pretty impressive results, especially given the tiny amount of training data that was used! I found two of the recent DeepMind x UCL Deep Learning Lectures to be a great introduction to computer vision concepts: Lecture 3 - Convolutional Neural Networks for Image Recognition Lecture 4 - Advanced Models for Computer Vision Segmentation Models Pytorch Github
[ { "code": null, "e": 424, "s": 172, "text": "Following on from my previous post here, I wanted to see how feasible it would be to reliably detect and segment a Futoshiki puzzle grid from an image without using a clunky capture grid. It works surprisingly well even when trained on a tiny dataset!" }, { "code": null, "e": 803, "s": 424, "text": "Semantic Segmentation is a step up in complexity versus the more common computer vision tasks such as classification and object detection. The goal is to produce a pixel-level prediction for one or more classes. This prediction is referred to as an image ‘mask’. The example here shows 3 overlaid masks for person, sheep, and dog represented by the different foreground colours." }, { "code": null, "e": 1148, "s": 803, "text": "For my task, the setup is somewhat simpler as there is only one class to predict - the puzzle grid. To train the model, we need pairs of images and masks. The images we are using are full colour, so as an array will have the shape (H, W, 3). The masks on the other hand only have a single value per pixel (1 or 0), so will have shape (H, W, 1)." }, { "code": null, "e": 1312, "s": 1148, "text": "How do we get the image masks I’ve just talked about? VIA is a great tool for image labelling — it’s open source and runs in a browser from a standalone HTML file." }, { "code": null, "e": 1422, "s": 1312, "text": "VIA lets you export labels for multiple images as a csv, with the coordinates of each polygon in json format:" }, { "code": null, "e": 1515, "s": 1422, "text": "{\"name\":\"polygon\",\"all_points_x\":[1973,2576,2579,1964],\"all_points_y\":[2792,2816,3423,3398]}" }, { "code": null, "e": 1695, "s": 1515, "text": "I then wrote a custom pytorch dataloader, which converts the polygon json into a single channel image mask. The training image and the target mask are then passed on to the model." }, { "code": null, "e": 2017, "s": 1695, "text": "In total I labelled 43 images, which I split 75:25 into training and validation sets. I later added an extra 7 images to serve as a test set. This might not seem like much data to be training a large neural network on - but fortunately there are some techniques we can use to get the most out of this small set of images!" }, { "code": null, "e": 2409, "s": 2017, "text": "As this is a prototype, I wanted to see if the approach would achieve decent results without building the whole thing myself from scratch and potentially wasting a lot of effort. With that in mind, I used the awesome segmentation-models-pytorch library. The power of this library hinges on transfer learning, which means we can avoid having to train the entire network from a standing start." }, { "code": null, "e": 2598, "s": 2409, "text": "U-Net consists of a coupled encoder and decoder structure, which builds high level abstractions of input images before expanding out these abstractions to provide a pixel-level prediction." }, { "code": null, "e": 2870, "s": 2598, "text": "The grey arrows signify residual connections between the encoder and decoder pathways. This means that at every upwards step of the decoder, the encoder matrices of the same dimensions are concatenated together with the decoder matrices. The benefits of this are twofold:" }, { "code": null, "e": 3304, "s": 2870, "text": "At each level of the decoder - which would otherwise only contain high level abstraction information of the image - the network is able to combine it’s learning about high and low level features, increasing the fidelity of predictions.Residual connections allow backpropagation during training to skip past layers, making optimisation easier. This is also crucial when training deeper models to avoid issues with vanishing gradients." }, { "code": null, "e": 3540, "s": 3304, "text": "At each level of the decoder - which would otherwise only contain high level abstraction information of the image - the network is able to combine it’s learning about high and low level features, increasing the fidelity of predictions." }, { "code": null, "e": 3739, "s": 3540, "text": "Residual connections allow backpropagation during training to skip past layers, making optimisation easier. This is also crucial when training deeper models to avoid issues with vanishing gradients." }, { "code": null, "e": 4233, "s": 3739, "text": "The beauty of this architecture is also that we can use a pre-trained model that has been used for a classification task - on a dataset such as ImageNet - as our encoder. Once we remove the final classification layer from this model, this can be connected to a decoder with untrained weights, and skip-connections are added to reflect the U-Net structure. This saves a lot of compute time, as our pre-trained encoder already has good parameters for building high levels abstractions of images." }, { "code": null, "e": 4339, "s": 4233, "text": "segmentation-models-pytorch provides pre-trained weights for a number of different encoder architectures." }, { "code": null, "e": 4585, "s": 4339, "text": "Google AI published their EfficientNet paper in 2019 with new thinking behind how to scale up convolutional neural networks. Alongside this, the paper proposed a range of models of increasing complexity that achieve state of the art performance." }, { "code": null, "e": 4673, "s": 4585, "text": "As a trade off between size and performance, I chose the B3 variant to use in my model." }, { "code": null, "e": 4757, "s": 4673, "text": "Specifying these architecture choices with segmentation-models-pytorch is a breeze:" }, { "code": null, "e": 5256, "s": 4757, "text": "As the training dataset only contains 36 images, overfitting is a serious concern. If we train for multiple epochs over this small dataset, we might worry that our model will start fitting to the noise in this small dataset, leading to poor performance on out of sample examples. This problem can be somewhat mitigated by data augmentation. As each training image and mask pair is read into memory to pass to the model, we apply several layers of non-deterministic image processing, as shown below." }, { "code": null, "e": 5395, "s": 5256, "text": "It’s useful to look at example image to see the individual effects of each of these layers. This is the first image from our training set:" }, { "code": null, "e": 5617, "s": 5395, "text": "As you can see below, most of the augmentations by themselves only provide a subtle change - however when stacked up, they add enough novelty to our training data to stop the model fitting to the noise of the base dataset" }, { "code": null, "e": 5865, "s": 5617, "text": "The most commonly used loss function is pixel wise Cross-Entropy Loss - similar to what is used in general classification tasks. Here, we instead use Dice Loss, which was introduced to address the issue of class imbalance in semantic segmentation:" }, { "code": null, "e": 5898, "s": 5865, "text": "Dice Loss = 2|A ∩ B| / |A| + |B|" }, { "code": null, "e": 6050, "s": 5898, "text": "In practice, the intersection term of this equation is approximated by calculating the element-wise product of the prediction and target mask matrices:" }, { "code": null, "e": 6254, "s": 6050, "text": "We also use Intersection-over-Union (IoU) as a scoring metric. This essentially looks at the overlapping over total area of both predicted and ground truth masks, which is a similar concept to Dice Loss." }, { "code": null, "e": 6271, "s": 6254, "text": "Training regime:" }, { "code": null, "e": 6326, "s": 6271, "text": "Trained for 40 epochs, initial learning rate = 5x10e-4" }, { "code": null, "e": 6372, "s": 6326, "text": "After the 30th epoch, learning rate = 5x10e-5" }, { "code": null, "e": 6584, "s": 6372, "text": "I tested the trained model on 7 held out images from my labelled dataset, and the model achieved a IOU Score = 0.94 for these images, including some with puzzles at odd angles and as a smaller part of the image." }, { "code": null, "e": 6742, "s": 6584, "text": "I also ran the model over a short video to see the results more visually, which was also pretty good - it also deals well with an object covering the puzzle!" }, { "code": null, "e": 6954, "s": 6742, "text": "The enhanced version of the code base I discussed in my prior post can be found here. This version of the model shows some slight activation on background features, which is perhaps the sign of some overfitting." }, { "code": null, "e": 7085, "s": 6954, "text": "To conclude, this approach showed some pretty impressive results, especially given the tiny amount of training data that was used!" }, { "code": null, "e": 7205, "s": 7085, "text": "I found two of the recent DeepMind x UCL Deep Learning Lectures to be a great introduction to computer vision concepts:" }, { "code": null, "e": 7269, "s": 7205, "text": "Lecture 3 - Convolutional Neural Networks for Image Recognition" }, { "code": null, "e": 7317, "s": 7269, "text": "Lecture 4 - Advanced Models for Computer Vision" } ]
DBSCAN — a density-based unsupervised algorithm for fraud detection | by Mahbubul Alam | Towards Data Science
According to a recent report financial losses due to fraudulent transactions have reached about $17 billion USD, with as many as 5% of consumers experiencing fraud incidents of some kind. In light of such a big volume of financial losses, every industry is taking fraud detection seriously. It’s not just the financial industries that are susceptible, anomalies are prevalent in every single industry and can take many different forms — such as network intrusion, disturbances in business performances and abrupt changes in KPIs etc. Fraud/anomaly/outlier detection has long been the subject of intense research in data science. In the ever-changing landscape of fraud detection, new tools and techniques are being tested and employed every day to screen out abnormalities. In this series of articles, so far I’ve discussed six different techniques for fraud detection: Elliptic Envelope Local Outlier Factor (LOF) Z-score Boxplot Statistical techniques Time series anomaly detection Today I’m going to introduce another technique called DBSCAN — short for Density-Based Spatial Clustering of Applications with Noise. As the name suggests, DBSCAN is a density-based and unsupervised machine learning algorithm. It takes multi-dimensional data as inputs and clusters them according to the model parameters — e.g. epsilon and minimum samples. Based on these parameters, the algorithm determines whether certain values in the dataset are outliers or not. Below is a simple demonstration in Python programming language. Scikit-learn has a DBSCAN module as part of its unsupervised machine learning algorithms. This algorithm can be used out of the box for fraud detection in only a few simple steps. For this demo, we need three key libraries for data wrangling, visualization and modeling. # data wranglingimport pandas as pd# visualizationimport matplotlib.pyplot as plt# algorithmfrom sklearn.cluster import DBSCAN I am using the famous Iris dataset from an online source, so you can practice along without worrying about where to get the data from how to clean that up. # import datadf = pd.read_csv("https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv")print(df.head()) Let’s choose a subset of data for testing the algorithm and visualize them in a scatter plot. The two most important parameter values the model takes are (i) esp, which specifies the distance between two points i.e., how close the data points should be to one another to be considered part of a cluster; and (ii) min_samples, which specifies the minimum number of neighbors a point should have in a cluster. # input datadata = df[["sepal_length", "sepal_width"]]# specify & fit modelmodel = DBSCAN(eps = 0.4, min_samples = 10).fit(data) # visualize outputscolors = model.labels_plt.scatter(data["sepal_length"], data["sepal_width"], c = colors) # outliers dataframeoutliers = data[model.labels_ == -1]print(outliers) The purpose of this article was to introduce DBSCAN — a clustering-based unsupervised machine learning technique for fraud/outlier/anomaly detection. Its implementation can be as simple as taking just the five steps using thesklearn library. But of course, this is a simple demonstration of the concept. A real-world application would require much more experimentation to find the best model that works for a particular context and industry.
[ { "code": null, "e": 360, "s": 172, "text": "According to a recent report financial losses due to fraudulent transactions have reached about $17 billion USD, with as many as 5% of consumers experiencing fraud incidents of some kind." }, { "code": null, "e": 706, "s": 360, "text": "In light of such a big volume of financial losses, every industry is taking fraud detection seriously. It’s not just the financial industries that are susceptible, anomalies are prevalent in every single industry and can take many different forms — such as network intrusion, disturbances in business performances and abrupt changes in KPIs etc." }, { "code": null, "e": 1042, "s": 706, "text": "Fraud/anomaly/outlier detection has long been the subject of intense research in data science. In the ever-changing landscape of fraud detection, new tools and techniques are being tested and employed every day to screen out abnormalities. In this series of articles, so far I’ve discussed six different techniques for fraud detection:" }, { "code": null, "e": 1060, "s": 1042, "text": "Elliptic Envelope" }, { "code": null, "e": 1087, "s": 1060, "text": "Local Outlier Factor (LOF)" }, { "code": null, "e": 1095, "s": 1087, "text": "Z-score" }, { "code": null, "e": 1103, "s": 1095, "text": "Boxplot" }, { "code": null, "e": 1126, "s": 1103, "text": "Statistical techniques" }, { "code": null, "e": 1156, "s": 1126, "text": "Time series anomaly detection" }, { "code": null, "e": 1290, "s": 1156, "text": "Today I’m going to introduce another technique called DBSCAN — short for Density-Based Spatial Clustering of Applications with Noise." }, { "code": null, "e": 1624, "s": 1290, "text": "As the name suggests, DBSCAN is a density-based and unsupervised machine learning algorithm. It takes multi-dimensional data as inputs and clusters them according to the model parameters — e.g. epsilon and minimum samples. Based on these parameters, the algorithm determines whether certain values in the dataset are outliers or not." }, { "code": null, "e": 1688, "s": 1624, "text": "Below is a simple demonstration in Python programming language." }, { "code": null, "e": 1868, "s": 1688, "text": "Scikit-learn has a DBSCAN module as part of its unsupervised machine learning algorithms. This algorithm can be used out of the box for fraud detection in only a few simple steps." }, { "code": null, "e": 1959, "s": 1868, "text": "For this demo, we need three key libraries for data wrangling, visualization and modeling." }, { "code": null, "e": 2086, "s": 1959, "text": "# data wranglingimport pandas as pd# visualizationimport matplotlib.pyplot as plt# algorithmfrom sklearn.cluster import DBSCAN" }, { "code": null, "e": 2242, "s": 2086, "text": "I am using the famous Iris dataset from an online source, so you can practice along without worrying about where to get the data from how to clean that up." }, { "code": null, "e": 2367, "s": 2242, "text": "# import datadf = pd.read_csv(\"https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv\")print(df.head())" }, { "code": null, "e": 2461, "s": 2367, "text": "Let’s choose a subset of data for testing the algorithm and visualize them in a scatter plot." }, { "code": null, "e": 2775, "s": 2461, "text": "The two most important parameter values the model takes are (i) esp, which specifies the distance between two points i.e., how close the data points should be to one another to be considered part of a cluster; and (ii) min_samples, which specifies the minimum number of neighbors a point should have in a cluster." }, { "code": null, "e": 2904, "s": 2775, "text": "# input datadata = df[[\"sepal_length\", \"sepal_width\"]]# specify & fit modelmodel = DBSCAN(eps = 0.4, min_samples = 10).fit(data)" }, { "code": null, "e": 3012, "s": 2904, "text": "# visualize outputscolors = model.labels_plt.scatter(data[\"sepal_length\"], data[\"sepal_width\"], c = colors)" }, { "code": null, "e": 3084, "s": 3012, "text": "# outliers dataframeoutliers = data[model.labels_ == -1]print(outliers)" } ]
Angular 6 - Environment Setup
In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following − Nodejs Npm Angular CLI IDE for writing your code Nodejs has to be greater than 8.11 and npm has to be greater than 5.6. To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system. C:\>node -v v8.11.3 If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The homepage of nodejs will look like the following − Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm. C:\>npm -v 5.6.0 Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command. Type npm install -g @angular/cli, to install angular cli on your system. You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc. The details of the project setup is explained in the next chapter. 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": 2123, "s": 1995, "text": "In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following −" }, { "code": null, "e": 2130, "s": 2123, "text": "Nodejs" }, { "code": null, "e": 2134, "s": 2130, "text": "Npm" }, { "code": null, "e": 2146, "s": 2134, "text": "Angular CLI" }, { "code": null, "e": 2172, "s": 2146, "text": "IDE for writing your code" }, { "code": null, "e": 2243, "s": 2172, "text": "Nodejs has to be greater than 8.11 and npm has to be greater than 5.6." }, { "code": null, "e": 2402, "s": 2243, "text": "To check if nodejs is installed on your system, type node -v in the terminal. This will help you see the version of nodejs currently installed on your system." }, { "code": null, "e": 2423, "s": 2402, "text": "C:\\>node -v\nv8.11.3\n" }, { "code": null, "e": 2604, "s": 2423, "text": "If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS." }, { "code": null, "e": 2658, "s": 2604, "text": "The homepage of nodejs will look like the following −" }, { "code": null, "e": 2883, "s": 2658, "text": "Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm -v in the terminal. It should display the version of the npm." }, { "code": null, "e": 2901, "s": 2883, "text": "C:\\>npm -v\n5.6.0\n" }, { "code": null, "e": 3062, "s": 2901, "text": "Angular 6 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command." }, { "code": null, "e": 3135, "s": 3062, "text": "Type npm install -g @angular/cli, to install angular cli on your system." }, { "code": null, "e": 3303, "s": 3135, "text": "You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc." }, { "code": null, "e": 3370, "s": 3303, "text": "The details of the project setup is explained in the next chapter." }, { "code": null, "e": 3405, "s": 3370, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3419, "s": 3405, "text": " Anadi Sharma" }, { "code": null, "e": 3454, "s": 3419, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3468, "s": 3454, "text": " Anadi Sharma" }, { "code": null, "e": 3503, "s": 3468, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3523, "s": 3503, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3558, "s": 3523, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3575, "s": 3558, "text": " Frahaan Hussain" }, { "code": null, "e": 3608, "s": 3575, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3620, "s": 3608, "text": " Senol Atac" }, { "code": null, "e": 3655, "s": 3620, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3667, "s": 3655, "text": " Senol Atac" }, { "code": null, "e": 3674, "s": 3667, "text": " Print" }, { "code": null, "e": 3685, "s": 3674, "text": " Add Notes" } ]
CSS Multiple Backgrounds
In this chapter you will learn how to add multiple background images to one element. You will also learn about the following properties: background-size background-origin background-clip CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer. The following example has two background images, the first image is a flower (aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner): Multiple background images can be specified using either the individual background properties (as above) or the background shorthand property. The following example uses the background shorthand property (same result as example above): The CSS background-size property allows you to specify the size of background images. The size can be specified in lengths, percentages, or by using one of the two keywords: contain or cover. The following example resizes a background image to much smaller than the original image (using pixels): Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Here is the code: The two other possible values for background-size are contain and cover. The contain keyword scales the background image to be as large as possible (but both its width and its height must fit inside the content area). As such, depending on the proportions of the background image and the background positioning area, there may be some areas of the background which are not covered by the background image. The cover keyword scales the background image so that the content area is completely covered by the background image (both its width and height are equal to or exceed the content area). As such, some parts of the background image may not be visible in the background positioning area. The following example illustrates the use of contain and cover: The background-size property also accepts multiple values for background size (using a comma-separated list), when working with multiple backgrounds. The following example has three background images specified, with different background-size value for each image: Now we want to have a background image on a website that covers the entire browser window at all times. The requirements are as follows: Fill the entire page with the image (no white space) Scale image as needed Center image on page Do not cause scrollbars The following example shows how to do it; Use the <html> element (the <html> element is always at least the height of the browser window). Then set a fixed and centered background on it. Then adjust its size with the background-size property: You could also use different background properties on a <div> to create a hero image (a large image with text), and place it where you want. The CSS background-origin property specifies where the background image is positioned. The property takes three different values: border-box - the background image starts from the upper left corner of the border padding-box - (default) the background image starts from the upper left corner of the padding edge content-box - the background image starts from the upper left corner of the content The following example illustrates the background-origin property: The CSS background-clip property specifies the painting area of the background. The property takes three different values: border-box - (default) the background is painted to the outside edge of the border padding-box - the background is painted to the outside edge of the padding content-box - the background is painted within the content box The following example illustrates the background-clip property: Add two background images to the <body> element. img1.gif and img2.gif. Make sure that img2.gif is displayed on top of img1.gif. <style> body { background-image: ; } </style> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 86, "s": 0, "text": "In this chapter you will learn how to add multiple background images to one \nelement." }, { "code": null, "e": 138, "s": 86, "text": "You will also learn about the following properties:" }, { "code": null, "e": 154, "s": 138, "text": "background-size" }, { "code": null, "e": 172, "s": 154, "text": "background-origin" }, { "code": null, "e": 188, "s": 172, "text": "background-clip" }, { "code": null, "e": 293, "s": 188, "text": "CSS allows you to add multiple background images for an element, through the \nbackground-image property." }, { "code": null, "e": 448, "s": 293, "text": "The different background images are separated by commas, and the images are \nstacked on top of each other, where the first image is closest to the viewer." }, { "code": null, "e": 637, "s": 448, "text": "The following example has two background images, the first image is a flower \n(aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner):" }, { "code": null, "e": 781, "s": 637, "text": "Multiple background images can be specified using either the individual \nbackground properties (as above) or the background shorthand property." }, { "code": null, "e": 875, "s": 781, "text": "The following example uses the background shorthand property (same result as \nexample above):" }, { "code": null, "e": 961, "s": 875, "text": "The CSS background-size property allows you to specify the size of background images." }, { "code": null, "e": 1068, "s": 961, "text": "The size can be specified in lengths, percentages, or by using one of the two \nkeywords: contain or cover." }, { "code": null, "e": 1173, "s": 1068, "text": "The following example resizes a background image to much smaller than the original image (using pixels):" }, { "code": null, "e": 1318, "s": 1173, "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat." }, { "code": null, "e": 1446, "s": 1318, "text": "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat." }, { "code": null, "e": 1464, "s": 1446, "text": "Here is the code:" }, { "code": null, "e": 1538, "s": 1464, "text": "The two other possible values for background-size are contain \nand cover." }, { "code": null, "e": 1874, "s": 1538, "text": "The contain keyword scales the background image to be as large as possible \n(but both its width and its height must fit inside the content area). As such, depending on the proportions of the background \nimage and the background positioning area, there may be some areas of \nthe background which are not covered by the background image." }, { "code": null, "e": 2162, "s": 1874, "text": "The cover keyword scales the background image so that the content area is \ncompletely covered by the background image (both its width and height are equal to or \nexceed the content area). As such, some parts of the background image may not be \nvisible in the background positioning area." }, { "code": null, "e": 2226, "s": 2162, "text": "The following example illustrates the use of contain and cover:" }, { "code": null, "e": 2377, "s": 2226, "text": "The background-size property also accepts multiple values for background size \n(using a comma-separated list), when working with multiple backgrounds." }, { "code": null, "e": 2492, "s": 2377, "text": "The following example has three background images specified, with different \nbackground-size value for each image:" }, { "code": null, "e": 2597, "s": 2492, "text": "Now we want to have a background image on a website that covers the entire \nbrowser window at all times." }, { "code": null, "e": 2630, "s": 2597, "text": "The requirements are as follows:" }, { "code": null, "e": 2683, "s": 2630, "text": "Fill the entire page with the image (no white space)" }, { "code": null, "e": 2705, "s": 2683, "text": "Scale image as needed" }, { "code": null, "e": 2726, "s": 2705, "text": "Center image on page" }, { "code": null, "e": 2750, "s": 2726, "text": "Do not cause scrollbars" }, { "code": null, "e": 2996, "s": 2750, "text": "The following example shows how to do it; Use the <html> element \n(the <html> element is always at least the height of the browser window). Then set a fixed and centered background on it. \nThen adjust its size with the \nbackground-size property:" }, { "code": null, "e": 3137, "s": 2996, "text": "You could also use different background properties on a <div> to create a hero image (a large image with text), and place it where you want." }, { "code": null, "e": 3225, "s": 3137, "text": "The CSS background-origin property specifies where the background image is \npositioned." }, { "code": null, "e": 3268, "s": 3225, "text": "The property takes three different values:" }, { "code": null, "e": 3350, "s": 3268, "text": "border-box - the background image starts from the upper left corner of the border" }, { "code": null, "e": 3449, "s": 3350, "text": "padding-box - (default) the background image starts from the upper left corner of the padding edge" }, { "code": null, "e": 3533, "s": 3449, "text": "content-box - the background image starts from the upper left corner of the content" }, { "code": null, "e": 3599, "s": 3533, "text": "The following example illustrates the background-origin property:" }, { "code": null, "e": 3679, "s": 3599, "text": "The CSS background-clip property specifies the painting area of the background." }, { "code": null, "e": 3722, "s": 3679, "text": "The property takes three different values:" }, { "code": null, "e": 3805, "s": 3722, "text": "border-box - (default) the background is painted to the outside edge of the border" }, { "code": null, "e": 3880, "s": 3805, "text": "padding-box - the background is painted to the outside edge of the padding" }, { "code": null, "e": 3943, "s": 3880, "text": "content-box - the background is painted within the content box" }, { "code": null, "e": 4007, "s": 3943, "text": "The following example illustrates the background-clip property:" }, { "code": null, "e": 4056, "s": 4007, "text": "Add two background images to the <body> element." }, { "code": null, "e": 4079, "s": 4056, "text": "img1.gif and img2.gif." }, { "code": null, "e": 4136, "s": 4079, "text": "Make sure that img2.gif is displayed on top of img1.gif." }, { "code": null, "e": 4288, "s": 4136, "text": "<style>\nbody {\n background-image: ;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 4307, "s": 4288, "text": "Start the Exercise" }, { "code": null, "e": 4340, "s": 4307, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4382, "s": 4340, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4489, "s": 4382, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4508, "s": 4489, "text": "help@w3schools.com" } ]
Rearrange characters | Practice | GeeksforGeeks
Given a string S with repeated characters. The task is to rearrange characters in a string such that no two adjacent characters are the same. Note: The string has only lowercase English alphabets and it can have multiple solutions. Return any one of them. Example 1: Input : str = "geeksforgeeks" Output: 1 Explanation: All the repeated characters of the given string can be rearranged so that no adjacent characters in the string is equal. Any correct rearrangement will show a output of 1. Example 2: Input : str = "bbbbb" Output: 0 Explanation: Repeated characters in the string cannot be rearranged such that there should not be any adjacent repeated character. +1 patelbhargav9320026 days ago string rearrangeString(string s) { int n=s.length(); sort(s.begin(),s.end()); string ans=s; int c=0; for(int i=0;i<n;i+=2) ans[i]=s[c++]; for(int i=1;i<n;i+=2) ans[i]=s[c++]; for(int i=1;i<n;i++) { if(ans[i]==ans[i-1]) return "-1"; } return ans; } +1 gaurabhkumarjha271020016 days ago // c++ unordered_map <char, int> m; priority_queue<pair <int,char> > p; for (auto c:s) m[c]++; for (auto x:m) p.push({x.second, x.first}); string ans; while (p.size() > 1){ auto top1= p.top(); p.pop(); auto top2= p.top(); p.pop(); ans+= top1.second; ans+= top2.second; top1.first--; top2.first--; if (top1.first > 0) p.push(top1); if (top2.first > 0) p.push(top2); } if (!p.empty()) { if (p.top().first > 1) return "-1"; else ans+= p.top().second; } return ans; 0 parthbabbar0011 month ago string output = ""; unordered_map<char,int> mp; priority_queue<pair<int,char> > pq; for(auto i : s){ mp[i] += 1; } for(auto i:mp){ pq.push({i.second,i.first}); } while(pq.size()>1){ pair<int,char> top1 = pq.top(); pq.pop(); pair<int,char> top2 = pq.top(); pq.pop(); output += top1.second; output += top2.second; if(--top1.first>0){ pq.push(top1); } if(--top2.first>0){ pq.push(top2); } } if(pq.size()){ if(pq.top().first == 1){ output += pq.top().second; } else{ return ""; } } return output; 0 navinkrsingh89812 months ago ******* O(n) solution with no extra space ****** string rearrangeString(string s) { //code here int n = s.length(); int j=0; for(int i=1; i<n; i++) // iterate in fwd direction { j = max(i, j); // find first element on i's right not matching to i's left neighbour while(j < n && s[i-1] == s[j]) j++; if(j == n) // if no such neighbour exists then break; break; //else swap element at i with element at j char temp = s[i]; s[i] = s[j]; s[j] = temp; } // if the adjacent elements towards the last are not same then // i will exceed j and loop will terminate and we have got the answer if(j < n) return s; // otherwise perform the same operation in reverse direction for(int i=n-2; i>=0; i--) { j = min(i, j); // find first element on i's left not matching to i's right neighbour while(j >=0 && s[j] == s[i+1]) j--; //if no such neighbour exists then break if(j == -1) break; char temp = s[i]; s[i] = s[j]; s[j] = temp; } // if the adjacent elements towards the starting are not same then // i will exceed j and loop will terminate and we have got the answer if(j >= 0) return s; else // otherwise rearrangement is not possible; return "-1"; } +2 samrathbhatia3 months ago class Solution{ public: string rearrangeString(string s) { int n=s.size(),max=0; map<char,int> m; for(int i=0;i<s.size();i++) { m[s[i]]++; if(max<m[s[i]]) max=m[s[i]]; } if(max>(n+1)/2)return s="-1"; multimap<int,char,greater<int>> mp; for(auto i:m) { mp.insert({i.second,i.first}); } vector<char> v; for(auto i:mp) { char x=i.second; int count=i.first; while(count>0) { v.push_back(x); count--; } } int l=-2; for(int i=0;i<n;i++) { l+=2; if(l>=n)l=1; s[l]=v[i]; } return s; } }; +1 arthurshelby3 months ago 😉🇮🇳✌️❄️ string rearrangeString(string s) { //code here map<char,int>m; priority_queue<pair<int ,char>>pq; for(auto &it:s) m[it]++; for(auto it:m) pq.push({it.second,it.first}); s=""; while(!pq.empty()) { pair<int,char>p1,p2; p1=pq.top(); pq.pop(); p1.first--; s=s+p1.second; if(pq.size()>0){ p2=pq.top(); pq.pop(); s=s+p2.second; p2.first--; } if(p1.first!=0) pq.push(p1); if(p2.first!=0) pq.push(p2); } for(int i=0;i<s.size()-1;i++) { if(s[i]==s[i+1]) return "-1"; } return s; } +9 equbalzeeshan3 months ago O(N) solution without priority_queue Explanation: Consider this example: "aaabbbcdd", we will construct the string in this way: a _ a _ a _ _ _ _ // fill in "a" at position 0, 2, 4a b a _ a _ b _ b // fill in "b" at position 6, 8, 1a b a c a _ b _ b // fill in "c" at position 3a b a c a d b d b // fill in "d" at position 5, 7 string rearrangeString(string str) { int S = str.length(); unordered_map<char, int> mp; char maxFreq; for(char ch : str) { mp[ch]++; if(mp[ch] > mp[maxFreq]) maxFreq = ch; } if(mp[maxFreq] > (S + 1) / 2) return "-1"; int idx = 0; while(mp[maxFreq]) { str[idx] = maxFreq; idx += 2; mp[maxFreq]--; } for(auto pr : mp) { char ch = pr.first; int cnt = pr.second; while(cnt > 0) { if(idx >= S) idx = 1; str[idx] = ch; idx += 2; cnt--; } } return str; } +3 utkarshrdce3 months ago SOLUTION WITH DETAILED EXPLANATION we try to process first the one which comes the most number of times if we have geeksforgeeks initial frequency map : g - 2, e - 4, k - 2, s - 2, f - 1, o - 1, r - 1 initial ans = "" now we see that e comes most number of times, so pop it out tp = (e, 4) now as the answer is empty, push e at the back, and decrement the count of e -> (e, 3) and push this one back into the priority queue now ans = "e" frequncy map Now : g - 2, e - 3, k - 2, s - 2, f - 1, o - 1, r - 1 again e is popped out tp = (e, 3) but now the last character in ans = e, so we cannot append e so we will have to pop again from the pq (in case the pq has nothing, we return -1) now the charactes with freq 2 is popped out tp2 = (g, 2) add this to the answerr and decrement its count (g, 2) -> (g, 1), and push both the popped elements back into it (push tp1 and tp2) class Solution { #define pci pair<char, int> public: class Comp { public: bool operator()(pair<char, int> &p1, pair<char, int> &p2) { return p1.second < p2.second; } }; string rearrangeString(string str) { // // priority_queue<pair<char, int>> pq; priority_queue<pci, vector<pci>, Comp> pq; unordered_map<char, int> mp; for (char c : str) mp[c]++; for (auto m : mp) { pq.push({m.first, m.second}); } string ans = ""; while (!pq.empty()) { auto tp = pq.top(); pq.pop(); if (ans.empty() || ans.back() != tp.first) { ans.push_back(tp.first); tp.second--; if (tp.second > 0) pq.push(tp); } else { if (pq.empty()) return "-1"; auto tp2 = pq.top(); pq.pop(); ans.push_back(tp2.first); tp2.second--; if (tp2.second > 0) pq.push(tp2); if (tp.second > 0) pq.push(tp); } } return ans; } }; 0 utkarshrdce This comment was deleted. 0 tahabasra924 months ago class solution { public: static bool comp(pair<int,char > a,pair<int,char> b){ if(a.first>b.first){ return true; } return false;} string rearrangeString(string &s){// Write your code here. if(s.length()<=1){ return s; } unordered_map<char,int> m; for(int i=0;i<s.length();i++){ m[s[i]]++; } vector<pair<int,char>> v; for(auto it:m){ v.push_back({it.second,it.first}); } sort(v.begin(),v.end(),comp); int x=0; int it=v[0].first; while(it-- ){ if(x>=s.length()){ return "-1"; } x=x+2; } char ans[s.length()]; int i=0,k=0; while(i<s.length()){ if(v[k].first==0){ k++; } ans[i]=v[k].second; if(i+1 < s.length()) ans[i+1]='$'; v[k].first--; i=i+2; } for(int j=0;j<s.length();j++){ if(ans[j]=='$'){ if(v[k].first == 0){ k++; } ans[j]=v[k].second; v[k].first--; } } string f=""; for(int j=0;j<s.length();j++){ f+=ans[j]; } //cout<<f; return f; } }; 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": 494, "s": 238, "text": "Given a string S with repeated characters. The task is to rearrange characters in a string such that no two adjacent characters are the same.\nNote: The string has only lowercase English alphabets and it can have multiple solutions. Return any one of them." }, { "code": null, "e": 505, "s": 494, "text": "Example 1:" }, { "code": null, "e": 731, "s": 505, "text": "Input : str = \"geeksforgeeks\"\nOutput: 1\nExplanation: All the repeated characters of the\ngiven string can be rearranged so that no \nadjacent characters in the string is equal.\nAny correct rearrangement will show a output\nof 1." }, { "code": null, "e": 742, "s": 731, "text": "Example 2:" }, { "code": null, "e": 905, "s": 742, "text": "Input : str = \"bbbbb\"\nOutput: 0\nExplanation: Repeated characters in the string\ncannot be rearranged such that there should not\nbe any adjacent repeated character." }, { "code": null, "e": 908, "s": 905, "text": "+1" }, { "code": null, "e": 937, "s": 908, "text": "patelbhargav9320026 days ago" }, { "code": null, "e": 1356, "s": 937, "text": " string rearrangeString(string s)\n {\n int n=s.length();\n sort(s.begin(),s.end());\n \n string ans=s;\n int c=0;\n for(int i=0;i<n;i+=2)\n ans[i]=s[c++];\n \n for(int i=1;i<n;i+=2)\n ans[i]=s[c++];\n \n for(int i=1;i<n;i++)\n {\n if(ans[i]==ans[i-1])\n return \"-1\";\n }\n \n return ans;\n }" }, { "code": null, "e": 1359, "s": 1356, "text": "+1" }, { "code": null, "e": 1393, "s": 1359, "text": "gaurabhkumarjha271020016 days ago" }, { "code": null, "e": 2258, "s": 1393, "text": "// c++\n unordered_map <char, int> m;\n priority_queue<pair <int,char> > p;\n \n for (auto c:s) m[c]++;\n \n for (auto x:m) p.push({x.second, x.first});\n \n string ans;\n \n while (p.size() > 1){\n \n auto top1= p.top(); p.pop();\n auto top2= p.top(); p.pop();\n \n ans+= top1.second;\n ans+= top2.second;\n top1.first--; top2.first--;\n \n if (top1.first > 0) p.push(top1);\n if (top2.first > 0) p.push(top2);\n }\n \n if (!p.empty()) {\n \n if (p.top().first > 1) return \"-1\";\n \n else\n ans+= p.top().second;\n } \n \n return ans;" }, { "code": null, "e": 2260, "s": 2258, "text": "0" }, { "code": null, "e": 2286, "s": 2260, "text": "parthbabbar0011 month ago" }, { "code": null, "e": 3194, "s": 2286, "text": "string output = \"\";\n unordered_map<char,int> mp;\n priority_queue<pair<int,char> > pq;\n \n for(auto i : s){\n mp[i] += 1;\n }\n \n for(auto i:mp){\n pq.push({i.second,i.first});\n }\n \n while(pq.size()>1){\n pair<int,char> top1 = pq.top();\n pq.pop();\n pair<int,char> top2 = pq.top();\n pq.pop();\n \n output += top1.second;\n output += top2.second;\n \n if(--top1.first>0){\n pq.push(top1); \n }\n if(--top2.first>0){\n pq.push(top2); \n }\n }\n \n if(pq.size()){\n if(pq.top().first == 1){\n output += pq.top().second;\n }\n else{\n return \"\";\n }\n }\n \n return output;" }, { "code": null, "e": 3196, "s": 3194, "text": "0" }, { "code": null, "e": 3225, "s": 3196, "text": "navinkrsingh89812 months ago" }, { "code": null, "e": 3274, "s": 3225, "text": "******* O(n) solution with no extra space ******" }, { "code": null, "e": 4849, "s": 3276, "text": "string rearrangeString(string s) { //code here int n = s.length(); int j=0; for(int i=1; i<n; i++) // iterate in fwd direction { j = max(i, j); // find first element on i's right not matching to i's left neighbour while(j < n && s[i-1] == s[j]) j++; if(j == n) // if no such neighbour exists then break; break; //else swap element at i with element at j char temp = s[i]; s[i] = s[j]; s[j] = temp; } // if the adjacent elements towards the last are not same then // i will exceed j and loop will terminate and we have got the answer if(j < n) return s; // otherwise perform the same operation in reverse direction for(int i=n-2; i>=0; i--) { j = min(i, j); // find first element on i's left not matching to i's right neighbour while(j >=0 && s[j] == s[i+1]) j--; //if no such neighbour exists then break if(j == -1) break; char temp = s[i]; s[i] = s[j]; s[j] = temp; } // if the adjacent elements towards the starting are not same then // i will exceed j and loop will terminate and we have got the answer if(j >= 0) return s; else // otherwise rearrangement is not possible; return \"-1\"; }" }, { "code": null, "e": 4852, "s": 4849, "text": "+2" }, { "code": null, "e": 4878, "s": 4852, "text": "samrathbhatia3 months ago" }, { "code": null, "e": 5531, "s": 4878, "text": "class Solution{ public: string rearrangeString(string s) { int n=s.size(),max=0; map<char,int> m; for(int i=0;i<s.size();i++) { m[s[i]]++; if(max<m[s[i]]) max=m[s[i]]; } if(max>(n+1)/2)return s=\"-1\"; multimap<int,char,greater<int>> mp; for(auto i:m) { mp.insert({i.second,i.first}); } vector<char> v; for(auto i:mp) { char x=i.second; int count=i.first; while(count>0) { v.push_back(x); count--; } } int l=-2; for(int i=0;i<n;i++) { l+=2; if(l>=n)l=1; s[l]=v[i]; } return s; } };" }, { "code": null, "e": 5534, "s": 5531, "text": "+1" }, { "code": null, "e": 5559, "s": 5534, "text": "arthurshelby3 months ago" }, { "code": null, "e": 6251, "s": 5559, "text": "😉🇮🇳✌️❄️\nstring rearrangeString(string s)\n {\n //code here\n map<char,int>m;\n\t priority_queue<pair<int ,char>>pq;\n\t for(auto &it:s)\n\t m[it]++;\n\t for(auto it:m)\n\t pq.push({it.second,it.first});\n\t s=\"\";\n\t while(!pq.empty())\n\t {\n\t pair<int,char>p1,p2;\n\t p1=pq.top();\n\t pq.pop();\n\t p1.first--;\n\t s=s+p1.second;\n\t if(pq.size()>0){\n\t p2=pq.top();\n\t pq.pop();\n\t s=s+p2.second;\n\t p2.first--;\n\t }\n\t if(p1.first!=0)\n\t pq.push(p1);\n\t if(p2.first!=0)\n\t pq.push(p2);\n\t }\n\t for(int i=0;i<s.size()-1;i++)\n\t {\n\t if(s[i]==s[i+1])\n\t return \"-1\";\n\t }\n\t return s;\n }" }, { "code": null, "e": 6254, "s": 6251, "text": "+9" }, { "code": null, "e": 6280, "s": 6254, "text": "equbalzeeshan3 months ago" }, { "code": null, "e": 6317, "s": 6280, "text": "O(N) solution without priority_queue" }, { "code": null, "e": 6408, "s": 6317, "text": "Explanation: Consider this example: \"aaabbbcdd\", we will construct the string in this way:" }, { "code": null, "e": 6613, "s": 6408, "text": "a _ a _ a _ _ _ _ // fill in \"a\" at position 0, 2, 4a b a _ a _ b _ b // fill in \"b\" at position 6, 8, 1a b a c a _ b _ b // fill in \"c\" at position 3a b a c a d b d b // fill in \"d\" at position 5, 7" }, { "code": null, "e": 7401, "s": 6615, "text": "\tstring rearrangeString(string str)\n {\n int S = str.length();\n unordered_map<char, int> mp;\n \n char maxFreq;\n for(char ch : str) {\n mp[ch]++;\n if(mp[ch] > mp[maxFreq])\n maxFreq = ch;\n }\n \n if(mp[maxFreq] > (S + 1) / 2) return \"-1\";\n \n int idx = 0;\n while(mp[maxFreq]) {\n str[idx] = maxFreq;\n idx += 2;\n mp[maxFreq]--;\n }\n \n for(auto pr : mp) {\n char ch = pr.first;\n int cnt = pr.second;\n while(cnt > 0) {\n if(idx >= S) idx = 1;\n str[idx] = ch;\n idx += 2;\n cnt--;\n }\n }\n \n return str;\n }" }, { "code": null, "e": 7404, "s": 7401, "text": "+3" }, { "code": null, "e": 7428, "s": 7404, "text": "utkarshrdce3 months ago" }, { "code": null, "e": 7465, "s": 7428, "text": " SOLUTION WITH DETAILED EXPLANATION" }, { "code": null, "e": 7659, "s": 7467, "text": " we try to process first the one which comes the most number of times if we have geeksforgeeks initial frequency map : g - 2, e - 4, k - 2, s - 2, f - 1, o - 1, r - 1 initial ans = \"\"" }, { "code": null, "e": 7874, "s": 7659, "text": " now we see that e comes most number of times, so pop it out tp = (e, 4) now as the answer is empty, push e at the back, and decrement the count of e -> (e, 3) and push this one back into the priority queue" }, { "code": null, "e": 7891, "s": 7874, "text": " now ans = \"e\"" }, { "code": null, "e": 8341, "s": 7891, "text": " frequncy map Now : g - 2, e - 3, k - 2, s - 2, f - 1, o - 1, r - 1 again e is popped out tp = (e, 3) but now the last character in ans = e, so we cannot append e so we will have to pop again from the pq (in case the pq has nothing, we return -1) now the charactes with freq 2 is popped out tp2 = (g, 2) add this to the answerr and decrement its count (g, 2) -> (g, 1), and push both the popped elements back into it (push tp1 and tp2)" }, { "code": null, "e": 9423, "s": 8343, "text": "class Solution\n{\n#define pci pair<char, int>\npublic:\n class Comp {\n public:\n bool operator()(pair<char, int> &p1, pair<char, int> &p2) {\n return p1.second < p2.second;\n }\n };\n\n string rearrangeString(string str)\n {\n //\n // priority_queue<pair<char, int>> pq;\n priority_queue<pci, vector<pci>, Comp> pq;\n unordered_map<char, int> mp;\n for (char c : str) mp[c]++;\n\n\n for (auto m : mp) {\n pq.push({m.first, m.second});\n }\n\n string ans = \"\";\n while (!pq.empty()) {\n auto tp = pq.top(); pq.pop();\n if (ans.empty() || ans.back() != tp.first) {\n ans.push_back(tp.first);\n tp.second--;\n if (tp.second > 0) pq.push(tp);\n } else {\n if (pq.empty()) return \"-1\";\n auto tp2 = pq.top(); pq.pop();\n ans.push_back(tp2.first); tp2.second--;\n if (tp2.second > 0) pq.push(tp2);\n if (tp.second > 0) pq.push(tp);\n }\n }\n return ans;\n }\n\n};" }, { "code": null, "e": 9427, "s": 9425, "text": "0" }, { "code": null, "e": 9439, "s": 9427, "text": "utkarshrdce" }, { "code": null, "e": 9465, "s": 9439, "text": "This comment was deleted." }, { "code": null, "e": 9467, "s": 9465, "text": "0" }, { "code": null, "e": 9491, "s": 9467, "text": "tahabasra924 months ago" }, { "code": null, "e": 9508, "s": 9493, "text": "class solution" }, { "code": null, "e": 9948, "s": 9508, "text": "{ public: static bool comp(pair<int,char > a,pair<int,char> b){ if(a.first>b.first){ return true; } return false;} string rearrangeString(string &s){// Write your code here. if(s.length()<=1){ return s; } unordered_map<char,int> m; for(int i=0;i<s.length();i++){ m[s[i]]++; } vector<pair<int,char>> v; for(auto it:m){ v.push_back({it.second,it.first}); } sort(v.begin(),v.end(),comp);" }, { "code": null, "e": 10608, "s": 9948, "text": " int x=0; int it=v[0].first; while(it-- ){ if(x>=s.length()){ return \"-1\"; } x=x+2; } char ans[s.length()]; int i=0,k=0; while(i<s.length()){ if(v[k].first==0){ k++; } ans[i]=v[k].second; if(i+1 < s.length()) ans[i+1]='$'; v[k].first--; i=i+2; } for(int j=0;j<s.length();j++){ if(ans[j]=='$'){ if(v[k].first == 0){ k++; } ans[j]=v[k].second; v[k].first--; } } string f=\"\"; for(int j=0;j<s.length();j++){ f+=ans[j]; } //cout<<f; " }, { "code": null, "e": 10627, "s": 10608, "text": " return f; }" }, { "code": null, "e": 10635, "s": 10629, "text": " };" }, { "code": null, "e": 10781, "s": 10635, "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": 10817, "s": 10781, "text": " Login to access your submissions. " }, { "code": null, "e": 10827, "s": 10817, "text": "\nProblem\n" }, { "code": null, "e": 10837, "s": 10827, "text": "\nContest\n" }, { "code": null, "e": 10900, "s": 10837, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11048, "s": 10900, "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": 11256, "s": 11048, "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": 11362, "s": 11256, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Play infinitely looping video on-load in HTML5
The <video> tag specifies video. Currently, there are 3 supported video formats for the <video> element that are MP4, WebM, and Ogg. Autoplay is used to start the video when the video and page loads. The loop attribute is a boolean attribute. When present, it specifies that the video will start over again, every time it is finished. The loop attribute should do it. <video width="600" height="500" autoplay loop> <source src="movie.mp4" type="video/mp4" /> <source src="movie.ogg" type="video/ogg" /> Your browser does not support the video element. </video> If you have a problem with the loop attribute, listen to the videoEnd event. After that call the play() method when it fires.
[ { "code": null, "e": 1262, "s": 1062, "text": "The <video> tag specifies video. Currently, there are 3 supported video formats for the <video> element that are MP4, WebM, and Ogg. Autoplay is used to start the video when the video and page loads." }, { "code": null, "e": 1397, "s": 1262, "text": "The loop attribute is a boolean attribute. When present, it specifies that the video will start over again, every time it is finished." }, { "code": null, "e": 1430, "s": 1397, "text": "The loop attribute should do it." }, { "code": null, "e": 1632, "s": 1430, "text": "<video width=\"600\" height=\"500\" autoplay loop>\n <source src=\"movie.mp4\" type=\"video/mp4\" />\n <source src=\"movie.ogg\" type=\"video/ogg\" />\n Your browser does not support the video element.\n</video>" }, { "code": null, "e": 1758, "s": 1632, "text": "If you have a problem with the loop attribute, listen to the videoEnd event. After that call the play() method when it fires." } ]
Apache Pig - CONCAT()
The CONCAT() function of Pig Latin is used to concatenate two or more expressions of the same type. grunt> CONCAT (expression, expression, [...expression]) Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below. student_details.txt 001,Rajiv,Reddy,21,9848022337,Hyderabad,89 002,siddarth,Battacharya,22,9848022338,Kolkata,78 003,Rajesh,Khanna,22,9848022339,Delhi,90 004,Preethi,Agarwal,21,9848022330,Pune,93 005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 006,Archana,Mishra,23,9848022335,Chennai,87 007,Komal,Nayak,24,9848022334,trivendram,83 008,Bharathi,Nambiayar,24,9848022333,Chennai,72 And we have loaded this file into Pig with the relation name student_details as shown below. grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',') as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int); We can use the CONCAT() function to concatenate two or more expressions. First of all, verify the contents of the student_details relation using the Dump operator as shown below. grunt> Dump student_details; ( 1,Rajiv,Reddy,21,9848022337,Hyderabad,89 ) ( 2,siddarth,Battacharya,22,9848022338,Kolkata,78 ) ( 3,Rajesh,Khanna,22,9848022339,Delhi,90 ) ( 4,Preethi,Agarwal,21,9848022330,Pune,93 ) ( 5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 ) ( 6,Archana,Mishra,23,9848022335,Chennai,87 ) ( 7,Komal,Nayak,24,9848022334,trivendram,83 ) ( 8,Bharathi,Nambiayar,24,9848022333,Chennai,72 ) And, verify the schema using describe operator as shown below. grunt> Describe student_details; student_details: {id: int, firstname: chararray, lastname: chararray, age: int, phone: chararray, city: chararray, gpa: int} In the above schema, you can observe that the name of the student is represented using two chararray values namely firstname and lastname. Let us concatinate these two values using the CONCAT() function. grunt> student_name_concat = foreach student_details Generate CONCAT (firstname, lastname); Verify the relation student_name_concat using the DUMP operator as shown below. grunt> Dump student_name_concat; It will produce the following output, displaying the contents of the relation student_name_concat. (RajivReddy) (siddarthBattacharya) (RajeshKhanna) (PreethiAgarwal) (TrupthiMohanthy) (ArchanaMishra) (KomalNayak) (BharathiNambiayar) We can also use an optional delimiter between the two expressions as shown below. grunt> CONCAT(firstname, '_',lastname); Now, let us concatenate the first name and last name of the student records in the student_details relation by placing ‘_’ between them as shown below. grunt> student_name_concat = foreach student_details GENERATE CONCAT(firstname, '_',lastname); Verify the relation student_name_concat using the DUMP operator as shown below. grunt> Dump student_name_concat; It will produce the following output, displaying the contents of the relation student_name_concat as follows. (Rajiv_Reddy) (siddarth_Battacharya) (Rajesh_Khanna) (Preethi_Agarwal) (Trupthi_Mohanthy) (Archana_Mishra) (Komal_Nayak) (Bharathi_Nambiayar) 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2784, "s": 2684, "text": "The CONCAT() function of Pig Latin is used to concatenate two or more expressions of the same type." }, { "code": null, "e": 2841, "s": 2784, "text": "grunt> CONCAT (expression, expression, [...expression])\n" }, { "code": null, "e": 2943, "s": 2841, "text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below." }, { "code": null, "e": 2963, "s": 2943, "text": "student_details.txt" }, { "code": null, "e": 3333, "s": 2963, "text": "001,Rajiv,Reddy,21,9848022337,Hyderabad,89\n002,siddarth,Battacharya,22,9848022338,Kolkata,78 \n003,Rajesh,Khanna,22,9848022339,Delhi,90 \n004,Preethi,Agarwal,21,9848022330,Pune,93 \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 \n006,Archana,Mishra,23,9848022335,Chennai,87 \n007,Komal,Nayak,24,9848022334,trivendram,83 \n008,Bharathi,Nambiayar,24,9848022333,Chennai,72\n" }, { "code": null, "e": 3426, "s": 3333, "text": "And we have loaded this file into Pig with the relation name student_details as shown below." }, { "code": null, "e": 3639, "s": 3426, "text": "grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')\n as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);" }, { "code": null, "e": 3818, "s": 3639, "text": "We can use the CONCAT() function to concatenate two or more expressions. First of all, verify the contents of the student_details relation using the Dump operator as shown below." }, { "code": null, "e": 4231, "s": 3818, "text": "grunt> Dump student_details;\n \n( 1,Rajiv,Reddy,21,9848022337,Hyderabad,89 ) \n( 2,siddarth,Battacharya,22,9848022338,Kolkata,78 )\n( 3,Rajesh,Khanna,22,9848022339,Delhi,90 ) \n( 4,Preethi,Agarwal,21,9848022330,Pune,93 )\n( 5,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 )\n( 6,Archana,Mishra,23,9848022335,Chennai,87 )\n( 7,Komal,Nayak,24,9848022334,trivendram,83 )\n( 8,Bharathi,Nambiayar,24,9848022333,Chennai,72 )\n" }, { "code": null, "e": 4294, "s": 4231, "text": "And, verify the schema using describe operator as shown below." }, { "code": null, "e": 4459, "s": 4294, "text": "grunt> Describe student_details;\n \nstudent_details: {id: int, firstname: chararray, lastname: chararray, age: int,\n phone: chararray, city: chararray, gpa: int}\n" }, { "code": null, "e": 4663, "s": 4459, "text": "In the above schema, you can observe that the name of the student is represented using two chararray values namely firstname and lastname. Let us concatinate these two values using the CONCAT() function." }, { "code": null, "e": 4755, "s": 4663, "text": "grunt> student_name_concat = foreach student_details Generate CONCAT (firstname, lastname);" }, { "code": null, "e": 4835, "s": 4755, "text": "Verify the relation student_name_concat using the DUMP operator as shown below." }, { "code": null, "e": 4868, "s": 4835, "text": "grunt> Dump student_name_concat;" }, { "code": null, "e": 4967, "s": 4868, "text": "It will produce the following output, displaying the contents of the relation student_name_concat." }, { "code": null, "e": 5110, "s": 4967, "text": "(RajivReddy) \n(siddarthBattacharya) \n(RajeshKhanna) \n(PreethiAgarwal) \n(TrupthiMohanthy) \n(ArchanaMishra) \n(KomalNayak) \n(BharathiNambiayar) \n" }, { "code": null, "e": 5192, "s": 5110, "text": "We can also use an optional delimiter between the two expressions as shown below." }, { "code": null, "e": 5232, "s": 5192, "text": "grunt> CONCAT(firstname, '_',lastname);" }, { "code": null, "e": 5384, "s": 5232, "text": "Now, let us concatenate the first name and last name of the student records in the student_details relation by placing ‘_’ between them as shown below." }, { "code": null, "e": 5480, "s": 5384, "text": "grunt> student_name_concat = foreach student_details GENERATE CONCAT(firstname, '_',lastname); " }, { "code": null, "e": 5560, "s": 5480, "text": "Verify the relation student_name_concat using the DUMP operator as shown below." }, { "code": null, "e": 5593, "s": 5560, "text": "grunt> Dump student_name_concat;" }, { "code": null, "e": 5703, "s": 5593, "text": "It will produce the following output, displaying the contents of the relation student_name_concat as follows." }, { "code": null, "e": 5853, "s": 5703, "text": "(Rajiv_Reddy) \n(siddarth_Battacharya) \n(Rajesh_Khanna) \n(Preethi_Agarwal) \n(Trupthi_Mohanthy) \n(Archana_Mishra) \n(Komal_Nayak) \n(Bharathi_Nambiayar)\n" }, { "code": null, "e": 5888, "s": 5853, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5907, "s": 5888, "text": " Arnab Chakraborty" }, { "code": null, "e": 5942, "s": 5907, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5963, "s": 5942, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5996, "s": 5963, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6009, "s": 5996, "text": " Nilay Mehta" }, { "code": null, "e": 6044, "s": 6009, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6062, "s": 6044, "text": " Bigdata Engineer" }, { "code": null, "e": 6095, "s": 6062, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6113, "s": 6095, "text": " Bigdata Engineer" }, { "code": null, "e": 6146, "s": 6113, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6164, "s": 6146, "text": " Bigdata Engineer" }, { "code": null, "e": 6171, "s": 6164, "text": " Print" }, { "code": null, "e": 6182, "s": 6171, "text": " Add Notes" } ]
JavaScript Number NaN Property - GeeksforGeeks
24 Dec, 2021 In JavaScript, NaN stands for Not a Number. It represents a value which is not a valid number. It can be used to check whether a number entered is a valid number or not a number. To assign a variable to NaN value, we can use one of the two following ways. var a = NaN var a = Number.NaN Example: In this example, we will use JavaScript Number NaN Property. var monthNumber = 14; if (monthNumber < 1 || monthNumber > 12) { // Assigning monthNumber NaN as // month number is not valid monthNumber = Number.NaN; console.log("Month number should be" + " between 1 and 12");}else { console.log(monthNumber);} Output: We will see some examples of operations that return NaN. Example 1: Whenever we try to parse a string or “undefined” to an int, it returns NaN. console.log(parseInt("higeeks")); Output: Example 2: Whenever we try to find square root of a negative number using Math.sqrt function, it returns NaN. console.log(Math.sqrt(-1)); Output: Example 3: Whenever we try to make on operation on NaN, it returns NaN. console.log(5 + NaN); Output: Example 4: Any indeterminate form also returns NaN. console.log(0 * Infinity) Output: Example 5: Any operation other than addition on a string also results in NaN. console.log("hi"/5) Output: Supported Browser: Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 3 and above safari 1 and above ysachin2314 JavaScript-Properties Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26801, "s": 26545, "text": "In JavaScript, NaN stands for Not a Number. It represents a value which is not a valid number. It can be used to check whether a number entered is a valid number or not a number. To assign a variable to NaN value, we can use one of the two following ways." }, { "code": null, "e": 26813, "s": 26801, "text": "var a = NaN" }, { "code": null, "e": 26832, "s": 26813, "text": "var a = Number.NaN" }, { "code": null, "e": 26902, "s": 26832, "text": "Example: In this example, we will use JavaScript Number NaN Property." }, { "code": "var monthNumber = 14; if (monthNumber < 1 || monthNumber > 12) { // Assigning monthNumber NaN as // month number is not valid monthNumber = Number.NaN; console.log(\"Month number should be\" + \" between 1 and 12\");}else { console.log(monthNumber);}", "e": 27185, "s": 26902, "text": null }, { "code": null, "e": 27193, "s": 27185, "text": "Output:" }, { "code": null, "e": 27250, "s": 27193, "text": "We will see some examples of operations that return NaN." }, { "code": null, "e": 27337, "s": 27250, "text": "Example 1: Whenever we try to parse a string or “undefined” to an int, it returns NaN." }, { "code": "console.log(parseInt(\"higeeks\"));", "e": 27371, "s": 27337, "text": null }, { "code": null, "e": 27379, "s": 27371, "text": "Output:" }, { "code": null, "e": 27489, "s": 27379, "text": "Example 2: Whenever we try to find square root of a negative number using Math.sqrt function, it returns NaN." }, { "code": "console.log(Math.sqrt(-1));", "e": 27517, "s": 27489, "text": null }, { "code": null, "e": 27525, "s": 27517, "text": "Output:" }, { "code": null, "e": 27597, "s": 27525, "text": "Example 3: Whenever we try to make on operation on NaN, it returns NaN." }, { "code": "console.log(5 + NaN);", "e": 27619, "s": 27597, "text": null }, { "code": null, "e": 27627, "s": 27619, "text": "Output:" }, { "code": null, "e": 27679, "s": 27627, "text": "Example 4: Any indeterminate form also returns NaN." }, { "code": "console.log(0 * Infinity)", "e": 27705, "s": 27679, "text": null }, { "code": null, "e": 27713, "s": 27705, "text": "Output:" }, { "code": null, "e": 27791, "s": 27713, "text": "Example 5: Any operation other than addition on a string also results in NaN." }, { "code": "console.log(\"hi\"/5)", "e": 27811, "s": 27791, "text": null }, { "code": null, "e": 27819, "s": 27811, "text": "Output:" }, { "code": null, "e": 27838, "s": 27819, "text": "Supported Browser:" }, { "code": null, "e": 27857, "s": 27838, "text": "Chrome 1 and above" }, { "code": null, "e": 27875, "s": 27857, "text": "Edge 12 and above" }, { "code": null, "e": 27895, "s": 27875, "text": "Firefox 1 and above" }, { "code": null, "e": 27925, "s": 27895, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 27943, "s": 27925, "text": "Opera 3 and above" }, { "code": null, "e": 27962, "s": 27943, "text": "safari 1 and above" }, { "code": null, "e": 27974, "s": 27962, "text": "ysachin2314" }, { "code": null, "e": 27996, "s": 27974, "text": "JavaScript-Properties" }, { "code": null, "e": 28003, "s": 27996, "text": "Picked" }, { "code": null, "e": 28014, "s": 28003, "text": "JavaScript" }, { "code": null, "e": 28031, "s": 28014, "text": "Web Technologies" }, { "code": null, "e": 28129, "s": 28031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28169, "s": 28129, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28230, "s": 28169, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28271, "s": 28230, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28293, "s": 28271, "text": "JavaScript | Promises" }, { "code": null, "e": 28347, "s": 28293, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28387, "s": 28347, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28420, "s": 28387, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28463, "s": 28420, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28513, "s": 28463, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Create an empty file using Python - GeeksforGeeks
28 May, 2020 File handling is a very important concept for any programmer. It can be used for creating, deleting, moving files or to store application data, user configurations, videos, images, etc. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Refer to the following articles to check the basics of file handling. Basics of file handling Reading and writing to a file File handling can also be used for creating a file. Even the file with different extension like .pdf, .txt, .jpeg can be created using file handling in Python. To create a file, the file must be open for writing. To open a file for writing access mode of file must be w, a, w+, a+. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. Below is the list of access modes for creating an empty file. Write Only (‘w’): Open the file for writing. For an existing file, the data is truncated and over-written. Write and Read (‘w+’): Open the file for reading and writing. For an existing file, data is truncated and over-written. Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data. Append and Read (‘a+’): Open the file for reading and writing. The data being written will be inserted at the end, after the existing data. Note: The file is created in the same directory of the script if no path is specified. Example #1: In this example we will create a new file myfile.txt. To verify this we will use os.listdir() method of os module to list out the directories before and after creating a new file. # Python program to demonstrate# creating a new file # importing moduleimport os # path of the current scriptpath = 'D:/Pycharm projects/gfg' # Before creatingdir_list = os.listdir(path) print("List of directories and files before creation:")print(dir_list)print() # Creates a new filewith open('myfile.txt', 'w') as fp: pass # To write data to new file uncomment # this fp.write("New file created") # After creating dir_list = os.listdir(path)print("List of directories and files after creation:")print(dir_list) Output: List of directories and files before creation: ['.idea', 'gfg.py', 'venv'] List of directories and files after creation: ['.idea', 'gfg.py', 'myfile.txt', 'venv'] # Example 2: Creating a new file at a specified location. For creating a file at a specified location os module is used. Below is the implementation. # Python program to demonstrate# creation of new file import os # Specify the pathpath = 'D:/Pycharm projects/GeeksforGeeks/Nikhil' # Specify the file namefile = 'myfile.txt' # Before creatingdir_list = os.listdir(path) print("List of directories and files before creation:")print(dir_list)print() # Creating a file at specified locationwith open(os.path.join(path, file), 'w') as fp: pass # To write data to new file uncomment # this fp.write("New file created") # After creating dir_list = os.listdir(path)print("List of directories and files after creation:")print(dir_list) Output: List of directories and files before creation: ['test_nikhil.txt'] List of directories and files after creation: ['myfile.txt', 'test_nikhil.txt'] DanielTinsley python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Convert integer to string in Python
[ { "code": null, "e": 25657, "s": 25629, "text": "\n28 May, 2020" }, { "code": null, "e": 26007, "s": 25657, "text": "File handling is a very important concept for any programmer. It can be used for creating, deleting, moving files or to store application data, user configurations, videos, images, etc. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files." }, { "code": null, "e": 26077, "s": 26007, "text": "Refer to the following articles to check the basics of file handling." }, { "code": null, "e": 26101, "s": 26077, "text": "Basics of file handling" }, { "code": null, "e": 26131, "s": 26101, "text": "Reading and writing to a file" }, { "code": null, "e": 26604, "s": 26131, "text": "File handling can also be used for creating a file. Even the file with different extension like .pdf, .txt, .jpeg can be created using file handling in Python. To create a file, the file must be open for writing. To open a file for writing access mode of file must be w, a, w+, a+. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. Below is the list of access modes for creating an empty file." }, { "code": null, "e": 26711, "s": 26604, "text": "Write Only (‘w’): Open the file for writing. For an existing file, the data is truncated and over-written." }, { "code": null, "e": 26831, "s": 26711, "text": "Write and Read (‘w+’): Open the file for reading and writing. For an existing file, data is truncated and over-written." }, { "code": null, "e": 26954, "s": 26831, "text": "Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data." }, { "code": null, "e": 27094, "s": 26954, "text": "Append and Read (‘a+’): Open the file for reading and writing. The data being written will be inserted at the end, after the existing data." }, { "code": null, "e": 27181, "s": 27094, "text": "Note: The file is created in the same directory of the script if no path is specified." }, { "code": null, "e": 27373, "s": 27181, "text": "Example #1: In this example we will create a new file myfile.txt. To verify this we will use os.listdir() method of os module to list out the directories before and after creating a new file." }, { "code": "# Python program to demonstrate# creating a new file # importing moduleimport os # path of the current scriptpath = 'D:/Pycharm projects/gfg' # Before creatingdir_list = os.listdir(path) print(\"List of directories and files before creation:\")print(dir_list)print() # Creates a new filewith open('myfile.txt', 'w') as fp: pass # To write data to new file uncomment # this fp.write(\"New file created\") # After creating dir_list = os.listdir(path)print(\"List of directories and files after creation:\")print(dir_list)", "e": 27903, "s": 27373, "text": null }, { "code": null, "e": 27911, "s": 27903, "text": "Output:" }, { "code": null, "e": 28076, "s": 27911, "text": "List of directories and files before creation:\n['.idea', 'gfg.py', 'venv']\n\nList of directories and files after creation:\n['.idea', 'gfg.py', 'myfile.txt', 'venv']\n" }, { "code": null, "e": 28226, "s": 28076, "text": "# Example 2: Creating a new file at a specified location. For creating a file at a specified location os module is used. Below is the implementation." }, { "code": "# Python program to demonstrate# creation of new file import os # Specify the pathpath = 'D:/Pycharm projects/GeeksforGeeks/Nikhil' # Specify the file namefile = 'myfile.txt' # Before creatingdir_list = os.listdir(path) print(\"List of directories and files before creation:\")print(dir_list)print() # Creating a file at specified locationwith open(os.path.join(path, file), 'w') as fp: pass # To write data to new file uncomment # this fp.write(\"New file created\") # After creating dir_list = os.listdir(path)print(\"List of directories and files after creation:\")print(dir_list)", "e": 28821, "s": 28226, "text": null }, { "code": null, "e": 28829, "s": 28821, "text": "Output:" }, { "code": null, "e": 28978, "s": 28829, "text": "List of directories and files before creation:\n['test_nikhil.txt']\n\nList of directories and files after creation:\n['myfile.txt', 'test_nikhil.txt']\n" }, { "code": null, "e": 28992, "s": 28978, "text": "DanielTinsley" }, { "code": null, "e": 29013, "s": 28992, "text": "python-file-handling" }, { "code": null, "e": 29020, "s": 29013, "text": "Python" }, { "code": null, "e": 29118, "s": 29020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29136, "s": 29118, "text": "Python Dictionary" }, { "code": null, "e": 29168, "s": 29136, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29190, "s": 29168, "text": "Enumerate() in Python" }, { "code": null, "e": 29232, "s": 29190, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29262, "s": 29232, "text": "Iterate over a list in Python" }, { "code": null, "e": 29288, "s": 29262, "text": "Python String | replace()" }, { "code": null, "e": 29317, "s": 29288, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29354, "s": 29317, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29396, "s": 29354, "text": "How To Convert Python Dictionary To JSON?" } ]
Python subprocess module to execute programs written in different languages - GeeksforGeeks
03 Aug, 2021 The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. To execute different programs using Python two functions of the subprocess module are used: 1.subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)Parameters:args=The command to be executed.Several commands can be passed as a string by separated by “;”.stdin=Value of standard input stream to be passed as (os.pipe()).stdout=Value of output obtained from standard output stream.stderr=Value of error obtained(if any) from standard error stream.shell=Boolean parameter.If True the commands get executed through a new shell environment.Return Value:The function returns the return code of the command.If the return code is zero, the function simply returns(command executed successfully) otherwise CalledProcessError is being raised. 2.subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)Parameters:args=The command to be executed. Several commands can be passed as a string by separated by “;”.stdin=Value of standard input stream to be passed as pipe(os.pipe()).stdout=Value of output obtained from standard output stream.stderr=Value of error obtained(if any) from standard error stream.shell=boolean parameter.If True the commands get executed through a new shell environment.universal_newlines=Boolean parameter.If true files containing stdout and stderr are opened in universal newline mode.Return Value:The function returns the return code of the command.If the return code is zero, the function simply returns the output as a byte string(command executed successfully) otherwise CalledProcessError is being raised. Let us consider the following examples: C program: #include<stdio.h>int main(){ printf("Hello World from C"); // returning with any other non zero value // would result in an exception // when called from python return 0;} C++ program: #include <iostream>using namespace std;int main(){ int a, b; cin >> a >> b; cout << "Hello World from C++.Values are:" << a << " " << b; return 0;} Java Program: class HelloWorld { public static void main(String args[]) { System.out.print("Hello World from Java."); }} # Python 3 program to demonstrate subprocess # module import subprocessimport os def excuteC(): # store the return code of the c program(return 0) # and display the output s = subprocess.check_call("gcc HelloWorld.c -o out1;./out1", shell = True) print(", return code", s) def executeCpp(): # create a pipe to a child process data, temp = os.pipe() # write to STDIN as a byte object(convert string # to bytes with encoding utf8) os.write(temp, bytes("5 10\n", "utf-8")); os.close(temp) # store output of the program as a byte string in s s = subprocess.check_output("g++ HelloWorld.cpp -o out2;./out2", stdin = data, shell = True) # decode s to a normal string print(s.decode("utf-8")) def executeJava(): # store the output of # the java program s = subprocess.check_output("javac HelloWorld.java;java HelloWorld", shell = True) print(s.decode("utf-8")) # Driver functionif __name__=="__main__": excuteC() executeCpp() executeJava() Output: Hello World from C, return code 0 Hello World from C++. Values are:5 10 Hello World from Java. Note: Although subprocess module is OS independent these commands must only be executed in Linux environments. Also according to Python documentation passing shell=True can be a security hazard if combined with untrusted input. SouravAChowdhury_97 Akanksha_Rai manikarora059 python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25701, "s": 25673, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25950, "s": 25701, "text": "The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands." }, { "code": null, "e": 26042, "s": 25950, "text": "To execute different programs using Python two functions of the subprocess module are used:" }, { "code": null, "e": 26710, "s": 26042, "text": "1.subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)Parameters:args=The command to be executed.Several commands can be passed as a string by separated by “;”.stdin=Value of standard input stream to be passed as (os.pipe()).stdout=Value of output obtained from standard output stream.stderr=Value of error obtained(if any) from standard error stream.shell=Boolean parameter.If True the commands get executed through a new shell environment.Return Value:The function returns the return code of the command.If the return code is zero, the function simply returns(command executed successfully) otherwise CalledProcessError is being raised." }, { "code": null, "e": 27543, "s": 26710, "text": "2.subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)Parameters:args=The command to be executed. Several commands can be passed as a string by separated by “;”.stdin=Value of standard input stream to be passed as pipe(os.pipe()).stdout=Value of output obtained from standard output stream.stderr=Value of error obtained(if any) from standard error stream.shell=boolean parameter.If True the commands get executed through a new shell environment.universal_newlines=Boolean parameter.If true files containing stdout and stderr are opened in universal newline mode.Return Value:The function returns the return code of the command.If the return code is zero, the function simply returns the output as a byte string(command executed successfully) otherwise CalledProcessError is being raised." }, { "code": null, "e": 27583, "s": 27543, "text": "Let us consider the following examples:" }, { "code": null, "e": 27594, "s": 27583, "text": "C program:" }, { "code": "#include<stdio.h>int main(){ printf(\"Hello World from C\"); // returning with any other non zero value // would result in an exception // when called from python return 0;}", "e": 27783, "s": 27594, "text": null }, { "code": null, "e": 27796, "s": 27783, "text": "C++ program:" }, { "code": "#include <iostream>using namespace std;int main(){ int a, b; cin >> a >> b; cout << \"Hello World from C++.Values are:\" << a << \" \" << b; return 0;}", "e": 27956, "s": 27796, "text": null }, { "code": null, "e": 27970, "s": 27956, "text": "Java Program:" }, { "code": "class HelloWorld { public static void main(String args[]) { System.out.print(\"Hello World from Java.\"); }}", "e": 28093, "s": 27970, "text": null }, { "code": "# Python 3 program to demonstrate subprocess # module import subprocessimport os def excuteC(): # store the return code of the c program(return 0) # and display the output s = subprocess.check_call(\"gcc HelloWorld.c -o out1;./out1\", shell = True) print(\", return code\", s) def executeCpp(): # create a pipe to a child process data, temp = os.pipe() # write to STDIN as a byte object(convert string # to bytes with encoding utf8) os.write(temp, bytes(\"5 10\\n\", \"utf-8\")); os.close(temp) # store output of the program as a byte string in s s = subprocess.check_output(\"g++ HelloWorld.cpp -o out2;./out2\", stdin = data, shell = True) # decode s to a normal string print(s.decode(\"utf-8\")) def executeJava(): # store the output of # the java program s = subprocess.check_output(\"javac HelloWorld.java;java HelloWorld\", shell = True) print(s.decode(\"utf-8\")) # Driver functionif __name__==\"__main__\": excuteC() executeCpp() executeJava()", "e": 29112, "s": 28093, "text": null }, { "code": null, "e": 29120, "s": 29112, "text": "Output:" }, { "code": null, "e": 29216, "s": 29120, "text": "Hello World from C, return code 0\nHello World from C++. Values are:5 10\nHello World from Java.\n" }, { "code": null, "e": 29444, "s": 29216, "text": "Note: Although subprocess module is OS independent these commands must only be executed in Linux environments. Also according to Python documentation passing shell=True can be a security hazard if combined with untrusted input." }, { "code": null, "e": 29464, "s": 29444, "text": "SouravAChowdhury_97" }, { "code": null, "e": 29477, "s": 29464, "text": "Akanksha_Rai" }, { "code": null, "e": 29491, "s": 29477, "text": "manikarora059" }, { "code": null, "e": 29506, "s": 29491, "text": "python-utility" }, { "code": null, "e": 29513, "s": 29506, "text": "Python" }, { "code": null, "e": 29529, "s": 29513, "text": "Python Programs" }, { "code": null, "e": 29627, "s": 29529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29645, "s": 29627, "text": "Python Dictionary" }, { "code": null, "e": 29680, "s": 29645, "text": "Read a file line by line in Python" }, { "code": null, "e": 29712, "s": 29680, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29734, "s": 29712, "text": "Enumerate() in Python" }, { "code": null, "e": 29776, "s": 29734, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29819, "s": 29776, "text": "Python program to convert a list to string" }, { "code": null, "e": 29841, "s": 29819, "text": "Defaultdict in Python" }, { "code": null, "e": 29880, "s": 29841, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29926, "s": 29880, "text": "Python | Split string into list of characters" } ]
Python | Pandas dataframe.div() - GeeksforGeeks
25 Aug, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.div() is used to find the floating division of the dataframe and other element-wise. This function is similar to dataframe/other, but with an additional support to handle missing value in one of the input data. Syntax: DataFrame.div(other, axis=’columns’, level=None, fill_value=None)Parameters: other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on fill_value : Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing level : Broadcast across a level, matching Index values on the passed MultiIndex levelReturns: result : DataFrame Example #1: Use div() function to find floating division of dataframe elements with a constant value. Also handle the NaN value present in the dataframe. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframe with NaN valuedf = pd.DataFrame({"A":[5, 3, None, 4], "B":[None, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, None]}) # Print the dataframedf Now find the division of each dataframe element with 2 Python3 # Find the division with 50 being substituted# for all the missing values in the dataframedf.div(2, fill_value = 50) Output : The output is a dataframe with cells containing the result of the division of each cell value with 2. All the NaN cells have been filled with 50 before performing the division. Example #2: Use div() function to find the floating division of a dataframe with a series object over the index axis. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[5, 3, 6, 4], "B":[11, 2, 4, 3], "C":[4, 3, 8, 5], "D":[5, 4, 2, 8]}) # Create a series object with no. of elements# equal to the element along the index axis. # Creating a pandas series objectseries_object = pd.Series([2, 3, 1.5, 4]) # Print the series_obejctseries_object Output : Note: If the dimension of the index axis of the dataframe and the series object is not same then an error will occur.Now, find the division of dataframe elements with the series object along the index axis Python3 # To find the divisiondf.div(series_object, axis = 0) Output : The output is a dataframe with cells containing the result of the division of the current cell element with the corresponding series object cell. sagartomar9927 Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25575, "s": 25547, "text": "\n25 Aug, 2021" }, { "code": null, "e": 26017, "s": 25575, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.div() is used to find the floating division of the dataframe and other element-wise. This function is similar to dataframe/other, but with an additional support to handle missing value in one of the input data. " }, { "code": null, "e": 26436, "s": 26017, "text": "Syntax: DataFrame.div(other, axis=’columns’, level=None, fill_value=None)Parameters: other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on fill_value : Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing level : Broadcast across a level, matching Index values on the passed MultiIndex levelReturns: result : DataFrame " }, { "code": null, "e": 26592, "s": 26436, "text": "Example #1: Use div() function to find floating division of dataframe elements with a constant value. Also handle the NaN value present in the dataframe. " }, { "code": null, "e": 26600, "s": 26592, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe with NaN valuedf = pd.DataFrame({\"A\":[5, 3, None, 4], \"B\":[None, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, None]}) # Print the dataframedf", "e": 26862, "s": 26600, "text": null }, { "code": null, "e": 26918, "s": 26862, "text": "Now find the division of each dataframe element with 2 " }, { "code": null, "e": 26926, "s": 26918, "text": "Python3" }, { "code": "# Find the division with 50 being substituted# for all the missing values in the dataframedf.div(2, fill_value = 50)", "e": 27043, "s": 26926, "text": null }, { "code": null, "e": 27054, "s": 27043, "text": "Output : " }, { "code": null, "e": 27352, "s": 27054, "text": "The output is a dataframe with cells containing the result of the division of each cell value with 2. All the NaN cells have been filled with 50 before performing the division. Example #2: Use div() function to find the floating division of a dataframe with a series object over the index axis. " }, { "code": null, "e": 27360, "s": 27352, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[5, 3, 6, 4], \"B\":[11, 2, 4, 3], \"C\":[4, 3, 8, 5], \"D\":[5, 4, 2, 8]}) # Create a series object with no. of elements# equal to the element along the index axis. # Creating a pandas series objectseries_object = pd.Series([2, 3, 1.5, 4]) # Print the series_obejctseries_object", "e": 27779, "s": 27360, "text": null }, { "code": null, "e": 27790, "s": 27779, "text": "Output : " }, { "code": null, "e": 27997, "s": 27790, "text": "Note: If the dimension of the index axis of the dataframe and the series object is not same then an error will occur.Now, find the division of dataframe elements with the series object along the index axis " }, { "code": null, "e": 28005, "s": 27997, "text": "Python3" }, { "code": "# To find the divisiondf.div(series_object, axis = 0)", "e": 28059, "s": 28005, "text": null }, { "code": null, "e": 28070, "s": 28059, "text": "Output : " }, { "code": null, "e": 28217, "s": 28070, "text": "The output is a dataframe with cells containing the result of the division of the current cell element with the corresponding series object cell. " }, { "code": null, "e": 28232, "s": 28217, "text": "sagartomar9927" }, { "code": null, "e": 28256, "s": 28232, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28288, "s": 28256, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28302, "s": 28288, "text": "Python-pandas" }, { "code": null, "e": 28309, "s": 28302, "text": "Python" }, { "code": null, "e": 28407, "s": 28309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28439, "s": 28407, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28461, "s": 28439, "text": "Enumerate() in Python" }, { "code": null, "e": 28503, "s": 28461, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28533, "s": 28503, "text": "Iterate over a list in Python" }, { "code": null, "e": 28559, "s": 28533, "text": "Python String | replace()" }, { "code": null, "e": 28603, "s": 28559, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28632, "s": 28603, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28669, "s": 28632, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28711, "s": 28669, "text": "Check if element exists in list in Python" } ]
How to check whether a thread is alive or not in C# - GeeksforGeeks
11 Jan, 2019 A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsAlive to check if the thread is alive or not. Or in other words, the value of this property indicates the current execution of the thread. Syntax: public bool IsAlive { get; } Return Value: This property returns true if the thread is started and not terminated normally or aborted. Otherwise, return false. The return type of this property is System.Boolean. Below programs illustrate the use of IsAlive property: Example 1: // C# program to illustrate the // use of IsAlive propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the current state of // the main thread Using IsAlive // property Console.WriteLine("Is main thread is alive"+ " ? : {0}", thr.IsAlive); }} Output: Is main thread is alive ? : True Example 2: // C# program to illustrate the // use of IsAlive propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread Thr1 = new Thread(new ThreadStart(job)); Thread Thr2 = new Thread(new ThreadStart(job)); // Display the current state of // the threads Using IsAlive // property Console.WriteLine("Is thread 1 is alive : {0}", Thr1.IsAlive); Console.WriteLine("Is thread 2 is alive : {0}", Thr2.IsAlive); Thr1.Start(); Thr2.Start(); // Display the current state of // the threads Using IsAlive // property Console.WriteLine("Is thread 1 is alive : {0}", Thr1.IsAlive); Console.WriteLine("Is thread 2 is alive : {0}", Thr2.IsAlive); } // Static method public static void job() { Thread.Sleep(2000); }} Output: Is thread 1 is alive : False Is thread 2 is alive : False Is thread 1 is alive : True Is thread 2 is alive : True Reference: https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isalive?view=netframework-4.7.2 CSharp Multithreading CSharp Thread Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Extension Method in C# Difference between Ref and Out keywords in C# C# | Replace() Method C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 26104, "s": 26076, "text": "\n11 Jan, 2019" }, { "code": null, "e": 26371, "s": 26104, "text": "A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsAlive to check if the thread is alive or not. Or in other words, the value of this property indicates the current execution of the thread." }, { "code": null, "e": 26379, "s": 26371, "text": "Syntax:" }, { "code": null, "e": 26408, "s": 26379, "text": "public bool IsAlive { get; }" }, { "code": null, "e": 26591, "s": 26408, "text": "Return Value: This property returns true if the thread is started and not terminated normally or aborted. Otherwise, return false. The return type of this property is System.Boolean." }, { "code": null, "e": 26646, "s": 26591, "text": "Below programs illustrate the use of IsAlive property:" }, { "code": null, "e": 26657, "s": 26646, "text": "Example 1:" }, { "code": "// C# program to illustrate the // use of IsAlive propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the current state of // the main thread Using IsAlive // property Console.WriteLine(\"Is main thread is alive\"+ \" ? : {0}\", thr.IsAlive); }}", "e": 27176, "s": 26657, "text": null }, { "code": null, "e": 27184, "s": 27176, "text": "Output:" }, { "code": null, "e": 27218, "s": 27184, "text": "Is main thread is alive ? : True\n" }, { "code": null, "e": 27229, "s": 27218, "text": "Example 2:" }, { "code": "// C# program to illustrate the // use of IsAlive propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread Thr1 = new Thread(new ThreadStart(job)); Thread Thr2 = new Thread(new ThreadStart(job)); // Display the current state of // the threads Using IsAlive // property Console.WriteLine(\"Is thread 1 is alive : {0}\", Thr1.IsAlive); Console.WriteLine(\"Is thread 2 is alive : {0}\", Thr2.IsAlive); Thr1.Start(); Thr2.Start(); // Display the current state of // the threads Using IsAlive // property Console.WriteLine(\"Is thread 1 is alive : {0}\", Thr1.IsAlive); Console.WriteLine(\"Is thread 2 is alive : {0}\", Thr2.IsAlive); } // Static method public static void job() { Thread.Sleep(2000); }}", "e": 28326, "s": 27229, "text": null }, { "code": null, "e": 28334, "s": 28326, "text": "Output:" }, { "code": null, "e": 28449, "s": 28334, "text": "Is thread 1 is alive : False\nIs thread 2 is alive : False\nIs thread 1 is alive : True\nIs thread 2 is alive : True\n" }, { "code": null, "e": 28460, "s": 28449, "text": "Reference:" }, { "code": null, "e": 28560, "s": 28460, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isalive?view=netframework-4.7.2" }, { "code": null, "e": 28582, "s": 28560, "text": "CSharp Multithreading" }, { "code": null, "e": 28602, "s": 28582, "text": "CSharp Thread Class" }, { "code": null, "e": 28605, "s": 28602, "text": "C#" }, { "code": null, "e": 28703, "s": 28605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28731, "s": 28703, "text": "C# Dictionary with examples" }, { "code": null, "e": 28746, "s": 28731, "text": "C# | Delegates" }, { "code": null, "e": 28769, "s": 28746, "text": "C# | Method Overriding" }, { "code": null, "e": 28791, "s": 28769, "text": "C# | Abstract Classes" }, { "code": null, "e": 28814, "s": 28791, "text": "Extension Method in C#" }, { "code": null, "e": 28860, "s": 28814, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28882, "s": 28860, "text": "C# | Replace() Method" }, { "code": null, "e": 28904, "s": 28882, "text": "C# | Class and Object" }, { "code": null, "e": 28922, "s": 28904, "text": "C# | Constructors" } ]
Perl | Basic Syntax of a Perl Program - GeeksforGeeks
25 Jun, 2019 Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form.Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Like other Programming Languages, Perl also follows a basic syntax for writing programs for applications and software or writing a simple Perl program. This syntax contains some predefined words known as Keywords, Variables for storing values, expressions, statements for executing the logic, loops for iterating over a variable value, blocks for grouping statements, subroutines for reducing the complexity of the code, etc. All these, when put together, will make a Perl program. A Perl program whether it be a small code for addition of Two numbers or a Complex one for executing web scripts, uses these variables, statements and other parameters that comprise of a program’s syntax. Variables are user-defined words that are used to hold the values passed to the program which will be used to evaluate the Code. Every Perl program contains values on which the Code performs its operations. These values can’t be manipulated or stored without the use of a Variable. A value can be processed only if it is stored in a variable, by using the variable’s name.A value is the data passed to the program to perform manipulation operation. This data can be either number, strings, characters, lists, etc.Example: Values: 5 geeks 15 Variables: $a = 5; $b = "geeks"; $c = 15; Above example contains one string variable and two integer variables. Expressions in Perl are made up of variables and an operator symbol. These expressions formulate the operation that is to be performed on the data provided in the respective code. An expression in Perl is something that returns a value on evaluating. An expression can also be simply a value with no variables and operator symbol. It can be an integer or just a string with no variable.Example: Value 10 is an expression, $x + $y is an expression that returns their sum, etc. Expressions can be more complex like Regular Expressions which are used to perform operations on Strings and Sub-strings. Perl developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program. There are two types of comment in Perl: Single line comments: Perl single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Perl’s single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment: #!/usr/bin/perl$b = 10; # Assigning value to $b$c = 30; # Assigning value to $c $a = $b + $c; # Performing the operationprint "$a"; # Printing the result Multi-line string as a comment: Perl multi-line comment is a piece of text enclosed within “=” and “=cut”. They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. Perl considers anything written after the ‘=’ sign as a comment until it is accompanied by a ‘=cut’ at the end. Please note that there should be no whitespace after the ‘=’ sign. See the following code snippet demonstrating a multi-line comment: #!/usr/bin/perl =Assigning values to variable $b and $c=cut$b = 10; $c = 30; =Performing the operationand printing the result=cut$a = $b + $c; print "$a"; A statement in Perl holds instructions for the compiler to perform operations. These statements perform the operations on the variables and values during the Run-time. every statement in Perl must end with a semicolon(;). Basically, instructions written in the source code for execution are called statements. There are different types of statements in the Perl programming language like Assignment statement, Conditional statement, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.Multi-Line Statements: Statements in Perl can be extended to one or more lines by simply dividing it into parts. Unlike other languages like Python, Perl looks for a semicolon to end the statement. Every line between two semicolons is considered as a single statement.When the programmer needs to do long calculations and cannot fit his statements into one line, one can easily divide it into multiple lines.Example: $x = $a + $b + $c + $d + $e + $f; A block is a group of statements that are used to perform a relative operation. In Perl, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements which gets executed simultaneously. This block can be used to make the program more optimized by organizing the statements in groups.Variables that are declared inside a block have their scope limited to that specific block and will be of no use outside the block. They will get executed only till that specific block is getting executed.Example: { $x = 15; $x = $x + 25; print($x); } In the above code, the variable $x will have its scope limited to this particular block only and will be of no use outside the block. Above block holds statements that have their operations related to each other. A function/Subroutine is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in an office in real life for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to his boss. Functions work in a similar manner. They take information as a parameter, execute a block of statements or perform operations on these parameters and returns the result. Perl provides us with two major types of functions: Built-in Functions: Perl provides us with a huge collection of built-in library functions. These functions are already coded and stored in the form of functions. To use those we just need to call them as per our requirement like sin(), cos(), chr(), return(), shift(), etc. User Defined Functions: Apart from the built-in functions, Perl allows us to create our own customized functions called the user-defined functions or Subroutines.Using this we can create our own packages of code and use it wherever necessary by simply calling it. Like any other language, loop in Perl is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times. Perl supports various types of looping techniques: for loopforeach loopwhile loopdo.... while loopuntil loopNested loops for loop foreach loop while loop do.... while loop until loop Nested loops Whitespaces in Perl are the blanks that are used between the variables and operators or between keywords, etc. Perl has no effect of whitespaces unless they are used within quotes. Whitespaces such as spaces, tabs, newlines, etc. have the same meaning in Perl if used outside the quotes.Example 1: $a = $b + $c; Here, spaces are of no use, it will cause no effect even if it is written as $a = $b + $c; Example 2: print "Geeks for Geeks"; will print Geeks for geeks whereas, print "Geeks for Geeks"; will print Geeks for Geeks Here, in the above examples, it is shown that whitespaces have their effect only if used within the quotes.Similarly, the process of indentation is used to arrange the code in an organized way to make it easier for the readers. Whenever a block of statements is used then the indentation will help reducing the reading complexity of the code.Example: Using Indentation: { $a = $b + $c; print "$a"; } Without using Indentation: { $a = $b + $c; print "$a"; } In the above example, both of the blocks will work in the exact same way but, for codes which have a large number of statements, the use of indentation makes it more compatible with the readers.Though it is not necessary to use Whitespaces and Indentation in your Perl code, but it is a good practice to do the same. Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. They have a special meaning to the compiler. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. In Perl, keywords include built-in functions as well along with the control words.These keywords can sometimes be used as a variable name but that will result in confusion and hence, debugging of such a program will be difficult.Example: One can use $print as a variable along with the keyword print(). perl-basics Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Removing leading and trailing white spaces (trim) Perl | sleep() Function
[ { "code": null, "e": 25305, "s": 25277, "text": "\n25 Jun, 2019" }, { "code": null, "e": 25730, "s": 25305, "text": "Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form.Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++." }, { "code": null, "e": 26417, "s": 25730, "text": "Like other Programming Languages, Perl also follows a basic syntax for writing programs for applications and software or writing a simple Perl program. This syntax contains some predefined words known as Keywords, Variables for storing values, expressions, statements for executing the logic, loops for iterating over a variable value, blocks for grouping statements, subroutines for reducing the complexity of the code, etc. All these, when put together, will make a Perl program. A Perl program whether it be a small code for addition of Two numbers or a Complex one for executing web scripts, uses these variables, statements and other parameters that comprise of a program’s syntax." }, { "code": null, "e": 26939, "s": 26417, "text": "Variables are user-defined words that are used to hold the values passed to the program which will be used to evaluate the Code. Every Perl program contains values on which the Code performs its operations. These values can’t be manipulated or stored without the use of a Variable. A value can be processed only if it is stored in a variable, by using the variable’s name.A value is the data passed to the program to perform manipulation operation. This data can be either number, strings, characters, lists, etc.Example:" }, { "code": null, "e": 27002, "s": 26939, "text": "Values: \n5\ngeeks\n15\n\nVariables:\n$a = 5;\n$b = \"geeks\";\n$c = 15;" }, { "code": null, "e": 27073, "s": 27002, "text": "Above example contains one string variable and two integer variables. " }, { "code": null, "e": 27468, "s": 27073, "text": "Expressions in Perl are made up of variables and an operator symbol. These expressions formulate the operation that is to be performed on the data provided in the respective code. An expression in Perl is something that returns a value on evaluating. An expression can also be simply a value with no variables and operator symbol. It can be an integer or just a string with no variable.Example:" }, { "code": null, "e": 27549, "s": 27468, "text": "Value 10 is an expression, $x + $y is an expression that returns their sum, etc." }, { "code": null, "e": 27672, "s": 27549, "text": "Expressions can be more complex like Regular Expressions which are used to perform operations on Strings and Sub-strings. " }, { "code": null, "e": 28253, "s": 27672, "text": "Perl developers often make use of the comment system as, without the use of it, things can get real confusing, real fast. Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program." }, { "code": null, "e": 28293, "s": 28253, "text": "There are two types of comment in Perl:" }, { "code": null, "e": 28722, "s": 28293, "text": "Single line comments: Perl single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment. Perl’s single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:" }, { "code": "#!/usr/bin/perl$b = 10; # Assigning value to $b$c = 30; # Assigning value to $c $a = $b + $c; # Performing the operationprint \"$a\"; # Printing the result", "e": 28889, "s": 28722, "text": null }, { "code": null, "e": 29433, "s": 28889, "text": "Multi-line string as a comment: Perl multi-line comment is a piece of text enclosed within “=” and “=cut”. They are useful when the comment text does not fit into one line; therefore needs to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. Perl considers anything written after the ‘=’ sign as a comment until it is accompanied by a ‘=cut’ at the end. Please note that there should be no whitespace after the ‘=’ sign. See the following code snippet demonstrating a multi-line comment:" }, { "code": "#!/usr/bin/perl =Assigning values to variable $b and $c=cut$b = 10; $c = 30; =Performing the operationand printing the result=cut$a = $b + $c; print \"$a\"; ", "e": 29599, "s": 29433, "text": null }, { "code": null, "e": 30575, "s": 29601, "text": "A statement in Perl holds instructions for the compiler to perform operations. These statements perform the operations on the variables and values during the Run-time. every statement in Perl must end with a semicolon(;). Basically, instructions written in the source code for execution are called statements. There are different types of statements in the Perl programming language like Assignment statement, Conditional statement, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.Multi-Line Statements: Statements in Perl can be extended to one or more lines by simply dividing it into parts. Unlike other languages like Python, Perl looks for a semicolon to end the statement. Every line between two semicolons is considered as a single statement.When the programmer needs to do long calculations and cannot fit his statements into one line, one can easily divide it into multiple lines.Example:" }, { "code": null, "e": 30616, "s": 30575, "text": "$x = $a + $b + $c + \n $d + $e + $f;\n" }, { "code": null, "e": 31201, "s": 30618, "text": "A block is a group of statements that are used to perform a relative operation. In Perl, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements which gets executed simultaneously. This block can be used to make the program more optimized by organizing the statements in groups.Variables that are declared inside a block have their scope limited to that specific block and will be of no use outside the block. They will get executed only till that specific block is getting executed.Example:" }, { "code": null, "e": 31255, "s": 31201, "text": "{\n $x = 15;\n $x = $x + 25;\n print($x);\n}\n" }, { "code": null, "e": 31469, "s": 31255, "text": "In the above code, the variable $x will have its scope limited to this particular block only and will be of no use outside the block. Above block holds statements that have their operations related to each other. " }, { "code": null, "e": 32109, "s": 31469, "text": "A function/Subroutine is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in an office in real life for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to his boss. Functions work in a similar manner. They take information as a parameter, execute a block of statements or perform operations on these parameters and returns the result." }, { "code": null, "e": 32161, "s": 32109, "text": "Perl provides us with two major types of functions:" }, { "code": null, "e": 32435, "s": 32161, "text": "Built-in Functions: Perl provides us with a huge collection of built-in library functions. These functions are already coded and stored in the form of functions. To use those we just need to call them as per our requirement like sin(), cos(), chr(), return(), shift(), etc." }, { "code": null, "e": 32700, "s": 32435, "text": "User Defined Functions: Apart from the built-in functions, Perl allows us to create our own customized functions called the user-defined functions or Subroutines.Using this we can create our own packages of code and use it wherever necessary by simply calling it. " }, { "code": null, "e": 32946, "s": 32700, "text": "Like any other language, loop in Perl is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times." }, { "code": null, "e": 32997, "s": 32946, "text": "Perl supports various types of looping techniques:" }, { "code": null, "e": 33067, "s": 32997, "text": "for loopforeach loopwhile loopdo.... while loopuntil loopNested loops" }, { "code": null, "e": 33076, "s": 33067, "text": "for loop" }, { "code": null, "e": 33089, "s": 33076, "text": "foreach loop" }, { "code": null, "e": 33100, "s": 33089, "text": "while loop" }, { "code": null, "e": 33118, "s": 33100, "text": "do.... while loop" }, { "code": null, "e": 33129, "s": 33118, "text": "until loop" }, { "code": null, "e": 33142, "s": 33129, "text": "Nested loops" }, { "code": null, "e": 33442, "s": 33144, "text": "Whitespaces in Perl are the blanks that are used between the variables and operators or between keywords, etc. Perl has no effect of whitespaces unless they are used within quotes. Whitespaces such as spaces, tabs, newlines, etc. have the same meaning in Perl if used outside the quotes.Example 1:" }, { "code": null, "e": 33564, "s": 33442, "text": "$a = $b + $c;\nHere, spaces are of no use, \nit will cause no effect even if it is written as \n$a = $b + $c;\n" }, { "code": null, "e": 33575, "s": 33564, "text": "Example 2:" }, { "code": null, "e": 33739, "s": 33575, "text": "print \"Geeks for Geeks\"; \nwill print \nGeeks for geeks\nwhereas, \nprint \"Geeks for\n Geeks\"; \nwill print \nGeeks for\n Geeks" }, { "code": null, "e": 34090, "s": 33739, "text": "Here, in the above examples, it is shown that whitespaces have their effect only if used within the quotes.Similarly, the process of indentation is used to arrange the code in an organized way to make it easier for the readers. Whenever a block of statements is used then the indentation will help reducing the reading complexity of the code.Example:" }, { "code": null, "e": 34206, "s": 34090, "text": "Using Indentation:\n{\n $a = $b + $c;\n print \"$a\";\n}\n\nWithout using Indentation:\n{\n$a = $b + $c;\nprint \"$a\";\n}\n" }, { "code": null, "e": 34524, "s": 34206, "text": "In the above example, both of the blocks will work in the exact same way but, for codes which have a large number of statements, the use of indentation makes it more compatible with the readers.Though it is not necessary to use Whitespaces and Indentation in your Perl code, but it is a good practice to do the same. " }, { "code": null, "e": 35063, "s": 34524, "text": "Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. They have a special meaning to the compiler. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. In Perl, keywords include built-in functions as well along with the control words.These keywords can sometimes be used as a variable name but that will result in confusion and hence, debugging of such a program will be difficult.Example:" }, { "code": null, "e": 35128, "s": 35063, "text": "One can use $print as a variable along with the keyword print()." }, { "code": null, "e": 35140, "s": 35128, "text": "perl-basics" }, { "code": null, "e": 35145, "s": 35140, "text": "Perl" }, { "code": null, "e": 35150, "s": 35145, "text": "Perl" }, { "code": null, "e": 35248, "s": 35150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35272, "s": 35248, "text": "Perl | split() Function" }, { "code": null, "e": 35295, "s": 35272, "text": "Perl | push() Function" }, { "code": null, "e": 35319, "s": 35295, "text": "Perl | chomp() Function" }, { "code": null, "e": 35344, "s": 35319, "text": "Perl | substr() function" }, { "code": null, "e": 35367, "s": 35344, "text": "Perl | grep() Function" }, { "code": null, "e": 35392, "s": 35367, "text": "Perl | exists() Function" }, { "code": null, "e": 35433, "s": 35392, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 35458, "s": 35433, "text": "Perl | length() Function" }, { "code": null, "e": 35515, "s": 35458, "text": "Perl | Removing leading and trailing white spaces (trim)" } ]
SWING - Container Class
The class Container is the super class for the containers of AWT. Container object can contain other AWT components. Following is the declaration for java.awt.Container class − public class Container extends Component Container() This creates a new Container. Component add(Component comp) Appends the specified component to the end of this container. Component add(Component comp, int index) Adds the specified component to this container at the given position. void add(Component comp, Object constraints) Adds the specified component to the end of this container. void add(Component comp, Object constraints, int index) Adds the specified component to this container with the specified constraints at the specified index. Component add(String name, Component comp) Adds the specified component to this container. void addContainerListener(ContainerListener l) Adds the specified container listener to receive container events from this container. protected void addImpl(Component comp, Object constraints, int index) Adds the specified component to this container at the specified index. void addNotify() Makes this Container displayable by connecting it to a native screen resource. void addPropertyChangeListener(PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list. void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) Adds a PropertyChangeListener to the listener list for a specific property. void applyComponentOrientation(ComponentOrientation o) Sets the ComponentOrientation property of this container and all components contained within it. boolean areFocusTraversalKeysSet(int id) Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container. int countComponents() Deprecated. As of JDK version 1.1, replaced by getComponentCount(). void deliverEvent(Event e) Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e) void doLayout() Causes this container to lay out its components. Component findComponentAt(int x, int y) Locates the visible child component that contains the specified position. Component findComponentAt(Point p) Locates the visible child component that contains the specified point. float getAlignmentX() Returns the alignment along the x axis. float getAlignmentY() Returns the alignment along the y axis. Component getComponent(int n) Gets the nth component in this container. Component getComponentAt(int x, int y) Locates the component that contains the x,y position. Component getComponentAt(Point p) Gets the component that contains the specified point. int getComponentCount() Gets the number of components in this panel. Component[] getComponents() Gets all the components in this container. int getComponentZOrder(Component comp) Returns the z-order index of the component inside the container. ContainerListener[] getContainerListeners() Returns an array of all the container listeners registered on this container. Set<AWTKeyStroke> getFocusTraversalKeys(int id) Returns the Set of focus traversal keys for a given traversal operation for this Container. FocusTraversalPolicy getFocusTraversalPolicy() Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root. Insets getInsets() Determines the insets of this container, which indicate the size of the container's border. LayoutManager getLayout() Gets the layout manager for this container. <T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Container. Dimension getMaximumSize() Returns the maximum size of this container. Dimension getMinimumSize() Returns the minimum size of this container. Point getMousePosition(boolean allowChildren) Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null. Dimension getPreferredSize() Returns the preferred size of this container. Insets insets() Deprecated. As of JDK version 1.1, replaced by getInsets(). void invalidate() Invalidates the container. boolean isAncestorOf(Component c) Checks if the component is contained in the component hierarchy of this container. boolean isFocusCycleRoot() Returns whether this Container is the root of a focus traversal cycle. boolean isFocusCycleRoot(Container container) Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle. boolean isFocusTraversalPolicyProvider() Returns whether this container provides focus traversal policy. boolean isFocusTraversalPolicySet() Returns whether the focus traversal policy has been explicitly set for this Container. void layout() Deprecated. As of JDK version 1.1, replaced by doLayout(). void list(PrintStream out, int indent) Prints a listing of this container to the specified output stream. void list(PrintWriter out, int indent) Prints out a list, starting at the specified indentation, to the specified print writer. Component locate(int x, int y) Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int). Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). void paint(Graphics g) Paints the container. void paintComponents(Graphics g) Paints each of the components in this container. protected String paramString() Returns a string representing the state of this Container. Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). void print(Graphics g) Prints the container. void printComponents(Graphics g) Prints each of the components in this container. protected void processContainerEvent(ContainerEvent e) Processes container events occurring on this container by dispatching them to any registered ContainerListener objects. protected void processEvent(AWTEvent e) Processes events on this container. void remove(Component comp) Removes the specified component from this container. void remove(int index) Removes the component, specified by index, from this container. void removeAll() Removes all the components from this container. void removeContainerListener(ContainerListener l) Removes the specified container listener so it no longer receives container events from this container. void removeNotify() Makes this container undisplayable by removing its connection to its native screen resource. void setComponentZOrder(Component comp, int index) Moves the specified component to the specified z-order index in the container. void setFocusCycleRoot(boolean focusCycleRoot) Sets whether this Container is the root of a focus traversal cycle. void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) Sets the focus traversal keys for a given traversal operation for this Container. void setFocusTraversalPolicy(FocusTraversalPolicy policy) Sets the focus traversal policy that will manage keyboard traversal of this container's children, if this container is a focus cycle root. void setFocusTraversalPolicyProvider(boolean provider) Sets whether this container will be used to provide focus traversal policy. void setFont(Font f) Sets the font of this container. void setLayout(LayoutManager mgr) Sets the layout manager for this container. void transferFocusBackward() Transfers the focus to the previous component, as though this Component were the focus owner. void transferFocusDownCycle() Transfers the focus down one focus traversal cycle. void update(Graphics g) Updates the container. void validate() Validates this container and all of its subcomponents. protected void validateTree() Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid). This class inherits methods from the following classes − java.awt.Component java.lang.Object 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1880, "s": 1763, "text": "The class Container is the super class for the containers of AWT. Container object can contain other AWT components." }, { "code": null, "e": 1940, "s": 1880, "text": "Following is the declaration for java.awt.Container class −" }, { "code": null, "e": 1985, "s": 1940, "text": "public class Container\n extends Component\n" }, { "code": null, "e": 1997, "s": 1985, "text": "Container()" }, { "code": null, "e": 2027, "s": 1997, "text": "This creates a new Container." }, { "code": null, "e": 2057, "s": 2027, "text": "Component add(Component comp)" }, { "code": null, "e": 2119, "s": 2057, "text": "Appends the specified component to the end of this container." }, { "code": null, "e": 2160, "s": 2119, "text": "Component add(Component comp, int index)" }, { "code": null, "e": 2230, "s": 2160, "text": "Adds the specified component to this container at the given position." }, { "code": null, "e": 2275, "s": 2230, "text": "void add(Component comp, Object constraints)" }, { "code": null, "e": 2334, "s": 2275, "text": "Adds the specified component to the end of this container." }, { "code": null, "e": 2390, "s": 2334, "text": "void add(Component comp, Object constraints, int index)" }, { "code": null, "e": 2492, "s": 2390, "text": "Adds the specified component to this container with the specified constraints at the specified index." }, { "code": null, "e": 2535, "s": 2492, "text": "Component add(String name, Component comp)" }, { "code": null, "e": 2583, "s": 2535, "text": "Adds the specified component to this container." }, { "code": null, "e": 2630, "s": 2583, "text": "void addContainerListener(ContainerListener l)" }, { "code": null, "e": 2717, "s": 2630, "text": "Adds the specified container listener to receive container events from this container." }, { "code": null, "e": 2787, "s": 2717, "text": "protected void addImpl(Component comp, Object constraints, int index)" }, { "code": null, "e": 2858, "s": 2787, "text": "Adds the specified component to this container at the specified index." }, { "code": null, "e": 2875, "s": 2858, "text": "void addNotify()" }, { "code": null, "e": 2954, "s": 2875, "text": "Makes this Container displayable by connecting it to a native screen resource." }, { "code": null, "e": 3018, "s": 2954, "text": "void addPropertyChangeListener(PropertyChangeListener listener)" }, { "code": null, "e": 3070, "s": 3018, "text": "Adds a PropertyChangeListener to the listener list." }, { "code": null, "e": 3155, "s": 3070, "text": "void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)" }, { "code": null, "e": 3231, "s": 3155, "text": "Adds a PropertyChangeListener to the listener list for a specific property." }, { "code": null, "e": 3286, "s": 3231, "text": "void applyComponentOrientation(ComponentOrientation o)" }, { "code": null, "e": 3383, "s": 3286, "text": "Sets the ComponentOrientation property of this container and all components contained within it." }, { "code": null, "e": 3424, "s": 3383, "text": "boolean areFocusTraversalKeysSet(int id)" }, { "code": null, "e": 3560, "s": 3424, "text": "Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container." }, { "code": null, "e": 3582, "s": 3560, "text": "int countComponents()" }, { "code": null, "e": 3650, "s": 3582, "text": "Deprecated. As of JDK version 1.1, replaced by getComponentCount()." }, { "code": null, "e": 3677, "s": 3650, "text": "void deliverEvent(Event e)" }, { "code": null, "e": 3750, "s": 3677, "text": "Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)" }, { "code": null, "e": 3766, "s": 3750, "text": "void doLayout()" }, { "code": null, "e": 3815, "s": 3766, "text": "Causes this container to lay out its components." }, { "code": null, "e": 3855, "s": 3815, "text": "Component findComponentAt(int x, int y)" }, { "code": null, "e": 3929, "s": 3855, "text": "Locates the visible child component that contains the specified position." }, { "code": null, "e": 3964, "s": 3929, "text": "Component findComponentAt(Point p)" }, { "code": null, "e": 4035, "s": 3964, "text": "Locates the visible child component that contains the specified point." }, { "code": null, "e": 4057, "s": 4035, "text": "float getAlignmentX()" }, { "code": null, "e": 4097, "s": 4057, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 4119, "s": 4097, "text": "float getAlignmentY()" }, { "code": null, "e": 4159, "s": 4119, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 4189, "s": 4159, "text": "Component getComponent(int n)" }, { "code": null, "e": 4231, "s": 4189, "text": "Gets the nth component in this container." }, { "code": null, "e": 4270, "s": 4231, "text": "Component getComponentAt(int x, int y)" }, { "code": null, "e": 4324, "s": 4270, "text": "Locates the component that contains the x,y position." }, { "code": null, "e": 4358, "s": 4324, "text": "Component getComponentAt(Point p)" }, { "code": null, "e": 4412, "s": 4358, "text": "Gets the component that contains the specified point." }, { "code": null, "e": 4436, "s": 4412, "text": "int getComponentCount()" }, { "code": null, "e": 4481, "s": 4436, "text": "Gets the number of components in this panel." }, { "code": null, "e": 4509, "s": 4481, "text": "Component[] getComponents()" }, { "code": null, "e": 4552, "s": 4509, "text": "Gets all the components in this container." }, { "code": null, "e": 4591, "s": 4552, "text": "int getComponentZOrder(Component comp)" }, { "code": null, "e": 4656, "s": 4591, "text": "Returns the z-order index of the component inside the container." }, { "code": null, "e": 4700, "s": 4656, "text": "ContainerListener[] getContainerListeners()" }, { "code": null, "e": 4778, "s": 4700, "text": "Returns an array of all the container listeners registered on this container." }, { "code": null, "e": 4826, "s": 4778, "text": "Set<AWTKeyStroke> getFocusTraversalKeys(int id)" }, { "code": null, "e": 4918, "s": 4826, "text": "Returns the Set of focus traversal keys for a given traversal operation for this Container." }, { "code": null, "e": 4965, "s": 4918, "text": "FocusTraversalPolicy getFocusTraversalPolicy()" }, { "code": null, "e": 5119, "s": 4965, "text": "Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root." }, { "code": null, "e": 5138, "s": 5119, "text": "Insets getInsets()" }, { "code": null, "e": 5230, "s": 5138, "text": "Determines the insets of this container, which indicate the size of the container's border." }, { "code": null, "e": 5256, "s": 5230, "text": "LayoutManager getLayout()" }, { "code": null, "e": 5300, "s": 5256, "text": "Gets the layout manager for this container." }, { "code": null, "e": 5366, "s": 5300, "text": "<T extends EventListener> T[] getListeners(Class<T> listenerType)" }, { "code": null, "e": 5460, "s": 5366, "text": "Returns an array of all the objects currently registered as FooListeners upon this Container." }, { "code": null, "e": 5487, "s": 5460, "text": "Dimension getMaximumSize()" }, { "code": null, "e": 5531, "s": 5487, "text": "Returns the maximum size of this container." }, { "code": null, "e": 5558, "s": 5531, "text": "Dimension getMinimumSize()" }, { "code": null, "e": 5602, "s": 5558, "text": "Returns the minimum size of this container." }, { "code": null, "e": 5648, "s": 5602, "text": "Point\tgetMousePosition(boolean allowChildren)" }, { "code": null, "e": 5796, "s": 5648, "text": "Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null." }, { "code": null, "e": 5825, "s": 5796, "text": "Dimension getPreferredSize()" }, { "code": null, "e": 5871, "s": 5825, "text": "Returns the preferred size of this container." }, { "code": null, "e": 5887, "s": 5871, "text": "Insets insets()" }, { "code": null, "e": 5947, "s": 5887, "text": "Deprecated. As of JDK version 1.1, replaced by getInsets()." }, { "code": null, "e": 5965, "s": 5947, "text": "void invalidate()" }, { "code": null, "e": 5992, "s": 5965, "text": "Invalidates the container." }, { "code": null, "e": 6026, "s": 5992, "text": "boolean isAncestorOf(Component c)" }, { "code": null, "e": 6109, "s": 6026, "text": "Checks if the component is contained in the component hierarchy of this container." }, { "code": null, "e": 6136, "s": 6109, "text": "boolean isFocusCycleRoot()" }, { "code": null, "e": 6207, "s": 6136, "text": "Returns whether this Container is the root of a focus traversal cycle." }, { "code": null, "e": 6253, "s": 6207, "text": "boolean isFocusCycleRoot(Container container)" }, { "code": null, "e": 6360, "s": 6253, "text": "Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle." }, { "code": null, "e": 6401, "s": 6360, "text": "boolean isFocusTraversalPolicyProvider()" }, { "code": null, "e": 6465, "s": 6401, "text": "Returns whether this container provides focus traversal policy." }, { "code": null, "e": 6501, "s": 6465, "text": "boolean isFocusTraversalPolicySet()" }, { "code": null, "e": 6588, "s": 6501, "text": "Returns whether the focus traversal policy has been explicitly set for this Container." }, { "code": null, "e": 6602, "s": 6588, "text": "void layout()" }, { "code": null, "e": 6661, "s": 6602, "text": "Deprecated. As of JDK version 1.1, replaced by doLayout()." }, { "code": null, "e": 6700, "s": 6661, "text": "void list(PrintStream out, int indent)" }, { "code": null, "e": 6767, "s": 6700, "text": "Prints a listing of this container to the specified output stream." }, { "code": null, "e": 6806, "s": 6767, "text": "void list(PrintWriter out, int indent)" }, { "code": null, "e": 6895, "s": 6806, "text": "Prints out a list, starting at the specified indentation, to the specified print writer." }, { "code": null, "e": 6926, "s": 6895, "text": "Component locate(int x, int y)" }, { "code": null, "e": 6999, "s": 6926, "text": "Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int)." }, { "code": null, "e": 7023, "s": 6999, "text": "Dimension minimumSize()" }, { "code": null, "e": 7088, "s": 7023, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize()." }, { "code": null, "e": 7111, "s": 7088, "text": "void paint(Graphics g)" }, { "code": null, "e": 7133, "s": 7111, "text": "Paints the container." }, { "code": null, "e": 7166, "s": 7133, "text": "void paintComponents(Graphics g)" }, { "code": null, "e": 7215, "s": 7166, "text": "Paints each of the components in this container." }, { "code": null, "e": 7246, "s": 7215, "text": "protected String paramString()" }, { "code": null, "e": 7305, "s": 7246, "text": "Returns a string representing the state of this Container." }, { "code": null, "e": 7331, "s": 7305, "text": "Dimension preferredSize()" }, { "code": null, "e": 7398, "s": 7331, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()." }, { "code": null, "e": 7421, "s": 7398, "text": "void print(Graphics g)" }, { "code": null, "e": 7443, "s": 7421, "text": "Prints the container." }, { "code": null, "e": 7476, "s": 7443, "text": "void printComponents(Graphics g)" }, { "code": null, "e": 7525, "s": 7476, "text": "Prints each of the components in this container." }, { "code": null, "e": 7580, "s": 7525, "text": "protected void processContainerEvent(ContainerEvent e)" }, { "code": null, "e": 7700, "s": 7580, "text": "Processes container events occurring on this container by dispatching them to any registered ContainerListener objects." }, { "code": null, "e": 7740, "s": 7700, "text": "protected void processEvent(AWTEvent e)" }, { "code": null, "e": 7776, "s": 7740, "text": "Processes events on this container." }, { "code": null, "e": 7804, "s": 7776, "text": "void remove(Component comp)" }, { "code": null, "e": 7857, "s": 7804, "text": "Removes the specified component from this container." }, { "code": null, "e": 7880, "s": 7857, "text": "void remove(int index)" }, { "code": null, "e": 7944, "s": 7880, "text": "Removes the component, specified by index, from this container." }, { "code": null, "e": 7961, "s": 7944, "text": "void removeAll()" }, { "code": null, "e": 8009, "s": 7961, "text": "Removes all the components from this container." }, { "code": null, "e": 8059, "s": 8009, "text": "void removeContainerListener(ContainerListener l)" }, { "code": null, "e": 8163, "s": 8059, "text": "Removes the specified container listener so it no longer receives container events from this container." }, { "code": null, "e": 8183, "s": 8163, "text": "void removeNotify()" }, { "code": null, "e": 8276, "s": 8183, "text": "Makes this container undisplayable by removing its connection to its native screen resource." }, { "code": null, "e": 8327, "s": 8276, "text": "void setComponentZOrder(Component comp, int index)" }, { "code": null, "e": 8406, "s": 8327, "text": "Moves the specified component to the specified z-order index in the container." }, { "code": null, "e": 8453, "s": 8406, "text": "void setFocusCycleRoot(boolean focusCycleRoot)" }, { "code": null, "e": 8521, "s": 8453, "text": "Sets whether this Container is the root of a focus traversal cycle." }, { "code": null, "e": 8596, "s": 8521, "text": "void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)" }, { "code": null, "e": 8678, "s": 8596, "text": "Sets the focus traversal keys for a given traversal operation for this Container." }, { "code": null, "e": 8736, "s": 8678, "text": "void setFocusTraversalPolicy(FocusTraversalPolicy policy)" }, { "code": null, "e": 8875, "s": 8736, "text": "Sets the focus traversal policy that will manage keyboard traversal of this container's children, if this container is a focus cycle root." }, { "code": null, "e": 8930, "s": 8875, "text": "void setFocusTraversalPolicyProvider(boolean provider)" }, { "code": null, "e": 9006, "s": 8930, "text": "Sets whether this container will be used to provide focus traversal policy." }, { "code": null, "e": 9027, "s": 9006, "text": "void setFont(Font f)" }, { "code": null, "e": 9060, "s": 9027, "text": "Sets the font of this container." }, { "code": null, "e": 9094, "s": 9060, "text": "void setLayout(LayoutManager mgr)" }, { "code": null, "e": 9138, "s": 9094, "text": "Sets the layout manager for this container." }, { "code": null, "e": 9167, "s": 9138, "text": "void transferFocusBackward()" }, { "code": null, "e": 9261, "s": 9167, "text": "Transfers the focus to the previous component, as though this Component were the focus owner." }, { "code": null, "e": 9291, "s": 9261, "text": "void transferFocusDownCycle()" }, { "code": null, "e": 9343, "s": 9291, "text": "Transfers the focus down one focus traversal cycle." }, { "code": null, "e": 9367, "s": 9343, "text": "void update(Graphics g)" }, { "code": null, "e": 9390, "s": 9367, "text": "Updates the container." }, { "code": null, "e": 9406, "s": 9390, "text": "void validate()" }, { "code": null, "e": 9461, "s": 9406, "text": "Validates this container and all of its subcomponents." }, { "code": null, "e": 9491, "s": 9461, "text": "protected void validateTree()" }, { "code": null, "e": 9622, "s": 9491, "text": "Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid)." }, { "code": null, "e": 9679, "s": 9622, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 9698, "s": 9679, "text": "java.awt.Component" }, { "code": null, "e": 9715, "s": 9698, "text": "java.lang.Object" }, { "code": null, "e": 9750, "s": 9715, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9770, "s": 9750, "text": " Pranjal Srivastava" }, { "code": null, "e": 9803, "s": 9770, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 9823, "s": 9803, "text": " Pranjal Srivastava" }, { "code": null, "e": 9858, "s": 9823, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9894, "s": 9858, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9929, "s": 9894, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9942, "s": 9929, "text": " Travis Rose" }, { "code": null, "e": 9975, "s": 9942, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9988, "s": 9975, "text": " Travis Rose" }, { "code": null, "e": 9995, "s": 9988, "text": " Print" }, { "code": null, "e": 10006, "s": 9995, "text": " Add Notes" } ]
Garbage Collection in C# | .NET Framework - GeeksforGeeks
21 Jun, 2021 Automatic memory management is made possible by Garbage Collection in .NET Framework. When a class object is created at runtime, certain memory space is allocated to it in the heap memory. However, after all the actions related to the object are completed in the program, the memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is very useful as it automatically releases the memory space after it is no longer required. Garbage collection will always work on Managed Heap and internally it has an Engine which is known as the Optimization Engine. Garbage Collection occurs if at least one of multiple conditions is satisfied. These conditions are given as follows: If the system has low physical memory, then garbage collection is necessary. If the memory allocated to various objects in the heap memory exceeds a pre-set threshold, then garbage collection occurs. If the GC.Collect method is called, then garbage collection occurs. However, this method is only called under unusual situations as normally garbage collector runs automatically. There are mainly 3 phases in garbage collection. Details about these are given as follows: Marking Phase: A list of all the live objects is created during the marking phase. This is done by following the references from all the root objects. All of the objects that are not on the list of live objects are potentially deleted from the heap memory.Relocating Phase: The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase.Compacting Phase: The heap gets compacted in the compacting phase as the space occupied by the dead objects is released and the live objects remaining are moved. All the live objects that remain after the garbage collection are moved towards the older end of the heap memory in their original order. Marking Phase: A list of all the live objects is created during the marking phase. This is done by following the references from all the root objects. All of the objects that are not on the list of live objects are potentially deleted from the heap memory. Relocating Phase: The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase. Compacting Phase: The heap gets compacted in the compacting phase as the space occupied by the dead objects is released and the live objects remaining are moved. All the live objects that remain after the garbage collection are moved towards the older end of the heap memory in their original order. The heap memory is organized into 3 generations so that various objects with different lifetimes can be handled appropriately during garbage collection. The memory to each Generation will be given by the Common Language Runtime(CLR) depending on the project size. Internally, Optimization Engine will call the Collection Means Method to select which objects will go into Generation 1 or Generation 2. Generation 0 : All the short-lived objects such as temporary variables are contained in the generation 0 of the heap memory. All the newly allocated objects are also generation 0 objects implicitly unless they are large objects. In general, the frequency of garbage collection is the highest in generation 0. Generation 1 : If space occupied by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1. The objects in this generation are a sort of buffer between the short-lived objects in generation 0 and the long-lived objects in generation 2. Generation 2 : If space occupied by some generation 1 objects that are not released in the next garbage collection run, then these objects get moved to generation 2. The objects in generation 2 are long lived such as static objects as they remain in the heap memory for the whole process duration. Note: Garbage collection of a generation implies the garbage collection of all its younger generations. This means that all the objects in that particular generation and its younger generations are released. Because of this reason, the garbage collection of generation 2 is called a full garbage collection as all the objects in the heap memory are.released. Also, the memory allocated to the Generation 2 will be greater than Generation 1’s memory and similarly the memory of Generation 1 will be greater than Generation 0’s memory(Generation 2 > Generation 1 > Generation 0).A program that demonstrates the number of heap generations in garbage collection using the GC.MaxGeneration property of the GC class is given as follows: csharp using System; public class Demo { // Main Method public static void Main(string[] args) { Console.WriteLine("The number of generations are: " + GC.MaxGeneration); }} The number of generations are: 2 In the above program, the GC.MaxGeneration property is used to find the maximum number of generations that are supported by the system i.e. 2. If you will run this program on online compilers then you may get different outputs as it depends on the system. The GC class controls the garbage collector of the system. Some of the methods in the GC class are given as follows:GC.GetGeneration() Method : This method returns the generation number of the target object. It requires a single parameter i.e. the target object for which the generation number is required.A program that demonstrates the GC.GetGeneration() method is given as follows: csharp using System; public class Demo { public static void Main(string[] args) { Demo obj = new Demo(); Console.WriteLine("The generation number of object obj is: " + GC.GetGeneration(obj)); }} The generation number of object obj is: 0 GC.GetTotalMemory() Method : This method returns the number of bytes that are allocated in the system. It requires a single boolean parameter where true means that the method waits for the occurrence of garbage collection before returning and false means the opposite.A program that demonstrates the GC.GetTotalMemory() method is given as follows: csharp using System; public class Demo { public static void Main(string[] args) { Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false)); Demo obj = new Demo(); Console.WriteLine("The generation number of object obj is: " + GC.GetGeneration(obj)); Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false)); }} Total Memory:4197120 The generation number of object obj is: 0 Total Memory:4204024 Note: The output may vary as it depends on the system.GC.Collect() Method : Garbage collection can be forced in the system using the GC.Collect() method. This method requires a single parameter i.e. number of the oldest generation for which garbage collection occurs.A program that demonstrates the GC.Collect() Method is given as follows: csharp using System; public class Demo { public static void Main(string[] args) { GC.Collect(0); Console.WriteLine("Garbage Collection in Generation 0 is: " + GC.CollectionCount(0)); }} Garbage Collection in Generation 0 is: 1 Benefits of Garbage Collection Garbage Collection succeeds in allocating objects efficiently on the heap memory using the generations of garbage collection. Manual freeing of memory is not needed as garbage collection automatically releases the memory space after it is no longer required. Garbage collection handles memory allocation safely so that no objects use the contents of another object mistakenly. The constructors of newly created objects do not have to initialize all the data fields as garbage collection clears the memory of objects that were previously released. sagar0719kumar CSharp-Basics Dot-NET C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object C# | Data Types Top 50 C# Interview Questions & Answers Common Language Runtime (CLR) in C# HashSet in C# with Examples C# | Encapsulation Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework C# | How to insert an element in an Array? C# | Inheritance C# | Method Overloading
[ { "code": null, "e": 24128, "s": 24100, "text": "\n21 Jun, 2021" }, { "code": null, "e": 24838, "s": 24128, "text": "Automatic memory management is made possible by Garbage Collection in .NET Framework. When a class object is created at runtime, certain memory space is allocated to it in the heap memory. However, after all the actions related to the object are completed in the program, the memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is very useful as it automatically releases the memory space after it is no longer required. Garbage collection will always work on Managed Heap and internally it has an Engine which is known as the Optimization Engine. Garbage Collection occurs if at least one of multiple conditions is satisfied. These conditions are given as follows: " }, { "code": null, "e": 24915, "s": 24838, "text": "If the system has low physical memory, then garbage collection is necessary." }, { "code": null, "e": 25038, "s": 24915, "text": "If the memory allocated to various objects in the heap memory exceeds a pre-set threshold, then garbage collection occurs." }, { "code": null, "e": 25217, "s": 25038, "text": "If the GC.Collect method is called, then garbage collection occurs. However, this method is only called under unusual situations as normally garbage collector runs automatically." }, { "code": null, "e": 25311, "s": 25219, "text": "There are mainly 3 phases in garbage collection. Details about these are given as follows: " }, { "code": null, "e": 26105, "s": 25313, "text": "Marking Phase: A list of all the live objects is created during the marking phase. This is done by following the references from all the root objects. All of the objects that are not on the list of live objects are potentially deleted from the heap memory.Relocating Phase: The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase.Compacting Phase: The heap gets compacted in the compacting phase as the space occupied by the dead objects is released and the live objects remaining are moved. All the live objects that remain after the garbage collection are moved towards the older end of the heap memory in their original order." }, { "code": null, "e": 26362, "s": 26105, "text": "Marking Phase: A list of all the live objects is created during the marking phase. This is done by following the references from all the root objects. All of the objects that are not on the list of live objects are potentially deleted from the heap memory." }, { "code": null, "e": 26599, "s": 26362, "text": "Relocating Phase: The references of all the objects that were on the list of all the live objects are updated in the relocating phase so that they point to the new location where the objects will be relocated to in the compacting phase." }, { "code": null, "e": 26899, "s": 26599, "text": "Compacting Phase: The heap gets compacted in the compacting phase as the space occupied by the dead objects is released and the live objects remaining are moved. All the live objects that remain after the garbage collection are moved towards the older end of the heap memory in their original order." }, { "code": null, "e": 27304, "s": 26901, "text": "The heap memory is organized into 3 generations so that various objects with different lifetimes can be handled appropriately during garbage collection. The memory to each Generation will be given by the Common Language Runtime(CLR) depending on the project size. Internally, Optimization Engine will call the Collection Means Method to select which objects will go into Generation 1 or Generation 2. " }, { "code": null, "e": 27615, "s": 27306, "text": "Generation 0 : All the short-lived objects such as temporary variables are contained in the generation 0 of the heap memory. All the newly allocated objects are also generation 0 objects implicitly unless they are large objects. In general, the frequency of garbage collection is the highest in generation 0." }, { "code": null, "e": 27918, "s": 27615, "text": "Generation 1 : If space occupied by some generation 0 objects that are not released in a garbage collection run, then these objects get moved to generation 1. The objects in this generation are a sort of buffer between the short-lived objects in generation 0 and the long-lived objects in generation 2." }, { "code": null, "e": 28216, "s": 27918, "text": "Generation 2 : If space occupied by some generation 1 objects that are not released in the next garbage collection run, then these objects get moved to generation 2. The objects in generation 2 are long lived such as static objects as they remain in the heap memory for the whole process duration." }, { "code": null, "e": 28948, "s": 28216, "text": "Note: Garbage collection of a generation implies the garbage collection of all its younger generations. This means that all the objects in that particular generation and its younger generations are released. Because of this reason, the garbage collection of generation 2 is called a full garbage collection as all the objects in the heap memory are.released. Also, the memory allocated to the Generation 2 will be greater than Generation 1’s memory and similarly the memory of Generation 1 will be greater than Generation 0’s memory(Generation 2 > Generation 1 > Generation 0).A program that demonstrates the number of heap generations in garbage collection using the GC.MaxGeneration property of the GC class is given as follows: " }, { "code": null, "e": 28955, "s": 28948, "text": "csharp" }, { "code": "using System; public class Demo { // Main Method public static void Main(string[] args) { Console.WriteLine(\"The number of generations are: \" + GC.MaxGeneration); }}", "e": 29183, "s": 28955, "text": null }, { "code": null, "e": 29216, "s": 29183, "text": "The number of generations are: 2" }, { "code": null, "e": 29475, "s": 29218, "text": "In the above program, the GC.MaxGeneration property is used to find the maximum number of generations that are supported by the system i.e. 2. If you will run this program on online compilers then you may get different outputs as it depends on the system. " }, { "code": null, "e": 29861, "s": 29475, "text": "The GC class controls the garbage collector of the system. Some of the methods in the GC class are given as follows:GC.GetGeneration() Method : This method returns the generation number of the target object. It requires a single parameter i.e. the target object for which the generation number is required.A program that demonstrates the GC.GetGeneration() method is given as follows: " }, { "code": null, "e": 29868, "s": 29861, "text": "csharp" }, { "code": "using System; public class Demo { public static void Main(string[] args) { Demo obj = new Demo(); Console.WriteLine(\"The generation number of object obj is: \" + GC.GetGeneration(obj)); }}", "e": 30121, "s": 29868, "text": null }, { "code": null, "e": 30163, "s": 30121, "text": "The generation number of object obj is: 0" }, { "code": null, "e": 30514, "s": 30165, "text": "GC.GetTotalMemory() Method : This method returns the number of bytes that are allocated in the system. It requires a single boolean parameter where true means that the method waits for the occurrence of garbage collection before returning and false means the opposite.A program that demonstrates the GC.GetTotalMemory() method is given as follows: " }, { "code": null, "e": 30521, "s": 30514, "text": "csharp" }, { "code": "using System; public class Demo { public static void Main(string[] args) { Console.WriteLine(\"Total Memory:\" + GC.GetTotalMemory(false)); Demo obj = new Demo(); Console.WriteLine(\"The generation number of object obj is: \" + GC.GetGeneration(obj)); Console.WriteLine(\"Total Memory:\" + GC.GetTotalMemory(false)); }}", "e": 30918, "s": 30521, "text": null }, { "code": null, "e": 31002, "s": 30918, "text": "Total Memory:4197120\nThe generation number of object obj is: 0\nTotal Memory:4204024" }, { "code": null, "e": 31345, "s": 31004, "text": "Note: The output may vary as it depends on the system.GC.Collect() Method : Garbage collection can be forced in the system using the GC.Collect() method. This method requires a single parameter i.e. number of the oldest generation for which garbage collection occurs.A program that demonstrates the GC.Collect() Method is given as follows: " }, { "code": null, "e": 31352, "s": 31345, "text": "csharp" }, { "code": "using System; public class Demo { public static void Main(string[] args) { GC.Collect(0); Console.WriteLine(\"Garbage Collection in Generation 0 is: \" + GC.CollectionCount(0)); }}", "e": 31596, "s": 31352, "text": null }, { "code": null, "e": 31637, "s": 31596, "text": "Garbage Collection in Generation 0 is: 1" }, { "code": null, "e": 31671, "s": 31639, "text": "Benefits of Garbage Collection " }, { "code": null, "e": 31797, "s": 31671, "text": "Garbage Collection succeeds in allocating objects efficiently on the heap memory using the generations of garbage collection." }, { "code": null, "e": 31930, "s": 31797, "text": "Manual freeing of memory is not needed as garbage collection automatically releases the memory space after it is no longer required." }, { "code": null, "e": 32048, "s": 31930, "text": "Garbage collection handles memory allocation safely so that no objects use the contents of another object mistakenly." }, { "code": null, "e": 32218, "s": 32048, "text": "The constructors of newly created objects do not have to initialize all the data fields as garbage collection clears the memory of objects that were previously released." }, { "code": null, "e": 32235, "s": 32220, "text": "sagar0719kumar" }, { "code": null, "e": 32249, "s": 32235, "text": "CSharp-Basics" }, { "code": null, "e": 32257, "s": 32249, "text": "Dot-NET" }, { "code": null, "e": 32260, "s": 32257, "text": "C#" }, { "code": null, "e": 32358, "s": 32260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32367, "s": 32358, "text": "Comments" }, { "code": null, "e": 32380, "s": 32367, "text": "Old Comments" }, { "code": null, "e": 32402, "s": 32380, "text": "C# | Class and Object" }, { "code": null, "e": 32418, "s": 32402, "text": "C# | Data Types" }, { "code": null, "e": 32458, "s": 32418, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 32494, "s": 32458, "text": "Common Language Runtime (CLR) in C#" }, { "code": null, "e": 32522, "s": 32494, "text": "HashSet in C# with Examples" }, { "code": null, "e": 32541, "s": 32522, "text": "C# | Encapsulation" }, { "code": null, "e": 32628, "s": 32541, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" }, { "code": null, "e": 32671, "s": 32628, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 32688, "s": 32671, "text": "C# | Inheritance" } ]
🚀 Introduction to Binary Classification with PyCaret | by Moez Ali | Towards Data Science
PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive. In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more. The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise. To learn more about PyCaret, you can check the official website or GitHub. In this tutorial we will learn: Getting Data: How to import data from the PyCaret repository Setting up Environment: How to set up an experiment in PyCaret and get started with building classification models Create Model: How to create a model, perform stratified cross-validation and evaluate classification metrics Tune Model: How to automatically tune the hyper-parameters of a classification model Plot Model: How to analyze model performance using various plots Finalize Model: How to finalize the best model at the end of the experiment Predict Model: How to make predictions on unseen data Save / Load Model: How to save/load a model for future use Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file. pip install pycaret To install the full version: pip install pycaret[full] Binary classification is a supervised machine learning technique where the goal is to predict categorical class labels which are discrete and unordered such as Pass/Fail, Positive/Negative, Default/Not-Default, etc. A few real-world use cases for classification are listed below: Medical testing to determine if a patient has a certain disease or not — the classification property is the presence of the disease. A “pass or fail” test method or quality control in factories, i.e. deciding if a specification has or has not been met — a go/no-go classification. Information retrieval, namely deciding whether a page or an article should be in the result set of a search or not — the classification property is the relevance of the article or the usefulness to the user. PyCaret’s classification module (pycaret.classification) is a supervised machine learning module that is used for classifying the elements into a binary group based on various techniques and algorithms. Some common use cases of classification problems include predicting customer default (yes or no), customer churn (customer will leave or stay), disease found (positive or negative). The PyCaret classification module can be used for Binary or Multi-class classification problems. It has over 18 algorithms and 14 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling, or advanced techniques like stacking, PyCaret’s classification module has it all. For this tutorial, we will use a dataset from UCI called Default of Credit Card Clients Dataset. This dataset contains information on default payments, demographic factors, credit data, payment history, and billing statements of credit card clients in Taiwan from April 2005 to September 2005. There are 24,000 samples and 25 features. Short descriptions of each column are as follows: ID: ID of each client LIMIT_BAL: Amount of given credit in NT dollars (includes individual and family/supplementary credit) SEX: Gender (1=male, 2=female) EDUCATION: (1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown) MARRIAGE: Marital status (1=married, 2=single, 3=others) AGE: Age in years PAY_0 to PAY_6: Repayment status by n months ago (PAY_0 = last month ... PAY_6 = 6 months ago) (Labels: -1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above) BILL_AMT1 to BILL_AMT6: Amount of bill statement by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago) PAY_AMT1 to PAY_AMT6: Amount of payment by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago) default: Default payment (1=yes, 0=no) Target Column Lichman, M. (2013). UCI Machine Learning Repository. Irvine, CA: University of California, School of Information and Computer Science. You can download the data from the original source found here and load it using pandas (learn how) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require an internet connection). # loading the datasetfrom pycaret.datasets import get_datadataset = get_data('credit') # check the shape of datadataset.shape>>> (24000, 24) In order to demonstrate the use of the predict_model function on unseen data, a sample of 1200 records (~5%) has been withheld from the original dataset to be used for predictions at the end. This should not be confused with a train-test-split, as this particular split is performed to simulate a real-life scenario. Another way to think about this is that these 1200 customers are not available at the time of training of machine learning models. # sample 5% of data to be used as unseen datadata = dataset.sample(frac=0.95, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(inplace=True, drop=True)data_unseen.reset_index(inplace=True, drop=True)# print the revised shapeprint('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (22800, 24)>>> Unseen Data For Predictions: (1200, 24) The setup function in PyCaret initializes the environment and creates the transformation pipeline for modeling and deployment. setup must be called before executing any other function in pycaret. It takes two mandatory parameters: a pandas dataframe and the name of the target column. All other parameters are optional can be used to customize the preprocessing pipeline. When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To handle this, PyCaret displays a prompt, asking for data types confirmation, once you execute the setup. You can press enter if all data types are correct or type quit to exit the setup. Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models. Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types. # init setupfrom pycaret.classification import *s = setup(data = data, target = 'default', session_id=123) Once the setup has been successfully executed it displays the information grid which contains some important information about the experiment. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for this tutorial, however, a few important things to note are: session_id: A pseudo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility. Target Type: Binary or Multiclass. The Target type is automatically detected and shown. There is no difference in how the experiment is performed for Binary or Multiclass problems. All functionalities are identical. Label Encoded: When the Target variable is of type string (i.e. ‘Yes’ or ‘No’) instead of 1 or 0, it automatically encodes the label into 1 and 0 and displays the mapping (0: No, 1: Yes) for reference. In this experiment, no label encoding is required since the target variable is of type numeric. Original Data: Displays the original shape of the dataset. In this experiment (22800, 24) means 22,800 samples and 24 features including the target column. Missing Values: When there are missing values in the original data this will show as True. For this experiment, there are no missing values in the dataset. Numeric Features: The number of features inferred as numeric. In this dataset, 14 out of 24 features are inferred as numeric. Categorical Features: The number of features inferred as categorical. In this dataset, 9 out of 24 features are inferred as categorical. Transformed Train Set: Displays the shape of the transformed training set. Notice that the original shape of (22800, 24) is transformed into (15959, 91) for the transformed train set and the number of features has increased to 91 from 24 due to one-hot-encoding. Transformed Test Set: Displays the shape of the transformed test/hold-out set. There are 6841 samples in the test/hold-out set. This split is based on the default value of 70/30 that can be changed using the train_size parameter in the setup. Notice how a few tasks that are imperative to perform modeling are automatically handled such as missing value imputation (in this case there are no missing values in the training data, but we still need imputers for unseen data), categorical encoding, etc. Most of the parameters in the setup are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but we will cover them in future tutorials. Comparing all models to evaluate performance is the recommended starting point for modeling once the setup is completed (unless you exactly know what kind of model you need, which is often not the case). This function trains all models in the model library and scores them using stratified cross-validation for metric evaluation. The output prints a scoring grid that shows average Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC across the folds (10 by default) along with training times. best_model = compare_models() The scoring grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using Accuracy (highest to lowest) which can be changed by passing the sort parameter. For example compare_models(sort = 'Recall') will sort the grid by recall instead of accuracy. If you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For example compare_models(fold = 5) will compare all models on 5 fold cross-validation. Reducing the number of folds will improve the training time. By default, compare_models return the best performing model based on default sort order but can be used to return a list of top N models by using n_select parameter. print(best_model)>>> OUTPUTRidgeClassifier(alpha=1.0, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=123, solver='auto', tol=0.001) create_model is the most granular function in PyCaret and is often the foundation behind most of the PyCaret functionalities. As the name suggests this function trains and evaluates a model using cross-validation that can be set with fold parameter. The output prints a scoring grid that shows Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC by fold. For the remaining part of this tutorial, we will work with the below models as our candidate models. The selections are for illustration purposes only and do not necessarily mean they are the top-performing or ideal for this type of data. Decision Tree Classifier (‘dt’) K Neighbors Classifier (‘knn’) Random Forest Classifier (‘rf’) There are 18 classifiers available in the model library of PyCaret. To see a list of all classifiers either check the documentation or use models function to see the library. # check available modelsmodels() dt = create_model('dt') # trained model object is stored in the variable 'dt'. print(dt)>>> OUTPUTDecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini', max_depth=None, max_features=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, presort='deprecated', random_state=123, splitter='best') knn = create_model('knn') rf = create_model('rf') Notice that the mean score of all models matches with the score printed in compare_models. This is because the metrics printed in the compare_models score grid are the average scores across all CV folds. Similar to thecompare_models, if you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For Example: create_model('dt', fold = 5) will create a Decision Tree Classifier using 5 fold stratified CV. When a model is created using the create_model function it uses the default hyperparameters to train the model. In order to tune hyperparameters, the tune_model function is used. This function automatically tunes the hyperparameters of a model using random grid search on a pre-defined search space. The output prints a scoring grid that shows Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC by fold for the best model. To use the custom search grid, you can pass custom_grid parameter in the tune_model function (see 11.2 KNN tuning below). tuned_dt = tune_model(dt) # tuned model object is stored in the variable 'tuned_dt'. print(tuned_dt)>>> OUTPUTDecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy', max_depth=6, max_features=1.0, max_leaf_nodes=None, min_impurity_decrease=0.002, min_impurity_split=None, min_samples_leaf=5, min_samples_split=5, min_weight_fraction_leaf=0.0, presort='deprecated', random_state=123, splitter='best') import numpy as nptuned_knn = tune_model(knn, custom_grid = {'n_neighbors' : np.arange(0,50,1)}) print(tuned_knn)>>> OUTPUTKNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=-1, n_neighbors=42, p=2, weights='uniform') tuned_rf = tune_model(rf) By default, tune_model optimizes Accuracy but this can be changed using optimize parameter. For example: tune_model(dt, optimize = 'AUC') will search for the hyperparameters of a Decision Tree Classifier that results in the highest AUC instead of Accuracy. For the purposes of this example, we have used the default metric Accuracy only for the sake of simplicity. Generally, when the dataset is imbalanced (such as the credit dataset we are working with) Accuracy is not a good metric for consideration. The methodology behind selecting the right metric to evaluate a classifier is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to read an article on how to choose the right evaluation metric. Metrics alone are not the only criteria you should consider when finalizing the best model for production. Other factors to consider include training time, the standard deviation of kfolds, etc. As you progress through the tutorial series we will discuss those factors in detail at the intermediate and expert levels. For now, let’s move forward considering the Tuned Random Forest Classifier tuned_rf, as our best model for the remainder of this tutorial. Before model finalization, the plot_model function can be used to analyze the performance across different aspects such as AUC, confusion_matrix, decision boundary, etc. This function takes a trained model object and returns a plot based on the test set. There are 15 different plots available, please see the plot_model documentation for the list of available plots. plot_model(tuned_rf, plot = 'auc') plot_model(tuned_rf, plot = 'pr') plot_model(tuned_rf, plot='feature') plot_model(tuned_rf, plot = 'confusion_matrix') Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function. evaluate_model(tuned_rf) Before finalizing the model, it is advisable to perform one final check by predicting the test/hold-out set and reviewing the evaluation metrics. If you look at the information grid in Section 8 above, you will see that 30% (6,841 samples) of the data has been separated out as a test/hold-out sample. All of the evaluation metrics we have seen above are cross-validated results based on the training set (70%). Now, using our final trained model stored in the tuned_rf we will predict the test / hold-out sample and evaluate the metrics to see if they are materially different than the CV results. predict_model(tuned_rf); The accuracy on the test/hold-out set is 0.8116 compared to 0.8203 achieved on the tuned_rf CV results (in section 11.3 above). This is not a significant difference. If there is a large variation between the test/hold-out and CV results, then this would normally indicate over-fitting but could also be due to several other factors and would require further investigation. In this case, we will move forward with finalizing the model and predicting on unseen data (the 5% that we had separated in the beginning and never exposed to PyCaret). (TIP: It’s always good to look at the standard deviation of CV results when using create_model) Model finalization is the last step in the experiment. A normal machine learning workflow in PyCaret starts with setup, followed by comparing all models using the compare_models and shortlisting a few candidate models (based on the metric of interest) to perform several modeling techniques such as hyperparameter tuning, ensembling, stacking, etc. This workflow will eventually lead you to the best model for use in making predictions on new and unseen data. The finalize_model function fits the model onto the complete dataset including the test/hold-out sample (30% in this case). The purpose of this function is to train the final model on the complete dataset before it is deployed in production. (This is optional, you may or may not use finalize_model). # finalize rf modelfinal_rf = finalize_model(tuned_rf)# print final model parametersprint(final_rf)>>> OUTPUTRandomForestClassifier(bootstrap=False, ccp_alpha=0.0, class_weight={}, criterion='entropy', max_depth=5, max_features=1.0, max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0002, min_impurity_split=None, min_samples_leaf=5, min_samples_split=10, min_weight_fraction_leaf=0.0, n_estimators=150, n_jobs=-1, oob_score=False, random_state=123, verbose=0, warm_start=False) Caution: One final word of caution. Once the model is finalized, the entire dataset including the test/hold-out set is used for training. As such, if the model is used for predictions on the hold-out set after finalize_model is used, the information grid printed will be misleading as you are trying to predict on the same data that was used for modeling. In order to demonstrate this point only, we will use final_rf under predict_model to compare the information grid with the one above in section 13. predict_model(final_rf); Notice how the AUC in final_rf has increased to 0.7526 from 0.7407, even though the model is the same. This is because the final_rf variable has been trained on the complete dataset including the test/hold-out set. The predict_model function is also used to predict on the unseen dataset. The only difference from section 13 above is that this time we will pass the data_unseen. It is the variable created at the beginning of this tutorial and contains 5% (1200 samples) of the original dataset which was never exposed to PyCaret. (see section 7 for explanation) unseen_predictions = predict_model(final_rf, data=data_unseen)unseen_predictions.head() The Label and Score columns are added onto the data_unseen set. The label is the prediction and the score is the probability of the prediction. Notice that predicted results are concatenated to the original dataset while all the transformations are automatically performed in the background. You can also check the metrics on this since you have an actual target column default available. To do that we will use pycaret.utils module. See the example below: # check metric on unseen datafrom pycaret.utils import check_metriccheck_metric(unseen_predictions['default'], unseen_predictions['Label'], metric = 'Accuracy')>>> OUTPUT0.8167 We have now finished the experiment by finalizing the tuned_rf model which is now stored in final_rf variable. We have also used the model stored in final_rf to predict data_unseen. This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret's inbuilt function save_model() allows you to save the model along with the entire transformation pipeline for later use. # saving the final modelsave_model(final_rf,'Final RF Model 11Nov2020')>>> Transformation Pipeline and Model Successfully Saved To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction. # loading the saved modelsaved_final_rf = load_model('Final RF Model 11Nov2020')>>> Transformation Pipeline and Model Successfully Loaded Once the model is loaded in the environment, you can simply use it to predict on any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above. # predict on new datanew_prediction = predict_model(saved_final_rf, data=data_unseen)new_prediction.head() Notice that the results of unseen_predictions and new_prediction are identical. from pycaret.utils import check_metriccheck_metric(new_prediction['default'], new_prediction['Label'], metric = 'Accuracy')>>> 0.8167 This tutorial has covered the entire machine learning pipeline from data ingestion, pre-processing, training the model, hyperparameter tuning, prediction, and saving the model for later use. We have completed all of these steps in less than 10 commands which are naturally constructed and very intuitive to remember such as create_model(), tune_model(), compare_models(). Re-creating the entire experiment without PyCaret would have taken well over 100 lines of code in most libraries. We have only covered the basics of pycaret.classification. In the future tutorials we will go deeper into advanced pre-processing, ensembling, generalized stacking, and other techniques that allow you to fully customize your machine learning pipeline and are must know for any data scientist. Thank you for reading 🙏 ⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan. I write about PyCaret and its use-cases in the real world, If you would like to be notified automatically, you can follow me on Medium, LinkedIn, and Twitter.
[ { "code": null, "e": 430, "s": 172, "text": "PyCaret is an open-source, low-code machine learning library in Python that automates machine learning workflows. It is an end-to-end machine learning and model management tool that speeds up the experiment cycle exponentially and makes you more productive." }, { "code": null, "e": 866, "s": 430, "text": "In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes experiments exponentially fast and efficient. PyCaret is essentially a Python wrapper around several machine learning libraries and frameworks such as scikit-learn, XGBoost, LightGBM, CatBoost, spaCy, Optuna, Hyperopt, Ray, and a few more." }, { "code": null, "e": 1171, "s": 866, "text": "The design and simplicity of PyCaret are inspired by the emerging role of citizen data scientists, a term first used by Gartner. Citizen Data Scientists are power users who can perform both simple and moderately sophisticated analytical tasks that would previously have required more technical expertise." }, { "code": null, "e": 1246, "s": 1171, "text": "To learn more about PyCaret, you can check the official website or GitHub." }, { "code": null, "e": 1278, "s": 1246, "text": "In this tutorial we will learn:" }, { "code": null, "e": 1339, "s": 1278, "text": "Getting Data: How to import data from the PyCaret repository" }, { "code": null, "e": 1454, "s": 1339, "text": "Setting up Environment: How to set up an experiment in PyCaret and get started with building classification models" }, { "code": null, "e": 1563, "s": 1454, "text": "Create Model: How to create a model, perform stratified cross-validation and evaluate classification metrics" }, { "code": null, "e": 1648, "s": 1563, "text": "Tune Model: How to automatically tune the hyper-parameters of a classification model" }, { "code": null, "e": 1713, "s": 1648, "text": "Plot Model: How to analyze model performance using various plots" }, { "code": null, "e": 1789, "s": 1713, "text": "Finalize Model: How to finalize the best model at the end of the experiment" }, { "code": null, "e": 1843, "s": 1789, "text": "Predict Model: How to make predictions on unseen data" }, { "code": null, "e": 1902, "s": 1843, "text": "Save / Load Model: How to save/load a model for future use" }, { "code": null, "e": 2069, "s": 1902, "text": "Installation is easy and will only take a few minutes. PyCaret’s default installation from pip only installs hard dependencies as listed in the requirements.txt file." }, { "code": null, "e": 2089, "s": 2069, "text": "pip install pycaret" }, { "code": null, "e": 2118, "s": 2089, "text": "To install the full version:" }, { "code": null, "e": 2145, "s": 2118, "text": "pip install pycaret[full] " }, { "code": null, "e": 2425, "s": 2145, "text": "Binary classification is a supervised machine learning technique where the goal is to predict categorical class labels which are discrete and unordered such as Pass/Fail, Positive/Negative, Default/Not-Default, etc. A few real-world use cases for classification are listed below:" }, { "code": null, "e": 2558, "s": 2425, "text": "Medical testing to determine if a patient has a certain disease or not — the classification property is the presence of the disease." }, { "code": null, "e": 2706, "s": 2558, "text": "A “pass or fail” test method or quality control in factories, i.e. deciding if a specification has or has not been met — a go/no-go classification." }, { "code": null, "e": 2914, "s": 2706, "text": "Information retrieval, namely deciding whether a page or an article should be in the result set of a search or not — the classification property is the relevance of the article or the usefulness to the user." }, { "code": null, "e": 3299, "s": 2914, "text": "PyCaret’s classification module (pycaret.classification) is a supervised machine learning module that is used for classifying the elements into a binary group based on various techniques and algorithms. Some common use cases of classification problems include predicting customer default (yes or no), customer churn (customer will leave or stay), disease found (positive or negative)." }, { "code": null, "e": 3597, "s": 3299, "text": "The PyCaret classification module can be used for Binary or Multi-class classification problems. It has over 18 algorithms and 14 plots to analyze the performance of models. Be it hyper-parameter tuning, ensembling, or advanced techniques like stacking, PyCaret’s classification module has it all." }, { "code": null, "e": 3983, "s": 3597, "text": "For this tutorial, we will use a dataset from UCI called Default of Credit Card Clients Dataset. This dataset contains information on default payments, demographic factors, credit data, payment history, and billing statements of credit card clients in Taiwan from April 2005 to September 2005. There are 24,000 samples and 25 features. Short descriptions of each column are as follows:" }, { "code": null, "e": 4005, "s": 3983, "text": "ID: ID of each client" }, { "code": null, "e": 4107, "s": 4005, "text": "LIMIT_BAL: Amount of given credit in NT dollars (includes individual and family/supplementary credit)" }, { "code": null, "e": 4138, "s": 4107, "text": "SEX: Gender (1=male, 2=female)" }, { "code": null, "e": 4230, "s": 4138, "text": "EDUCATION: (1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown)" }, { "code": null, "e": 4287, "s": 4230, "text": "MARRIAGE: Marital status (1=married, 2=single, 3=others)" }, { "code": null, "e": 4305, "s": 4287, "text": "AGE: Age in years" }, { "code": null, "e": 4566, "s": 4305, "text": "PAY_0 to PAY_6: Repayment status by n months ago (PAY_0 = last month ... PAY_6 = 6 months ago) (Labels: -1=pay duly, 1=payment delay for one month, 2=payment delay for two months, ... 8=payment delay for eight months, 9=payment delay for nine months and above)" }, { "code": null, "e": 4685, "s": 4566, "text": "BILL_AMT1 to BILL_AMT6: Amount of bill statement by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago)" }, { "code": null, "e": 4795, "s": 4685, "text": "PAY_AMT1 to PAY_AMT6: Amount of payment by n months ago ( BILL_AMT1 = last_month .. BILL_AMT6 = 6 months ago)" }, { "code": null, "e": 4848, "s": 4795, "text": "default: Default payment (1=yes, 0=no) Target Column" }, { "code": null, "e": 4983, "s": 4848, "text": "Lichman, M. (2013). UCI Machine Learning Repository. Irvine, CA: University of California, School of Information and Computer Science." }, { "code": null, "e": 5214, "s": 4983, "text": "You can download the data from the original source found here and load it using pandas (learn how) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require an internet connection)." }, { "code": null, "e": 5301, "s": 5214, "text": "# loading the datasetfrom pycaret.datasets import get_datadataset = get_data('credit')" }, { "code": null, "e": 5355, "s": 5301, "text": "# check the shape of datadataset.shape>>> (24000, 24)" }, { "code": null, "e": 5803, "s": 5355, "text": "In order to demonstrate the use of the predict_model function on unseen data, a sample of 1200 records (~5%) has been withheld from the original dataset to be used for predictions at the end. This should not be confused with a train-test-split, as this particular split is performed to simulate a real-life scenario. Another way to think about this is that these 1200 customers are not available at the time of training of machine learning models." }, { "code": null, "e": 6237, "s": 5803, "text": "# sample 5% of data to be used as unseen datadata = dataset.sample(frac=0.95, random_state=786)data_unseen = dataset.drop(data.index)data.reset_index(inplace=True, drop=True)data_unseen.reset_index(inplace=True, drop=True)# print the revised shapeprint('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))>>> Data for Modeling: (22800, 24)>>> Unseen Data For Predictions: (1200, 24)" }, { "code": null, "e": 6609, "s": 6237, "text": "The setup function in PyCaret initializes the environment and creates the transformation pipeline for modeling and deployment. setup must be called before executing any other function in pycaret. It takes two mandatory parameters: a pandas dataframe and the name of the target column. All other parameters are optional can be used to customize the preprocessing pipeline." }, { "code": null, "e": 7014, "s": 6609, "text": "When setup is executed, PyCaret's inference algorithm will automatically infer the data types for all features based on certain properties. The data type should be inferred correctly but this is not always the case. To handle this, PyCaret displays a prompt, asking for data types confirmation, once you execute the setup. You can press enter if all data types are correct or type quit to exit the setup." }, { "code": null, "e": 7208, "s": 7014, "text": "Ensuring that the data types are correct is really important in PyCaret as it automatically performs multiple type-specific preprocessing tasks which are imperative for machine learning models." }, { "code": null, "e": 7336, "s": 7208, "text": "Alternatively, you can also use numeric_features and categorical_features parameters in the setup to pre-define the data types." }, { "code": null, "e": 7443, "s": 7336, "text": "# init setupfrom pycaret.classification import *s = setup(data = data, target = 'default', session_id=123)" }, { "code": null, "e": 7809, "s": 7443, "text": "Once the setup has been successfully executed it displays the information grid which contains some important information about the experiment. Most of the information is related to the pre-processing pipeline which is constructed when setup is executed. The majority of these features are out of scope for this tutorial, however, a few important things to note are:" }, { "code": null, "e": 8095, "s": 7809, "text": "session_id: A pseudo-random number distributed as a seed in all functions for later reproducibility. If no session_id is passed, a random number is automatically generated that is distributed to all functions. In this experiment, the session_id is set as 123 for later reproducibility." }, { "code": null, "e": 8311, "s": 8095, "text": "Target Type: Binary or Multiclass. The Target type is automatically detected and shown. There is no difference in how the experiment is performed for Binary or Multiclass problems. All functionalities are identical." }, { "code": null, "e": 8609, "s": 8311, "text": "Label Encoded: When the Target variable is of type string (i.e. ‘Yes’ or ‘No’) instead of 1 or 0, it automatically encodes the label into 1 and 0 and displays the mapping (0: No, 1: Yes) for reference. In this experiment, no label encoding is required since the target variable is of type numeric." }, { "code": null, "e": 8765, "s": 8609, "text": "Original Data: Displays the original shape of the dataset. In this experiment (22800, 24) means 22,800 samples and 24 features including the target column." }, { "code": null, "e": 8921, "s": 8765, "text": "Missing Values: When there are missing values in the original data this will show as True. For this experiment, there are no missing values in the dataset." }, { "code": null, "e": 9047, "s": 8921, "text": "Numeric Features: The number of features inferred as numeric. In this dataset, 14 out of 24 features are inferred as numeric." }, { "code": null, "e": 9184, "s": 9047, "text": "Categorical Features: The number of features inferred as categorical. In this dataset, 9 out of 24 features are inferred as categorical." }, { "code": null, "e": 9447, "s": 9184, "text": "Transformed Train Set: Displays the shape of the transformed training set. Notice that the original shape of (22800, 24) is transformed into (15959, 91) for the transformed train set and the number of features has increased to 91 from 24 due to one-hot-encoding." }, { "code": null, "e": 9690, "s": 9447, "text": "Transformed Test Set: Displays the shape of the transformed test/hold-out set. There are 6841 samples in the test/hold-out set. This split is based on the default value of 70/30 that can be changed using the train_size parameter in the setup." }, { "code": null, "e": 10147, "s": 9690, "text": "Notice how a few tasks that are imperative to perform modeling are automatically handled such as missing value imputation (in this case there are no missing values in the training data, but we still need imputers for unseen data), categorical encoding, etc. Most of the parameters in the setup are optional and used for customizing the pre-processing pipeline. These parameters are out of scope for this tutorial but we will cover them in future tutorials." }, { "code": null, "e": 10642, "s": 10147, "text": "Comparing all models to evaluate performance is the recommended starting point for modeling once the setup is completed (unless you exactly know what kind of model you need, which is often not the case). This function trains all models in the model library and scores them using stratified cross-validation for metric evaluation. The output prints a scoring grid that shows average Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC across the folds (10 by default) along with training times." }, { "code": null, "e": 10672, "s": 10642, "text": "best_model = compare_models()" }, { "code": null, "e": 10985, "s": 10672, "text": "The scoring grid printed above highlights the highest performing metric for comparison purposes only. The grid by default is sorted using Accuracy (highest to lowest) which can be changed by passing the sort parameter. For example compare_models(sort = 'Recall') will sort the grid by recall instead of accuracy." }, { "code": null, "e": 11429, "s": 10985, "text": "If you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For example compare_models(fold = 5) will compare all models on 5 fold cross-validation. Reducing the number of folds will improve the training time. By default, compare_models return the best performing model based on default sort order but can be used to return a list of top N models by using n_select parameter." }, { "code": null, "e": 11641, "s": 11429, "text": "print(best_model)>>> OUTPUTRidgeClassifier(alpha=1.0, class_weight=None, copy_X=True, fit_intercept=True, max_iter=None, normalize=False, random_state=123, solver='auto', tol=0.001)" }, { "code": null, "e": 11997, "s": 11641, "text": "create_model is the most granular function in PyCaret and is often the foundation behind most of the PyCaret functionalities. As the name suggests this function trains and evaluates a model using cross-validation that can be set with fold parameter. The output prints a scoring grid that shows Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC by fold." }, { "code": null, "e": 12236, "s": 11997, "text": "For the remaining part of this tutorial, we will work with the below models as our candidate models. The selections are for illustration purposes only and do not necessarily mean they are the top-performing or ideal for this type of data." }, { "code": null, "e": 12268, "s": 12236, "text": "Decision Tree Classifier (‘dt’)" }, { "code": null, "e": 12299, "s": 12268, "text": "K Neighbors Classifier (‘knn’)" }, { "code": null, "e": 12331, "s": 12299, "text": "Random Forest Classifier (‘rf’)" }, { "code": null, "e": 12506, "s": 12331, "text": "There are 18 classifiers available in the model library of PyCaret. To see a list of all classifiers either check the documentation or use models function to see the library." }, { "code": null, "e": 12539, "s": 12506, "text": "# check available modelsmodels()" }, { "code": null, "e": 12563, "s": 12539, "text": "dt = create_model('dt')" }, { "code": null, "e": 13058, "s": 12563, "text": "# trained model object is stored in the variable 'dt'. print(dt)>>> OUTPUTDecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini', max_depth=None, max_features=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, presort='deprecated', random_state=123, splitter='best')" }, { "code": null, "e": 13084, "s": 13058, "text": "knn = create_model('knn')" }, { "code": null, "e": 13108, "s": 13084, "text": "rf = create_model('rf')" }, { "code": null, "e": 13579, "s": 13108, "text": "Notice that the mean score of all models matches with the score printed in compare_models. This is because the metrics printed in the compare_models score grid are the average scores across all CV folds. Similar to thecompare_models, if you want to change the fold parameter from the default value of 10 to a different value then you can use the fold parameter. For Example: create_model('dt', fold = 5) will create a Decision Tree Classifier using 5 fold stratified CV." }, { "code": null, "e": 14126, "s": 13579, "text": "When a model is created using the create_model function it uses the default hyperparameters to train the model. In order to tune hyperparameters, the tune_model function is used. This function automatically tunes the hyperparameters of a model using random grid search on a pre-defined search space. The output prints a scoring grid that shows Accuracy, AUC, Recall, Precision, F1, Kappa, and MCC by fold for the best model. To use the custom search grid, you can pass custom_grid parameter in the tune_model function (see 11.2 KNN tuning below)." }, { "code": null, "e": 14152, "s": 14126, "text": "tuned_dt = tune_model(dt)" }, { "code": null, "e": 14658, "s": 14152, "text": "# tuned model object is stored in the variable 'tuned_dt'. print(tuned_dt)>>> OUTPUTDecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='entropy', max_depth=6, max_features=1.0, max_leaf_nodes=None, min_impurity_decrease=0.002, min_impurity_split=None, min_samples_leaf=5, min_samples_split=5, min_weight_fraction_leaf=0.0, presort='deprecated', random_state=123, splitter='best')" }, { "code": null, "e": 14755, "s": 14658, "text": "import numpy as nptuned_knn = tune_model(knn, custom_grid = {'n_neighbors' : np.arange(0,50,1)})" }, { "code": null, "e": 14965, "s": 14755, "text": "print(tuned_knn)>>> OUTPUTKNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=-1, n_neighbors=42, p=2, weights='uniform')" }, { "code": null, "e": 14991, "s": 14965, "text": "tuned_rf = tune_model(rf)" }, { "code": null, "e": 15738, "s": 14991, "text": "By default, tune_model optimizes Accuracy but this can be changed using optimize parameter. For example: tune_model(dt, optimize = 'AUC') will search for the hyperparameters of a Decision Tree Classifier that results in the highest AUC instead of Accuracy. For the purposes of this example, we have used the default metric Accuracy only for the sake of simplicity. Generally, when the dataset is imbalanced (such as the credit dataset we are working with) Accuracy is not a good metric for consideration. The methodology behind selecting the right metric to evaluate a classifier is beyond the scope of this tutorial but if you would like to learn more about it, you can click here to read an article on how to choose the right evaluation metric." }, { "code": null, "e": 16195, "s": 15738, "text": "Metrics alone are not the only criteria you should consider when finalizing the best model for production. Other factors to consider include training time, the standard deviation of kfolds, etc. As you progress through the tutorial series we will discuss those factors in detail at the intermediate and expert levels. For now, let’s move forward considering the Tuned Random Forest Classifier tuned_rf, as our best model for the remainder of this tutorial." }, { "code": null, "e": 16450, "s": 16195, "text": "Before model finalization, the plot_model function can be used to analyze the performance across different aspects such as AUC, confusion_matrix, decision boundary, etc. This function takes a trained model object and returns a plot based on the test set." }, { "code": null, "e": 16563, "s": 16450, "text": "There are 15 different plots available, please see the plot_model documentation for the list of available plots." }, { "code": null, "e": 16598, "s": 16563, "text": "plot_model(tuned_rf, plot = 'auc')" }, { "code": null, "e": 16632, "s": 16598, "text": "plot_model(tuned_rf, plot = 'pr')" }, { "code": null, "e": 16669, "s": 16632, "text": "plot_model(tuned_rf, plot='feature')" }, { "code": null, "e": 16717, "s": 16669, "text": "plot_model(tuned_rf, plot = 'confusion_matrix')" }, { "code": null, "e": 16934, "s": 16717, "text": "Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function." }, { "code": null, "e": 16959, "s": 16934, "text": "evaluate_model(tuned_rf)" }, { "code": null, "e": 17558, "s": 16959, "text": "Before finalizing the model, it is advisable to perform one final check by predicting the test/hold-out set and reviewing the evaluation metrics. If you look at the information grid in Section 8 above, you will see that 30% (6,841 samples) of the data has been separated out as a test/hold-out sample. All of the evaluation metrics we have seen above are cross-validated results based on the training set (70%). Now, using our final trained model stored in the tuned_rf we will predict the test / hold-out sample and evaluate the metrics to see if they are materially different than the CV results." }, { "code": null, "e": 17583, "s": 17558, "text": "predict_model(tuned_rf);" }, { "code": null, "e": 18125, "s": 17583, "text": "The accuracy on the test/hold-out set is 0.8116 compared to 0.8203 achieved on the tuned_rf CV results (in section 11.3 above). This is not a significant difference. If there is a large variation between the test/hold-out and CV results, then this would normally indicate over-fitting but could also be due to several other factors and would require further investigation. In this case, we will move forward with finalizing the model and predicting on unseen data (the 5% that we had separated in the beginning and never exposed to PyCaret)." }, { "code": null, "e": 18221, "s": 18125, "text": "(TIP: It’s always good to look at the standard deviation of CV results when using create_model)" }, { "code": null, "e": 18982, "s": 18221, "text": "Model finalization is the last step in the experiment. A normal machine learning workflow in PyCaret starts with setup, followed by comparing all models using the compare_models and shortlisting a few candidate models (based on the metric of interest) to perform several modeling techniques such as hyperparameter tuning, ensembling, stacking, etc. This workflow will eventually lead you to the best model for use in making predictions on new and unseen data. The finalize_model function fits the model onto the complete dataset including the test/hold-out sample (30% in this case). The purpose of this function is to train the final model on the complete dataset before it is deployed in production. (This is optional, you may or may not use finalize_model)." }, { "code": null, "e": 19628, "s": 18982, "text": "# finalize rf modelfinal_rf = finalize_model(tuned_rf)# print final model parametersprint(final_rf)>>> OUTPUTRandomForestClassifier(bootstrap=False, ccp_alpha=0.0, class_weight={}, criterion='entropy', max_depth=5, max_features=1.0, max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0002, min_impurity_split=None, min_samples_leaf=5, min_samples_split=10, min_weight_fraction_leaf=0.0, n_estimators=150, n_jobs=-1, oob_score=False, random_state=123, verbose=0, warm_start=False)" }, { "code": null, "e": 20132, "s": 19628, "text": "Caution: One final word of caution. Once the model is finalized, the entire dataset including the test/hold-out set is used for training. As such, if the model is used for predictions on the hold-out set after finalize_model is used, the information grid printed will be misleading as you are trying to predict on the same data that was used for modeling. In order to demonstrate this point only, we will use final_rf under predict_model to compare the information grid with the one above in section 13." }, { "code": null, "e": 20157, "s": 20132, "text": "predict_model(final_rf);" }, { "code": null, "e": 20372, "s": 20157, "text": "Notice how the AUC in final_rf has increased to 0.7526 from 0.7407, even though the model is the same. This is because the final_rf variable has been trained on the complete dataset including the test/hold-out set." }, { "code": null, "e": 20720, "s": 20372, "text": "The predict_model function is also used to predict on the unseen dataset. The only difference from section 13 above is that this time we will pass the data_unseen. It is the variable created at the beginning of this tutorial and contains 5% (1200 samples) of the original dataset which was never exposed to PyCaret. (see section 7 for explanation)" }, { "code": null, "e": 20808, "s": 20720, "text": "unseen_predictions = predict_model(final_rf, data=data_unseen)unseen_predictions.head()" }, { "code": null, "e": 21265, "s": 20808, "text": "The Label and Score columns are added onto the data_unseen set. The label is the prediction and the score is the probability of the prediction. Notice that predicted results are concatenated to the original dataset while all the transformations are automatically performed in the background. You can also check the metrics on this since you have an actual target column default available. To do that we will use pycaret.utils module. See the example below:" }, { "code": null, "e": 21442, "s": 21265, "text": "# check metric on unseen datafrom pycaret.utils import check_metriccheck_metric(unseen_predictions['default'], unseen_predictions['Label'], metric = 'Accuracy')>>> OUTPUT0.8167" }, { "code": null, "e": 21964, "s": 21442, "text": "We have now finished the experiment by finalizing the tuned_rf model which is now stored in final_rf variable. We have also used the model stored in final_rf to predict data_unseen. This brings us to the end of our experiment, but one question is still to be asked: What happens when you have more new data to predict? Do you have to go through the entire experiment again? The answer is no, PyCaret's inbuilt function save_model() allows you to save the model along with the entire transformation pipeline for later use." }, { "code": null, "e": 22092, "s": 21964, "text": "# saving the final modelsave_model(final_rf,'Final RF Model 11Nov2020')>>> Transformation Pipeline and Model Successfully Saved" }, { "code": null, "e": 22292, "s": 22092, "text": "To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction." }, { "code": null, "e": 22430, "s": 22292, "text": "# loading the saved modelsaved_final_rf = load_model('Final RF Model 11Nov2020')>>> Transformation Pipeline and Model Successfully Loaded" }, { "code": null, "e": 22670, "s": 22430, "text": "Once the model is loaded in the environment, you can simply use it to predict on any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in section 13 above." }, { "code": null, "e": 22777, "s": 22670, "text": "# predict on new datanew_prediction = predict_model(saved_final_rf, data=data_unseen)new_prediction.head()" }, { "code": null, "e": 22857, "s": 22777, "text": "Notice that the results of unseen_predictions and new_prediction are identical." }, { "code": null, "e": 22991, "s": 22857, "text": "from pycaret.utils import check_metriccheck_metric(new_prediction['default'], new_prediction['Label'], metric = 'Accuracy')>>> 0.8167" }, { "code": null, "e": 23477, "s": 22991, "text": "This tutorial has covered the entire machine learning pipeline from data ingestion, pre-processing, training the model, hyperparameter tuning, prediction, and saving the model for later use. We have completed all of these steps in less than 10 commands which are naturally constructed and very intuitive to remember such as create_model(), tune_model(), compare_models(). Re-creating the entire experiment without PyCaret would have taken well over 100 lines of code in most libraries." }, { "code": null, "e": 23770, "s": 23477, "text": "We have only covered the basics of pycaret.classification. In the future tutorials we will go deeper into advanced pre-processing, ensembling, generalized stacking, and other techniques that allow you to fully customize your machine learning pipeline and are must know for any data scientist." }, { "code": null, "e": 23794, "s": 23770, "text": "Thank you for reading 🙏" }, { "code": null, "e": 24222, "s": 23794, "text": "⭐ Tutorials New to PyCaret? Check out our official notebooks!📋 Example Notebooks created by the community.📙 Blog Tutorials and articles by contributors.📚 Documentation The detailed API docs of PyCaret📺 Video Tutorials Our video tutorial from various events.📢 Discussions Have questions? Engage with community and contributors.🛠️ Changelog Changes and version history.🌳 Roadmap PyCaret’s software and community development plan." } ]
What is nodeValue property in JavaScript HTML DOM?
The nodeValue property is used to get the node value. You need to specify the node. You can try to run the following code to learn how to get nodeValue property. Live Demo <!DOCTYPE html> <html> <body> <p>Get the node value</p> <button>Demo Button Text</button> <script> var val = document.getElementsByTagName("BUTTON")[0]; var res = val.childNodes[0].nodeValue; document.write("<br>Node Value: "+res); </script> </body> </html>
[ { "code": null, "e": 1146, "s": 1062, "text": "The nodeValue property is used to get the node value. You need to specify the node." }, { "code": null, "e": 1224, "s": 1146, "text": "You can try to run the following code to learn how to get nodeValue property." }, { "code": null, "e": 1234, "s": 1224, "text": "Live Demo" }, { "code": null, "e": 1549, "s": 1234, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Get the node value</p>\n <button>Demo Button Text</button>\n <script>\n var val = document.getElementsByTagName(\"BUTTON\")[0];\n var res = val.childNodes[0].nodeValue;\n document.write(\"<br>Node Value: \"+res);\n </script>\n </body>\n</html>" } ]
sfdisk - Unix, Linux Command
sfdisk doesn’t understand GUID Partition Table (GPT) and it is not designed for large partitions. In particular case use more advanced GNU parted(8). % sfdisk -s /dev/hda9 81599 % % sfdisk -s /dev/hda: 208896 /dev/hdb: 1025136 /dev/hdc: 1031063 /dev/sda: 8877895 /dev/sdb: 1758927 total: 12901917 blocks % % sfdisk -l /dev/hdc Disk /dev/hdc: 16 heads, 63 sectors, 2045 cylinders Units = cylinders of 516096 bytes, blocks of 1024 bytes, counting from 0 Device Boot Start End #cyls #blocks Id System /dev/hdc1 0+ 406 407- 205096+ 83 Linux native /dev/hdc2 407 813 407 205128 83 Linux native /dev/hdc3 814 2044 1231 620424 83 Linux native /dev/hdc4 0 - 0 0 0 Empty % Disk /dev/hdc: 16 heads, 63 sectors, 2045 cylinders Units = cylinders of 516096 bytes, blocks of 1024 bytes, counting from 0 Device Boot Start End #cyls #blocks Id System /dev/hdc1 0+ 406 407- 205096+ 83 Linux native /dev/hdc2 407 813 407 205128 83 Linux native /dev/hdc3 814 2044 1231 620424 83 Linux native /dev/hdc4 0 - 0 0 0 Empty % BE EXTREMELY CAREFUL - ONE TYPING MISTAKE AND ALL YOUR DATA IS LOST As a precaution, one can save the sectors changed by sfdisk: % sfdisk /dev/hdd -O hdd-partition-sectors.save ... % Then, if you discover that you did something stupid before anything else has been written to disk, it may be possible to recover the old situation with % sfdisk /dev/hdd -I hdd-partition-sectors.save % (This is not the same as saving the old partition table: a readable version of the old partition table can be saved using the -d option. However, if you create logical partitions, the sectors describing them are located somewhere on disk, possibly on sectors that were not part of the partition table before. Thus, the information the -O option saves is not a binary version of the output of -d.) There are many options. % sfdisk -d /dev/hda > hda.out % sfdisk /dev/hda < hda.out % sfdisk /dev/hdb -N5 ,,,* % % sfdisk --print-id /dev/hdb 5 6 % sfdisk --change-id /dev/hdb 5 83 OK A partition descriptor has 6 fields: struct partition { unsigned char bootable; /* 0 or 0x80 */ hsc begin_hsc; unsigned char id; hsc end_hsc; unsigned int starting_sector; unsigned int nr_of_sectors; } The two hsc fields indicate head, sector and cylinder of the begin and the end of the partition. Since each hsc field only takes 3 bytes, only 24 bits are available, which does not suffice for big disks (say > 8GB). In fact, due to the wasteful representation (that uses a byte for the number of heads, which is typically 16), problems already start with 0.5GB. However Linux does not use these fields, and problems can arise only at boot time, before Linux has been started. For more details, see the lilo documentation. Each partition has a type, its ‘Id’, and if this type is 5 or f (‘extended partition’) the starting sector of the partition again contains 4 partition descriptors. MSDOS only uses the first two of these: the first one an actual data partition, and the second one again an extended partition (or empty). In this way one gets a chain of extended partitions. Other operating systems have slightly different conventions. Linux also accepts type 85 as equivalent to 5 and f - this can be useful if one wants to have extended partitions under Linux past the 1024 cylinder boundary, without DOS FDISK hanging. (If there is no good reason, you should just use 5, which is understood by other systems.) Partitions that are not primary or extended are called logical. Often, one cannot boot from logical partitions (because the process of finding them is more involved than just looking at the MBR). Note that of an extended partition only the Id and the start are used. There are various conventions about what to write in the other fields. One should not try to use extended partitions for data storage or swap. Fields are separated by whitespace, or comma or semicolon possibly followed by whitespace; initial and trailing whitespace is ignored. Numbers can be octal, decimal or hexadecimal, decimal is default. When a field is absent or empty, a default value is used. The <c,h,s> parts can (and probably should) be omitted - sfdisk computes them from <start> and <size> and the disk geometry as given by the kernel or specified using the -H, -S, -C flags. Bootable is specified as [*|-], with as default not-bootable. (The value of this field is irrelevant for Linux - when Linux runs it has been booted already - but might play a role for certain boot loaders and for other operating systems. For example, when there are several primary DOS partitions, DOS assigns C: to the first among these that is bootable.) Id is given in hex, without the 0x prefix, or is [E|S|L|X], where L (LINUX_NATIVE (83)) is the default, S is LINUX_SWAP (82), E is EXTENDED_PARTITION (5), and X is LINUX_EXTENDED (85). The default value of start is the first nonassigned sector/cylinder/... The default value of size is as much as possible (until next partition or end-of-disk). However, for the four partitions inside an extended partition, the defaults are: Linux partition, Extended partition, Empty, Empty. But when the -N option (change a single partition only) is given, the default for each field is its previous value. sfdisk /dev/hdc << EOF 0,407 ,407 ; ; EOF The command sfdisk /dev/hdb << EOF ,3,L ,60,L ,19,S ,,E ,130,L ,130,L ,130,L ,,L EOF With the -x option, the number of input lines must be a multiple of 4: you have to list the two empty partitions that you never want using two blank lines. Without the -x option, you give one line for the partitions inside a extended partition, instead of four, and terminate with end-of-file (^D). (And sfdisk will assume that your input line represents the first of four, that the second one is extended, and the 3rd and 4th are empty.) The DOS 6.x FORMAT command looks for some information in the first sector of the data area of the partition, and treats this information as more reliable than the information in the partition table. DOS FORMAT expects DOS FDISK to clear the first 512 bytes of the data area of a partition whenever a size change occurs. DOS FORMAT will look at this extra information even if the /U flag is given -- we consider this a bug in DOS FORMAT and DOS FDISK. The bottom line is that if you use sfdisk to change the size of a DOS partition table entry, then you must also use dd to zero the first 512 bytes of that partition before using DOS FORMAT to format the partition. For example, if you were using sfdisk to make a DOS partition table entry for /dev/hda1, then (after exiting sfdisk and rebooting Linux so that the partition table information is valid) you would use the command "dd if=/dev/zero of=/dev/hda1 bs=512 count=1" to zero the first 512 bytes of the partition. BE EXTREMELY CAREFUL if you use the dd command, since a small typo can make all of the data on your disk useless. For best results, you should always use an OS-specific partition table program. For example, you should make DOS partitions with the DOS FDISK program and Linux partitions with the Linux sfdisk program. Stephen Tweedie reported (930515): ‘Most reports of superblock corruption turn out to be due to bad partitioning, with one filesystem overrunning the start of the next and corrupting its superblock. I have even had this problem with the supposedly-reliable DRDOS. This was quite possibly due to DRDOS-6.0’s FDISK command. Unless I created a blank track or cylinder between the DRDOS partition and the immediately following one, DRDOS would happily stamp all over the start of the next partition. Mind you, as long as I keep a little free disk space after any DRDOS partition, I don’t have any other problems with the two coexisting on the one drive.’ A. V. Le Blanc writes in README.efdisk: ‘Dr. DOS 5.0 and 6.0 has been reported to have problems cooperating with Linux, and with this version of efdisk in particular. This efdisk sets the system type to hexadecimal 81. Dr. DOS seems to confuse this with hexadecimal 1, a DOS code. If you use Dr. DOS, use the efdisk command ’t’ to change the system code of any Linux partitions to some number less than hexadecimal 80; I suggest 41 and 42 for the moment.’ A. V. Le Blanc writes in his README.fdisk: ‘DR-DOS 5.0 and 6.0 are reported to have difficulties with partition ID codes of 80 or more. The Linux ‘fdisk’ used to set the system type of new partitions to hexadecimal 81. DR-DOS seems to confuse this with hexadecimal 1, a DOS code. The values 82 for swap and 83 for file systems should not cause problems with DR-DOS. If they do, you may use the ‘fdisk’ command ‘t’ to change the system code of any Linux partitions to some number less than hexadecimal 80; I suggest 42 and 43 for the moment.’ In fact, it seems that only 4 bits are significant for the DRDOS FDISK, so that for example 11 and 21 are listed as DOS 2.0. However, DRDOS itself seems to use the full byte. I have not been able to reproduce any corruption with DRDOS or its fdisk. There are too many options. There is no support for non-DOS partition types. cfdisk (8) cfdisk (8) fdisk (8) fdisk (8) mkfs (8) mkfs (8) parted (8) parted (8) 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": 10729, "s": 10577, "text": "\nsfdisk doesn’t understand GUID Partition Table (GPT) and\nit is not designed for large partitions. In particular case use more advanced GNU\nparted(8). " }, { "code": null, "e": 10763, "s": 10731, "text": "\n% sfdisk -s /dev/hda9\n81599\n%\n" }, { "code": null, "e": 10891, "s": 10763, "text": "\n% sfdisk -s\n/dev/hda: 208896\n/dev/hdb: 1025136\n/dev/hdc: 1031063\n/dev/sda: 8877895\n/dev/sdb: 1758927\ntotal: 12901917 blocks\n%\n" }, { "code": null, "e": 11362, "s": 10893, "text": "\n% sfdisk -l /dev/hdc\n\nDisk /dev/hdc: 16 heads, 63 sectors, 2045 cylinders\nUnits = cylinders of 516096 bytes, blocks of 1024 bytes, counting from 0\n\n Device Boot Start End #cyls #blocks Id System\n/dev/hdc1 0+ 406 407- 205096+ 83 Linux native\n/dev/hdc2 407 813 407 205128 83 Linux native\n/dev/hdc3 814 2044 1231 620424 83 Linux native\n/dev/hdc4 0 - 0 0 0 Empty\n%\n" }, { "code": null, "e": 11489, "s": 11362, "text": "\nDisk /dev/hdc: 16 heads, 63 sectors, 2045 cylinders\nUnits = cylinders of 516096 bytes, blocks of 1024 bytes, counting from 0\n" }, { "code": null, "e": 11810, "s": 11489, "text": "\n Device Boot Start End #cyls #blocks Id System\n/dev/hdc1 0+ 406 407- 205096+ 83 Linux native\n/dev/hdc2 407 813 407 205128 83 Linux native\n/dev/hdc3 814 2044 1231 620424 83 Linux native\n/dev/hdc4 0 - 0 0 0 Empty\n%\n" }, { "code": null, "e": 11884, "s": 11814, "text": "\nBE EXTREMELY CAREFUL - ONE TYPING MISTAKE AND ALL YOUR DATA IS LOST\n" }, { "code": null, "e": 11947, "s": 11884, "text": "\nAs a precaution, one can save the sectors changed by\nsfdisk: " }, { "code": null, "e": 12002, "s": 11947, "text": "% sfdisk /dev/hdd -O hdd-partition-sectors.save\n...\n%\n" }, { "code": null, "e": 12156, "s": 12002, "text": "\nThen, if you discover that you did something stupid before anything\nelse has been written to disk, it may be possible to recover\nthe old situation with\n" }, { "code": null, "e": 12207, "s": 12156, "text": "% sfdisk /dev/hdd -I hdd-partition-sectors.save\n%\n" }, { "code": null, "e": 12606, "s": 12207, "text": "\n(This is not the same as saving the old partition table:\na readable version of the old partition table can be saved\nusing the -d option. However, if you create logical partitions,\nthe sectors describing them are located somewhere on disk,\npossibly on sectors that were not part of the partition table\nbefore. Thus, the information the -O option saves is not a binary\nversion of the output of -d.)\n" }, { "code": null, "e": 12632, "s": 12606, "text": "\nThere are many options.\n" }, { "code": null, "e": 12703, "s": 12634, "text": "\n % sfdisk -d /dev/hda > hda.out\n % sfdisk /dev/hda < hda.out\n" }, { "code": null, "e": 12746, "s": 12703, "text": "\n % sfdisk /dev/hdb -N5\n ,,,*\n %\n" }, { "code": null, "e": 12835, "s": 12746, "text": "\n % sfdisk --print-id /dev/hdb 5\n 6\n % sfdisk --change-id /dev/hdb 5 83\n OK\n" }, { "code": null, "e": 12876, "s": 12837, "text": "\nA partition descriptor has 6 fields:\n" }, { "code": null, "e": 13079, "s": 12876, "text": "\nstruct partition {\n unsigned char bootable; /* 0 or 0x80 */\n hsc begin_hsc;\n unsigned char id;\n hsc end_hsc;\n unsigned int starting_sector;\n unsigned int nr_of_sectors;\n}\n" }, { "code": null, "e": 13603, "s": 13079, "text": "\nThe two hsc fields indicate head, sector and cylinder of the\nbegin and the end of the partition. Since each hsc field only\ntakes 3 bytes, only 24 bits are available, which does not\nsuffice for big disks (say > 8GB). In fact, due to the wasteful\nrepresentation (that uses a byte for the number of heads, which\nis typically 16), problems already start with 0.5GB.\nHowever Linux does not use these fields, and problems can arise\nonly at boot time, before Linux has been started. For more\ndetails, see the\nlilo documentation.\n" }, { "code": null, "e": 14299, "s": 13603, "text": "\nEach partition has a type, its ‘Id’, and if this type is 5 or f\n(‘extended partition’) the starting sector of the partition\nagain contains 4 partition descriptors. MSDOS only uses the\nfirst two of these: the first one an actual data partition,\nand the second one again an extended partition (or empty).\nIn this way one gets a chain of extended partitions.\nOther operating systems have slightly different conventions.\nLinux also accepts type 85 as equivalent to 5 and f - this can be\nuseful if one wants to have extended partitions under Linux past\nthe 1024 cylinder boundary, without DOS FDISK hanging.\n(If there is no good reason, you should just use 5, which is\nunderstood by other systems.)\n" }, { "code": null, "e": 14711, "s": 14299, "text": "\nPartitions that are not primary or extended are called\nlogical. Often, one cannot boot from logical partitions (because the\nprocess of finding them is more involved than just looking\nat the MBR).\nNote that of an extended partition only the Id and the start\nare used. There are various conventions about what to write\nin the other fields. One should not try to use extended partitions\nfor data storage or swap.\n" }, { "code": null, "e": 14974, "s": 14713, "text": "\nFields are separated by whitespace, or comma or semicolon possibly\nfollowed by whitespace; initial and trailing whitespace is ignored.\nNumbers can be octal, decimal or hexadecimal, decimal is default.\nWhen a field is absent or empty, a default value is used.\n" }, { "code": null, "e": 15164, "s": 14974, "text": "\nThe <c,h,s> parts can (and probably should) be omitted -\nsfdisk computes them from <start> and <size> and the disk geometry\nas given by the kernel or specified using the -H, -S, -C flags.\n" }, { "code": null, "e": 15523, "s": 15164, "text": "\nBootable is specified as [*|-], with as default not-bootable.\n(The value of this field is irrelevant for Linux - when Linux\nruns it has been booted already - but might play a role for\ncertain boot loaders and for other operating systems.\nFor example, when there are several primary DOS partitions,\nDOS assigns C: to the first among these that is bootable.)\n" }, { "code": null, "e": 15710, "s": 15523, "text": "\nId is given in hex, without the 0x prefix, or is [E|S|L|X], where\nL (LINUX_NATIVE (83)) is the default, S is LINUX_SWAP (82), E\nis EXTENDED_PARTITION (5), and X is LINUX_EXTENDED (85).\n" }, { "code": null, "e": 15784, "s": 15710, "text": "\nThe default value of start is the first nonassigned sector/cylinder/...\n" }, { "code": null, "e": 15874, "s": 15784, "text": "\nThe default value of size is as much as possible (until next\npartition or end-of-disk).\n" }, { "code": null, "e": 16008, "s": 15874, "text": "\nHowever, for the four partitions inside an extended partition,\nthe defaults are: Linux partition, Extended partition, Empty, Empty.\n" }, { "code": null, "e": 16126, "s": 16008, "text": "\nBut when the -N option (change a single partition only) is given,\nthe default for each field is its previous value.\n" }, { "code": null, "e": 16171, "s": 16128, "text": "sfdisk /dev/hdc << EOF\n0,407\n,407\n;\n;\nEOF\n" }, { "code": null, "e": 16185, "s": 16171, "text": "\nThe command\n" }, { "code": null, "e": 16259, "s": 16185, "text": "sfdisk /dev/hdb << EOF\n,3,L\n,60,L\n,19,S\n,,E\n,130,L\n,130,L\n,130,L\n,,L\nEOF\n" }, { "code": null, "e": 16700, "s": 16259, "text": "\nWith the -x option, the number of input lines must be a multiple of 4:\nyou have to list the two empty partitions that you never want\nusing two blank lines. Without the -x option, you give one line\nfor the partitions inside a extended partition, instead of four,\nand terminate with end-of-file (^D).\n(And\nsfdisk will assume that your input line represents the first of four,\nthat the second one is extended, and the 3rd and 4th are empty.)\n" }, { "code": null, "e": 17157, "s": 16702, "text": "\nThe DOS 6.x FORMAT command looks for some information in the first\nsector of the data area of the partition, and treats this information\nas more reliable than the information in the partition table. DOS\nFORMAT expects DOS FDISK to clear the first 512 bytes of the data area\nof a partition whenever a size change occurs. DOS FORMAT will look at\nthis extra information even if the /U flag is given -- we consider\nthis a bug in DOS FORMAT and DOS FDISK.\n" }, { "code": null, "e": 17792, "s": 17157, "text": "\nThe bottom line is that if you use sfdisk to change the size of a\nDOS partition table entry, then you must also use\ndd to zero the first 512 bytes of that partition before using DOS FORMAT to\nformat the partition. For example, if you were using sfdisk to make a DOS\npartition table entry for /dev/hda1, then (after exiting sfdisk and\nrebooting Linux so that the partition table information is valid) you\nwould use the command \"dd if=/dev/zero of=/dev/hda1 bs=512 count=1\" to zero\nthe first 512 bytes of the partition.\nBE EXTREMELY CAREFUL if you use the\ndd command, since a small typo can make all of the data on your disk useless.\n" }, { "code": null, "e": 17998, "s": 17792, "text": "\nFor best results, you should always use an OS-specific partition table\nprogram. For example, you should make DOS partitions with the DOS FDISK\nprogram and Linux partitions with the Linux sfdisk program.\n" }, { "code": null, "e": 18656, "s": 18000, "text": "\nStephen Tweedie reported (930515): ‘Most reports of superblock\ncorruption turn out to be due to bad partitioning, with one filesystem\noverrunning the start of the next and corrupting its superblock.\nI have even had this problem with the supposedly-reliable DRDOS. This\nwas quite possibly due to DRDOS-6.0’s FDISK command. Unless I created\na blank track or cylinder between the DRDOS partition and the\nimmediately following one, DRDOS would happily stamp all over the\nstart of the next partition. Mind you, as long as I keep a little\nfree disk space after any DRDOS partition, I don’t have any other\nproblems with the two coexisting on the one drive.’\n" }, { "code": null, "e": 19117, "s": 18656, "text": "\nA. V. Le Blanc writes in README.efdisk: ‘Dr. DOS 5.0 and 6.0 has been\nreported to have problems cooperating with Linux, and with this version\nof efdisk in particular. This efdisk sets the system type\nto hexadecimal 81. Dr. DOS seems to confuse\nthis with hexadecimal 1, a DOS code. If you use Dr. DOS, use the\nefdisk command ’t’ to change the system code of any Linux partitions\nto some number less than hexadecimal 80; I suggest 41 and 42 for\nthe moment.’\n" }, { "code": null, "e": 19664, "s": 19117, "text": "\nA. V. Le Blanc writes in his README.fdisk: ‘DR-DOS 5.0 and 6.0\nare reported to have difficulties with partition ID codes of 80 or more.\nThe Linux ‘fdisk’ used to set the system type\nof new partitions to hexadecimal 81. DR-DOS seems to confuse this with\nhexadecimal 1, a DOS code. The values 82 for swap and 83 for file\nsystems should not cause problems with DR-DOS. If they do, you may use\nthe ‘fdisk’ command ‘t’ to change the system code of any Linux\npartitions to some number less than hexadecimal 80; I suggest 42 and 43\nfor the moment.’\n" }, { "code": null, "e": 19915, "s": 19664, "text": "\nIn fact, it seems that only 4 bits are significant for the DRDOS FDISK,\nso that for example 11 and 21 are listed as DOS 2.0. However, DRDOS\nitself seems to use the full byte. I have not been able to reproduce\nany corruption with DRDOS or its fdisk.\n" }, { "code": null, "e": 19947, "s": 19917, "text": "\nThere are too many options.\n" }, { "code": null, "e": 19998, "s": 19947, "text": "\nThere is no support for non-DOS partition types.\n" }, { "code": null, "e": 20011, "s": 20000, "text": "cfdisk (8)" }, { "code": null, "e": 20022, "s": 20011, "text": "cfdisk (8)" }, { "code": null, "e": 20032, "s": 20022, "text": "fdisk (8)" }, { "code": null, "e": 20042, "s": 20032, "text": "fdisk (8)" }, { "code": null, "e": 20051, "s": 20042, "text": "mkfs (8)" }, { "code": null, "e": 20060, "s": 20051, "text": "mkfs (8)" }, { "code": null, "e": 20071, "s": 20060, "text": "parted (8)" }, { "code": null, "e": 20082, "s": 20071, "text": "parted (8)" }, { "code": null, "e": 20099, "s": 20082, "text": "\nAdvertisements\n" }, { "code": null, "e": 20134, "s": 20099, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 20162, "s": 20134, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 20196, "s": 20162, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 20213, "s": 20196, "text": " Frahaan Hussain" }, { "code": null, "e": 20246, "s": 20213, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 20257, "s": 20246, "text": " Pradeep D" }, { "code": null, "e": 20292, "s": 20257, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 20308, "s": 20292, "text": " Musab Zayadneh" }, { "code": null, "e": 20341, "s": 20308, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 20353, "s": 20341, "text": " GUHARAJANM" }, { "code": null, "e": 20385, "s": 20353, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 20393, "s": 20385, "text": " Uplatz" }, { "code": null, "e": 20400, "s": 20393, "text": " Print" }, { "code": null, "e": 20411, "s": 20400, "text": " Add Notes" } ]
Machine Learning to Predict Stock Prices | by Roshan Adusumilli | Towards Data Science
As financial institutions begin to embrace artificial intelligence, machine learning is increasingly utilized to help make trading decisions. Although there is an abundance of stock data for machine learning models to train on, a high noise to signal ratio and the multitude of factors that affect stock prices are among the several reasons that predicting the market difficult. At the same time, these models don’t need to reach high levels of accuracy because even 60% accuracy can deliver solid returns. One method for predicting stock prices is using a long short-term memory neural network (LSTM) for times series forecasting. LSTMs are an improved version of recurrent neural networks (RNNs). RNNs are analogous to human learning. When humans think, we don’t start our thinking from scratch each second. For example, in the sentence “Bob plays basketball”, we know that Bob is the person who plays basketball because we retain information about past words while reading sentences. Similarly, RNNs are networks with loops in them, which allow them to use past information before arriving at a final output. However, RNNs can only connect recent previous information and cannot connect information as the time gap grows. This is where LSTMs come into play; LSTMs are a type of RNN that remember information over long periods of time, making them better suited for predicting stock prices. For a technical explanation of LSTMs click here. To begin our project, we import numpy for making scientific computations, pandas for loading and modifying datasets, and matplotlib for plotting graphs. import numpy as npimport matplotlib.pyplot as pltimport pandas as pd After making the necessary imports, we load data on Tata Global Beverage’s past stock prices. From the data, we select the values of the first and second columns (“Open” and “High” respectively) as our training dataset. The “Open” column represents the opening price for shares that day and the “High” column represents the highest price shares reached that day. url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/NSE-TATAGLOBAL.csv'dataset_train = pd.read_csv(url)training_set = dataset_train.iloc[:, 1:2].values To get a look at the dataset we’re using, we can check the head, which shows us the first five rows of our dataset. dataset_train.head() “Low” represents the lowest share price for the day, “Last” represents the price at which the last transaction for a share went through. “Close” represents the price shares ended at for the day. Normalization is changing the values of numeric columns in the dataset to a common scale, which helps the performance of our model. To scale the training dataset we use Scikit-Learn’s MinMaxScaler with numbers between zero and one. from sklearn.preprocessing import MinMaxScalersc = MinMaxScaler(feature_range=(0,1))training_set_scaled = sc.fit_transform(training_set) We should input our data in the form of a 3D array to the LSTM model. First, we create data in 60 timesteps before using numpy to convert it into an array. Finally, we convert the data into a 3D array with X_train samples, 60 timestamps, and one feature at each step. X_train = []y_train = []for i in range(60, 2035):X_train.append(training_set_scaled[i-60:i, 0])y_train.append(training_set_scaled[i, 0])X_train, y_train = np.array(X_train), np.array(y_train)X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) Before we can develop the LSTM, we have to make a few imports from Keras: Sequential for initializing the neural network, LSTM to add the LSTM layer, Dropout for preventing overfitting with dropout layers, and Dense to add a densely connected neural network layer. from keras.models import Sequentialfrom keras.layers import LSTMfrom keras.layers import Dropoutfrom keras.layers import Dense The LSTM layer is added with the following arguments: 50 units is the dimensionality of the output space, return_sequences=True is necessary for stacking LSTM layers so the consequent LSTM layer has a three-dimensional sequence input, and input_shape is the shape of the training dataset. Specifying 0.2 in the Dropout layer means that 20% of the layers will be dropped. Following the LSTM and Dropout layers, we add the Dense layer that specifies an output of one unit. To compile our model we use the Adam optimizer and set the loss as the mean_squared_error. After that, we fit the model to run for 100 epochs (the epochs are the number of times the learning algorithm will work through the entire training set) with a batch size of 32. model = Sequential()model.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1], 1)))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50))model.add(Dropout(0.2))model.add(Dense(units=1))model.compile(optimizer='adam',loss='mean_squared_error')model.fit(X_train,y_train,epochs=100,batch_size=32) We start off by importing the test set url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/tatatest.csv'dataset_test = pd.read_csv(url)real_stock_price = dataset_test.iloc[:, 1:2].values Before predicting future stock prices, we have to modify the test set (notice similarities to the edits we made to the training set): merge the training set and the test set on the 0 axis, set 60 as the time step again, use MinMaxScaler, and reshape data. Then, inverse_transform puts the stock prices in a normal readable format. dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].valuesinputs = inputs.reshape(-1,1)inputs = sc.transform(inputs)X_test = []for i in range(60, 76):X_test.append(inputs[i-60:i, 0])X_test = np.array(X_test)X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))predicted_stock_price = model.predict(X_test)predicted_stock_price = sc.inverse_transform(predicted_stock_price) After all these steps, we can use matplotlib to visualize the result of our predicted stock price and the actual stock price. plt.plot(real_stock_price, color = 'black', label = 'TATA Stock Price')plt.plot(predicted_stock_price, color = 'green', label = 'Predicted TATA Stock Price')plt.title('TATA Stock Price Prediction')plt.xlabel('Time')plt.ylabel('TATA Stock Price')plt.legend()plt.show() While the exact price points from our predicted price weren’t always close to the actual price, our model did still indicate overall trends such as going up or down. This project teaches us the LSTMs can be somewhat effective in times series forecasting. Click here for the entire code [1] Derrick Mwiti, Data and Notebook for the Stock Price Prediction Tutorial(2018), Github Don’t leave yet! I’m Roshan, a 16 year old passionate about the intersection of artificial intelligence and finance. For a broad view of AI in finance, check out this article: https://becominghuman.ai/artificial-intelligence-and-its-application-in-finance-9f1e0588e777. Reach out to me on Linkedin: https://www.linkedin.com/in/roshan-adusumilli-96b104194/
[ { "code": null, "e": 679, "s": 47, "text": "As financial institutions begin to embrace artificial intelligence, machine learning is increasingly utilized to help make trading decisions. Although there is an abundance of stock data for machine learning models to train on, a high noise to signal ratio and the multitude of factors that affect stock prices are among the several reasons that predicting the market difficult. At the same time, these models don’t need to reach high levels of accuracy because even 60% accuracy can deliver solid returns. One method for predicting stock prices is using a long short-term memory neural network (LSTM) for times series forecasting." }, { "code": null, "e": 1489, "s": 679, "text": "LSTMs are an improved version of recurrent neural networks (RNNs). RNNs are analogous to human learning. When humans think, we don’t start our thinking from scratch each second. For example, in the sentence “Bob plays basketball”, we know that Bob is the person who plays basketball because we retain information about past words while reading sentences. Similarly, RNNs are networks with loops in them, which allow them to use past information before arriving at a final output. However, RNNs can only connect recent previous information and cannot connect information as the time gap grows. This is where LSTMs come into play; LSTMs are a type of RNN that remember information over long periods of time, making them better suited for predicting stock prices. For a technical explanation of LSTMs click here." }, { "code": null, "e": 1642, "s": 1489, "text": "To begin our project, we import numpy for making scientific computations, pandas for loading and modifying datasets, and matplotlib for plotting graphs." }, { "code": null, "e": 1711, "s": 1642, "text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd" }, { "code": null, "e": 2074, "s": 1711, "text": "After making the necessary imports, we load data on Tata Global Beverage’s past stock prices. From the data, we select the values of the first and second columns (“Open” and “High” respectively) as our training dataset. The “Open” column represents the opening price for shares that day and the “High” column represents the highest price shares reached that day." }, { "code": null, "e": 2246, "s": 2074, "text": "url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/NSE-TATAGLOBAL.csv'dataset_train = pd.read_csv(url)training_set = dataset_train.iloc[:, 1:2].values" }, { "code": null, "e": 2362, "s": 2246, "text": "To get a look at the dataset we’re using, we can check the head, which shows us the first five rows of our dataset." }, { "code": null, "e": 2383, "s": 2362, "text": "dataset_train.head()" }, { "code": null, "e": 2578, "s": 2383, "text": "“Low” represents the lowest share price for the day, “Last” represents the price at which the last transaction for a share went through. “Close” represents the price shares ended at for the day." }, { "code": null, "e": 2810, "s": 2578, "text": "Normalization is changing the values of numeric columns in the dataset to a common scale, which helps the performance of our model. To scale the training dataset we use Scikit-Learn’s MinMaxScaler with numbers between zero and one." }, { "code": null, "e": 2947, "s": 2810, "text": "from sklearn.preprocessing import MinMaxScalersc = MinMaxScaler(feature_range=(0,1))training_set_scaled = sc.fit_transform(training_set)" }, { "code": null, "e": 3215, "s": 2947, "text": "We should input our data in the form of a 3D array to the LSTM model. First, we create data in 60 timesteps before using numpy to convert it into an array. Finally, we convert the data into a 3D array with X_train samples, 60 timestamps, and one feature at each step." }, { "code": null, "e": 3477, "s": 3215, "text": "X_train = []y_train = []for i in range(60, 2035):X_train.append(training_set_scaled[i-60:i, 0])y_train.append(training_set_scaled[i, 0])X_train, y_train = np.array(X_train), np.array(y_train)X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))" }, { "code": null, "e": 3742, "s": 3477, "text": "Before we can develop the LSTM, we have to make a few imports from Keras: Sequential for initializing the neural network, LSTM to add the LSTM layer, Dropout for preventing overfitting with dropout layers, and Dense to add a densely connected neural network layer." }, { "code": null, "e": 3869, "s": 3742, "text": "from keras.models import Sequentialfrom keras.layers import LSTMfrom keras.layers import Dropoutfrom keras.layers import Dense" }, { "code": null, "e": 4158, "s": 3869, "text": "The LSTM layer is added with the following arguments: 50 units is the dimensionality of the output space, return_sequences=True is necessary for stacking LSTM layers so the consequent LSTM layer has a three-dimensional sequence input, and input_shape is the shape of the training dataset." }, { "code": null, "e": 4609, "s": 4158, "text": "Specifying 0.2 in the Dropout layer means that 20% of the layers will be dropped. Following the LSTM and Dropout layers, we add the Dense layer that specifies an output of one unit. To compile our model we use the Adam optimizer and set the loss as the mean_squared_error. After that, we fit the model to run for 100 epochs (the epochs are the number of times the learning algorithm will work through the entire training set) with a batch size of 32." }, { "code": null, "e": 5055, "s": 4609, "text": "model = Sequential()model.add(LSTM(units=50,return_sequences=True,input_shape=(X_train.shape[1], 1)))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50,return_sequences=True))model.add(Dropout(0.2))model.add(LSTM(units=50))model.add(Dropout(0.2))model.add(Dense(units=1))model.compile(optimizer='adam',loss='mean_squared_error')model.fit(X_train,y_train,epochs=100,batch_size=32)" }, { "code": null, "e": 5094, "s": 5055, "text": "We start off by importing the test set" }, { "code": null, "e": 5262, "s": 5094, "text": "url = 'https://raw.githubusercontent.com/mwitiderrick/stockprice/master/tatatest.csv'dataset_test = pd.read_csv(url)real_stock_price = dataset_test.iloc[:, 1:2].values" }, { "code": null, "e": 5593, "s": 5262, "text": "Before predicting future stock prices, we have to modify the test set (notice similarities to the edits we made to the training set): merge the training set and the test set on the 0 axis, set 60 as the time step again, use MinMaxScaler, and reshape data. Then, inverse_transform puts the stock prices in a normal readable format." }, { "code": null, "e": 6078, "s": 5593, "text": "dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].valuesinputs = inputs.reshape(-1,1)inputs = sc.transform(inputs)X_test = []for i in range(60, 76):X_test.append(inputs[i-60:i, 0])X_test = np.array(X_test)X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))predicted_stock_price = model.predict(X_test)predicted_stock_price = sc.inverse_transform(predicted_stock_price)" }, { "code": null, "e": 6204, "s": 6078, "text": "After all these steps, we can use matplotlib to visualize the result of our predicted stock price and the actual stock price." }, { "code": null, "e": 6472, "s": 6204, "text": "plt.plot(real_stock_price, color = 'black', label = 'TATA Stock Price')plt.plot(predicted_stock_price, color = 'green', label = 'Predicted TATA Stock Price')plt.title('TATA Stock Price Prediction')plt.xlabel('Time')plt.ylabel('TATA Stock Price')plt.legend()plt.show()" }, { "code": null, "e": 6727, "s": 6472, "text": "While the exact price points from our predicted price weren’t always close to the actual price, our model did still indicate overall trends such as going up or down. This project teaches us the LSTMs can be somewhat effective in times series forecasting." }, { "code": null, "e": 6758, "s": 6727, "text": "Click here for the entire code" }, { "code": null, "e": 6849, "s": 6758, "text": "[1] Derrick Mwiti, Data and Notebook for the Stock Price Prediction Tutorial(2018), Github" }, { "code": null, "e": 6866, "s": 6849, "text": "Don’t leave yet!" }, { "code": null, "e": 7119, "s": 6866, "text": "I’m Roshan, a 16 year old passionate about the intersection of artificial intelligence and finance. For a broad view of AI in finance, check out this article: https://becominghuman.ai/artificial-intelligence-and-its-application-in-finance-9f1e0588e777." } ]
Scrape Company Reviews & Ratings from Indeed in 2 Minutes | by Yasser Elsedawy | Towards Data Science
In this tutorial, I will show you how to perform web scraping using Anaconda Jupyter notebook and the BeautifulSoup library. We’ll be scraping Company reviews and ratings from Indeed platform, and then we will export them to Pandas library dataframe and then to a .CSV file. Let us get straight down to business, however, if you’re looking on a guide to understanding Web Scraping in general, I advise you of reading this article from Dataquest. Let us start by importing our 3 libraries from bs4 import BeautifulSoupimport pandas as pdimport requests Then, let’s go to indeed website and examine which information we want, we will be targeting Ernst & Young firm page, you can check it from the following link https://www.indeed.com/cmp/Ey/reviews?fcountry=IT Based on my location, the country is indicated as Italy but you can choose and control that if you want. In the next picture, we can see the multiple information that we can tackle and scrape: 1- Review Title 2- Review Body 3- Rating 4- The role of the reviewer 5- The location of the reviewer 6- The review date However, you can notice that Points 4,5&6 are all in one line and will be scraped together, this can cause a bit of confusion for some people, but my advice is to scrape first then solve problems later. So, let’s try to do this. After knowing what we want to scrape, we need to find out how much do we need to scrape, do we want only 1 review? 1 page of reviews or all pages of reviews? I guess the answer should be all pages!! If you scrolled down the page and went over to page 2 you will find that the link for that page became as following: https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start=20 Then try to go to page 3, you will find the link became as following: https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start=4 Looks like we have a pattern here, page 2=20 , page 3 = 40, then page 4 = 60, right? All untill page 8 = 140 Let’s get back to coding, start by defining your dataframe that you want. df = pd.DataFrame({‘review_title’: [],’review’:[],’author’:[],’rating’:[]}) In the next code I will make a for loop that starts from 0, jumps 20 and stops at 140. 1- Inside that for loop we will make a GET request to the web server, which will download the HTML contents of a given web page for us. 2- Then, We will use the BeautifulSoup library to parse this page, and extract the text from it. We first have to create an instance of the BeautifulSoup class to parse our document 3- Then by inspecting the html, we choose the classes from the web page, classes are used when scraping to specify specific elements we want to scrape. 4- And then we can conclude by adding the results to our DataFrame created before. “I added a picture down for how the code should be in case you copied and some spaces were added wrong” for i in range(10,140,20): url = (f’https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start={i}') header = {“User-Agent”:”Mozilla/5.0 Gecko/20100101 Firefox/33.0 GoogleChrome/10.0"} page = requests.get(url,headers = header) soup = BeautifulSoup(page.content, ‘lxml’) results = soup.find(“div”, { “id” : ‘cmp-container’}) elems = results.find_all(class_=’cmp-Review-container’) for elem in elems: title = elem.find(attrs = {‘class’:’cmp-Review-title’}) review = elem.find(‘div’, {‘class’: ‘cmp-Review-text’}) author = elem.find(attrs = {‘class’:’cmp-Review-author’}) rating = elem.find(attrs = {‘class’:’cmp-ReviewRating-text’}) df = df.append({‘review_title’: title.text, ‘review’: review.text, ‘author’: author.text, ‘rating’: rating.text }, ignore_index=True) DONE. Let’s check our dataframe df.head() Now, once scraped, let’s try solve the problem we have. Notice the author coulmn had 3 differnt information seperated by (-) So, let’s split them author = df[‘author’].str.split(‘-’, expand=True) Now, let’s rename the columns and delete the last one. author = author.rename(columns={0: “job”, 1: “location”,2:’time’})del author[3] Then let’s join those new columns to our original dataframe and delete the old author column df1 = pd.concat([df,author],axis=1)del df1[‘author’] let’s examine our new dataframe df1.head() Let’s re-organize the columns and remove any duplicates df1 = df1[[‘job’, ‘review_title’, ‘review’, ‘rating’,’location’,’time’]]df1 = df1.drop_duplicates() Then finally let’s save the dataframe to a CSV file df1.to_csv(‘EY_indeed.csv’) You should now have a good understanding of how to scrape and extract data from Indeed. A good next step for you if you are familiar a bit with web scraping it to pick a site and try some web scraping on your own.
[ { "code": null, "e": 297, "s": 172, "text": "In this tutorial, I will show you how to perform web scraping using Anaconda Jupyter notebook and the BeautifulSoup library." }, { "code": null, "e": 447, "s": 297, "text": "We’ll be scraping Company reviews and ratings from Indeed platform, and then we will export them to Pandas library dataframe and then to a .CSV file." }, { "code": null, "e": 618, "s": 447, "text": "Let us get straight down to business, however, if you’re looking on a guide to understanding Web Scraping in general, I advise you of reading this article from Dataquest." }, { "code": null, "e": 660, "s": 618, "text": "Let us start by importing our 3 libraries" }, { "code": null, "e": 724, "s": 660, "text": "from bs4 import BeautifulSoupimport pandas as pdimport requests" }, { "code": null, "e": 883, "s": 724, "text": "Then, let’s go to indeed website and examine which information we want, we will be targeting Ernst & Young firm page, you can check it from the following link" }, { "code": null, "e": 933, "s": 883, "text": "https://www.indeed.com/cmp/Ey/reviews?fcountry=IT" }, { "code": null, "e": 1038, "s": 933, "text": "Based on my location, the country is indicated as Italy but you can choose and control that if you want." }, { "code": null, "e": 1126, "s": 1038, "text": "In the next picture, we can see the multiple information that we can tackle and scrape:" }, { "code": null, "e": 1142, "s": 1126, "text": "1- Review Title" }, { "code": null, "e": 1157, "s": 1142, "text": "2- Review Body" }, { "code": null, "e": 1167, "s": 1157, "text": "3- Rating" }, { "code": null, "e": 1195, "s": 1167, "text": "4- The role of the reviewer" }, { "code": null, "e": 1227, "s": 1195, "text": "5- The location of the reviewer" }, { "code": null, "e": 1246, "s": 1227, "text": "6- The review date" }, { "code": null, "e": 1475, "s": 1246, "text": "However, you can notice that Points 4,5&6 are all in one line and will be scraped together, this can cause a bit of confusion for some people, but my advice is to scrape first then solve problems later. So, let’s try to do this." }, { "code": null, "e": 1674, "s": 1475, "text": "After knowing what we want to scrape, we need to find out how much do we need to scrape, do we want only 1 review? 1 page of reviews or all pages of reviews? I guess the answer should be all pages!!" }, { "code": null, "e": 1791, "s": 1674, "text": "If you scrolled down the page and went over to page 2 you will find that the link for that page became as following:" }, { "code": null, "e": 1850, "s": 1791, "text": "https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start=20" }, { "code": null, "e": 1920, "s": 1850, "text": "Then try to go to page 3, you will find the link became as following:" }, { "code": null, "e": 1978, "s": 1920, "text": "https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start=4" }, { "code": null, "e": 2087, "s": 1978, "text": "Looks like we have a pattern here, page 2=20 , page 3 = 40, then page 4 = 60, right? All untill page 8 = 140" }, { "code": null, "e": 2161, "s": 2087, "text": "Let’s get back to coding, start by defining your dataframe that you want." }, { "code": null, "e": 2237, "s": 2161, "text": "df = pd.DataFrame({‘review_title’: [],’review’:[],’author’:[],’rating’:[]})" }, { "code": null, "e": 2324, "s": 2237, "text": "In the next code I will make a for loop that starts from 0, jumps 20 and stops at 140." }, { "code": null, "e": 2460, "s": 2324, "text": "1- Inside that for loop we will make a GET request to the web server, which will download the HTML contents of a given web page for us." }, { "code": null, "e": 2642, "s": 2460, "text": "2- Then, We will use the BeautifulSoup library to parse this page, and extract the text from it. We first have to create an instance of the BeautifulSoup class to parse our document" }, { "code": null, "e": 2794, "s": 2642, "text": "3- Then by inspecting the html, we choose the classes from the web page, classes are used when scraping to specify specific elements we want to scrape." }, { "code": null, "e": 2877, "s": 2794, "text": "4- And then we can conclude by adding the results to our DataFrame created before." }, { "code": null, "e": 2981, "s": 2877, "text": "“I added a picture down for how the code should be in case you copied and some spaces were added wrong”" }, { "code": null, "e": 3847, "s": 2981, "text": "for i in range(10,140,20): url = (f’https://www.indeed.com/cmp/Ey/reviews?fcountry=IT&start={i}') header = {“User-Agent”:”Mozilla/5.0 Gecko/20100101 Firefox/33.0 GoogleChrome/10.0\"} page = requests.get(url,headers = header) soup = BeautifulSoup(page.content, ‘lxml’) results = soup.find(“div”, { “id” : ‘cmp-container’}) elems = results.find_all(class_=’cmp-Review-container’) for elem in elems: title = elem.find(attrs = {‘class’:’cmp-Review-title’}) review = elem.find(‘div’, {‘class’: ‘cmp-Review-text’}) author = elem.find(attrs = {‘class’:’cmp-Review-author’}) rating = elem.find(attrs = {‘class’:’cmp-ReviewRating-text’}) df = df.append({‘review_title’: title.text, ‘review’: review.text, ‘author’: author.text, ‘rating’: rating.text }, ignore_index=True)" }, { "code": null, "e": 3879, "s": 3847, "text": "DONE. Let’s check our dataframe" }, { "code": null, "e": 3889, "s": 3879, "text": "df.head()" }, { "code": null, "e": 3945, "s": 3889, "text": "Now, once scraped, let’s try solve the problem we have." }, { "code": null, "e": 4014, "s": 3945, "text": "Notice the author coulmn had 3 differnt information seperated by (-)" }, { "code": null, "e": 4035, "s": 4014, "text": "So, let’s split them" }, { "code": null, "e": 4085, "s": 4035, "text": "author = df[‘author’].str.split(‘-’, expand=True)" }, { "code": null, "e": 4140, "s": 4085, "text": "Now, let’s rename the columns and delete the last one." }, { "code": null, "e": 4220, "s": 4140, "text": "author = author.rename(columns={0: “job”, 1: “location”,2:’time’})del author[3]" }, { "code": null, "e": 4313, "s": 4220, "text": "Then let’s join those new columns to our original dataframe and delete the old author column" }, { "code": null, "e": 4366, "s": 4313, "text": "df1 = pd.concat([df,author],axis=1)del df1[‘author’]" }, { "code": null, "e": 4398, "s": 4366, "text": "let’s examine our new dataframe" }, { "code": null, "e": 4409, "s": 4398, "text": "df1.head()" }, { "code": null, "e": 4465, "s": 4409, "text": "Let’s re-organize the columns and remove any duplicates" }, { "code": null, "e": 4565, "s": 4465, "text": "df1 = df1[[‘job’, ‘review_title’, ‘review’, ‘rating’,’location’,’time’]]df1 = df1.drop_duplicates()" }, { "code": null, "e": 4617, "s": 4565, "text": "Then finally let’s save the dataframe to a CSV file" }, { "code": null, "e": 4645, "s": 4617, "text": "df1.to_csv(‘EY_indeed.csv’)" } ]
How to import an Excel File into R ? - GeeksforGeeks
21 Apr, 2021 In this article, we will discuss how to import an excel file in the R Programming Language. There two different types of approaches to import the excel file into the R programming language and those are discussed properly below. File in use: In this approach to import the Excel file in the R, the user needs to call the read_excel() function from readxl library of the R language with the name of the file as the parameter. With the use of this function, the user will be able to import the Excel file in R. Syntax: read_excel(filename, sheet, dtype = “float32”) Parameters: filename:-File name to read from. sheet:-Name of the sheet in Excel file. dtype:-Numpy data type. Returns: The variable is treated to be a data frame. Example: R library(readxl) gfg_data=read_excel('Data_gfg.xlsx') gfg_data Output: This approach is the easy approach to import the excel file in R compared with the previous one as this is the only approach to import an excel file in R where the user need not type any code in the console to import the excel file. Further, here user just needs to work on the environment window of the studio. Environment window of the Rstudio: Steps to import excel file using Dataset option from the environment window of Rstudio: Step 1: Select the Import Dataset option in the environment window. Here the user needs to select the option to import the dataset from the environment window in Rstudio. Step 2: Select the option of “From excel” under the import Dataset option. In this step, the user needs to select the option to “from excel” as the file is in the form of excel under the import dataset option to import the excel file. Step 3: Select the browse option and select the excel file to be imported. Now, under this with the click to the browse option user will be given the choice to select the needed excel file to be imported in R.And then the user need to select the needed excel file to be imported in R. Step 4: Select the import option and the excel file is successfully imported. Now, in this final step user need to select the import button and this will lead to successful importation of the selected excel file by the user in R. Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement Time Series Analysis in R How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24876, "s": 24848, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25105, "s": 24876, "text": "In this article, we will discuss how to import an excel file in the R Programming Language. There two different types of approaches to import the excel file into the R programming language and those are discussed properly below." }, { "code": null, "e": 25118, "s": 25105, "text": "File in use:" }, { "code": null, "e": 25385, "s": 25118, "text": "In this approach to import the Excel file in the R, the user needs to call the read_excel() function from readxl library of the R language with the name of the file as the parameter. With the use of this function, the user will be able to import the Excel file in R." }, { "code": null, "e": 25440, "s": 25385, "text": "Syntax: read_excel(filename, sheet, dtype = “float32”)" }, { "code": null, "e": 25452, "s": 25440, "text": "Parameters:" }, { "code": null, "e": 25486, "s": 25452, "text": "filename:-File name to read from." }, { "code": null, "e": 25526, "s": 25486, "text": "sheet:-Name of the sheet in Excel file." }, { "code": null, "e": 25550, "s": 25526, "text": "dtype:-Numpy data type." }, { "code": null, "e": 25559, "s": 25550, "text": "Returns:" }, { "code": null, "e": 25603, "s": 25559, "text": "The variable is treated to be a data frame." }, { "code": null, "e": 25612, "s": 25603, "text": "Example:" }, { "code": null, "e": 25614, "s": 25612, "text": "R" }, { "code": "library(readxl) gfg_data=read_excel('Data_gfg.xlsx') gfg_data", "e": 25678, "s": 25614, "text": null }, { "code": null, "e": 25686, "s": 25678, "text": "Output:" }, { "code": null, "e": 25998, "s": 25686, "text": "This approach is the easy approach to import the excel file in R compared with the previous one as this is the only approach to import an excel file in R where the user need not type any code in the console to import the excel file. Further, here user just needs to work on the environment window of the studio." }, { "code": null, "e": 26033, "s": 25998, "text": "Environment window of the Rstudio:" }, { "code": null, "e": 26121, "s": 26033, "text": "Steps to import excel file using Dataset option from the environment window of Rstudio:" }, { "code": null, "e": 26292, "s": 26121, "text": "Step 1: Select the Import Dataset option in the environment window. Here the user needs to select the option to import the dataset from the environment window in Rstudio." }, { "code": null, "e": 26527, "s": 26292, "text": "Step 2: Select the option of “From excel” under the import Dataset option. In this step, the user needs to select the option to “from excel” as the file is in the form of excel under the import dataset option to import the excel file." }, { "code": null, "e": 26812, "s": 26527, "text": "Step 3: Select the browse option and select the excel file to be imported. Now, under this with the click to the browse option user will be given the choice to select the needed excel file to be imported in R.And then the user need to select the needed excel file to be imported in R." }, { "code": null, "e": 27042, "s": 26812, "text": "Step 4: Select the import option and the excel file is successfully imported. Now, in this final step user need to select the import button and this will lead to successful importation of the selected excel file by the user in R." }, { "code": null, "e": 27049, "s": 27042, "text": "Picked" }, { "code": null, "e": 27057, "s": 27049, "text": "R-Excel" }, { "code": null, "e": 27068, "s": 27057, "text": "R Language" }, { "code": null, "e": 27166, "s": 27068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27175, "s": 27166, "text": "Comments" }, { "code": null, "e": 27188, "s": 27175, "text": "Old Comments" }, { "code": null, "e": 27240, "s": 27188, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27278, "s": 27240, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27313, "s": 27278, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27371, "s": 27313, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27420, "s": 27371, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27463, "s": 27420, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27513, "s": 27463, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27530, "s": 27513, "text": "R - if statement" }, { "code": null, "e": 27556, "s": 27530, "text": "Time Series Analysis in R" } ]
Machine Learning Made Simple With Excel | by Oscar Armas Luy | Towards Data Science
By the end of this tutorial, you’ll have implemented your first algorithm without touching a single line of code. You’ll use Machine Learning techniques to classify real data using basic functions in Excel. You don’t have to be a genius or a programmer to understand machine learning. Despite the popularized applications of self-driving cars, killer robots, and facial recognition, the foundations of machine learning (ML) are quite simple. This is a chance to get your feet wet and understand the power of these new techniques. All of the data scientists are probably cringing at the title of this tutorial. Excel is generally considered to be a terrible tool for serious data analytics. It does not scale to process the large datasets we deal with in the real world and it lacks some key functionality of programming languages and machine learning libraries. You’ll see a lot of the formulas given in this tutorial are complicated to accommodate for the shortfalls and peculiarities of Excel. The reason I’m using Excel is to make this introduction accessible for non-programmers since most of us have basic knowledge of the tool. Those that choose to pursue Machine Learning and Data Science more seriously will eventually upgrade to using Python or R, but there’s no harm in starting simple. The end goal of this tutorial is to use Machine Learning to build a classification model on a set of real data using an implementation of the k-nearest neighbors (KNN) algorithm. Don’t get overwhelmed, let’s break down what that means bit by bit. Machine Learning is a collection of techniques to optimize models. In other words, Machine Learning takes the models we’ve built and uses real world data to “learn” how to fine tune the parameters of the model to be most useful in a real world scenario based on the training data. In this tutorial we’ll be applying machine learning to a classification model. Don’t worry if you’re not fully clear right now, by the end of the tutorial you’ll know exactly what I’m talking about. Machine Learning algorithms adapt the model based on a set of training data. Training data is a data set that contains all of the variables we have available as well as the correct classification. Training sets can be developed in a variety of ways but in this tutorial, we’ll be using a training set that was classified by a human expert. It’s important to remember that machine learning models are only as good as the training data. The more accurate your training data and the more of it you have the better. In other words — garbage in, garbage out. A test set is typically a subset of the training data in that it also contains all variables and the correct classifications. The difference is in how we use it. While the training set helps to develop the model, the test set tries it out in a real world scenario and sees how well it fares. There are lots of complicated ways to measure error and test models but as long as you get the basic idea we can keep going. A Classification Model is simply a mathematical tool to determine what category or class of something you’re dealing with based on a set of variables or inputs. For example, if I wanted to classify whether an animal was a cat or a fish, I might use variables such as whether or not the animal swims, whether or not it has fur, and whether or not it eats to determine which class it falls under. You’ll notice two things. Firstly, the more variables you have the better. With more information, you can be more confident that your classification is correct. Secondly, some variables are more useful or predictive than others. Take the last example, whether or not the animal eats. The casual observer knows that both fish and cats eat, so having this piece of data isn’t useful in determining the class of the animal. The goal of machine learning in this context is to create the most useful classification model given the available data and to weed out the inputs that don’t improve the effectiveness of the model. K-Nearest Neighbors (KNN) is a specific type of Classification Model. The intuition is simple to understand. The model takes all of the data available about an unknown data point and compares it to a training set of data to determine which points in that training set the unknown point is most similar, or closest, to. The idea is that the unknown data point will most likely fall under the same class as the known data points it is most similar to. KNN is simply a mathematical way to determine the similarity between two data points. For this tutorial, we’ll be using a classic data set used to teach machine learning called the Iris Data Set. This is a collection of data about three species of the Iris flower and four pieces of data about them: sepal length, sepal width, petal length, and petal width. The data set has already been prepared to make it easy for beginners to jump right in. You can download the data in a compatible excel format at this link by clicking “download zip” in the top right and opening the contents in Excel. As I mentioned, this data set is meant to be simple to work with. Each of the first 4 columns (A-D)is a dimension, or feature, of the data. The fifth column, E, is the variety or the class of the flower. Each row is its own record, or data point. As you can see we have 150 known data points to work with. We have an important decision to make: how do we want to segregate this data set into a training set and a test set. Given a bigger data set, there are optimization techniques we could use to make this decision. Since this data set is small and made for beginners, we’re just going to split it 70/30 as a matter of convention. In other words, we will use 70% of the data, or 105 data points as a training set and the remaining 45 data points as a test set. We will now use Excel to randomly sample 70% of the data. First, add a column to your sheet called “Random Value” and use the RAND() function to randomly select a value between 0 and 1. Keep in mind that the RAND() function will re-select a new number each time your sheet recalculates. To avoid that, after generating my numbers I’m going to copy them (Ctrl+C) and then special paste over them as values (Ctrl+Shift+V) so that they stay fixed. We will start in cell F2 and drag down to the last data point. =RAND() Next I’m going to rank them 1 to 150 using Excel’s RANK() function, starting in cell G2 as shown below and dragging all the way down to the last data point. Make sure to lock the reference frame as shown by hitting F4 or adding the $ signs manually or else this formula won’t work as we intend. =RANK(F2, $F$2:$F$15) We now have a unique value between 1 and 150 for each data point. Because we want 105 values for our training set, we’re going to add one more column and select the values ranked 1 through 105 for our training set using a quick IF() function. Otherwise, we will add the value to our test set. Again, we will start at H2 and drag down to the last data point. =IF(G2<=105,”Training”, “Test”) At this point your data set should be set up like the screenshot. Remember that because we each took a different random sample the specific values in columns F-H will look different for you. You should also take a minute to add filters for our next step. Next we will break our two sets of data into their own worksheets (or tabs) to keep things organized. Create a new worksheet called “Training Set” and filter for the “Training” data in the original worksheet. Copy this data along with the headers and paste it into your “Training Set.” You should have 106 rows (105 values + the header row). Do the same for the worksheet “Test Set.” You should have 46 rows (45 values + the header row). At this point you can get rid of the “Iris” worksheet and delete columns F-H in both of your remaining worksheets since we’ve already segregated our data. Finally, I will add an “ID” column at the start of each worksheet and label each data point 1–105 and 1–45 respectively by simply typing in the number (dragging down the fill handle will be your friend here to save you work). This will help us do our calculations in the next sections. Make sure each of your sets is arranged like the example below. Our data is now ready and we can proceed to build our model. As a reminder, this model works by comparing the unknown data point we wish to classify to its nearest, or most similar, neighbors. To do that we will need to take each point in our test set and calculate its distance to each point in the training set. Distance is the way mathematicians determine which points are most similar in an n-dimensional space. The intuition is that the smaller the distance between the points the more similar they are. Most of us are used to calculating distance in a 2-dimensional space, such as an x,y coordinate system or using longitude and latitude. There are several ways to calculate distance but to keep it simple we’re going to use the Euclidean distance. Below is a visualization of the Euclidean distance formula in a 2-dimensional space. As you can see, the formula works by creating a right triangle between two points and determining the length of the hypotenuse, the longest side of the triangle, as identified by the arrow. Our data set is 4-dimensional. It’s difficult for us to visualize spaces beyond 3 dimensions, but regardless of whether or not you can visualize it we can still calculate the distance between two points the same way regardless of the number of dimensions. Here is the generic formula for Euclidean Distance: In plain language this is saying is that the Euclidean distance between two points, q & p, can be determined by taking each dimension for each point, starting with the first dimension, and squaring the difference between them iteratively until you’ve done so for all dimensions and added the differences together. Then we take the square root of that sum and we have the Euclidean distance. It sounds complicated but you’ll see that it is actually quite simple to use once we get back into our data. In our workbook, create a new worksheet called “Distance.” Our goal for this sheet is to create a 45X105 matrix of the distances between each data point in the test set and the training set. In our case, each row will correspond to one data point in the test set and each column will correspond to one data point in the training set. Starting in A2 and working down line by line until you hit A46, fill each cell with the numbers 1–45. Again, the fill handle is useful here so you don’t have to type the numbers one by one. Now, working from B1 and then column by column horizontally across until you hit DB1, fill each column with the numbers 1–105. Your matrix should look something like the screenshot below which shows a small portion of it. Before moving on, you’ll need to convert your matrix to a Table so we can keep things organized. Select your entire matrix and hit Ctrl+T and then name the table “Distance_Table” and select to create the table with Headers. Next, you’ll want to name your first Column “Test ID” by typing that into cell A1. Now that our table is set up we can start our calculations. We’ll start in cell B2 which will calculate the distance between the first point in our Training Set (ID #1) and the first point in our Test Set (ID #1). We can apply the Euclidean distance formula quickly by using the VLOOKUP function in excel to find the values for each dimension and then preforming the calculations as necessary. It’s best to copy and paste this formula into your formula bar in Cell B2 as it handles a couple peculiarities of the Table feature in Excel, but make sure you understand that all this formula is doing is applying the Euclidean Distance formula we discussed earlier. As written you can then drag this to fill your entire table. =SQRT(((VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 2, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 2, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 3, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 3, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 4, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 4, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 5, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 5, FALSE)) ^ 2)) You should end up with something like this: At this stage we have calculated the distance between every point in our test set and every point in our training set. Now we need to identify the closest neighbors to each point in our test set. Create a new worksheet called “Nearest Neighbors” and starting at A2 work down line by line to fill the cells with the numbers 1–45 to correspond with the points in our Test Set. Our columns are not going to represent the Training Set like they have on previous sheets. Instead, these are going to represent the 6 closest neighbors, starting with the 1st closest and then the second closest and so on. The 1st closest neighbor has the smallest distance, the 2nd closest neighbor has the second smallest distance and so on. Your sheet should look like this: As we have before we will write a formula in cell B2 that can be dragged to fill the rest of our matrix. Our approach is to identify the smallest value in our corresponding row (2) in the distance table, find the column number for that value, and then return the column name since that will give us the ID of the value in the Training Set. We will use a combination of the Index and the Match functions to achieve this. Note that we’re able to make this formula simple because we had the foresight to set up our Distance matrix as a table in Excel and so we can easily pull in the headers. =INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 1), Distance!2:2, FALSE)) Drag this formula to fill the top row of your nearest neighbors matrix. You will need to manually adjust the bold value in the SMALL() function to represent the neighbor we’re looking for. So for example, to find the second nearest neighbor the formula would be as follows. =INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 2), Distance!2:2, FALSE)) Remember your values will be different since your random sample used to form the Test Set is different from mine. At this stage, I usually take a minute to double check one of the rows manually when feasible just to make sure my formulas are working as expected. At scale you’ll want to use automated testing, but for now we’re keeping it simple. We have one last step: we need to identify the classification of each of our nearest neighbors. We’ll go back to the formula in B2 and modify it to do a VLOOKUP of the ID in the Training Set and return the classification. We’ll then drag that to fill the matrix. =VLOOKUP(NUMBERVALUE(INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 1), Distance!2:2, FALSE))), ‘Training Set’!$A$1:$F$106, 6, FALSE) Let’s take a step back and look at what we’ve accomplished. You’ve now identified for each point in your test set the classification for the 6 nearest neighbors. You will likely notice that for all or almost all of your data points the 6 nearest neighbors will all fall into the same classification. This means that our data set his highly clustered. In our case, our data is highly clustered for two reasons. Firstly, as we discussed at the start of the tutorial the data set is designed to be easy to work with. Secondly, this is a low-dimensional data set since we are only working with 4 dimensions. As you deal with real-world data, you will typically find that it is far less clustered especially as the number of dimensions increases. The less clustered your data, the larger the training set will need to be to build a useful model. If our data was always as neatly clustered as the Iris Data Set there would be no need for machine learning. We would simply find the nearest neighbor using our formula and use that to determine the classification of each unknown data point. Since this is not usually the case, machine learning helps us more accurately predict the classification of an unknown data point by looking at multiple neighbors at once. But how many neighbors should we look at? That’s where the “K” in K-Nearest Neighbors comes in. K describes the number of neighbors we’ll consider when predicting the classification of an unknown data point. Intuitively, it’s important to understand why this problem is tricky. It is possible to look at too few neighbors and also too many neighbors. Especially as the number of dimensions increase, it is possible that the nearest neighbor is not always the correct classification. Looking at too few neighbors limits the amount of information your model has available to make its determination. Considering too many neighbors will actually degrade the quality of the information your model uses as an input. This is because as more neighbors are introduced you are also introducing noise to the data. Just think about it — it wouldn’t make sense to consider all 104 neighbors in our example! See a visual representation of this concept below. Thus this becomes a classic optimization problem where we attempt to find the K value that gives the most information without being too high or too low. For this tutorial, we’ll use a very simple process of trial & error to determine the optimal K value. Before we move on, I recommend looking at your Nearest Neighbors worksheet and making a guess as to what the best k value might be, just for fun. We’ll find out soon enough if you’re right! An algorithm is just a set of steps for a computer to repeat over and over again according to a defined set of rules. In this case, we will tell the computer to try different K values, calculate the rate of error for each one using our test set, and then ultimately return the value that produces the lowest error rate. To do this we’ll need to create a new worksheet called “KNN Model.” We’ll set it up as follows, labeling rows A4 through A48 with 1–45 for each of our test data points. Let’s start with the predicted value in Column B. We need this formula to adjust based on the K value. In the case that the K Value is 1, the formula is simple, we just take the closest neighbor. =’Nearest Neighbors’!B2 In the case that the K Value is greater than 1, we’re going to take the most common neighbor that appears. If the occurrence of neighbors is equally distributed, for example if 3 of the neighbors are Setosa and 3 of the neighbors are Virginica when K=6, we’ll side with the classification of the closest neighbor. The formula for K=2 would be as follows. We use IFERROR because this formula returns an error when there are two neighbors that occur an equal number of times for the given K value. =IFERROR(INDEX(‘Nearest Neighbors’!B2:C2,MODE(MATCH(‘Nearest Neighbors’!B2:C2,’Nearest Neighbors’!B2:C2,0))), ‘Nearest Neighbors’!B2) You’ll want to use the expanded formula below in cell B4 which enables you to use K values up to and including K=6. No need to worry about the specifics of this formula, just copy and paste it. By the way, having to use complicated, finicky, and hard to understand formulas like these are one of the limitations of Excel I was referring to earlier. This would have been a piece of cake in Python. Note that this formula will return an error if there is a no value in K or a value not between 1 and 6. You should copy this formula from cell B4 down Column B. =IFS($B$1=1, 'Nearest Neighbors'!B2, $B$1=2, IFERROR(INDEX('Nearest Neighbors'!B2:C2,MODE(MATCH('Nearest Neighbors'!B2:C2,'Nearest Neighbors'!B2:C2,0))), 'Nearest Neighbors'!B2), $B$1=3, IFERROR(INDEX('Nearest Neighbors'!B2:D2,MODE(MATCH('Nearest Neighbors'!B2:D2,'Nearest Neighbors'!B2:D2,0))), 'Nearest Neighbors'!B2), $B$1=4, IFERROR(INDEX('Nearest Neighbors'!B2:E2,MODE(MATCH('Nearest Neighbors'!B2:E2,'Nearest Neighbors'!B2:E2,0))), 'Nearest Neighbors'!B2), $B$1=5, IFERROR(INDEX('Nearest Neighbors'!B2:F2,MODE(MATCH('Nearest Neighbors'!B2:F2,'Nearest Neighbors'!B2:F2,0))), 'Nearest Neighbors'!B2),$B$1=6, IFERROR(INDEX('Nearest Neighbors'!B2:G2,MODE(MATCH('Nearest Neighbors'!B2:G2,'Nearest Neighbors'!B2:G2,0))), 'Nearest Neighbors'!B2)) Next, we want to pull in the actual, known classification of each test point so we can determine if our model was right or not. For this we use a quick VLOOKUP in Column C, starting in cell C4 and dragging down. =VLOOKUP(A4, ‘Test Set’!$A$1:$F$46, 6, FALSE) Then we’ll set up a formula in Column D to return a 1 if the prediction was incorrect, or in error, and a 0 if the prediction was correct. You’ll start in cell D4 and drag the formula down. =IF(B4=C4, 0, 1) Finally we’ll calculate the error rate by dividing the number of errors by the total number of data points, using this formula in cell B2. As a matter of convention we will format this as a percentage. =SUM(D4:D48)/COUNT(D4:D48) We’re now ready to run our algorithm for different K values. Because we’re only testing 6 values, we could do it by hand. But that would be no fun and more importantly doesn’t scale. You’ll need to enable the Solver Add-In for Excel following the instructions in this article before we proceed. Now, navigate to the Data ribbon and click the Solver button. The solver button does the trial and error for us automatically according to our instructions. You’ll have a dialogue box of parameters, or instructions, which you’ll want to set up as shown below. We’re setting it up so that it seeks to minimize the error rate while testing values between 1 and 6, only testing integer values. Excel will spin for a minute and you may see it flash a few values on your screen before getting this dialogue box. You should click OK to Keep Solver Solution. Many optimization algorithms have multiple solutions due to the fact that the data has multiple minima or maxima. This happened in my case. In fact, in my particular case, all integer values 1 through 6 represent minima with an error rate of approximately 2%. So what do we do now? A few things run through my head. First, this test set isn’t very good. The model didn’t gain any optimization benefits from the test set and as such, I would probably re-do the test set and try again to see if I get different results. I’d also consider using more sophisticated methods of testing such as cross validation. At an error rate this low in my test set, I also start to worry about over-fitting. Over-fitting is a problem that occurs in machine learning when a model is too tailored to the nuances of a particular training or test data set. When a model is over-fit it is not as predictive or effective when encountering new data in the wild. Of course, with an academic data set like this we’d expect our error rate to be fairly low. The next consideration is which value to choose if I have identified several minima. While the test wasn’t effective in this particular example, generally I would pick the lowest number of neighbors that is at a minima to conserve computing resources. My model will run faster if it has to consider fewer neighbors. It won’t make a difference with a small data set but decisions like this conserve substantial resources at scale. Kudos! You’ve learned the basics of machine learning and implemented the KNN algorithm all without leaving the confines of Excel. Remember that Excel is merely a tool and that the important part is that you understand the intuition and concepts that make this approach work. Understanding the fundamentals will help you as you dive deeper into Data Science and Machine Learning and start to develop your own models.
[ { "code": null, "e": 702, "s": 172, "text": "By the end of this tutorial, you’ll have implemented your first algorithm without touching a single line of code. You’ll use Machine Learning techniques to classify real data using basic functions in Excel. You don’t have to be a genius or a programmer to understand machine learning. Despite the popularized applications of self-driving cars, killer robots, and facial recognition, the foundations of machine learning (ML) are quite simple. This is a chance to get your feet wet and understand the power of these new techniques." }, { "code": null, "e": 1469, "s": 702, "text": "All of the data scientists are probably cringing at the title of this tutorial. Excel is generally considered to be a terrible tool for serious data analytics. It does not scale to process the large datasets we deal with in the real world and it lacks some key functionality of programming languages and machine learning libraries. You’ll see a lot of the formulas given in this tutorial are complicated to accommodate for the shortfalls and peculiarities of Excel. The reason I’m using Excel is to make this introduction accessible for non-programmers since most of us have basic knowledge of the tool. Those that choose to pursue Machine Learning and Data Science more seriously will eventually upgrade to using Python or R, but there’s no harm in starting simple." }, { "code": null, "e": 1716, "s": 1469, "text": "The end goal of this tutorial is to use Machine Learning to build a classification model on a set of real data using an implementation of the k-nearest neighbors (KNN) algorithm. Don’t get overwhelmed, let’s break down what that means bit by bit." }, { "code": null, "e": 2196, "s": 1716, "text": "Machine Learning is a collection of techniques to optimize models. In other words, Machine Learning takes the models we’ve built and uses real world data to “learn” how to fine tune the parameters of the model to be most useful in a real world scenario based on the training data. In this tutorial we’ll be applying machine learning to a classification model. Don’t worry if you’re not fully clear right now, by the end of the tutorial you’ll know exactly what I’m talking about." }, { "code": null, "e": 2750, "s": 2196, "text": "Machine Learning algorithms adapt the model based on a set of training data. Training data is a data set that contains all of the variables we have available as well as the correct classification. Training sets can be developed in a variety of ways but in this tutorial, we’ll be using a training set that was classified by a human expert. It’s important to remember that machine learning models are only as good as the training data. The more accurate your training data and the more of it you have the better. In other words — garbage in, garbage out." }, { "code": null, "e": 3167, "s": 2750, "text": "A test set is typically a subset of the training data in that it also contains all variables and the correct classifications. The difference is in how we use it. While the training set helps to develop the model, the test set tries it out in a real world scenario and sees how well it fares. There are lots of complicated ways to measure error and test models but as long as you get the basic idea we can keep going." }, { "code": null, "e": 4181, "s": 3167, "text": "A Classification Model is simply a mathematical tool to determine what category or class of something you’re dealing with based on a set of variables or inputs. For example, if I wanted to classify whether an animal was a cat or a fish, I might use variables such as whether or not the animal swims, whether or not it has fur, and whether or not it eats to determine which class it falls under. You’ll notice two things. Firstly, the more variables you have the better. With more information, you can be more confident that your classification is correct. Secondly, some variables are more useful or predictive than others. Take the last example, whether or not the animal eats. The casual observer knows that both fish and cats eat, so having this piece of data isn’t useful in determining the class of the animal. The goal of machine learning in this context is to create the most useful classification model given the available data and to weed out the inputs that don’t improve the effectiveness of the model." }, { "code": null, "e": 4717, "s": 4181, "text": "K-Nearest Neighbors (KNN) is a specific type of Classification Model. The intuition is simple to understand. The model takes all of the data available about an unknown data point and compares it to a training set of data to determine which points in that training set the unknown point is most similar, or closest, to. The idea is that the unknown data point will most likely fall under the same class as the known data points it is most similar to. KNN is simply a mathematical way to determine the similarity between two data points." }, { "code": null, "e": 5223, "s": 4717, "text": "For this tutorial, we’ll be using a classic data set used to teach machine learning called the Iris Data Set. This is a collection of data about three species of the Iris flower and four pieces of data about them: sepal length, sepal width, petal length, and petal width. The data set has already been prepared to make it easy for beginners to jump right in. You can download the data in a compatible excel format at this link by clicking “download zip” in the top right and opening the contents in Excel." }, { "code": null, "e": 5529, "s": 5223, "text": "As I mentioned, this data set is meant to be simple to work with. Each of the first 4 columns (A-D)is a dimension, or feature, of the data. The fifth column, E, is the variety or the class of the flower. Each row is its own record, or data point. As you can see we have 150 known data points to work with." }, { "code": null, "e": 5986, "s": 5529, "text": "We have an important decision to make: how do we want to segregate this data set into a training set and a test set. Given a bigger data set, there are optimization techniques we could use to make this decision. Since this data set is small and made for beginners, we’re just going to split it 70/30 as a matter of convention. In other words, we will use 70% of the data, or 105 data points as a training set and the remaining 45 data points as a test set." }, { "code": null, "e": 6494, "s": 5986, "text": "We will now use Excel to randomly sample 70% of the data. First, add a column to your sheet called “Random Value” and use the RAND() function to randomly select a value between 0 and 1. Keep in mind that the RAND() function will re-select a new number each time your sheet recalculates. To avoid that, after generating my numbers I’m going to copy them (Ctrl+C) and then special paste over them as values (Ctrl+Shift+V) so that they stay fixed. We will start in cell F2 and drag down to the last data point." }, { "code": null, "e": 6502, "s": 6494, "text": "=RAND()" }, { "code": null, "e": 6797, "s": 6502, "text": "Next I’m going to rank them 1 to 150 using Excel’s RANK() function, starting in cell G2 as shown below and dragging all the way down to the last data point. Make sure to lock the reference frame as shown by hitting F4 or adding the $ signs manually or else this formula won’t work as we intend." }, { "code": null, "e": 6819, "s": 6797, "text": "=RANK(F2, $F$2:$F$15)" }, { "code": null, "e": 7177, "s": 6819, "text": "We now have a unique value between 1 and 150 for each data point. Because we want 105 values for our training set, we’re going to add one more column and select the values ranked 1 through 105 for our training set using a quick IF() function. Otherwise, we will add the value to our test set. Again, we will start at H2 and drag down to the last data point." }, { "code": null, "e": 7209, "s": 7177, "text": "=IF(G2<=105,”Training”, “Test”)" }, { "code": null, "e": 7464, "s": 7209, "text": "At this point your data set should be set up like the screenshot. Remember that because we each took a different random sample the specific values in columns F-H will look different for you. You should also take a minute to add filters for our next step." }, { "code": null, "e": 7902, "s": 7464, "text": "Next we will break our two sets of data into their own worksheets (or tabs) to keep things organized. Create a new worksheet called “Training Set” and filter for the “Training” data in the original worksheet. Copy this data along with the headers and paste it into your “Training Set.” You should have 106 rows (105 values + the header row). Do the same for the worksheet “Test Set.” You should have 46 rows (45 values + the header row)." }, { "code": null, "e": 8407, "s": 7902, "text": "At this point you can get rid of the “Iris” worksheet and delete columns F-H in both of your remaining worksheets since we’ve already segregated our data. Finally, I will add an “ID” column at the start of each worksheet and label each data point 1–105 and 1–45 respectively by simply typing in the number (dragging down the fill handle will be your friend here to save you work). This will help us do our calculations in the next sections. Make sure each of your sets is arranged like the example below." }, { "code": null, "e": 8721, "s": 8407, "text": "Our data is now ready and we can proceed to build our model. As a reminder, this model works by comparing the unknown data point we wish to classify to its nearest, or most similar, neighbors. To do that we will need to take each point in our test set and calculate its distance to each point in the training set." }, { "code": null, "e": 9437, "s": 8721, "text": "Distance is the way mathematicians determine which points are most similar in an n-dimensional space. The intuition is that the smaller the distance between the points the more similar they are. Most of us are used to calculating distance in a 2-dimensional space, such as an x,y coordinate system or using longitude and latitude. There are several ways to calculate distance but to keep it simple we’re going to use the Euclidean distance. Below is a visualization of the Euclidean distance formula in a 2-dimensional space. As you can see, the formula works by creating a right triangle between two points and determining the length of the hypotenuse, the longest side of the triangle, as identified by the arrow." }, { "code": null, "e": 9745, "s": 9437, "text": "Our data set is 4-dimensional. It’s difficult for us to visualize spaces beyond 3 dimensions, but regardless of whether or not you can visualize it we can still calculate the distance between two points the same way regardless of the number of dimensions. Here is the generic formula for Euclidean Distance:" }, { "code": null, "e": 10245, "s": 9745, "text": "In plain language this is saying is that the Euclidean distance between two points, q & p, can be determined by taking each dimension for each point, starting with the first dimension, and squaring the difference between them iteratively until you’ve done so for all dimensions and added the differences together. Then we take the square root of that sum and we have the Euclidean distance. It sounds complicated but you’ll see that it is actually quite simple to use once we get back into our data." }, { "code": null, "e": 10991, "s": 10245, "text": "In our workbook, create a new worksheet called “Distance.” Our goal for this sheet is to create a 45X105 matrix of the distances between each data point in the test set and the training set. In our case, each row will correspond to one data point in the test set and each column will correspond to one data point in the training set. Starting in A2 and working down line by line until you hit A46, fill each cell with the numbers 1–45. Again, the fill handle is useful here so you don’t have to type the numbers one by one. Now, working from B1 and then column by column horizontally across until you hit DB1, fill each column with the numbers 1–105. Your matrix should look something like the screenshot below which shows a small portion of it." }, { "code": null, "e": 11298, "s": 10991, "text": "Before moving on, you’ll need to convert your matrix to a Table so we can keep things organized. Select your entire matrix and hit Ctrl+T and then name the table “Distance_Table” and select to create the table with Headers. Next, you’ll want to name your first Column “Test ID” by typing that into cell A1." }, { "code": null, "e": 12020, "s": 11298, "text": "Now that our table is set up we can start our calculations. We’ll start in cell B2 which will calculate the distance between the first point in our Training Set (ID #1) and the first point in our Test Set (ID #1). We can apply the Euclidean distance formula quickly by using the VLOOKUP function in excel to find the values for each dimension and then preforming the calculations as necessary. It’s best to copy and paste this formula into your formula bar in Cell B2 as it handles a couple peculiarities of the Table feature in Excel, but make sure you understand that all this formula is doing is applying the Euclidean Distance formula we discussed earlier. As written you can then drag this to fill your entire table." }, { "code": null, "e": 12733, "s": 12020, "text": "=SQRT(((VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 2, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 2, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 3, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 3, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 4, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 4, FALSE)) ^ 2+(VLOOKUP(NUMBERVALUE(Distance_Table[[#Headers],[1]]), ‘Training Set’!$A$1:$F$106, 5, FALSE)-VLOOKUP(Distance_Table[@[Test ID]:[Test ID]], ‘Test Set’!$A$1:$F$46, 5, FALSE)) ^ 2))" }, { "code": null, "e": 12777, "s": 12733, "text": "You should end up with something like this:" }, { "code": null, "e": 13530, "s": 12777, "text": "At this stage we have calculated the distance between every point in our test set and every point in our training set. Now we need to identify the closest neighbors to each point in our test set. Create a new worksheet called “Nearest Neighbors” and starting at A2 work down line by line to fill the cells with the numbers 1–45 to correspond with the points in our Test Set. Our columns are not going to represent the Training Set like they have on previous sheets. Instead, these are going to represent the 6 closest neighbors, starting with the 1st closest and then the second closest and so on. The 1st closest neighbor has the smallest distance, the 2nd closest neighbor has the second smallest distance and so on. Your sheet should look like this:" }, { "code": null, "e": 14120, "s": 13530, "text": "As we have before we will write a formula in cell B2 that can be dragged to fill the rest of our matrix. Our approach is to identify the smallest value in our corresponding row (2) in the distance table, find the column number for that value, and then return the column name since that will give us the ID of the value in the Training Set. We will use a combination of the Index and the Match functions to achieve this. Note that we’re able to make this formula simple because we had the foresight to set up our Distance matrix as a table in Excel and so we can easily pull in the headers." }, { "code": null, "e": 14210, "s": 14120, "text": "=INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 1), Distance!2:2, FALSE))" }, { "code": null, "e": 14484, "s": 14210, "text": "Drag this formula to fill the top row of your nearest neighbors matrix. You will need to manually adjust the bold value in the SMALL() function to represent the neighbor we’re looking for. So for example, to find the second nearest neighbor the formula would be as follows." }, { "code": null, "e": 14574, "s": 14484, "text": "=INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 2), Distance!2:2, FALSE))" }, { "code": null, "e": 14688, "s": 14574, "text": "Remember your values will be different since your random sample used to form the Test Set is different from mine." }, { "code": null, "e": 14921, "s": 14688, "text": "At this stage, I usually take a minute to double check one of the rows manually when feasible just to make sure my formulas are working as expected. At scale you’ll want to use automated testing, but for now we’re keeping it simple." }, { "code": null, "e": 15184, "s": 14921, "text": "We have one last step: we need to identify the classification of each of our nearest neighbors. We’ll go back to the formula in B2 and modify it to do a VLOOKUP of the ID in the Training Set and return the classification. We’ll then drag that to fill the matrix." }, { "code": null, "e": 15334, "s": 15184, "text": "=VLOOKUP(NUMBERVALUE(INDEX(Distance_Table[#Headers], MATCH(SMALL(Distance!$B2:$DB2, 1), Distance!2:2, FALSE))), ‘Training Set’!$A$1:$F$106, 6, FALSE)" }, { "code": null, "e": 16175, "s": 15334, "text": "Let’s take a step back and look at what we’ve accomplished. You’ve now identified for each point in your test set the classification for the 6 nearest neighbors. You will likely notice that for all or almost all of your data points the 6 nearest neighbors will all fall into the same classification. This means that our data set his highly clustered. In our case, our data is highly clustered for two reasons. Firstly, as we discussed at the start of the tutorial the data set is designed to be easy to work with. Secondly, this is a low-dimensional data set since we are only working with 4 dimensions. As you deal with real-world data, you will typically find that it is far less clustered especially as the number of dimensions increases. The less clustered your data, the larger the training set will need to be to build a useful model." }, { "code": null, "e": 16797, "s": 16175, "text": "If our data was always as neatly clustered as the Iris Data Set there would be no need for machine learning. We would simply find the nearest neighbor using our formula and use that to determine the classification of each unknown data point. Since this is not usually the case, machine learning helps us more accurately predict the classification of an unknown data point by looking at multiple neighbors at once. But how many neighbors should we look at? That’s where the “K” in K-Nearest Neighbors comes in. K describes the number of neighbors we’ll consider when predicting the classification of an unknown data point." }, { "code": null, "e": 17534, "s": 16797, "text": "Intuitively, it’s important to understand why this problem is tricky. It is possible to look at too few neighbors and also too many neighbors. Especially as the number of dimensions increase, it is possible that the nearest neighbor is not always the correct classification. Looking at too few neighbors limits the amount of information your model has available to make its determination. Considering too many neighbors will actually degrade the quality of the information your model uses as an input. This is because as more neighbors are introduced you are also introducing noise to the data. Just think about it — it wouldn’t make sense to consider all 104 neighbors in our example! See a visual representation of this concept below." }, { "code": null, "e": 17687, "s": 17534, "text": "Thus this becomes a classic optimization problem where we attempt to find the K value that gives the most information without being too high or too low." }, { "code": null, "e": 17979, "s": 17687, "text": "For this tutorial, we’ll use a very simple process of trial & error to determine the optimal K value. Before we move on, I recommend looking at your Nearest Neighbors worksheet and making a guess as to what the best k value might be, just for fun. We’ll find out soon enough if you’re right!" }, { "code": null, "e": 18468, "s": 17979, "text": "An algorithm is just a set of steps for a computer to repeat over and over again according to a defined set of rules. In this case, we will tell the computer to try different K values, calculate the rate of error for each one using our test set, and then ultimately return the value that produces the lowest error rate. To do this we’ll need to create a new worksheet called “KNN Model.” We’ll set it up as follows, labeling rows A4 through A48 with 1–45 for each of our test data points." }, { "code": null, "e": 18664, "s": 18468, "text": "Let’s start with the predicted value in Column B. We need this formula to adjust based on the K value. In the case that the K Value is 1, the formula is simple, we just take the closest neighbor." }, { "code": null, "e": 18688, "s": 18664, "text": "=’Nearest Neighbors’!B2" }, { "code": null, "e": 19184, "s": 18688, "text": "In the case that the K Value is greater than 1, we’re going to take the most common neighbor that appears. If the occurrence of neighbors is equally distributed, for example if 3 of the neighbors are Setosa and 3 of the neighbors are Virginica when K=6, we’ll side with the classification of the closest neighbor. The formula for K=2 would be as follows. We use IFERROR because this formula returns an error when there are two neighbors that occur an equal number of times for the given K value." }, { "code": null, "e": 19318, "s": 19184, "text": "=IFERROR(INDEX(‘Nearest Neighbors’!B2:C2,MODE(MATCH(‘Nearest Neighbors’!B2:C2,’Nearest Neighbors’!B2:C2,0))), ‘Nearest Neighbors’!B2)" }, { "code": null, "e": 19876, "s": 19318, "text": "You’ll want to use the expanded formula below in cell B4 which enables you to use K values up to and including K=6. No need to worry about the specifics of this formula, just copy and paste it. By the way, having to use complicated, finicky, and hard to understand formulas like these are one of the limitations of Excel I was referring to earlier. This would have been a piece of cake in Python. Note that this formula will return an error if there is a no value in K or a value not between 1 and 6. You should copy this formula from cell B4 down Column B." }, { "code": null, "e": 20622, "s": 19876, "text": "=IFS($B$1=1, 'Nearest Neighbors'!B2, $B$1=2, IFERROR(INDEX('Nearest Neighbors'!B2:C2,MODE(MATCH('Nearest Neighbors'!B2:C2,'Nearest Neighbors'!B2:C2,0))), 'Nearest Neighbors'!B2), $B$1=3, IFERROR(INDEX('Nearest Neighbors'!B2:D2,MODE(MATCH('Nearest Neighbors'!B2:D2,'Nearest Neighbors'!B2:D2,0))), 'Nearest Neighbors'!B2), $B$1=4, IFERROR(INDEX('Nearest Neighbors'!B2:E2,MODE(MATCH('Nearest Neighbors'!B2:E2,'Nearest Neighbors'!B2:E2,0))), 'Nearest Neighbors'!B2), $B$1=5, IFERROR(INDEX('Nearest Neighbors'!B2:F2,MODE(MATCH('Nearest Neighbors'!B2:F2,'Nearest Neighbors'!B2:F2,0))), 'Nearest Neighbors'!B2),$B$1=6, IFERROR(INDEX('Nearest Neighbors'!B2:G2,MODE(MATCH('Nearest Neighbors'!B2:G2,'Nearest Neighbors'!B2:G2,0))), 'Nearest Neighbors'!B2))" }, { "code": null, "e": 20834, "s": 20622, "text": "Next, we want to pull in the actual, known classification of each test point so we can determine if our model was right or not. For this we use a quick VLOOKUP in Column C, starting in cell C4 and dragging down." }, { "code": null, "e": 20880, "s": 20834, "text": "=VLOOKUP(A4, ‘Test Set’!$A$1:$F$46, 6, FALSE)" }, { "code": null, "e": 21070, "s": 20880, "text": "Then we’ll set up a formula in Column D to return a 1 if the prediction was incorrect, or in error, and a 0 if the prediction was correct. You’ll start in cell D4 and drag the formula down." }, { "code": null, "e": 21087, "s": 21070, "text": "=IF(B4=C4, 0, 1)" }, { "code": null, "e": 21289, "s": 21087, "text": "Finally we’ll calculate the error rate by dividing the number of errors by the total number of data points, using this formula in cell B2. As a matter of convention we will format this as a percentage." }, { "code": null, "e": 21316, "s": 21289, "text": "=SUM(D4:D48)/COUNT(D4:D48)" }, { "code": null, "e": 21611, "s": 21316, "text": "We’re now ready to run our algorithm for different K values. Because we’re only testing 6 values, we could do it by hand. But that would be no fun and more importantly doesn’t scale. You’ll need to enable the Solver Add-In for Excel following the instructions in this article before we proceed." }, { "code": null, "e": 22002, "s": 21611, "text": "Now, navigate to the Data ribbon and click the Solver button. The solver button does the trial and error for us automatically according to our instructions. You’ll have a dialogue box of parameters, or instructions, which you’ll want to set up as shown below. We’re setting it up so that it seeks to minimize the error rate while testing values between 1 and 6, only testing integer values." }, { "code": null, "e": 22163, "s": 22002, "text": "Excel will spin for a minute and you may see it flash a few values on your screen before getting this dialogue box. You should click OK to Keep Solver Solution." }, { "code": null, "e": 22445, "s": 22163, "text": "Many optimization algorithms have multiple solutions due to the fact that the data has multiple minima or maxima. This happened in my case. In fact, in my particular case, all integer values 1 through 6 represent minima with an error rate of approximately 2%. So what do we do now?" }, { "code": null, "e": 22769, "s": 22445, "text": "A few things run through my head. First, this test set isn’t very good. The model didn’t gain any optimization benefits from the test set and as such, I would probably re-do the test set and try again to see if I get different results. I’d also consider using more sophisticated methods of testing such as cross validation." }, { "code": null, "e": 23192, "s": 22769, "text": "At an error rate this low in my test set, I also start to worry about over-fitting. Over-fitting is a problem that occurs in machine learning when a model is too tailored to the nuances of a particular training or test data set. When a model is over-fit it is not as predictive or effective when encountering new data in the wild. Of course, with an academic data set like this we’d expect our error rate to be fairly low." }, { "code": null, "e": 23622, "s": 23192, "text": "The next consideration is which value to choose if I have identified several minima. While the test wasn’t effective in this particular example, generally I would pick the lowest number of neighbors that is at a minima to conserve computing resources. My model will run faster if it has to consider fewer neighbors. It won’t make a difference with a small data set but decisions like this conserve substantial resources at scale." } ]
How to provide multiple statements on a single line in Python?
More than one statements in a block of uniform indent form a compound statement. Normally each statement is written on separate physical line in editor. However, statements in a block can be written in one line if they are separated by semicolon. Following is code of three statements written in separate lines a=10 b=20 c=a*b print (c) These statements can very well be written in one line by putting semicolon in between. a=10; b=20; c=1*b; print (c) A new block of increased indent generally starts after : symbol as in case of if, else, while, for, try statements. However, using above syntax, statements in block can be written in one line by putting semicolon. Following is a straight forward example of a block of statements in a for loop for i in range(5): print ("Hello") print ("i=",i) This block can also be written in single line as follows − for i in range(5): print ("Hello"); print ("i=",i) However, this practice is not allowed if there is a nested block of statements.
[ { "code": null, "e": 1373, "s": 1062, "text": "More than one statements in a block of uniform indent form a compound statement. Normally each statement is written on separate physical line in editor. However, statements in a block can be written in one line if they are separated by semicolon. Following is code of three statements written in separate lines" }, { "code": null, "e": 1399, "s": 1373, "text": "a=10\nb=20\nc=a*b\nprint (c)" }, { "code": null, "e": 1486, "s": 1399, "text": "These statements can very well be written in one line by putting semicolon in between." }, { "code": null, "e": 1515, "s": 1486, "text": "a=10; b=20; c=1*b; print (c)" }, { "code": null, "e": 1808, "s": 1515, "text": "A new block of increased indent generally starts after : symbol as in case of if, else, while, for, try statements. However, using above syntax, statements in block can be written in one line by putting semicolon. Following is a straight forward example of a block of statements in a for loop" }, { "code": null, "e": 1864, "s": 1808, "text": "for i in range(5):\n print (\"Hello\")\n print (\"i=\",i)" }, { "code": null, "e": 1923, "s": 1864, "text": "This block can also be written in single line as follows −" }, { "code": null, "e": 1974, "s": 1923, "text": "for i in range(5): print (\"Hello\"); print (\"i=\",i)" }, { "code": null, "e": 2054, "s": 1974, "text": "However, this practice is not allowed if there is a nested block of statements." } ]
Tryit Editor v3.7
Tryit: Grey HEX color values
[]
The Art of Geofencing in Python. Tutorial — Triggering notifications and... | by Abdishakur | Towards Data Science
Geofencing is often used tool in Geographic data science, especially in marketing, security and zoning applications. The example in the above GIF shows an app that alerts vehicles based on their location and London’s Congestion Charge Zone (CCZ). The application calculates the congestion charge and tracks the number of vehicles inside the congestion area at a given time. The concept of geofencing is straightforward, yet it is a powerful technique that enhances location applications. Simply put, a geofence is a defining virtual boundary around geographic objects or an area, so that every time a user enters or leaves the boundary perimeters, actions or notifications can be triggered. With the increased use of smartphones, GPS, and location services, geofencing becomes an indispensable tool in location data analytics and intelligence. In this tutorial, we use a GPS Trajectory dataset. It contains GPSpoints (latitude and longitude) with timestamps. It also provides unique track_id for each trajectory. Let us read the data with the Pandas library. import pandas as pdimport geopandas as gpdimport plotly_express as pximport matplotlib.pyplot as plt!wget https://www.dropbox.com/s/ejev7z29lzirbo5/GPSTrajectory.zip!unzip GPSTrajectory.zipdf = pd.read_csv(‘GPSTrajectory/go_track_trackspoints.csv’)df.head() The first five rows of the dataset are shown below. We have latitude and longitude as well as track_id and time. We convert the Dataframe into Geodataframe, which allows us to perform geofencing. Converting the data frame to Geodataframe with Geopandas is straightforward. gdf = gpd.GeoDataFrame( df, geometry=gpd.points_from_xy(df.longitude, df.latitude))gdf.head() Let us plot a map of the dataset. We use Plotly Express here as offers an easy interface and high-level API for plotting with Plotly. We need to set Mapbox token here. px.set_mapbox_access_token(“pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w”)px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude” ,size_max=6, zoom=8, width=1200, height=800) The plot below shows all the points in the dataset. As you can see, these trajectories fall in 3 different cities. Let us filter out other cities and focus on the central city(Aracuja) since most of the data fall here. gdf = df[(gdf[‘latitude’]<-10.80) & (gdf[‘longitude’]>-37.5)]px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude” ,size_max=6, zoom=8, width=1200, height=800) Now we have only points that we are interested in Aracuja city, Brazil. Now that we have cleaned the data let us do geofencing. First, we need to have an area that marks the geofence. Let us download an area that I have created which is in the city centre. # Get the data!wget https://www.dropbox.com/s/e9g5n7e7iwnue4x/CENTERAREA.zip!unzip CENTERAREA.zippolygon = gpd.read_file(“CENTERAREA.geojson”) Let us plot the polygon with Geopandas and overlay the points to see both data. # Plot track_id 1 points over the Buffer Polygonfig, ax = plt.subplots(figsize=(10,10))gdf.plot(ax=ax, color=’black’)polygon.plot(ax=ax)#plt.tight_layout()#plt.axis(‘off’)plt.show() Here is the map overlaying both the polygon and points data, shown below. Now, let us perform what we call Point in Polygon (PIP). We can use “within” operation in Geopandas to check whether the points are inside the polygon or not. mask = (polygon.loc[0, ‘geometry’])pip_mask_geofence = gdf.within(mask) The above code will return a series of False and True values depending on whether the point is inside the polygon or not. Let us add a column to our data that marks False and True values. We call this “geofence”. #Create PIP maskgdf.loc[:,’geofence’] = pip_mask_geofencegdf.sample(5) Now, our data has a “geofence” column. Let us look at a sample of the data. As you can see, there is addition column in the data: geofence. The first four rows show that they are not inside the geofence, while the last row indicates that it is inside the geofence. Let us replace False and True values with In and Out values, respectively. # Replace True with In and False with Outgdf[‘geofence’] = gdf[‘geofence’].replace({True: ‘In’, False: ‘Out’}) We can see now if we plot a map with Plotly Express and use geofence as a colour, which points are inside or outside the geofencing area. px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude”, color=”geofence”, size=’track_id’ ,size_max=6, zoom=12, width=1200, height=800) Finally, we can animate the points to visualize with track movements. The annimation can be accomplished easily with Plotly Express. However, it can not visualize all our points at one time due to some limitations. Let us visualize one Track ID now. px.scatter_mapbox(gdf[gdf[“track_id”]== 23], lat=”latitude”, lon=”longitude”, color=”geofence”, size=’track_id’, animation_frame=’time’, size_max=10, zoom=12, width=1200, height=800) Here is GIF animation of our simple Geofencing example. Once the track gets inside the geofence area, the points become red, while being blue outside of the marked area. In this tutorial, we have seen how to do a simple Geofencing example with Python using Pandas, Geopandas and Plotly Express. If you want to experiment with the code, here is the link to Google Colab Notebook.
[ { "code": null, "e": 546, "s": 172, "text": "Geofencing is often used tool in Geographic data science, especially in marketing, security and zoning applications. The example in the above GIF shows an app that alerts vehicles based on their location and London’s Congestion Charge Zone (CCZ). The application calculates the congestion charge and tracks the number of vehicles inside the congestion area at a given time." }, { "code": null, "e": 1016, "s": 546, "text": "The concept of geofencing is straightforward, yet it is a powerful technique that enhances location applications. Simply put, a geofence is a defining virtual boundary around geographic objects or an area, so that every time a user enters or leaves the boundary perimeters, actions or notifications can be triggered. With the increased use of smartphones, GPS, and location services, geofencing becomes an indispensable tool in location data analytics and intelligence." }, { "code": null, "e": 1231, "s": 1016, "text": "In this tutorial, we use a GPS Trajectory dataset. It contains GPSpoints (latitude and longitude) with timestamps. It also provides unique track_id for each trajectory. Let us read the data with the Pandas library." }, { "code": null, "e": 1489, "s": 1231, "text": "import pandas as pdimport geopandas as gpdimport plotly_express as pximport matplotlib.pyplot as plt!wget https://www.dropbox.com/s/ejev7z29lzirbo5/GPSTrajectory.zip!unzip GPSTrajectory.zipdf = pd.read_csv(‘GPSTrajectory/go_track_trackspoints.csv’)df.head()" }, { "code": null, "e": 1602, "s": 1489, "text": "The first five rows of the dataset are shown below. We have latitude and longitude as well as track_id and time." }, { "code": null, "e": 1762, "s": 1602, "text": "We convert the Dataframe into Geodataframe, which allows us to perform geofencing. Converting the data frame to Geodataframe with Geopandas is straightforward." }, { "code": null, "e": 1856, "s": 1762, "text": "gdf = gpd.GeoDataFrame( df, geometry=gpd.points_from_xy(df.longitude, df.latitude))gdf.head()" }, { "code": null, "e": 2024, "s": 1856, "text": "Let us plot a map of the dataset. We use Plotly Express here as offers an easy interface and high-level API for plotting with Plotly. We need to set Mapbox token here." }, { "code": null, "e": 2244, "s": 2024, "text": "px.set_mapbox_access_token(“pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w”)px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude” ,size_max=6, zoom=8, width=1200, height=800)" }, { "code": null, "e": 2359, "s": 2244, "text": "The plot below shows all the points in the dataset. As you can see, these trajectories fall in 3 different cities." }, { "code": null, "e": 2463, "s": 2359, "text": "Let us filter out other cities and focus on the central city(Aracuja) since most of the data fall here." }, { "code": null, "e": 2624, "s": 2463, "text": "gdf = df[(gdf[‘latitude’]<-10.80) & (gdf[‘longitude’]>-37.5)]px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude” ,size_max=6, zoom=8, width=1200, height=800)" }, { "code": null, "e": 2696, "s": 2624, "text": "Now we have only points that we are interested in Aracuja city, Brazil." }, { "code": null, "e": 2752, "s": 2696, "text": "Now that we have cleaned the data let us do geofencing." }, { "code": null, "e": 2881, "s": 2752, "text": "First, we need to have an area that marks the geofence. Let us download an area that I have created which is in the city centre." }, { "code": null, "e": 3024, "s": 2881, "text": "# Get the data!wget https://www.dropbox.com/s/e9g5n7e7iwnue4x/CENTERAREA.zip!unzip CENTERAREA.zippolygon = gpd.read_file(“CENTERAREA.geojson”)" }, { "code": null, "e": 3104, "s": 3024, "text": "Let us plot the polygon with Geopandas and overlay the points to see both data." }, { "code": null, "e": 3286, "s": 3104, "text": "# Plot track_id 1 points over the Buffer Polygonfig, ax = plt.subplots(figsize=(10,10))gdf.plot(ax=ax, color=’black’)polygon.plot(ax=ax)#plt.tight_layout()#plt.axis(‘off’)plt.show()" }, { "code": null, "e": 3360, "s": 3286, "text": "Here is the map overlaying both the polygon and points data, shown below." }, { "code": null, "e": 3519, "s": 3360, "text": "Now, let us perform what we call Point in Polygon (PIP). We can use “within” operation in Geopandas to check whether the points are inside the polygon or not." }, { "code": null, "e": 3591, "s": 3519, "text": "mask = (polygon.loc[0, ‘geometry’])pip_mask_geofence = gdf.within(mask)" }, { "code": null, "e": 3804, "s": 3591, "text": "The above code will return a series of False and True values depending on whether the point is inside the polygon or not. Let us add a column to our data that marks False and True values. We call this “geofence”." }, { "code": null, "e": 3875, "s": 3804, "text": "#Create PIP maskgdf.loc[:,’geofence’] = pip_mask_geofencegdf.sample(5)" }, { "code": null, "e": 3951, "s": 3875, "text": "Now, our data has a “geofence” column. Let us look at a sample of the data." }, { "code": null, "e": 4215, "s": 3951, "text": "As you can see, there is addition column in the data: geofence. The first four rows show that they are not inside the geofence, while the last row indicates that it is inside the geofence. Let us replace False and True values with In and Out values, respectively." }, { "code": null, "e": 4326, "s": 4215, "text": "# Replace True with In and False with Outgdf[‘geofence’] = gdf[‘geofence’].replace({True: ‘In’, False: ‘Out’})" }, { "code": null, "e": 4464, "s": 4326, "text": "We can see now if we plot a map with Plotly Express and use geofence as a colour, which points are inside or outside the geofencing area." }, { "code": null, "e": 4600, "s": 4464, "text": "px.scatter_mapbox(gdf, lat=”latitude”, lon=”longitude”, color=”geofence”, size=’track_id’ ,size_max=6, zoom=12, width=1200, height=800)" }, { "code": null, "e": 4850, "s": 4600, "text": "Finally, we can animate the points to visualize with track movements. The annimation can be accomplished easily with Plotly Express. However, it can not visualize all our points at one time due to some limitations. Let us visualize one Track ID now." }, { "code": null, "e": 5033, "s": 4850, "text": "px.scatter_mapbox(gdf[gdf[“track_id”]== 23], lat=”latitude”, lon=”longitude”, color=”geofence”, size=’track_id’, animation_frame=’time’, size_max=10, zoom=12, width=1200, height=800)" }, { "code": null, "e": 5203, "s": 5033, "text": "Here is GIF animation of our simple Geofencing example. Once the track gets inside the geofence area, the points become red, while being blue outside of the marked area." } ]
CSS - Roll Out Effect
An Element can move in a particular direction by turning over and over on an axis. @keyframes rollOut { 0% { opacity: 1; transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; transform: translateX(100%) rotate(120deg); } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes rollOut { 0% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; -webkit-transform: translateX(100%) rotate(120deg); } } @keyframes rollOut { 0% { opacity: 1; transform: translateX(0px) rotate(0deg); } 100% { opacity: 0; transform: translateX(100%) rotate(120deg); } } .rollOut { -webkit-animation-name: rollOut; animation-name: rollOut; } </style> </head> <body> <div id = "animated-example" class = "animated rollOut"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2709, "s": 2626, "text": "An Element can move in a particular direction by turning over and over on an axis." }, { "code": null, "e": 2894, "s": 2709, "text": "@keyframes rollOut {\n 0% {\n opacity: 1;\n transform: translateX(0px) rotate(0deg);\n }\n 100% {\n opacity: 0;\n transform: translateX(100%) rotate(120deg);\n }\n} " }, { "code": null, "e": 2967, "s": 2894, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3040, "s": 2967, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3102, "s": 3040, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3164, "s": 3102, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 4623, "s": 3164, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes rollOut {\n 0% {\n opacity: 1;\n -webkit-transform: translateX(0px) rotate(0deg);\n }\n 100% {\n opacity: 0;\n -webkit-transform: translateX(100%) rotate(120deg);\n }\n }\n \n @keyframes rollOut {\n 0% {\n opacity: 1;\n transform: translateX(0px) rotate(0deg);\n }\n 100% {\n opacity: 0;\n transform: translateX(100%) rotate(120deg);\n }\n }\n \n .rollOut {\n -webkit-animation-name: rollOut;\n animation-name: rollOut;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated rollOut\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4662, "s": 4623, "text": "It will produce the following result −" }, { "code": null, "e": 5309, "s": 4662, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 5329, "s": 5309, "text": " Academic Tutorials" }, { "code": null, "e": 5352, "s": 5329, "text": " Big Data & Analytics " }, { "code": null, "e": 5375, "s": 5352, "text": " Computer Programming " }, { "code": null, "e": 5394, "s": 5375, "text": " Computer Science " }, { "code": null, "e": 5406, "s": 5394, "text": " Databases " }, { "code": null, "e": 5415, "s": 5406, "text": " DevOps " }, { "code": null, "e": 5435, "s": 5415, "text": " Digital Marketing " }, { "code": null, "e": 5459, "s": 5435, "text": " Engineering Tutorials " }, { "code": null, "e": 5476, "s": 5459, "text": " Exams Syllabus " }, { "code": null, "e": 5495, "s": 5476, "text": " Famous Monuments " }, { "code": null, "e": 5517, "s": 5495, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5539, "s": 5517, "text": " Latest Technologies " }, { "code": null, "e": 5558, "s": 5539, "text": " Machine Learning " }, { "code": null, "e": 5582, "s": 5558, "text": " Mainframe Development " }, { "code": null, "e": 5605, "s": 5582, "text": " Management Tutorials " }, { "code": null, "e": 5628, "s": 5605, "text": " Mathematics Tutorials" }, { "code": null, "e": 5653, "s": 5628, "text": " Microsoft Technologies " }, { "code": null, "e": 5670, "s": 5653, "text": " Misc tutorials " }, { "code": null, "e": 5691, "s": 5670, "text": " Mobile Development " }, { "code": null, "e": 5711, "s": 5691, "text": " Java Technologies " }, { "code": null, "e": 5733, "s": 5711, "text": " Python Technologies " }, { "code": null, "e": 5749, "s": 5733, "text": " SAP Tutorials " }, { "code": null, "e": 5770, "s": 5749, "text": "Programming Scripts " }, { "code": null, "e": 5789, "s": 5770, "text": " Selected Reading " }, { "code": null, "e": 5808, "s": 5789, "text": " Software Quality " }, { "code": null, "e": 5822, "s": 5808, "text": " Soft Skills " }, { "code": null, "e": 5842, "s": 5822, "text": " Telecom Tutorials " }, { "code": null, "e": 5859, "s": 5842, "text": " UPSC IAS Exams " }, { "code": null, "e": 5877, "s": 5859, "text": " Web Development " }, { "code": null, "e": 5896, "s": 5877, "text": " Sports Tutorials " }, { "code": null, "e": 5915, "s": 5896, "text": " XML Technologies " }, { "code": null, "e": 5931, "s": 5915, "text": " Multi-Language" }, { "code": null, "e": 5952, "s": 5931, "text": " Interview Questions" }, { "code": null, "e": 5969, "s": 5952, "text": "Selected Reading" }, { "code": null, "e": 5990, "s": 5969, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 6017, "s": 5990, "text": "Developer's Best Practices" }, { "code": null, "e": 6039, "s": 6017, "text": "Questions and Answers" }, { "code": null, "e": 6064, "s": 6039, "text": "Effective Resume Writing" }, { "code": null, "e": 6087, "s": 6064, "text": "HR Interview Questions" }, { "code": null, "e": 6105, "s": 6087, "text": "Computer Glossary" }, { "code": null, "e": 6116, "s": 6105, "text": "Who is Who" }, { "code": null, "e": 6123, "s": 6116, "text": " Print" }, { "code": null, "e": 6134, "s": 6123, "text": " Add Notes" } ]
Google Guice - Field Injection
Injection is a process of injecting dependeny into an object. Field injection is used to set value object as dependency to the field of an object. See the example below. Create a java class named GuiceTester. GuiceTester.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.ImplementedBy; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; public class GuiceTester { public static void main(String[] args) { Injector injector = Guice.createInjector(new TextEditorModule()); TextEditor editor = injector.getInstance(TextEditor.class); editor.makeSpellCheck(); } } class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor( SpellChecker spellChecker) { this.spellChecker = spellChecker; } public void makeSpellCheck(){ spellChecker.checkSpelling(); } } //Binding Module class TextEditorModule extends AbstractModule { @Override protected void configure() { bind(String.class) .annotatedWith(Names.named("JDBC")) .toInstance("jdbc:mysql://localhost:5326/emp"); } } @ImplementedBy(SpellCheckerImpl.class) interface SpellChecker { public void checkSpelling(); } //spell checker implementation class SpellCheckerImpl implements SpellChecker { @Inject @Named("JDBC") private String dbUrl; public SpellCheckerImpl(){} @Override public void checkSpelling() { System.out.println("Inside checkSpelling." ); System.out.println(dbUrl); } } Compile and run the file, you will see the following output. Inside checkSpelling. jdbc:mysql://localhost:5326/emp 27 Lectures 1.5 hours Lemuel Ogbunude Print Add Notes Bookmark this page
[ { "code": null, "e": 2272, "s": 2102, "text": "Injection is a process of injecting dependeny into an object. Field injection is used to set value object as dependency to the field of an object. See the example below." }, { "code": null, "e": 2311, "s": 2272, "text": "Create a java class named GuiceTester." }, { "code": null, "e": 2328, "s": 2311, "text": "GuiceTester.java" }, { "code": null, "e": 3729, "s": 2328, "text": "import com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\nimport com.google.inject.name.Names;\n\npublic class GuiceTester {\n public static void main(String[] args) {\n Injector injector = Guice.createInjector(new TextEditorModule());\n TextEditor editor = injector.getInstance(TextEditor.class);\n editor.makeSpellCheck();\n } \n}\n\nclass TextEditor {\n private SpellChecker spellChecker;\n\n @Inject\n public TextEditor( SpellChecker spellChecker) {\n this.spellChecker = spellChecker;\n }\n\n public void makeSpellCheck(){\n spellChecker.checkSpelling();\n } \n}\n\n//Binding Module\nclass TextEditorModule extends AbstractModule {\n\n @Override\n protected void configure() { \n bind(String.class)\n .annotatedWith(Names.named(\"JDBC\"))\n .toInstance(\"jdbc:mysql://localhost:5326/emp\");\n } \n}\n\n@ImplementedBy(SpellCheckerImpl.class)\ninterface SpellChecker {\n public void checkSpelling();\n}\n\n//spell checker implementation\nclass SpellCheckerImpl implements SpellChecker {\n\n @Inject @Named(\"JDBC\")\n private String dbUrl;\n\n public SpellCheckerImpl(){}\n\n @Override\n public void checkSpelling() { \n System.out.println(\"Inside checkSpelling.\" );\n System.out.println(dbUrl); \n }\n}" }, { "code": null, "e": 3790, "s": 3729, "text": "Compile and run the file, you will see the following output." }, { "code": null, "e": 3845, "s": 3790, "text": "Inside checkSpelling.\njdbc:mysql://localhost:5326/emp\n" }, { "code": null, "e": 3880, "s": 3845, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3897, "s": 3880, "text": " Lemuel Ogbunude" }, { "code": null, "e": 3904, "s": 3897, "text": " Print" }, { "code": null, "e": 3915, "s": 3904, "text": " Add Notes" } ]
Sort an Array of Points by their distance from a reference Point - GeeksforGeeks
26 Nov, 2021 Given an array arr[] containing N points and a reference point P, the task is to sort these points according to their distance from the given point P. Examples: Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0) Explanation: Distance between (0, 0) and (1, 0) = 1 Distance between (0, 0) and (2, 0) = 2 Distance between (0, 0) and (3, 0) = 3 Distance between (0, 0) and (4, 0) = 4 Distance between (0, 0) and (5, 0) = 5 Hence, the sorted array of points will be: {(1, 0) (2, 0) (3, 0) (4, 0) (5, 0)}Input: arr[] = {{5, 0}, {0, 4}, {0, 3}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (0, 3) (0, 4) (5, 0) Explanation: Distance between (0, 0) and (1, 0) = 1 Distance between (0, 0) and (2, 0) = 2 Distance between (0, 0) and (0, 3) = 3 Distance between (0, 0) and (0, 4) = 4 Distance between (0, 0) and (5, 0) = 5 Hence, the sorted array of points will be: {(1, 0) (2, 0) (0, 3) (0, 4) (5, 0)} Approach: The idea is to store each element at its distance from the given point P in a pair and then sort all the elements of the vector according to the distance stored. For each of the given points: Find the distance of the point from the reference point P formula below: Find the distance of the point from the reference point P formula below: Distance = Append the distance in an array Sort the array of distance and print the points based on the sorted distance.Time Complexity: As in the above approach, there is sorting of an array of length N, which takes O(N*logN) time in the worst case. Hence, the Time Complexity will be O(N*log N).Auxiliary Space Complexity: As in the above approach, there is extra space used to store the distance and the points as pairs. Hence, the auxiliary space complexity will be O(N). Time Complexity: As in the above approach, there is sorting of an array of length N, which takes O(N*logN) time in the worst case. Hence, the Time Complexity will be O(N*log N). Auxiliary Space Complexity: As in the above approach, there is extra space used to store the distance and the points as pairs. Hence, the auxiliary space complexity will be O(N). Javascript <script>// Javascript program function sortFunction(a, b) { if (a[0] === b[0]) { return 0; } else { return (a[0] < b[0]) ? -1 : 1; }} // Function to sort the array of// points by its distance from Pfunction sortArr(arr, n, p){ // Vector to store the distance // with respective elements var vp = new Array(n); // Storing the distance with its // distance in the vector array for (var i = 0; i < n; i++) { var dist = Math.pow((p[0] - arr[i][0]), 2) + Math.pow((p[1] - arr[i][1]), 2); vp[i] = [dist, [arr[i][0], arr[i][1]]]; } // Sorting the array with // respect to its distance vp.sort(sortFunction); // Output for (var i = 0; i < n; i++) { document.write("(" + vp[i][1][0] + ", " + vp[i][1][1] + ") "); }} var arr = [[ 5, 5 ], [ 6, 6 ], [ 1, 0], [ 2, 0 ], [ 3, 1 ], [ 1, -2 ]];var n = 6;var p = [ 0, 0 ];// Function to perform sortingsortArr(arr, n, p);</script> Output: (1, 0) (2, 0) (1, -2) (3, 1) (5, 5) (6, 6) shivanisinghss2110 jrishabh99 rishavmahato348 cpp-pair Arrays Geometric Mathematical Arrays Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays How to check if two given line segments intersect? Program for distance between two points on earth How to check if a given point lies inside or outside a polygon? Find if two rectangles overlap Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
[ { "code": null, "e": 25250, "s": 25222, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25401, "s": 25250, "text": "Given an array arr[] containing N points and a reference point P, the task is to sort these points according to their distance from the given point P." }, { "code": null, "e": 25411, "s": 25401, "text": "Examples:" }, { "code": null, "e": 25731, "s": 25411, "text": "Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0) Explanation: Distance between (0, 0) and (1, 0) = 1 Distance between (0, 0) and (2, 0) = 2 Distance between (0, 0) and (3, 0) = 3 Distance between (0, 0) and (4, 0) = 4 Distance between (0, 0) and (5, 0) = 5 " }, { "code": null, "e": 26209, "s": 25731, "text": "Hence, the sorted array of points will be: {(1, 0) (2, 0) (3, 0) (4, 0) (5, 0)}Input: arr[] = {{5, 0}, {0, 4}, {0, 3}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (0, 3) (0, 4) (5, 0) Explanation: Distance between (0, 0) and (1, 0) = 1 Distance between (0, 0) and (2, 0) = 2 Distance between (0, 0) and (0, 3) = 3 Distance between (0, 0) and (0, 4) = 4 Distance between (0, 0) and (5, 0) = 5 Hence, the sorted array of points will be: {(1, 0) (2, 0) (0, 3) (0, 4) (5, 0)}" }, { "code": null, "e": 26381, "s": 26209, "text": "Approach: The idea is to store each element at its distance from the given point P in a pair and then sort all the elements of the vector according to the distance stored." }, { "code": null, "e": 26484, "s": 26381, "text": "For each of the given points: Find the distance of the point from the reference point P formula below:" }, { "code": null, "e": 26557, "s": 26484, "text": "Find the distance of the point from the reference point P formula below:" }, { "code": null, "e": 26569, "s": 26557, "text": "Distance = " }, { "code": null, "e": 26601, "s": 26569, "text": "Append the distance in an array" }, { "code": null, "e": 27034, "s": 26601, "text": "Sort the array of distance and print the points based on the sorted distance.Time Complexity: As in the above approach, there is sorting of an array of length N, which takes O(N*logN) time in the worst case. Hence, the Time Complexity will be O(N*log N).Auxiliary Space Complexity: As in the above approach, there is extra space used to store the distance and the points as pairs. Hence, the auxiliary space complexity will be O(N)." }, { "code": null, "e": 27212, "s": 27034, "text": "Time Complexity: As in the above approach, there is sorting of an array of length N, which takes O(N*logN) time in the worst case. Hence, the Time Complexity will be O(N*log N)." }, { "code": null, "e": 27391, "s": 27212, "text": "Auxiliary Space Complexity: As in the above approach, there is extra space used to store the distance and the points as pairs. Hence, the auxiliary space complexity will be O(N)." }, { "code": null, "e": 27402, "s": 27391, "text": "Javascript" }, { "code": "<script>// Javascript program function sortFunction(a, b) { if (a[0] === b[0]) { return 0; } else { return (a[0] < b[0]) ? -1 : 1; }} // Function to sort the array of// points by its distance from Pfunction sortArr(arr, n, p){ // Vector to store the distance // with respective elements var vp = new Array(n); // Storing the distance with its // distance in the vector array for (var i = 0; i < n; i++) { var dist = Math.pow((p[0] - arr[i][0]), 2) + Math.pow((p[1] - arr[i][1]), 2); vp[i] = [dist, [arr[i][0], arr[i][1]]]; } // Sorting the array with // respect to its distance vp.sort(sortFunction); // Output for (var i = 0; i < n; i++) { document.write(\"(\" + vp[i][1][0] + \", \" + vp[i][1][1] + \") \"); }} var arr = [[ 5, 5 ], [ 6, 6 ], [ 1, 0], [ 2, 0 ], [ 3, 1 ], [ 1, -2 ]];var n = 6;var p = [ 0, 0 ];// Function to perform sortingsortArr(arr, n, p);</script>", "e": 28381, "s": 27402, "text": null }, { "code": null, "e": 28389, "s": 28381, "text": "Output:" }, { "code": null, "e": 28433, "s": 28389, "text": "(1, 0) (2, 0) (1, -2) (3, 1) (5, 5) (6, 6) " }, { "code": null, "e": 28452, "s": 28433, "text": "shivanisinghss2110" }, { "code": null, "e": 28463, "s": 28452, "text": "jrishabh99" }, { "code": null, "e": 28479, "s": 28463, "text": "rishavmahato348" }, { "code": null, "e": 28488, "s": 28479, "text": "cpp-pair" }, { "code": null, "e": 28495, "s": 28488, "text": "Arrays" }, { "code": null, "e": 28505, "s": 28495, "text": "Geometric" }, { "code": null, "e": 28518, "s": 28505, "text": "Mathematical" }, { "code": null, "e": 28525, "s": 28518, "text": "Arrays" }, { "code": null, "e": 28538, "s": 28525, "text": "Mathematical" }, { "code": null, "e": 28548, "s": 28538, "text": "Geometric" }, { "code": null, "e": 28646, "s": 28548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28694, "s": 28646, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 28762, "s": 28694, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 28806, "s": 28762, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 28838, "s": 28806, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28861, "s": 28838, "text": "Introduction to Arrays" }, { "code": null, "e": 28912, "s": 28861, "text": "How to check if two given line segments intersect?" }, { "code": null, "e": 28961, "s": 28912, "text": "Program for distance between two points on earth" }, { "code": null, "e": 29025, "s": 28961, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 29056, "s": 29025, "text": "Find if two rectangles overlap" } ]
Python - tensorflow.math.reduce_sum() - GeeksforGeeks
17 May, 2021 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. reduce_sum() is used to find sum of elements across dimensions of a tensor. Syntax: tensorflow.math.reduce_sum( input_tensor, axis, keepdims, name) Parameters: input_tensor: It is numeric tensor to reduce. axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced. keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1. name(optional): It defines the name for the operation. Returns: It returns a tensor. Example 1: Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_sum(a) # Printing the resultprint('Result: ', res) Output: Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64) Result: tf.Tensor(10., shape=(), dtype=float64) Example 2: Python3 # importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_sum(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res) Output: Input: tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float64) Result: tf.Tensor( [[3.] [7.]], shape=(2, 1), dtype=float64) surinderdawra388 Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n17 May, 2021" }, { "code": null, "e": 24423, "s": 24292, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks." }, { "code": null, "e": 24499, "s": 24423, "text": "reduce_sum() is used to find sum of elements across dimensions of a tensor." }, { "code": null, "e": 24571, "s": 24499, "text": "Syntax: tensorflow.math.reduce_sum( input_tensor, axis, keepdims, name)" }, { "code": null, "e": 24583, "s": 24571, "text": "Parameters:" }, { "code": null, "e": 24629, "s": 24583, "text": "input_tensor: It is numeric tensor to reduce." }, { "code": null, "e": 24816, "s": 24629, "text": "axis(optional): It represent the dimensions to reduce. It’s value should be in range [-rank(input_tensor), rank(input_tensor)). If no value is given for this all dimensions are reduced." }, { "code": null, "e": 24937, "s": 24816, "text": "keepdims(optional): It’s default value is False. If it’s set to True it will retain the reduced dimension with length 1." }, { "code": null, "e": 24992, "s": 24937, "text": "name(optional): It defines the name for the operation." }, { "code": null, "e": 25022, "s": 24992, "text": "Returns: It returns a tensor." }, { "code": null, "e": 25033, "s": 25022, "text": "Example 1:" }, { "code": null, "e": 25041, "s": 25033, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([1, 2, 3, 4], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_sum(a) # Printing the resultprint('Result: ', res)", "e": 25308, "s": 25041, "text": null }, { "code": null, "e": 25316, "s": 25308, "text": "Output:" }, { "code": null, "e": 25426, "s": 25316, "text": "Input: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)\nResult: tf.Tensor(10., shape=(), dtype=float64)" }, { "code": null, "e": 25437, "s": 25426, "text": "Example 2:" }, { "code": null, "e": 25445, "s": 25437, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([[1, 2], [3, 4]], dtype = tf.float64) # Printing the input tensorprint('Input: ', a) # Calculating resultres = tf.math.reduce_sum(a, axis = 1, keepdims = True) # Printing the resultprint('Result: ', res)", "e": 25743, "s": 25445, "text": null }, { "code": null, "e": 25751, "s": 25743, "text": "Output:" }, { "code": null, "e": 25882, "s": 25751, "text": "Input: tf.Tensor(\n[[1. 2.]\n [3. 4.]], shape=(2, 2), dtype=float64)\nResult: tf.Tensor(\n[[3.]\n [7.]], shape=(2, 1), dtype=float64)" }, { "code": null, "e": 25899, "s": 25882, "text": "surinderdawra388" }, { "code": null, "e": 25932, "s": 25899, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 25950, "s": 25932, "text": "Python-Tensorflow" }, { "code": null, "e": 25957, "s": 25950, "text": "Python" }, { "code": null, "e": 26055, "s": 25957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26064, "s": 26055, "text": "Comments" }, { "code": null, "e": 26077, "s": 26064, "text": "Old Comments" }, { "code": null, "e": 26109, "s": 26077, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26165, "s": 26109, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26220, "s": 26165, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26262, "s": 26220, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26304, "s": 26262, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26335, "s": 26304, "text": "Python | os.path.join() method" }, { "code": null, "e": 26374, "s": 26335, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26403, "s": 26374, "text": "Create a directory in Python" }, { "code": null, "e": 26425, "s": 26403, "text": "Defaultdict in Python" } ]
C program for pipe in Linux - GeeksforGeeks
26 Apr, 2018 Working and implementation of Pipe in Linux. Prerequisite : Pipe in Linux Approach : Pipe is highly used in Linux. Basically, pipe has 2 parts, one part is for writing and another is used for reading. So, an array of size 2 is taken. a[1] is used for writing and a[0] for reading.After reading from pipe, program will show output on console. // C program to implement pipe in Linux#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>#include <unistd.h> int main(){ // array of 2 size a[0] is for reading // and a[1] is for writing over a pipe int a[2]; // opening of pipe using pipe(a) char buff[10]; if (pipe(a) == -1) { perror("pipe"); // error in pipe exit(1); // exit from the program } // writing a string "code" in pipe write(a[1], "code", 5); printf("\n"); // reading pipe now buff is equal to "code" read(a[0], buff, 5); // it will print "code" printf("%s", buff); } Output : More examples on pipe() C Programs Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Regular expressions in C Handling multiple clients on server with multithreading using Socket Programming in C/C++ Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux TCP Server-Client implementation in C cut command in Linux with examples
[ { "code": null, "e": 24874, "s": 24846, "text": "\n26 Apr, 2018" }, { "code": null, "e": 24919, "s": 24874, "text": "Working and implementation of Pipe in Linux." }, { "code": null, "e": 24948, "s": 24919, "text": "Prerequisite : Pipe in Linux" }, { "code": null, "e": 25216, "s": 24948, "text": "Approach : Pipe is highly used in Linux. Basically, pipe has 2 parts, one part is for writing and another is used for reading. So, an array of size 2 is taken. a[1] is used for writing and a[0] for reading.After reading from pipe, program will show output on console." }, { "code": "// C program to implement pipe in Linux#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>#include <unistd.h> int main(){ // array of 2 size a[0] is for reading // and a[1] is for writing over a pipe int a[2]; // opening of pipe using pipe(a) char buff[10]; if (pipe(a) == -1) { perror(\"pipe\"); // error in pipe exit(1); // exit from the program } // writing a string \"code\" in pipe write(a[1], \"code\", 5); printf(\"\\n\"); // reading pipe now buff is equal to \"code\" read(a[0], buff, 5); // it will print \"code\" printf(\"%s\", buff); }", "e": 25867, "s": 25216, "text": null }, { "code": null, "e": 25876, "s": 25867, "text": "Output :" }, { "code": null, "e": 25900, "s": 25876, "text": "More examples on pipe()" }, { "code": null, "e": 25911, "s": 25900, "text": "C Programs" }, { "code": null, "e": 25922, "s": 25911, "text": "Linux-Unix" }, { "code": null, "e": 25941, "s": 25922, "text": "Technical Scripter" }, { "code": null, "e": 26039, "s": 25941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26048, "s": 26039, "text": "Comments" }, { "code": null, "e": 26061, "s": 26048, "text": "Old Comments" }, { "code": null, "e": 26102, "s": 26061, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26133, "s": 26102, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26204, "s": 26133, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 26229, "s": 26204, "text": "Regular expressions in C" }, { "code": null, "e": 26319, "s": 26229, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 26359, "s": 26319, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 26399, "s": 26359, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 26426, "s": 26399, "text": "grep command in Unix/Linux" }, { "code": null, "e": 26464, "s": 26426, "text": "TCP Server-Client implementation in C" } ]
1st place solution for Kaggle’s skin cancer (Melanoma) Competition | by Mostafa Ibrahim | Towards Data Science
5 months ago I participated in my first official kaggle competition, SSIM-ISIC Melanoma. Here is a brief overview of what the competition was about (from Kaggle): Skin cancer is the most prevalent type of cancer. Melanoma, specifically, is responsible for 75% of skin cancer deaths, despite being the least common skin cancer. The American Cancer Society estimates over 100,000 new melanoma cases will be diagnosed in 2020. It’s also expected that almost 7,000 people will die from the disease. As with other cancers, early and accurate detection — potentially aided by data science — can make treatment more effective. Personally, I feel very motivated when working on something that I believe in. This feeling resonated with me throughout this competition as skin cancer ruins a lot of people’s lives immensely. As someone who is passionate about machine learning and especially in healthcare this was super interesting for me. Since this was my first competition, most of what I was doing was learning rather than actually coding and therefore I ended up in the top 72%. This story will be mainly about my experience and the first place solution (which there is a lot to learn from). One of the quite difficult challenges of this competition is that the dataset was extremely unbalanced. The domain of the problem was binary classification for images. The distribution of the classes was 98% for class 1 and only 2% for class 2 ! For the sake of brevity and not duplicating content, I found this article quite helpful to tackle this issue : towardsdatascience.com The rest of this story will be about tackling other challenges in this competition. In terms on the actual model, these 3 nets were extremely popular among all solutions and thus it made a lot of sense that the top solution would be using an ensemble of those 3. I won’t dive into the details of how each of them works since there are tons of resources for that, but I will give an overview. One of the main challenges in modelling CNNs is scaling them up and determining their width and depth. These networks tackle those challenges in different ways. There are multiple issues that you will have to deal with if you just keep on increasing the number of layers (bruteforce solution!) like the vanishing gradient problem. ResNet & ResNext: Residual networks operate on the idea of “residual blocks” which have identity skip connections. If you want to further understand this, check out this story: https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035 ResNext is just a variation of ResNet that adds a “split-transform-merge” step where the outputs of different paths are merged by adding them together. EfficientNet: EfficientNet is to me, the most impressive one. Probably because it has only been around for about 2 years. The main idea of EfficientNet is an efficient technique to scale up the CNN so that you get higher accuracy with a much lower number of parameters. To explain how this works is a bit out of the scope of this story, but you can probably get a sense of it if you are familiar with the different types of scaling: Fully Connected Networks One of the lessons that I have learned from this competition is to use all of the data given, I was mostly focused on using the images and did not pay much attention to the metadata that was provided for each patient. The first place solution was using a concatenation of the CNNs outputs and the output of a fully connected network. This fully connected network was using an activation function called Swish, which is an upgrade of the classic ReLu. For this fully connected network, they were also using Batch Normalisation and Dropout, which are also typically used in a lot of networks. This is the final model pipeline: The CNN model block represents an ensemble of the 3 CNN models discussed above. Ensembling was also a new trick that I have learned that proved to be very effective. Not only does it give you better accuracy / results, but because the final competition rankings are evaluated on a small subset of the data, ensembling gives you a much better chances of surviving a “shake down”. A shake down is where your models overfit the training data and thus the final result is much worse so you end up with a worse rank. I also found it quite helpful to think about your machine learning solution as a pipeline and visualise it in this way. As a web developer, I am used to data architecture diagrams, however I never applied the same methodology of architecture in machine learning (which is a huge mistake). One of the main reasons that they managed to achieve the first place was that they were using a much bigger ensemble of networks and a bigger combination of data. To have stable validation, we used 2018+2019+2020’s data for both train and validation. We track two cv scores, cv_all and cv_2020. The former is much more stable than the latter. Also a common trick to further increase the size of the dataset it to use data augmentation. They were using a very good mixture of simple data augmentation techniques and complex ones. As for the simple ones they were using vertical & horizontal flips, random brightness & contrast and resizing. For the complex ones, they were using Gaussian Blur / Gaussian Noise, Elastic transform and Grid distortion. There are others that you can pick up from their code: transforms_train = A.Compose([ A.Transpose(p=0.5), A.VerticalFlip(p=0.5), A.HorizontalFlip(p=0.5), A.RandomBrightness(limit=0.2, p=0.75), A.RandomContrast(limit=0.2, p=0.75), A.OneOf([ A.MotionBlur(blur_limit=5), A.MedianBlur(blur_limit=5), A.GaussianBlur(blur_limit=5), A.GaussNoise(var_limit=(5.0, 30.0)), ], p=0.7), A.OneOf([ A.OpticalDistortion(distort_limit=1.0), A.GridDistortion(num_steps=5, distort_limit=1.), A.ElasticTransform(alpha=3), ], p=0.7), A.CLAHE(clip_limit=4.0, p=0.7), A.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=20, val_shift_limit=10, p=0.5), A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, border_mode=0, p=0.85), A.Resize(image_size, image_size), A.Cutout(max_h_size=int(image_size * 0.375), max_w_size=int(image_size * 0.375), num_holes=1, p=0.7), A.Normalize()])transforms_val = A.Compose([ A.Resize(image_size, image_size), A.Normalize()]) source: Github And finally, they were ranking the final prediction of the models to ensure that they were evenly distributed. One important point to note here is that data augmentation is becoming a very heavily used technique in almost all modern machine learning projects, I have seen this technique being used in a great amount of competitions and solutions. Conclusion: In terms of my model I was simply using a ResNext model with K-fold cross validation. I have learned the concept of ensembling, concatenating the results with metadata, the power of data augmentation and many other bits. And I think this is one of the main benefits of Kaggle competitions, they expose you to the awesome community and their solutions. Many thanks as well to the “Notebooks” section on the Kaggle competition where every one shares their solutions. A very good tip for beginner Kagglers is to always take a look at the top solutions, this is where you will experience a huge amount of learning. Compare it to your solution and evaluate the differences. My main takeaway was to not place all of my efforts on modelling, but rather focus on data engineering and preprocessing. Finally, don’t use only one type of a CNN architecture, use several ones and ensemble, most of the time this will give you better results. I am not going to dive into the advantages of ensembling as this has been covered thoroughly, if you are interested you can check out this article: towardsdatascience.com If you want to receive regular paper reviews about the latest papers in AI & Machine learning, add your email here & Subscribe!
[ { "code": null, "e": 335, "s": 172, "text": "5 months ago I participated in my first official kaggle competition, SSIM-ISIC Melanoma. Here is a brief overview of what the competition was about (from Kaggle):" }, { "code": null, "e": 792, "s": 335, "text": "Skin cancer is the most prevalent type of cancer. Melanoma, specifically, is responsible for 75% of skin cancer deaths, despite being the least common skin cancer. The American Cancer Society estimates over 100,000 new melanoma cases will be diagnosed in 2020. It’s also expected that almost 7,000 people will die from the disease. As with other cancers, early and accurate detection — potentially aided by data science — can make treatment more effective." }, { "code": null, "e": 1246, "s": 792, "text": "Personally, I feel very motivated when working on something that I believe in. This feeling resonated with me throughout this competition as skin cancer ruins a lot of people’s lives immensely. As someone who is passionate about machine learning and especially in healthcare this was super interesting for me. Since this was my first competition, most of what I was doing was learning rather than actually coding and therefore I ended up in the top 72%." }, { "code": null, "e": 1359, "s": 1246, "text": "This story will be mainly about my experience and the first place solution (which there is a lot to learn from)." }, { "code": null, "e": 1716, "s": 1359, "text": "One of the quite difficult challenges of this competition is that the dataset was extremely unbalanced. The domain of the problem was binary classification for images. The distribution of the classes was 98% for class 1 and only 2% for class 2 ! For the sake of brevity and not duplicating content, I found this article quite helpful to tackle this issue :" }, { "code": null, "e": 1739, "s": 1716, "text": "towardsdatascience.com" }, { "code": null, "e": 1823, "s": 1739, "text": "The rest of this story will be about tackling other challenges in this competition." }, { "code": null, "e": 2131, "s": 1823, "text": "In terms on the actual model, these 3 nets were extremely popular among all solutions and thus it made a lot of sense that the top solution would be using an ensemble of those 3. I won’t dive into the details of how each of them works since there are tons of resources for that, but I will give an overview." }, { "code": null, "e": 2462, "s": 2131, "text": "One of the main challenges in modelling CNNs is scaling them up and determining their width and depth. These networks tackle those challenges in different ways. There are multiple issues that you will have to deal with if you just keep on increasing the number of layers (bruteforce solution!) like the vanishing gradient problem." }, { "code": null, "e": 2480, "s": 2462, "text": "ResNet & ResNext:" }, { "code": null, "e": 2639, "s": 2480, "text": "Residual networks operate on the idea of “residual blocks” which have identity skip connections. If you want to further understand this, check out this story:" }, { "code": null, "e": 2722, "s": 2639, "text": "https://towardsdatascience.com/an-overview-of-resnet-and-its-variants-5281e2f56035" }, { "code": null, "e": 2874, "s": 2722, "text": "ResNext is just a variation of ResNet that adds a “split-transform-merge” step where the outputs of different paths are merged by adding them together." }, { "code": null, "e": 2888, "s": 2874, "text": "EfficientNet:" }, { "code": null, "e": 3144, "s": 2888, "text": "EfficientNet is to me, the most impressive one. Probably because it has only been around for about 2 years. The main idea of EfficientNet is an efficient technique to scale up the CNN so that you get higher accuracy with a much lower number of parameters." }, { "code": null, "e": 3307, "s": 3144, "text": "To explain how this works is a bit out of the scope of this story, but you can probably get a sense of it if you are familiar with the different types of scaling:" }, { "code": null, "e": 3332, "s": 3307, "text": "Fully Connected Networks" }, { "code": null, "e": 3783, "s": 3332, "text": "One of the lessons that I have learned from this competition is to use all of the data given, I was mostly focused on using the images and did not pay much attention to the metadata that was provided for each patient. The first place solution was using a concatenation of the CNNs outputs and the output of a fully connected network. This fully connected network was using an activation function called Swish, which is an upgrade of the classic ReLu." }, { "code": null, "e": 3923, "s": 3783, "text": "For this fully connected network, they were also using Batch Normalisation and Dropout, which are also typically used in a lot of networks." }, { "code": null, "e": 3957, "s": 3923, "text": "This is the final model pipeline:" }, { "code": null, "e": 4469, "s": 3957, "text": "The CNN model block represents an ensemble of the 3 CNN models discussed above. Ensembling was also a new trick that I have learned that proved to be very effective. Not only does it give you better accuracy / results, but because the final competition rankings are evaluated on a small subset of the data, ensembling gives you a much better chances of surviving a “shake down”. A shake down is where your models overfit the training data and thus the final result is much worse so you end up with a worse rank." }, { "code": null, "e": 4758, "s": 4469, "text": "I also found it quite helpful to think about your machine learning solution as a pipeline and visualise it in this way. As a web developer, I am used to data architecture diagrams, however I never applied the same methodology of architecture in machine learning (which is a huge mistake)." }, { "code": null, "e": 4921, "s": 4758, "text": "One of the main reasons that they managed to achieve the first place was that they were using a much bigger ensemble of networks and a bigger combination of data." }, { "code": null, "e": 5101, "s": 4921, "text": "To have stable validation, we used 2018+2019+2020’s data for both train and validation. We track two cv scores, cv_all and cv_2020. The former is much more stable than the latter." }, { "code": null, "e": 5562, "s": 5101, "text": "Also a common trick to further increase the size of the dataset it to use data augmentation. They were using a very good mixture of simple data augmentation techniques and complex ones. As for the simple ones they were using vertical & horizontal flips, random brightness & contrast and resizing. For the complex ones, they were using Gaussian Blur / Gaussian Noise, Elastic transform and Grid distortion. There are others that you can pick up from their code:" }, { "code": null, "e": 6569, "s": 5562, "text": "transforms_train = A.Compose([ A.Transpose(p=0.5), A.VerticalFlip(p=0.5), A.HorizontalFlip(p=0.5), A.RandomBrightness(limit=0.2, p=0.75), A.RandomContrast(limit=0.2, p=0.75), A.OneOf([ A.MotionBlur(blur_limit=5), A.MedianBlur(blur_limit=5), A.GaussianBlur(blur_limit=5), A.GaussNoise(var_limit=(5.0, 30.0)), ], p=0.7), A.OneOf([ A.OpticalDistortion(distort_limit=1.0), A.GridDistortion(num_steps=5, distort_limit=1.), A.ElasticTransform(alpha=3), ], p=0.7), A.CLAHE(clip_limit=4.0, p=0.7), A.HueSaturationValue(hue_shift_limit=10, sat_shift_limit=20, val_shift_limit=10, p=0.5), A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, border_mode=0, p=0.85), A.Resize(image_size, image_size), A.Cutout(max_h_size=int(image_size * 0.375), max_w_size=int(image_size * 0.375), num_holes=1, p=0.7), A.Normalize()])transforms_val = A.Compose([ A.Resize(image_size, image_size), A.Normalize()])" }, { "code": null, "e": 6584, "s": 6569, "text": "source: Github" }, { "code": null, "e": 6931, "s": 6584, "text": "And finally, they were ranking the final prediction of the models to ensure that they were evenly distributed. One important point to note here is that data augmentation is becoming a very heavily used technique in almost all modern machine learning projects, I have seen this technique being used in a great amount of competitions and solutions." }, { "code": null, "e": 6943, "s": 6931, "text": "Conclusion:" }, { "code": null, "e": 7408, "s": 6943, "text": "In terms of my model I was simply using a ResNext model with K-fold cross validation. I have learned the concept of ensembling, concatenating the results with metadata, the power of data augmentation and many other bits. And I think this is one of the main benefits of Kaggle competitions, they expose you to the awesome community and their solutions. Many thanks as well to the “Notebooks” section on the Kaggle competition where every one shares their solutions." }, { "code": null, "e": 7734, "s": 7408, "text": "A very good tip for beginner Kagglers is to always take a look at the top solutions, this is where you will experience a huge amount of learning. Compare it to your solution and evaluate the differences. My main takeaway was to not place all of my efforts on modelling, but rather focus on data engineering and preprocessing." }, { "code": null, "e": 8021, "s": 7734, "text": "Finally, don’t use only one type of a CNN architecture, use several ones and ensemble, most of the time this will give you better results. I am not going to dive into the advantages of ensembling as this has been covered thoroughly, if you are interested you can check out this article:" }, { "code": null, "e": 8044, "s": 8021, "text": "towardsdatascience.com" } ]
How to Listen for Volume Button and Back Key Events Programmatically in Android? - GeeksforGeeks
23 Feb, 2021 By production, Android devices are provided with specific physical keys, such as Volume keys, Power key, Back key, Home key, and Activities key. These keys respond to a press. The same keys have particular functionality on the nature of the press. The volume key on a Single press increases or decreases the volume by some amount. Similarly, the Power key on a Single press locks the device, but on a Long press, Switches on or off the device. This article will create an application that responds to key press and generates a message confirming the same. This idea can further be implemented for creating useful applications: Gaming Applications: Physical keys could be used for desired actions in Games.Ambiance: Volume keys could be used to increase or decrease the screen’s brightness rather than doing it the traditional way.Shortcuts to other Applications: Google Assistant pops up when the home key is pressed for long, similar shortcuts can be made. Gaming Applications: Physical keys could be used for desired actions in Games. Ambiance: Volume keys could be used to increase or decrease the screen’s brightness rather than doing it the traditional way. Shortcuts to other Applications: Google Assistant pops up when the home key is pressed for long, similar shortcuts can be made. This article aims to breach through the codes of this process and use the same keys for creating any desired applications or features. The codes’ scope explained in the latter section of the article is limited to the application that we will create. The created feature or functionality will work only inside the application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Working with the MainActivity.kt file In the MainActivity.kt file, declare an override function onKeyDown and add the following code, as shown in the below. We would generate a Toast in response to the key pressed. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.KeyEventimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } // 1. onKeyDown is a boolean function, which returns the state of the KeyEvent. // 2. This function is an internal function, that functions outside the actual application. // 3. When the any Key is pressed, a Toast appears with the following message. // 4. This code can be used to check if the device responds to any Key. override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { when (keyCode) { KeyEvent.KEYCODE_VOLUME_DOWN -> Toast.makeText(applicationContext, "Volume Down Key Pressed", Toast.LENGTH_SHORT).show() KeyEvent.KEYCODE_VOLUME_UP -> Toast.makeText(applicationContext, "Volume Up Key Pressed", Toast.LENGTH_SHORT).show() KeyEvent.KEYCODE_BACK -> Toast.makeText(applicationContext, "Back Key Pressed", Toast.LENGTH_SHORT).show() } return true }} Android-Misc Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Broadcast Receiver in Android With Example How to Create and Add Data to SQLite Database in Android? Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Content Providers in Android with Example Services in Android with Example Android UI Layouts Android RecyclerView in Kotlin
[ { "code": null, "e": 24472, "s": 24444, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25099, "s": 24472, "text": "By production, Android devices are provided with specific physical keys, such as Volume keys, Power key, Back key, Home key, and Activities key. These keys respond to a press. The same keys have particular functionality on the nature of the press. The volume key on a Single press increases or decreases the volume by some amount. Similarly, the Power key on a Single press locks the device, but on a Long press, Switches on or off the device. This article will create an application that responds to key press and generates a message confirming the same. This idea can further be implemented for creating useful applications:" }, { "code": null, "e": 25430, "s": 25099, "text": "Gaming Applications: Physical keys could be used for desired actions in Games.Ambiance: Volume keys could be used to increase or decrease the screen’s brightness rather than doing it the traditional way.Shortcuts to other Applications: Google Assistant pops up when the home key is pressed for long, similar shortcuts can be made." }, { "code": null, "e": 25509, "s": 25430, "text": "Gaming Applications: Physical keys could be used for desired actions in Games." }, { "code": null, "e": 25635, "s": 25509, "text": "Ambiance: Volume keys could be used to increase or decrease the screen’s brightness rather than doing it the traditional way." }, { "code": null, "e": 25763, "s": 25635, "text": "Shortcuts to other Applications: Google Assistant pops up when the home key is pressed for long, similar shortcuts can be made." }, { "code": null, "e": 26256, "s": 25763, "text": "This article aims to breach through the codes of this process and use the same keys for creating any desired applications or features. The codes’ scope explained in the latter section of the article is limited to the application that we will create. The created feature or functionality will work only inside the application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 26285, "s": 26256, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26449, "s": 26285, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 26495, "s": 26449, "text": "Step 2: Working with the MainActivity.kt file" }, { "code": null, "e": 26794, "s": 26495, "text": "In the MainActivity.kt file, declare an override function onKeyDown and add the following code, as shown in the below. We would generate a Toast in response to the key pressed. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 26801, "s": 26794, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.KeyEventimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } // 1. onKeyDown is a boolean function, which returns the state of the KeyEvent. // 2. This function is an internal function, that functions outside the actual application. // 3. When the any Key is pressed, a Toast appears with the following message. // 4. This code can be used to check if the device responds to any Key. override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { when (keyCode) { KeyEvent.KEYCODE_VOLUME_DOWN -> Toast.makeText(applicationContext, \"Volume Down Key Pressed\", Toast.LENGTH_SHORT).show() KeyEvent.KEYCODE_VOLUME_UP -> Toast.makeText(applicationContext, \"Volume Up Key Pressed\", Toast.LENGTH_SHORT).show() KeyEvent.KEYCODE_BACK -> Toast.makeText(applicationContext, \"Back Key Pressed\", Toast.LENGTH_SHORT).show() } return true }}", "e": 27997, "s": 26801, "text": null }, { "code": null, "e": 28010, "s": 27997, "text": "Android-Misc" }, { "code": null, "e": 28018, "s": 28010, "text": "Android" }, { "code": null, "e": 28025, "s": 28018, "text": "Kotlin" }, { "code": null, "e": 28033, "s": 28025, "text": "Android" }, { "code": null, "e": 28131, "s": 28033, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28140, "s": 28131, "text": "Comments" }, { "code": null, "e": 28153, "s": 28140, "text": "Old Comments" }, { "code": null, "e": 28196, "s": 28153, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28254, "s": 28196, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 28287, "s": 28254, "text": "Services in Android with Example" }, { "code": null, "e": 28329, "s": 28287, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28360, "s": 28329, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 28403, "s": 28360, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 28445, "s": 28403, "text": "Content Providers in Android with Example" }, { "code": null, "e": 28478, "s": 28445, "text": "Services in Android with Example" }, { "code": null, "e": 28497, "s": 28478, "text": "Android UI Layouts" } ]
Adding two Sets in Javascript
The operation of adding 2 sets is known as a union. You need to add every object from one set to another while checking for duplicates. We can just use the 2 methods we already implemented to implement this method. We'll implement this function as a static function as we don’t want to mutate existing sets, but create and return a new one. We first need to check if the object passed to it is really an instance of the MySet class. static union(s1, s2) { if (!s1 instanceof MySet || !s2 instanceof MySet) { console.log("The given objects are not of type MySet"); return null; } let newSet = new MySet(); s1.forEach(elem => newSet.add(elem)); s2.forEach(elem => newSet.add(elem)); newSet; } You can test this using − const testSet1 = new MySet(); testSet1.add(1); testSet1.add(2); const testSet2 = new MySet(); testSet2.add(2); testSet2.add(5); let testSet3 = MySet.union(testSet1, testSet2); testSet3.display(); This will give the output − { '1': '1', '2': '2', '5': '5' } Note that the union function is not there in the ES6 API as well. You can make this function be available in the Set class as follows &minusl Set.union = function(s1, s2) { if (!s1 instanceof Set || !s2 instanceof Set) { console.log("The given objects are not of type Set"); return null; } let newSet = new Set(); s1.forEach(elem => newSet.add(elem)); s2.forEach(elem => newSet.add(elem)); return newSet; } You can test this using − let setA = new Set([1, 2, 3, 4]); let setB = new Set([2, 3]); console.log(Set.union(setA, setB)); This will give the output − Set { 1, 2, 3, 4 }
[ { "code": null, "e": 1277, "s": 1062, "text": "The operation of adding 2 sets is known as a union. You need to add every object from one set to another while checking for duplicates. We can just use the 2 methods we already implemented to implement this method." }, { "code": null, "e": 1496, "s": 1277, "text": "We'll implement this function as a static function as we don’t want to mutate existing sets, but create and return a new one. We first need to check if the object passed to it is really an instance of the MySet class. " }, { "code": null, "e": 1784, "s": 1496, "text": "static union(s1, s2) {\n if (!s1 instanceof MySet || !s2 instanceof MySet) {\n console.log(\"The given objects are not of type MySet\");\n return null;\n }\n let newSet = new MySet();\n s1.forEach(elem => newSet.add(elem));\n s2.forEach(elem => newSet.add(elem));\n newSet;\n}" }, { "code": null, "e": 1811, "s": 1784, "text": "You can test this using − " }, { "code": null, "e": 2009, "s": 1811, "text": "const testSet1 = new MySet();\ntestSet1.add(1);\ntestSet1.add(2);\n\nconst testSet2 = new MySet();\ntestSet2.add(2);\ntestSet2.add(5);\n\nlet testSet3 = MySet.union(testSet1, testSet2);\ntestSet3.display();" }, { "code": null, "e": 2037, "s": 2009, "text": "This will give the output −" }, { "code": null, "e": 2070, "s": 2037, "text": "{ '1': '1', '2': '2', '5': '5' }" }, { "code": null, "e": 2213, "s": 2070, "text": "Note that the union function is not there in the ES6 API as well. You can make this function be available in the Set class as follows &minusl " }, { "code": null, "e": 2508, "s": 2213, "text": "Set.union = function(s1, s2) {\n if (!s1 instanceof Set || !s2 instanceof Set) {\n console.log(\"The given objects are not of type Set\");\n return null;\n }\n let newSet = new Set();\n s1.forEach(elem => newSet.add(elem));\n s2.forEach(elem => newSet.add(elem));\n return newSet;\n}" }, { "code": null, "e": 2534, "s": 2508, "text": "You can test this using −" }, { "code": null, "e": 2632, "s": 2534, "text": "let setA = new Set([1, 2, 3, 4]);\nlet setB = new Set([2, 3]);\nconsole.log(Set.union(setA, setB));" }, { "code": null, "e": 2660, "s": 2632, "text": "This will give the output −" }, { "code": null, "e": 2679, "s": 2660, "text": "Set { 1, 2, 3, 4 }" } ]
Python Pandas - Create a DateOffset and increment date
To create a DateOffset, use the DateOffset() method in Pandas. Set the Increment value as an argument. At first, import the required libraries − from pandas.tseries.offsets import DateOffset import pandas as pd Set the timestamp object in Pandas − timestamp = pd.Timestamp('2021-09-11 02:30:55') DateOffset for date increment. We are incrementing the months here using the "months" parameter − print("DateOffset...\n",timestamp + DateOffset(months=2)) Following is the code − from pandas.tseries.offsets import DateOffset import pandas as pd # Set the timestamp object in Pandas timestamp = pd.Timestamp('2021-09-11 02:30:55') # Display the Timestamp print("Timestamp...\n",timestamp) # DateOffset for date increment # We are incrementing the months here using the "months" parameter print("DateOffset...\n",timestamp + DateOffset(months=2)) This will produce the following code − Timestamp... 2021-09-11 02:30:55 DateOffset... 2021-11-11 02:30:55
[ { "code": null, "e": 1165, "s": 1062, "text": "To create a DateOffset, use the DateOffset() method in Pandas. Set the Increment value as an argument." }, { "code": null, "e": 1207, "s": 1165, "text": "At first, import the required libraries −" }, { "code": null, "e": 1273, "s": 1207, "text": "from pandas.tseries.offsets import DateOffset\nimport pandas as pd" }, { "code": null, "e": 1310, "s": 1273, "text": "Set the timestamp object in Pandas −" }, { "code": null, "e": 1359, "s": 1310, "text": "timestamp = pd.Timestamp('2021-09-11 02:30:55')\n" }, { "code": null, "e": 1457, "s": 1359, "text": "DateOffset for date increment. We are incrementing the months here using the \"months\" parameter −" }, { "code": null, "e": 1515, "s": 1457, "text": "print(\"DateOffset...\\n\",timestamp + DateOffset(months=2))" }, { "code": null, "e": 1539, "s": 1515, "text": "Following is the code −" }, { "code": null, "e": 1908, "s": 1539, "text": "from pandas.tseries.offsets import DateOffset\nimport pandas as pd\n\n# Set the timestamp object in Pandas\ntimestamp = pd.Timestamp('2021-09-11 02:30:55')\n\n# Display the Timestamp\nprint(\"Timestamp...\\n\",timestamp)\n\n# DateOffset for date increment\n# We are incrementing the months here using the \"months\" parameter\nprint(\"DateOffset...\\n\",timestamp + DateOffset(months=2))" }, { "code": null, "e": 1947, "s": 1908, "text": "This will produce the following code −" }, { "code": null, "e": 2014, "s": 1947, "text": "Timestamp...\n2021-09-11 02:30:55\nDateOffset...\n2021-11-11 02:30:55" } ]
How to find the length of sequence vector in R?
A sequence vector is created by using the sequence of numbers such as 1 to 15, 21 to 51, 101 to 150, -5 to 10. The length of this type of vectors can be found only by using the length function. For example, if we have a sequence vector say X then the length of X can be found by using the command given below − length(X) To find the length of sequence vector in R, use the code given below − x1<-c(1:51,57:200,201:213) x1 If you execute the above given code, it generates the following output − [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 57 58 59 [55] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 [73] 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 [91] 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 [109] 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 [127] 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 [145] 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 [163] 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 [181] 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 [199] 204 205 206 207 208 209 210 211 212 213 To find the length of sequence vector in R, add the following code to the above code − x1<-c(1:51,57:200,201:213) length(x1) If you execute all the above given codes as a single program, it generates the following output − [1] 208 To find the length of sequence vector in R, use the code given below − x2<-c(14:-50,7:48,23:98,21:-10) x2 If you execute the above given code, it generates the following output − [1] 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 [19] -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 [37] -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39 [55] -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 7 8 9 10 11 12 13 [73] 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 [91] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 23 [109] 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 [127] 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 [145] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 [163] 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 [181] 96 97 98 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 [199] 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 To find the length of sequence vector in R, add the following code to the above code − x2<-c(14:-50,7:48,23:98,21:-10) length(x2) If you execute all the above given codes as a single program, it generates the following output − [1] 215 To find the length of sequence vector in R, use the code given below − x3<-c(25:-100,1:78,35:-10,40:-5) x3 If you execute the above given code, it generates the following output − [1] 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 [16] 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 [31] -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 [46] -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 [61] -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 [76] -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64 [91] -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79 [106] -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 [121] -95 -96 -97 -98 -99 -100 1 2 3 4 5 6 7 8 9 [136] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 [151] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 [166] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 [181] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 [196] 70 71 72 73 74 75 76 77 78 35 34 33 32 31 30 [211] 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 [226] 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 [241] -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 40 39 38 37 36 [256] 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 [271] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 [286] 5 4 3 2 1 0 -1 -2 -3 -4 -5 To find the length of sequence vector in R, add the following code to the above code − x3<-c(25:-100,1:78,35:-10,40:-5) length(x3) If you execute all the above given codes as a single program, it generates the following output − [1] 296 To find the length of sequence vector in R, use the code given below − x4<-c(-50:25,5:61,69:151) x4 If you execute the above given code, it generates the following output − [1] -50 -49 -48 -47 -46 -45 -44 -43 -42 -41 -40 -39 -38 -37 -36 -35 -34 -33 [19] -32 -31 -30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 [37] -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 [55] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 [73] 22 23 24 25 5 6 7 8 9 10 11 12 13 14 15 16 17 18 [91] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 [109] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 [127] 55 56 57 58 59 60 61 69 70 71 72 73 74 75 76 77 78 79 [145] 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 [163] 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 [181] 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 [199] 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 To find the length of sequence vector in R, add the following code to the above code − x4<-c(-50:25,5:61,69:151) length(x4) If you execute all the above given codes as a single program, it generates the following output − [1] 216 To find the length of sequence vector in R, use the code given below − x5<-c(-5:100,9:79,21:-21) x5 If you execute the above given code, it generates the following output − [1] -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 [19] 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 [37] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 [55] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 [73] 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 [91] 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 9 10 [109] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 [127] 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 [145] 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 [163] 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 21 20 19 [181] 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [199] 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 [217] -18 -19 -20 -21 To find the length of sequence vector in R, add the following code to the above code − x5<-c(-5:100,9:79,21:-21) length(x5) If you execute all the above given codes as a single program, it generates the following output − [1] 220
[ { "code": null, "e": 1256, "s": 1062, "text": "A sequence vector is created by using the sequence of numbers such as 1 to 15, 21 to 51, 101 to 150, -5 to 10. The length of this type of vectors can be found only by using the length function." }, { "code": null, "e": 1373, "s": 1256, "text": "For example, if we have a sequence vector say X then the length of X can be found by using the command given below −" }, { "code": null, "e": 1383, "s": 1373, "text": "length(X)" }, { "code": null, "e": 1454, "s": 1383, "text": "To find the length of sequence vector in R, use the code given below −" }, { "code": null, "e": 1484, "s": 1454, "text": "x1<-c(1:51,57:200,201:213)\nx1" }, { "code": null, "e": 1557, "s": 1484, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 2351, "s": 1557, "text": "[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n[19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36\n[37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 57 58 59\n[55] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77\n[73] 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95\n[91] 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113\n[109] 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131\n[127] 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149\n[145] 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167\n[163] 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185\n[181] 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203\n[199] 204 205 206 207 208 209 210 211 212 213" }, { "code": null, "e": 2438, "s": 2351, "text": "To find the length of sequence vector in R, add the following code to the above code −" }, { "code": null, "e": 2476, "s": 2438, "text": "x1<-c(1:51,57:200,201:213)\nlength(x1)" }, { "code": null, "e": 2574, "s": 2476, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 2582, "s": 2574, "text": "[1] 208" }, { "code": null, "e": 2653, "s": 2582, "text": "To find the length of sequence vector in R, use the code given below −" }, { "code": null, "e": 2688, "s": 2653, "text": "x2<-c(14:-50,7:48,23:98,21:-10)\nx2" }, { "code": null, "e": 2761, "s": 2688, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 3490, "s": 2761, "text": "[1] 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3\n[19] -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21\n[37] -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39\n[55] -40 -41 -42 -43 -44 -45 -46 -47 -48 -49 -50 7 8 9 10 11 12 13\n[73] 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n[91] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 23\n[109] 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41\n[127] 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59\n[145] 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77\n[163] 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95\n[181] 96 97 98 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7\n[199] 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10" }, { "code": null, "e": 3577, "s": 3490, "text": "To find the length of sequence vector in R, add the following code to the above code −" }, { "code": null, "e": 3620, "s": 3577, "text": "x2<-c(14:-50,7:48,23:98,21:-10)\nlength(x2)" }, { "code": null, "e": 3718, "s": 3620, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 3726, "s": 3718, "text": "[1] 215" }, { "code": null, "e": 3797, "s": 3726, "text": "To find the length of sequence vector in R, use the code given below −" }, { "code": null, "e": 3833, "s": 3797, "text": "x3<-c(25:-100,1:78,35:-10,40:-5)\nx3" }, { "code": null, "e": 3906, "s": 3833, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 4960, "s": 3906, "text": "[1] 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11\n[16] 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4\n[31] -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19\n[46] -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34\n[61] -35 -36 -37 -38 -39 -40 -41 -42 -43 -44 -45 -46 -47 -48 -49\n[76] -50 -51 -52 -53 -54 -55 -56 -57 -58 -59 -60 -61 -62 -63 -64\n[91] -65 -66 -67 -68 -69 -70 -71 -72 -73 -74 -75 -76 -77 -78 -79\n[106] -80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94\n[121] -95 -96 -97 -98 -99 -100 1 2 3 4 5 6 7 8 9\n[136] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24\n[151] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39\n[166] 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54\n[181] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69\n[196] 70 71 72 73 74 75 76 77 78 35 34 33 32 31 30\n[211] 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15\n[226] 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0\n[241] -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 40 39 38 37 36\n[256] 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21\n[271] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6\n[286] 5 4 3 2 1 0 -1 -2 -3 -4 -5" }, { "code": null, "e": 5047, "s": 4960, "text": "To find the length of sequence vector in R, add the following code to the above code −" }, { "code": null, "e": 5091, "s": 5047, "text": "x3<-c(25:-100,1:78,35:-10,40:-5)\nlength(x3)" }, { "code": null, "e": 5189, "s": 5091, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 5197, "s": 5189, "text": "[1] 296" }, { "code": null, "e": 5268, "s": 5197, "text": "To find the length of sequence vector in R, use the code given below −" }, { "code": null, "e": 5297, "s": 5268, "text": "x4<-c(-50:25,5:61,69:151)\nx4" }, { "code": null, "e": 5370, "s": 5297, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 6161, "s": 5370, "text": "[1] -50 -49 -48 -47 -46 -45 -44 -43 -42 -41 -40 -39 -38 -37 -36 -35 -34 -33\n[19] -32 -31 -30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15\n[37] -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3\n[55] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n[73] 22 23 24 25 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n[91] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36\n[109] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54\n[127] 55 56 57 58 59 60 61 69 70 71 72 73 74 75 76 77 78 79\n[145] 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97\n[163] 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115\n[181] 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133\n[199] 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151" }, { "code": null, "e": 6248, "s": 6161, "text": "To find the length of sequence vector in R, add the following code to the above code −" }, { "code": null, "e": 6285, "s": 6248, "text": "x4<-c(-50:25,5:61,69:151)\nlength(x4)" }, { "code": null, "e": 6383, "s": 6285, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 6391, "s": 6383, "text": "[1] 216" }, { "code": null, "e": 6462, "s": 6391, "text": "To find the length of sequence vector in R, use the code given below −" }, { "code": null, "e": 6491, "s": 6462, "text": "x5<-c(-5:100,9:79,21:-21)\nx5" }, { "code": null, "e": 6564, "s": 6491, "text": "If you execute the above given code, it generates the following output −" }, { "code": null, "e": 7287, "s": 6564, "text": "[1] -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12\n[19] 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n[37] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48\n[55] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66\n[73] 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84\n[91] 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 9 10\n[109] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28\n[127] 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46\n[145] 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64\n[163] 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 21 20 19\n[181] 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1\n[199] 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17\n[217] -18 -19 -20 -21" }, { "code": null, "e": 7374, "s": 7287, "text": "To find the length of sequence vector in R, add the following code to the above code −" }, { "code": null, "e": 7411, "s": 7374, "text": "x5<-c(-5:100,9:79,21:-21)\nlength(x5)" }, { "code": null, "e": 7509, "s": 7411, "text": "If you execute all the above given codes as a single program, it generates the following output −" }, { "code": null, "e": 7517, "s": 7509, "text": "[1] 220" } ]
How can we implement the paintComponent() method of a JPanel in Java?
A JPanel is a lightweight container and it is an invisible component in Java. A JPanel's default layout is FlowLayout. After the JPanel has been created, other components can be added to the JPanel object by calling its add() method inherited from the Container class. This method is needed to draw something on JPanel other than drawing the background color. This method already exists in a JPanel class so that we need to use the super declaration to add something to this method and takes Graphics objects as parameters. The super.paintComponent() which represents the normal the paintComponent() method of the JPanel which can only handle the background of the panel must be called in the first line. protected void paintComponent(Graphics g) import java.awt.*; import javax.swing.*; public class SmileyApp extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.YELLOW); g.fillOval(10, 10, 200, 200); // draw Eyes g.setColor(Color.BLACK); g.fillOval(55, 65, 30, 30); g.fillOval(135, 65, 30, 30); // draw Mouth g.fillOval(50, 110, 120, 60); // adding smile g.setColor(Color.YELLOW); g.fillRect(50, 110, 120, 30); g.fillOval(50, 120, 120, 40); } public static void main(String[] args) { SmileyApp smiley = new SmileyApp(); JFrame app = new JFrame("Smiley App"); app.add(smiley, BorderLayout.CENTER); app.setSize(300, 300); app.setLocationRelativeTo(null); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setVisible(true); } }
[ { "code": null, "e": 1331, "s": 1062, "text": "A JPanel is a lightweight container and it is an invisible component in Java. A JPanel's default layout is FlowLayout. After the JPanel has been created, other components can be added to the JPanel object by calling its add() method inherited from the Container class." }, { "code": null, "e": 1767, "s": 1331, "text": "This method is needed to draw something on JPanel other than drawing the background color. This method already exists in a JPanel class so that we need to use the super declaration to add something to this method and takes Graphics objects as parameters. The super.paintComponent() which represents the normal the paintComponent() method of the JPanel which can only handle the background of the panel must be called in the first line." }, { "code": null, "e": 1809, "s": 1767, "text": "protected void paintComponent(Graphics g)" }, { "code": null, "e": 2688, "s": 1809, "text": "import java.awt.*;\nimport javax.swing.*;\npublic class SmileyApp extends JPanel {\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.setColor(Color.YELLOW);\n g.fillOval(10, 10, 200, 200);\n // draw Eyes\n g.setColor(Color.BLACK);\n g.fillOval(55, 65, 30, 30);\n g.fillOval(135, 65, 30, 30);\n // draw Mouth\n g.fillOval(50, 110, 120, 60);\n // adding smile\n g.setColor(Color.YELLOW);\n g.fillRect(50, 110, 120, 30);\n g.fillOval(50, 120, 120, 40);\n }\n public static void main(String[] args) {\n SmileyApp smiley = new SmileyApp();\n JFrame app = new JFrame(\"Smiley App\");\n app.add(smiley, BorderLayout.CENTER);\n app.setSize(300, 300);\n app.setLocationRelativeTo(null);\n app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n app.setVisible(true);\n }\n}" } ]
7 steps to run a linear regression analysis using R | by Tomomi A Emori | Towards Data Science
My manager thinks I know how to run a regression analysis using R. So, to save my butt, I decided to dedicate my whole weekend to learning how to do it. Think of this post as a crash course intro to learn how to brute force your way into doing one. Skip to the section you want to read. Table of contents below: Part I | My scope of knowledge upon beginning to write this post Part II | How I searched for my resources Part III | Regression tips: learnings from an engineer Part IV | 7 copy & paste steps to run a linear regression analysis using R Part V | Next steps: Improving your model First, to establish grounds, let me tell you what I do know about regression, and what I can do in R. The equation is in the format: y=ax+b, where y is the dependent variable, x is the independent variable, a is a coefficient, and b is a constant/y-intercept. I know what each of these terms means. It’s a way of figuring out the impact the independent variable x has on the dependent variable y. In order to do this, you take the existing data that you have and test all of the cases against this equation to find the most appropriate a and b in order to predict y values that you don’t have data for. You can add any number of independent variables with a coefficient attached to each to see the impact each has on the dependent variable. That said, too many variables will not improve the model and in some cases hurt it. It’s best to normalize your data so that you work with values between 0 and 1. That way, coefficients aren’t tiny or enormous because of the nature of the independent variables (e.g. 4634 days vs 13 years are two variables you can use in the same model, but because they are so different in size, the coefficients would probably be skewed). Basic data wrangling in dplyr (mutate, filter, select, pipe operator %>%, summarize, dot placeholder, group_by, arrange, top_n) Plots in dplyr (plot, hist, boxplot) Plots in ggplot2 (the geoms, facet_grid, time series plots, axis transformations, stratify, boxplot, slope charts) I learned everything I know about R from two online courses I’ve taken so far (1. R Basics, 2. Visualization). How I figured out what to focus on this weekend. These are the top four links that came up for me: https://www.r-bloggers.com/how-to-apply-linear-regression-in-r/https://www.r-bloggers.com/linear-regression-using-r/https://www.r-bloggers.com/regression-analysis-using-r/https://www.r-bloggers.com/linear-regression-from-scratch-in-r/ https://www.r-bloggers.com/how-to-apply-linear-regression-in-r/ https://www.r-bloggers.com/linear-regression-using-r/ https://www.r-bloggers.com/regression-analysis-using-r/ https://www.r-bloggers.com/linear-regression-from-scratch-in-r/ I clicked the link “next blog,” and BINGO! “Predict Bounce Rate based on Page Load Time in Google Analytics.” Since I didn’t mention already, to note here: I am in the performance advertising space, so this is literally right up my alley. They even do a part 3 on improving the model! I’ve found what I’m going to focus on this weekend. Going to compile learnings here as I learn anything! I had a really helpful conversation with an engineer who entertained my questions this weekend, and I’d like to share with you some tips that he shared. In summary, running a regression analysis is just the start of your investigation in assessing whether some data has a relationship with other data. With that context, here are ways you can ensure you come up with an analysis that is honest and helps you figure out your next steps. Normalize the data so that you can compare coefficients as fairly as possible. Though there isn’t a set way to compare coefficients of independent variables apples to apples with each other, normalizing data allows you to at least be able to eyeball the impact that an independent variable has on the dependent variable. This is a great starting point for research: once you see that one coefficient is larger than another, you can begin to investigate what is causing any “high” coefficients. If you don’t normalize your data, you can have a massive range of values for each, resulting in the coefficients also ranging widely in order to compensate for the weight of larger values. p-value significance is an indicator of certainty. Even if a coefficient is high, if it is not statistically significant, it’s at best meaningless, and at worst ruining the model. (See section “The Asterisks” in this blog post to learn about how to read p-values.) Remove outliers when running the regression, then after creating the model, test the model with each of the outliers to compare the predicted vs true values for the dependent variable. This allows you to see how robust your model is. If the error for the outliers is low, then it’s a huge win for the model; if the error is still high, then you can simply continue to assert the fact that they are outliers. In addition to looking at the aggregate error, it’s also important to look at the error of each individual data point. By doing this, you can dig into any reasons or trends as to why a certain point or set of points might have a larger error than others. Crap in, crap out. Without good data, you’re not going to have good results. Make sure you know where your data is coming from, and make sure it’s high quality. So here we are. Time to actually run a regression analysis using R. As a note, I use RStudio. General tips and instructions: For each step that introduces code, I’ve added a screenshot with my example, and then a code block of the same thing that you can copy & paste into your own R Script. The code blocks are for the case that you have 1 independent variable. Follow instructions in the R comments if you have more than one independent variable. In each code block, I’ve included brackets in italics that you can replace with your own code, like so:[[insert your code]]. When you replace with your own code, make sure you remove both the brackets AND the text. Don’t add any spaces when you do so. Use my screenshots as a guide, especially if you have more than one independent variable. You can execute at each step, or you can execute all at once when you’ve copied and pasted everything. Here we go! Obtain a dataset that includes all the variables you want to test. Choose the dependent and independent variables you want to model off of. Tip: All good regressions start with a question. In order to figure out what variables you want, ask yourself a real-life question to determine what you need. What is the relationship you want to test?Clean up your data and save it as a csv file — remove all columns of variables you don’t need. In my case, I want to see whether Conversions are dependent on Spend, imp, click, usv, and pv, so I’ll leave those six and delete everything else. Also, make sure you delete any rows with grand totals in them. After cleaning it up, save it as a csv file. Obtain a dataset that includes all the variables you want to test. Choose the dependent and independent variables you want to model off of. Tip: All good regressions start with a question. In order to figure out what variables you want, ask yourself a real-life question to determine what you need. What is the relationship you want to test? Clean up your data and save it as a csv file — remove all columns of variables you don’t need. In my case, I want to see whether Conversions are dependent on Spend, imp, click, usv, and pv, so I’ll leave those six and delete everything else. Also, make sure you delete any rows with grand totals in them. After cleaning it up, save it as a csv file. 3. Import the csv file into R Studio with function read.csv(). (See this link for how to get the pathname on a mac.) #import data from csv filedata <- read.csv('[[insert your pathname]]') 4. Remove all NA values of the dependent variable using drop_na() in tidyverse. See here for the reference that describes this function. #install tidyverse if you don't have it alreadyinstall.packages("tidyverse")#launch tidyverselibrary(tidyverse)#remove na values of independent variabledata <- data %>% drop_na([[insert column name of your independent variable]]) 5. Normalize your independent variables. I did this in R by dividing out each of the independent variables by their respective max value. #normalize data (add additional %>% for any number of independent variables you have)norm_data <- data %>% mutate([[insert a simple name of independent variable]]_norm = [[insert column name of independent variable]]/max([[insert column name of independent variable]],na.rm=TRUE)) To break down what I’m doing above, let’s look at what I did with the column Spend: mutate(spend_norm = Spend/max(Spend,na.rm=TRUE)) mutate(): function used to append a new column to the existing dataset spend_norm =the name of my new column Spend/max(Spend): the normalization formula na.rm=TRUE: argument used to remove the null values Since I mutated each of the columns with new names, thus creating 5 extra columns, I used the function select() in order to keep just the relevant columns. #select relevant columns (add additional commas and variable names for any number of independent variables)select_data <- norm_data %>% select([[insert column name of dependent variable]],[[insert new normalized column name of independent variable]]) 6. Find and remove outliers. I used the method of not considering anything 1.5 times the interquartile range (IQR) below the 1st quartile or 1.5 times the IQR above the 3rd quartile for my dataset. See here for the reference I used to determine this and the functions I copied. There are two mini-steps in this: 1. Find the outliers. Determine IQR and upper/lower ranges from the original dataset for each independent variable. 2. Remove the outliers. Select only the data that falls between the upper and lower ranges found in step 1 from the updated dataset obtained after removing the previous independent variable’s outliers. I repeated these 2 steps for each independent variable and ended up with the subset removed5. See my code in RStudio below. (You’ll see that I didn’t do this in the most efficient way possible. Would love any suggestions to make this more efficient.) #removing outliers#1. run this code to determine iqr and upper/lower ranges for independent variablex <-select_data$[[insert new normalized column name of independent variable]]Q <- quantile(x,probs=c(.25,.75),na.rm=TRUE)iqr <- IQR(x,na.rm=TRUE)up <- Q[2]+1.5*iqr # Upper Rangelow<- Q[1]-1.5*iqr # Lower Range#2. run this code to select only the data that's between the upper and lower rangesremoved1 <- subset(select_data, select_data$[[insert new normalized column name of independent variable]] > (Q[1] - 1.5*iqr) & select_data$[[insert new normalized column name of independent variable]] < (Q[2]+1.5*iqr))#if you're curious, see the new boxplotggplot(removed1,aes([[insert new normalized column name of independent variable]])) + geom_boxplot()#this is the new dataset you'll be working withView(removed[[insert # of total independent variables you normalized data for]])########if you have two or more independent variables, copy and paste the code below as many times as you need:#2nd independent variable ranges - repeating #1 and #2 above#1. run this code to determine iqr and upper/lower ranges for independent variablex <-select_data$[[insert new normalized column name of independent variable]]Q <- quantile(x,probs=c(.25,.75),na.rm=TRUE)iqr <- IQR(x,na.rm=TRUE)up <- Q[2]+1.5*iqr # Upper Rangelow<- Q[1]-1.5*iqr # Lower Range#2. run this code to select only the data that's between the upper and lower rangesremoved[[insert # for what number independent variable you are on]] <- subset(select_data, select_data$[[insert new normalized column name of independent variable]] > (Q[1] - 1.5*iqr) & select_data$[[insert new normalized column name of independent variable]] < (Q[2]+1.5*iqr))#if you're curious, see the new boxplotggplot(removed[[insert # for what number independent variable you are on]],aes([[insert new normalized column name of independent variable]])) + geom_boxplot()#this is the new dataset you'll be working withView(removed[[insert # of total independent variables you normalized data for]]) 7. Regression time! Use the R function lm() with your data. Go back to the original post I’m learning from for an explanation of what you’re doing here. #add additional variables as needed with + signModel1 <- lm(removed[[insert # of total independent variables you normalized data for]]$[[insert column name of dependent variable]] ~removed[[insert # of total independent variables you normalized data for]]$[[insert new normalized column name of independent variable]]) You’ve created your model! Now for the summary of results, run the final piece of code for the regression: summary(Model1) The engineer I mentioned above looked at these results and immediately said, “Yeah, your data sucks.” He said the Std. Error for each variable is too large compared to its Estimate. He also mentioned that with just 15 rows of data, using five variables for the model just doesn’t make sense. But no matter... we did it! Hooray! So we’ve run our regression analysis! ...but this isn’t the end. As the saying goes, “All models are wrong, but some are useful.” So your next steps are to figure out how to improve your model to make sure what you are pulling is actually useful. From the third post of the series I’m learning from this weekend, along with the support of a more detailed post, I found that the combination of the function regsubsets() along with the metrics Adjusted R2, Cp and BIC allows us to figure out how many variables from your dataset are actually useful for the model in question. This helps for any models that have more than 2 independent variables. install.packages("leaps")library(leaps)#add any number of independent variables that you need to the equation (note: this will not work if you only have 1 independent variable)leaps <- regsubsets(removed[[insert # of total independent variables you normalized data for]]$[[insert column name of dependent variable]] ~ removed[[insert # of total independent variables you normalized data for]]$[[insert new normalized column name of independent variable]],data=removed[[insert # of total independent variables you normalized data for]],nvmax=[[insert # of total independent variables you normalized data for]])summary(leaps)res.sum <- summary(leaps)data.frame( Adj.R2 = which.max(res.sum$adjr2), CP = which.min(res.sum$cp), BIC = which.min(res.sum$bic)) To explain what I’m doing above using the words of the posts I linked above, here’s an excerpt from one of the posts: The R function regsubsets() [leaps package] can be used to identify different best models of different sizes. You need to specify the option nvmax, which represents the maximum number of predictors to incorporate in the model. For example, if nvmax = 5, the function will return up to the best 5-variables model, that is, it returns the best 1-variable model, the best 2-variables model, ..., the best 5-variables models. In our example, we have only 5 predictor variables in the data. So, we’ll use nvmax = 5. (Source) And regarding the second half of the code above: The summary() function returns some metrics - Adjusted R2, Cp and BIC (see Chapter [...] - allowing us to identify the best overall model, where best is defined as the model that maximize the adjusted R2 and minimize the prediction error (RSS, cp and BIC). The adjusted R2 represents the proportion of variation, in the outcome, that are explained by the variation in predictors values. the higher the adjusted R2, the better the model. (Source) The best model, according to each of these metrics, they mention, is in the code block below and produces the results following. res.sum <- summary(leaps)data.frame( Adj.R2 = which.max(res.sum$adjr2), CP = which.min(res.sum$cp), BIC = which.min(res.sum$bic)) Based on the results, Adjusted R2 tells us that the best model is the one with 1 predictor variable, as does the Cp and BIC criteria. It’s saying I should decrease the number of variables in my model from five down to one. This isn’t surprising since I only had 15 rows of data to begin with. And with that, I conclude my weekend bonanza of learning linear regression using R. If you’re like me at all, brute forcing it and learn by doing is the perfect start to getting to know a topic. I hope you got as much out of it as I did. Onward!
[ { "code": null, "e": 421, "s": 172, "text": "My manager thinks I know how to run a regression analysis using R. So, to save my butt, I decided to dedicate my whole weekend to learning how to do it. Think of this post as a crash course intro to learn how to brute force your way into doing one." }, { "code": null, "e": 484, "s": 421, "text": "Skip to the section you want to read. Table of contents below:" }, { "code": null, "e": 549, "s": 484, "text": "Part I | My scope of knowledge upon beginning to write this post" }, { "code": null, "e": 591, "s": 549, "text": "Part II | How I searched for my resources" }, { "code": null, "e": 646, "s": 591, "text": "Part III | Regression tips: learnings from an engineer" }, { "code": null, "e": 721, "s": 646, "text": "Part IV | 7 copy & paste steps to run a linear regression analysis using R" }, { "code": null, "e": 763, "s": 721, "text": "Part V | Next steps: Improving your model" }, { "code": null, "e": 865, "s": 763, "text": "First, to establish grounds, let me tell you what I do know about regression, and what I can do in R." }, { "code": null, "e": 1062, "s": 865, "text": "The equation is in the format: y=ax+b, where y is the dependent variable, x is the independent variable, a is a coefficient, and b is a constant/y-intercept. I know what each of these terms means." }, { "code": null, "e": 1366, "s": 1062, "text": "It’s a way of figuring out the impact the independent variable x has on the dependent variable y. In order to do this, you take the existing data that you have and test all of the cases against this equation to find the most appropriate a and b in order to predict y values that you don’t have data for." }, { "code": null, "e": 1588, "s": 1366, "text": "You can add any number of independent variables with a coefficient attached to each to see the impact each has on the dependent variable. That said, too many variables will not improve the model and in some cases hurt it." }, { "code": null, "e": 1929, "s": 1588, "text": "It’s best to normalize your data so that you work with values between 0 and 1. That way, coefficients aren’t tiny or enormous because of the nature of the independent variables (e.g. 4634 days vs 13 years are two variables you can use in the same model, but because they are so different in size, the coefficients would probably be skewed)." }, { "code": null, "e": 2057, "s": 1929, "text": "Basic data wrangling in dplyr (mutate, filter, select, pipe operator %>%, summarize, dot placeholder, group_by, arrange, top_n)" }, { "code": null, "e": 2094, "s": 2057, "text": "Plots in dplyr (plot, hist, boxplot)" }, { "code": null, "e": 2209, "s": 2094, "text": "Plots in ggplot2 (the geoms, facet_grid, time series plots, axis transformations, stratify, boxplot, slope charts)" }, { "code": null, "e": 2320, "s": 2209, "text": "I learned everything I know about R from two online courses I’ve taken so far (1. R Basics, 2. Visualization)." }, { "code": null, "e": 2369, "s": 2320, "text": "How I figured out what to focus on this weekend." }, { "code": null, "e": 2419, "s": 2369, "text": "These are the top four links that came up for me:" }, { "code": null, "e": 2654, "s": 2419, "text": "https://www.r-bloggers.com/how-to-apply-linear-regression-in-r/https://www.r-bloggers.com/linear-regression-using-r/https://www.r-bloggers.com/regression-analysis-using-r/https://www.r-bloggers.com/linear-regression-from-scratch-in-r/" }, { "code": null, "e": 2718, "s": 2654, "text": "https://www.r-bloggers.com/how-to-apply-linear-regression-in-r/" }, { "code": null, "e": 2772, "s": 2718, "text": "https://www.r-bloggers.com/linear-regression-using-r/" }, { "code": null, "e": 2828, "s": 2772, "text": "https://www.r-bloggers.com/regression-analysis-using-r/" }, { "code": null, "e": 2892, "s": 2828, "text": "https://www.r-bloggers.com/linear-regression-from-scratch-in-r/" }, { "code": null, "e": 3177, "s": 2892, "text": "I clicked the link “next blog,” and BINGO! “Predict Bounce Rate based on Page Load Time in Google Analytics.” Since I didn’t mention already, to note here: I am in the performance advertising space, so this is literally right up my alley. They even do a part 3 on improving the model!" }, { "code": null, "e": 3282, "s": 3177, "text": "I’ve found what I’m going to focus on this weekend. Going to compile learnings here as I learn anything!" }, { "code": null, "e": 3718, "s": 3282, "text": "I had a really helpful conversation with an engineer who entertained my questions this weekend, and I’d like to share with you some tips that he shared. In summary, running a regression analysis is just the start of your investigation in assessing whether some data has a relationship with other data. With that context, here are ways you can ensure you come up with an analysis that is honest and helps you figure out your next steps." }, { "code": null, "e": 4401, "s": 3718, "text": "Normalize the data so that you can compare coefficients as fairly as possible. Though there isn’t a set way to compare coefficients of independent variables apples to apples with each other, normalizing data allows you to at least be able to eyeball the impact that an independent variable has on the dependent variable. This is a great starting point for research: once you see that one coefficient is larger than another, you can begin to investigate what is causing any “high” coefficients. If you don’t normalize your data, you can have a massive range of values for each, resulting in the coefficients also ranging widely in order to compensate for the weight of larger values." }, { "code": null, "e": 4666, "s": 4401, "text": "p-value significance is an indicator of certainty. Even if a coefficient is high, if it is not statistically significant, it’s at best meaningless, and at worst ruining the model. (See section “The Asterisks” in this blog post to learn about how to read p-values.)" }, { "code": null, "e": 5074, "s": 4666, "text": "Remove outliers when running the regression, then after creating the model, test the model with each of the outliers to compare the predicted vs true values for the dependent variable. This allows you to see how robust your model is. If the error for the outliers is low, then it’s a huge win for the model; if the error is still high, then you can simply continue to assert the fact that they are outliers." }, { "code": null, "e": 5329, "s": 5074, "text": "In addition to looking at the aggregate error, it’s also important to look at the error of each individual data point. By doing this, you can dig into any reasons or trends as to why a certain point or set of points might have a larger error than others." }, { "code": null, "e": 5490, "s": 5329, "text": "Crap in, crap out. Without good data, you’re not going to have good results. Make sure you know where your data is coming from, and make sure it’s high quality." }, { "code": null, "e": 5584, "s": 5490, "text": "So here we are. Time to actually run a regression analysis using R. As a note, I use RStudio." }, { "code": null, "e": 5615, "s": 5584, "text": "General tips and instructions:" }, { "code": null, "e": 5782, "s": 5615, "text": "For each step that introduces code, I’ve added a screenshot with my example, and then a code block of the same thing that you can copy & paste into your own R Script." }, { "code": null, "e": 5939, "s": 5782, "text": "The code blocks are for the case that you have 1 independent variable. Follow instructions in the R comments if you have more than one independent variable." }, { "code": null, "e": 6064, "s": 5939, "text": "In each code block, I’ve included brackets in italics that you can replace with your own code, like so:[[insert your code]]." }, { "code": null, "e": 6191, "s": 6064, "text": "When you replace with your own code, make sure you remove both the brackets AND the text. Don’t add any spaces when you do so." }, { "code": null, "e": 6384, "s": 6191, "text": "Use my screenshots as a guide, especially if you have more than one independent variable. You can execute at each step, or you can execute all at once when you’ve copied and pasted everything." }, { "code": null, "e": 6396, "s": 6384, "text": "Here we go!" }, { "code": null, "e": 7087, "s": 6396, "text": "Obtain a dataset that includes all the variables you want to test. Choose the dependent and independent variables you want to model off of. Tip: All good regressions start with a question. In order to figure out what variables you want, ask yourself a real-life question to determine what you need. What is the relationship you want to test?Clean up your data and save it as a csv file — remove all columns of variables you don’t need. In my case, I want to see whether Conversions are dependent on Spend, imp, click, usv, and pv, so I’ll leave those six and delete everything else. Also, make sure you delete any rows with grand totals in them. After cleaning it up, save it as a csv file." }, { "code": null, "e": 7429, "s": 7087, "text": "Obtain a dataset that includes all the variables you want to test. Choose the dependent and independent variables you want to model off of. Tip: All good regressions start with a question. In order to figure out what variables you want, ask yourself a real-life question to determine what you need. What is the relationship you want to test?" }, { "code": null, "e": 7779, "s": 7429, "text": "Clean up your data and save it as a csv file — remove all columns of variables you don’t need. In my case, I want to see whether Conversions are dependent on Spend, imp, click, usv, and pv, so I’ll leave those six and delete everything else. Also, make sure you delete any rows with grand totals in them. After cleaning it up, save it as a csv file." }, { "code": null, "e": 7896, "s": 7779, "text": "3. Import the csv file into R Studio with function read.csv(). (See this link for how to get the pathname on a mac.)" }, { "code": null, "e": 7967, "s": 7896, "text": "#import data from csv filedata <- read.csv('[[insert your pathname]]')" }, { "code": null, "e": 8104, "s": 7967, "text": "4. Remove all NA values of the dependent variable using drop_na() in tidyverse. See here for the reference that describes this function." }, { "code": null, "e": 8334, "s": 8104, "text": "#install tidyverse if you don't have it alreadyinstall.packages(\"tidyverse\")#launch tidyverselibrary(tidyverse)#remove na values of independent variabledata <- data %>% drop_na([[insert column name of your independent variable]])" }, { "code": null, "e": 8472, "s": 8334, "text": "5. Normalize your independent variables. I did this in R by dividing out each of the independent variables by their respective max value." }, { "code": null, "e": 8753, "s": 8472, "text": "#normalize data (add additional %>% for any number of independent variables you have)norm_data <- data %>% mutate([[insert a simple name of independent variable]]_norm = [[insert column name of independent variable]]/max([[insert column name of independent variable]],na.rm=TRUE))" }, { "code": null, "e": 8886, "s": 8753, "text": "To break down what I’m doing above, let’s look at what I did with the column Spend: mutate(spend_norm = Spend/max(Spend,na.rm=TRUE))" }, { "code": null, "e": 8957, "s": 8886, "text": "mutate(): function used to append a new column to the existing dataset" }, { "code": null, "e": 8995, "s": 8957, "text": "spend_norm =the name of my new column" }, { "code": null, "e": 9039, "s": 8995, "text": "Spend/max(Spend): the normalization formula" }, { "code": null, "e": 9091, "s": 9039, "text": "na.rm=TRUE: argument used to remove the null values" }, { "code": null, "e": 9247, "s": 9091, "text": "Since I mutated each of the columns with new names, thus creating 5 extra columns, I used the function select() in order to keep just the relevant columns." }, { "code": null, "e": 9498, "s": 9247, "text": "#select relevant columns (add additional commas and variable names for any number of independent variables)select_data <- norm_data %>% select([[insert column name of dependent variable]],[[insert new normalized column name of independent variable]])" }, { "code": null, "e": 9527, "s": 9498, "text": "6. Find and remove outliers." }, { "code": null, "e": 9810, "s": 9527, "text": "I used the method of not considering anything 1.5 times the interquartile range (IQR) below the 1st quartile or 1.5 times the IQR above the 3rd quartile for my dataset. See here for the reference I used to determine this and the functions I copied. There are two mini-steps in this:" }, { "code": null, "e": 9926, "s": 9810, "text": "1. Find the outliers. Determine IQR and upper/lower ranges from the original dataset for each independent variable." }, { "code": null, "e": 10128, "s": 9926, "text": "2. Remove the outliers. Select only the data that falls between the upper and lower ranges found in step 1 from the updated dataset obtained after removing the previous independent variable’s outliers." }, { "code": null, "e": 10379, "s": 10128, "text": "I repeated these 2 steps for each independent variable and ended up with the subset removed5. See my code in RStudio below. (You’ll see that I didn’t do this in the most efficient way possible. Would love any suggestions to make this more efficient.)" }, { "code": null, "e": 12405, "s": 10379, "text": "#removing outliers#1. run this code to determine iqr and upper/lower ranges for independent variablex <-select_data$[[insert new normalized column name of independent variable]]Q <- quantile(x,probs=c(.25,.75),na.rm=TRUE)iqr <- IQR(x,na.rm=TRUE)up <- Q[2]+1.5*iqr # Upper Rangelow<- Q[1]-1.5*iqr # Lower Range#2. run this code to select only the data that's between the upper and lower rangesremoved1 <- subset(select_data, select_data$[[insert new normalized column name of independent variable]] > (Q[1] - 1.5*iqr) & select_data$[[insert new normalized column name of independent variable]] < (Q[2]+1.5*iqr))#if you're curious, see the new boxplotggplot(removed1,aes([[insert new normalized column name of independent variable]])) + geom_boxplot()#this is the new dataset you'll be working withView(removed[[insert # of total independent variables you normalized data for]])########if you have two or more independent variables, copy and paste the code below as many times as you need:#2nd independent variable ranges - repeating #1 and #2 above#1. run this code to determine iqr and upper/lower ranges for independent variablex <-select_data$[[insert new normalized column name of independent variable]]Q <- quantile(x,probs=c(.25,.75),na.rm=TRUE)iqr <- IQR(x,na.rm=TRUE)up <- Q[2]+1.5*iqr # Upper Rangelow<- Q[1]-1.5*iqr # Lower Range#2. run this code to select only the data that's between the upper and lower rangesremoved[[insert # for what number independent variable you are on]] <- subset(select_data, select_data$[[insert new normalized column name of independent variable]] > (Q[1] - 1.5*iqr) & select_data$[[insert new normalized column name of independent variable]] < (Q[2]+1.5*iqr))#if you're curious, see the new boxplotggplot(removed[[insert # for what number independent variable you are on]],aes([[insert new normalized column name of independent variable]])) + geom_boxplot()#this is the new dataset you'll be working withView(removed[[insert # of total independent variables you normalized data for]])" }, { "code": null, "e": 12558, "s": 12405, "text": "7. Regression time! Use the R function lm() with your data. Go back to the original post I’m learning from for an explanation of what you’re doing here." }, { "code": null, "e": 12877, "s": 12558, "text": "#add additional variables as needed with + signModel1 <- lm(removed[[insert # of total independent variables you normalized data for]]$[[insert column name of dependent variable]] ~removed[[insert # of total independent variables you normalized data for]]$[[insert new normalized column name of independent variable]])" }, { "code": null, "e": 12984, "s": 12877, "text": "You’ve created your model! Now for the summary of results, run the final piece of code for the regression:" }, { "code": null, "e": 13000, "s": 12984, "text": "summary(Model1)" }, { "code": null, "e": 13292, "s": 13000, "text": "The engineer I mentioned above looked at these results and immediately said, “Yeah, your data sucks.” He said the Std. Error for each variable is too large compared to its Estimate. He also mentioned that with just 15 rows of data, using five variables for the model just doesn’t make sense." }, { "code": null, "e": 13328, "s": 13292, "text": "But no matter... we did it! Hooray!" }, { "code": null, "e": 13973, "s": 13328, "text": "So we’ve run our regression analysis! ...but this isn’t the end. As the saying goes, “All models are wrong, but some are useful.” So your next steps are to figure out how to improve your model to make sure what you are pulling is actually useful. From the third post of the series I’m learning from this weekend, along with the support of a more detailed post, I found that the combination of the function regsubsets() along with the metrics Adjusted R2, Cp and BIC allows us to figure out how many variables from your dataset are actually useful for the model in question. This helps for any models that have more than 2 independent variables." }, { "code": null, "e": 14729, "s": 13973, "text": "install.packages(\"leaps\")library(leaps)#add any number of independent variables that you need to the equation (note: this will not work if you only have 1 independent variable)leaps <- regsubsets(removed[[insert # of total independent variables you normalized data for]]$[[insert column name of dependent variable]] ~ removed[[insert # of total independent variables you normalized data for]]$[[insert new normalized column name of independent variable]],data=removed[[insert # of total independent variables you normalized data for]],nvmax=[[insert # of total independent variables you normalized data for]])summary(leaps)res.sum <- summary(leaps)data.frame( Adj.R2 = which.max(res.sum$adjr2), CP = which.min(res.sum$cp), BIC = which.min(res.sum$bic))" }, { "code": null, "e": 14847, "s": 14729, "text": "To explain what I’m doing above using the words of the posts I linked above, here’s an excerpt from one of the posts:" }, { "code": null, "e": 15269, "s": 14847, "text": "The R function regsubsets() [leaps package] can be used to identify different best models of different sizes. You need to specify the option nvmax, which represents the maximum number of predictors to incorporate in the model. For example, if nvmax = 5, the function will return up to the best 5-variables model, that is, it returns the best 1-variable model, the best 2-variables model, ..., the best 5-variables models." }, { "code": null, "e": 15367, "s": 15269, "text": "In our example, we have only 5 predictor variables in the data. So, we’ll use nvmax = 5. (Source)" }, { "code": null, "e": 15416, "s": 15367, "text": "And regarding the second half of the code above:" }, { "code": null, "e": 15673, "s": 15416, "text": "The summary() function returns some metrics - Adjusted R2, Cp and BIC (see Chapter [...] - allowing us to identify the best overall model, where best is defined as the model that maximize the adjusted R2 and minimize the prediction error (RSS, cp and BIC)." }, { "code": null, "e": 15862, "s": 15673, "text": "The adjusted R2 represents the proportion of variation, in the outcome, that are explained by the variation in predictors values. the higher the adjusted R2, the better the model. (Source)" }, { "code": null, "e": 15991, "s": 15862, "text": "The best model, according to each of these metrics, they mention, is in the code block below and produces the results following." }, { "code": null, "e": 16124, "s": 15991, "text": "res.sum <- summary(leaps)data.frame( Adj.R2 = which.max(res.sum$adjr2), CP = which.min(res.sum$cp), BIC = which.min(res.sum$bic))" }, { "code": null, "e": 16417, "s": 16124, "text": "Based on the results, Adjusted R2 tells us that the best model is the one with 1 predictor variable, as does the Cp and BIC criteria. It’s saying I should decrease the number of variables in my model from five down to one. This isn’t surprising since I only had 15 rows of data to begin with." } ]
PHP strtotime() Function
The strtotime() function accepts a date/time string, with textual date/time values and parses it as an Unix timestamp. strtotime($time) time(Mandatory) This value represents the date/time string. now(Optional) This represents a timestamp which is used as a base for the calculation of relative dates.. PHP strtotime() function returns a timestamp value for the given date string. Incase of failure, this function returns the boolean value false. This function was first introduced in PHP Version 4.0 and, works with all the later versions. Following example demonstrates the usage of the strtotime() function − <?php $str = strtotime("12 September 2009"); print("Timestamp: ".$str); ?> This will produce following result − Timestamp: 1252713600 If you pass "now" as a parameter this function returns the current time stamp <?php $str = strtotime("now"); print("Timestamp: ".$str); ?> This will produce following result − Timestamp: 1589369948 Now letus invoke this method by passing various date values − <?php print("Time stamp of 25 December 2019: ".strtotime("25 December 2019")."\n"); print("Time stamp of +26 day: ".strtotime("+26 day")."\n"); print("Time stamp of +3 week: ".strtotime("+3 week")."\n"); print("Time stamp of +3 month 9 days 9 hours: ".strtotime("+3 month 9 days 9 hours")."\n"); print("Time stamp of last Sunday: ".strtotime("last Sunday")."\n"); print("Time stamp of next Friday: ".strtotime("next Friday")."\n"); ?> This will produce the following output − Time stamp of 25 December 2019: 1577232000 Time stamp of +26 day: 1591617718 Time stamp of +3 week: 1591185718 Time stamp of +3 month 9 days 9 hours: 1598130118 Time stamp of last Sunday: 1589068800 Time stamp of next Friday: 1589500800 <?php $timestamp = strtotime( "February 15, 2015" ); print date( 'Y-m-d', $timestamp ); ?> This will produce the following output − 2015-02-15 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2876, "s": 2757, "text": "The strtotime() function accepts a date/time string, with textual date/time values and parses it as an Unix timestamp." }, { "code": null, "e": 2894, "s": 2876, "text": "strtotime($time)\n" }, { "code": null, "e": 2910, "s": 2894, "text": "time(Mandatory)" }, { "code": null, "e": 2954, "s": 2910, "text": "This value represents the date/time string." }, { "code": null, "e": 2968, "s": 2954, "text": "now(Optional)" }, { "code": null, "e": 3060, "s": 2968, "text": "This represents a timestamp which is used as a base for the calculation of relative dates.." }, { "code": null, "e": 3204, "s": 3060, "text": "PHP strtotime() function returns a timestamp value for the given date string. Incase of failure, this function returns the boolean value false." }, { "code": null, "e": 3298, "s": 3204, "text": "This function was first introduced in PHP Version 4.0 and, works with all the later versions." }, { "code": null, "e": 3369, "s": 3298, "text": "Following example demonstrates the usage of the strtotime() function −" }, { "code": null, "e": 3451, "s": 3369, "text": "<?php\n $str = strtotime(\"12 September 2009\");\n print(\"Timestamp: \".$str); \n?>" }, { "code": null, "e": 3488, "s": 3451, "text": "This will produce following result −" }, { "code": null, "e": 3511, "s": 3488, "text": "Timestamp: 1252713600\n" }, { "code": null, "e": 3589, "s": 3511, "text": "If you pass \"now\" as a parameter this function returns the current time stamp" }, { "code": null, "e": 3657, "s": 3589, "text": "<?php\n $str = strtotime(\"now\");\n print(\"Timestamp: \".$str); \n?>" }, { "code": null, "e": 3694, "s": 3657, "text": "This will produce following result −" }, { "code": null, "e": 3717, "s": 3694, "text": "Timestamp: 1589369948\n" }, { "code": null, "e": 3779, "s": 3717, "text": "Now letus invoke this method by passing various date values −" }, { "code": null, "e": 4232, "s": 3779, "text": "<?php\n print(\"Time stamp of 25 December 2019: \".strtotime(\"25 December 2019\").\"\\n\");\n print(\"Time stamp of +26 day: \".strtotime(\"+26 day\").\"\\n\");\n print(\"Time stamp of +3 week: \".strtotime(\"+3 week\").\"\\n\");\n print(\"Time stamp of +3 month 9 days 9 hours: \".strtotime(\"+3 month 9 days 9 hours\").\"\\n\");\n print(\"Time stamp of last Sunday: \".strtotime(\"last Sunday\").\"\\n\");\n print(\"Time stamp of next Friday: \".strtotime(\"next Friday\").\"\\n\");\n?>" }, { "code": null, "e": 4273, "s": 4232, "text": "This will produce the following output −" }, { "code": null, "e": 4511, "s": 4273, "text": "Time stamp of 25 December 2019: 1577232000\nTime stamp of +26 day: 1591617718\nTime stamp of +3 week: 1591185718\nTime stamp of +3 month 9 days 9 hours: 1598130118\nTime stamp of last Sunday: 1589068800\nTime stamp of next Friday: 1589500800\n" }, { "code": null, "e": 4611, "s": 4511, "text": "<?php\n $timestamp = strtotime( \"February 15, 2015\" ); \n print date( 'Y-m-d', $timestamp );\n?>" }, { "code": null, "e": 4652, "s": 4611, "text": "This will produce the following output −" }, { "code": null, "e": 4664, "s": 4652, "text": "2015-02-15\n" }, { "code": null, "e": 4697, "s": 4664, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4713, "s": 4697, "text": " Malhar Lathkar" }, { "code": null, "e": 4746, "s": 4713, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4757, "s": 4746, "text": " Syed Raza" }, { "code": null, "e": 4792, "s": 4757, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4809, "s": 4792, "text": " Frahaan Hussain" }, { "code": null, "e": 4842, "s": 4809, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4857, "s": 4842, "text": " Nivedita Jain" }, { "code": null, "e": 4892, "s": 4857, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4904, "s": 4892, "text": " Azaz Patel" }, { "code": null, "e": 4939, "s": 4904, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4967, "s": 4939, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4974, "s": 4967, "text": " Print" }, { "code": null, "e": 4985, "s": 4974, "text": " Add Notes" } ]
Interpretability in Deep Learning with W&B — CAM and GradCAM | by Ayush Thakur | Towards Data Science
Training a classification model is interesting, but have you ever wondered how your model is making its predictions? Is your model actually looking at the dog in the image before classifying it as a dog with 98% accuracy? Interesting, isn’t it. In today’s report, we will explore why deep learning models need to be interpretable, and some interesting methods to peek under the hood of a deep learning model. Deep learning interpretability is a very exciting area of research and much progress is being made in this direction already. So why should you care about interpretability? After all, the success of your business or your project is judged primarily by how good the accuracy of your model is. But in order to deploy our models in the real world, we need to consider other factors too. For instance, is racially biased? Or, what if it’s classifying humans with 97% accuracy, but while it classifies men with 99% accuracy, it only achieves 95% accuracy on women? Understanding how a model makes its predictions can also help us debug your network. [Check out this blog post on ‘Debugging Neural Networks with PyTorch and W&B Using Gradients and Visualizations’ for some other techniques that can help]. At this point, we are all familiar with the concept that deep learning models make predictions based on the learned representation expressed in terms of other simpler representations. That is, deep learning allows us to build complex concepts out of simpler concepts. Here’s an amazing Distill Pub post to help you understand this concept better. We also know that these representations are learned while we train the model with our input data and the label, in case of some supervised learning task like image classification. One of the criticisms of this approach is that the learned features in a neural network are not interpretable. Today we’ll look at 2techniques that address this criticism and shed light into neural networks’ “black-box” nature of learning. Class Activation Map(CAM) Gradient CAM It has been observed that convolution units of various layers of a convolutional neural network act as an object detector even though no such prior about the location of the object is provided while training the network for a classification task. Even though convolution has this remarkable property, it is lost when we use a fully connected layer for the classification task. To avoid the use of a fully connected network some architectures like Network in Network(NiN) and GoogLeNet are fully convolutional neural networks. Global Average Pooling(GAP) is a very commonly used layer in such architectures. It is mainly used as a regularizer to prevent overfitting while training. The authors of Learning Deep Features for Discriminative Localization found out that by tweaking such an architecture, they can extend the advantages of GAP and can retain its localization ability until the last layer. Let’s try to quickly understand the procedure of generating CAM using GAP. The class activation map simply indicates the discriminative region in the image which the CNN uses to classify that image in a particular category. For this technique, the network consists of ConvNet and just before the Softmax layer(for multi-class classification), global average pooling is performed on the convolutional feature maps. The output of this layer is used as features for a fully-connected layer that produces the desired classification output. Given this simple connectivity structure, we can identify the importance of the image regions by projecting back the weights of the output layer on to the convolutional feature maps. Let’s try to implement this. 😄 Suppose you have built your deep classifier with Conv blocks and a few fully connected layers. We will have to modify this architecture such that there aren’t any fully connected layers. We will use the GlobalAveragePooling2D layer between the output layer (softmax/sigmoid) and the last convolutional block. The CAMmodel provides a required modification to our cat and dog classifier. Here I am using pre-trained VGG16 model to simulate my already trained cat-dog classifier. def CAMmodel(): ## Simulating my pretrained dog and cat classifier. vgg = VGG16(include_top=False, weights='imagenet') vgg.trainable = False ## Flatten the layer so that it's not nested in the sequential model. vgg_flat = flatten_model(vgg) ## Insert GAP vgg_flat.append(keras.layers.GlobalAveragePooling2D()) vgg_flat.append(keras.layers.Dense(1, activation='sigmoid')) model = keras.models.Sequential(vgg_flat) return model A simple utility flatten_model returns the list of layers in my pre-trained model. This is done so that the layers are not nested when modified using Sequential model and the last convolutional layer can be accessed and used as an output. I appended GlobalAveragePooling2D and Dense in the returned array from flatten_model. Finally, the Sequential model is returned. def flatten_model(model_nested): ''' Utility to flatten pretrained model ''' layers_flat = [] for layer in model_nested.layers: try: layers_flat.extend(layer.layers) except AttributeError: layers_flat.append(layer) return layers_flat Next we call model.build() with the appropriate model input shape. keras.backend.clear_session()model = CAMmodel()model.build((None, None, None, 3)) # Notemodel.summary() Since a new layer was introduced, we have to retrain the model. But we don’t need to retrain the entire model. We can freeze the convolutional blocks by using vgg.trainable=False. Observations: There is a decline in the model performance in terms of both training and validation accuracy. The optimal train and validation accuracy that I achieved was 99.01% and 95.67% respectively. Thus for the implementation of CAM, we have to modify our architecture and thus a decline in model performance. In the __init__for the CAM class, we initialize cammodel. Notice there are two outputs from this cammodel: Output from the last convolutional layer (block5_conv3 here) The model prediction (softmax/sigmoid). class CAM: def __init__(self, model, layerName): self.model = model self.layerName = layerName ## Prepare cammodel last_conv_layer = self.model.get_layer(self.layerName).output self.cammodel = keras.models.Model(inputs=self.model.input, outputs=[last_conv_layer, self.model.output]) def compute_heatmap(self, image, classIdx): ## Get the output of last conv layer and model prediction [conv_outputs, predictions] = self.cammodel.predict(image) conv_outputs = conv_outputs[0, :, :, :] conv_outputs = np.rollaxis(conv_outputs, 2) ## Get class weights between class_weights = self.model.layers[-1].get_weights()[0] ## Create the class activation map. caml = np.zeros(shape = conv_outputs.shape[1:3], dtype=np.float32) for i, w in enumerate(class_weights[:]): caml += w * conv_outputs[i, :, :] caml /= np.max(caml) caml = cv2.resize(caml, (image.shape[1], image.shape[2])) ## Prepare heat map heatmap = cv2.applyColorMap(np.uint8(255*caml), cv2.COLORMAP_JET) heatmap[np.where(caml < 0.2)] = 0 return heatmap def overlay_heatmap(self, heatmap, image): img = heatmap*0.5 + image img = img*255 img = img.astype('uint8') return (heatmap, img) The compute_heatmap method is responsible for generating the heatmap which is the discriminative region used by CNN to identify the category (class of image). cammodel.predict() on the input image will give the feature map of the last convolutional layer of shape (1,7,7,512). We also extract the weights of the output layer of shape (512,1). Finally, the dot product of the extracted weights from the final layer and the feature map is calculated to produce the class activation map. Now we wrap everything in a callback. The CamLogger callback integrates wandb.log() method to log the generated activation maps onto the W&B run page. The heatmap returned from the CAM is finally overlayed on the original image by calling overlay_heatmap() method. We can draw lot of conclusions from the the plots as shown below. 👇 Note the examples chart contains validation images along with their prediction scores. If the prediction score is greater than 0.5, the network classifies the image as a dog, otherwise as a cat. While CAM charts have their corresponding class activation maps. Let's go through some observations: The model is classifying the images as dogs by looking at the facial region in the image. For some images it’s able to look at the entire body, except the paws. The model is classifying the images as cats by looking at the ears, paws and whiskers. For a misclassified image the model is not looking at where it should be looking. Thus by using CAM we are able to interpret the reason behind this misclassification, which is really cool. Why is that? Even though the ears, paws and whiskers are present in the image why did it look at something else. One reason I can think of is that since we haven’t fine tuned our pretrained VGG16 on our cat-dog dataset, the CNN as feature extractor is not entirely familiar with the patterns (distributions) appearing in our dataset. When multiple instances of the same class are present in the image, the model looks only at one of them. But that is okay, given that we are not concerned about object detection. Note that the confidence is low because of this. Other use cases: CAM can be used for a weakly supervised object localization task. The authors of the linked paper tested the ability of the CAM for a localization task on the ILSVRC 2014 benchmark dataset. The technique was able to achieve 37.1% top-5 error for object localization on this dataset, which is close to the 34.2% top-5 error achieved by a fully supervised CNN approach. Even though CAM was amazing it had some limitations: The model needs to be modified in order to use CAM. The modified model needs to be retrained, which is computationally expensive. Since fully connected Dense layers are removed. the model performance will surely suffer. This means the prediction score doesn’t give the actual picture of the model’s ability. The use case was bound by architectural constraints, i.e., architectures performing GAP over convolutional maps immediately before output layer. What makes a good visual explanation?: Certainly the technique should localize the class in the image. We saw this in CAM and it was worked remarkable good. Finer details should be captured, i.e., the activation map should be high resolution. Thus the authors of Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization, a really amazing paper, came up with modifications to CAM and previous approaches. Their approach uses the gradients of any target prediction flowing into the final convolutional layer to produce a coarse localization map highlighting the important regions in the image for predicting the class of the image. Thus Grad-CAM is a strict generalization over CAM. Beside overcoming the limitations of CAM it’s applicable to different deep learning tasks involving CNNs. It is applicable to: CNNs with fully-connected layers (e.g. VGG) without any modification to the network. CNNs used for structured outputs like image captioning. CNNs used in tasks with multi-modal inputs like visual Q&A or reinforcement learning, without architectural changes or re-training. Let’s implement this 😄 We will focus on the image classification task. Unlike CAM we don’t have to modify our model for this task and retrain it. I have used a VGG16 model pretrained on ImageNet as my base model and I'm simulating Transfer Learning with this. The layers of the baseline model are turned to non-trainable by using vgg.trainable = False. Note how I have used fully connected layers in the model. def catdogmodel(): inp = keras.layers.Input(shape=(224,224,3)) vgg = tf.keras.applications.VGG16(include_top=False, weights='imagenet', input_tensor=inp, input_shape=(224,224,3)) vgg.trainable = False x = vgg.get_layer('block5_pool').output x = tf.keras.layers.GlobalAveragePooling2D()(x) x = keras.layers.Dense(64, activation='relu')(x) output = keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.models.Model(inputs = inp, outputs=output) return model You will find the class GradCAM in the linked notebook. This is a modified implementation from Grad-CAM: Visualize class activation maps with Keras, TensorFlow, and Deep Learning, an amazing blog post, by Adrian Rosebrook of PyImageSearch.com. I would highly suggest checking out the step by step implementation of the GradCAM class in that blog post. I made two modifications to it: While doing transfer learning, that is, if your target (last) convolutional layer is non trainable, tape.gradient(loss, convOutputs) will return None. This is because tape.gradient() by default does not trace non-trainable variables/layers. Thus to use that layer for computing your gradients you need to allow GradientTape to watch it by calling tape.watch() on the target layer output (tensor). Hence the change, with tf.GradientTape() as tape: tape.watch(self.gradModel.get_layer(self.layerName).output) inputs = tf.cast(image, tf.float32) (convOutputs, predictions) = self.gradModel(inputs) The original implementation didn’t account for binary classification. The original authors also talked about softmax-ing the output. So in order to train a simple cat and dog classifier, I made a small modification. Hence the change, if len(predictions)==1: # Binary Classification loss = predictions[0] else: loss = predictions[:, classIdx] The GRADCAM class can be used after the model is trained or as a callback. Here's a small excerpt from his blog post. The third point motivated me to work on this project. I built a custom callback around this GRADCAM implementation and used wandb.log() to log the activation maps. Thus by using this callback you can use GradCAM while training. Given we’re working with a simple dataset I have only trained for few epochs and the model seems to work well. Here’s the GradCAM custom callback. class GRADCamLogger(tf.keras.callbacks.Callback): def __init__(self, validation_data, layer_name): super(GRADCamLogger, self).__init__() self.validation_data = validation_data self.layer_name = layer_name def on_epoch_end(self, logs, epoch): images = [] grad_cam = [] ## Initialize GRADCam Class cam = GradCAM(model, self.layer_name) for image in self.validation_data: image = np.expand_dims(image, 0) pred = model.predict(image) classIDx = np.argmax(pred[0]) ## Compute Heatmap heatmap = cam.compute_heatmap(image, classIDx) image = image.reshape(image.shape[1:]) image = image*255 image = image.astype(np.uint8) ## Overlay heatmap on original image heatmap = cv2.resize(heatmap, (image.shape[0],image.shape[1])) (heatmap, output) = cam.overlay_heatmap(heatmap, image, alpha=0.5) images.append(image) grad_cam.append(output) wandb.log({"images": [wandb.Image(image) for image in images]}) wandb.log({"gradcam": [wandb.Image(cam) for cam in grad_cam]}) GradCAM being a strict generalization over CAM, should be preferred over CAM. To understand the theoretical underpinnings of this technique I recommend reading Demystifying Convolutional Neural Networks using GradCam by Divyanshu Mishra or simply reading the linked paper. A couple interesting conclusions we can draw include: The model looks at the face of the dogs to classify them correctly, while I am unsure about the cat. The model is able to localize multiple instances of the class in an image, i.e. the prediction score is accounting for multiple dogs and cats in the image. Class Activation Maps and Grad-CAMs are a few approaches that introduce some explainability/interpretability into deep learning models, and are quite widely used. What’s most fascinating about these techniques is the ability to perform the object localization task, even without training the model with a location prior. GradCAM, when used for image captioning, can help us understand what region in the image is used to generate a certain word. When used for a Visual Q&A task, it can help us understand why the model came to a particular answer. Even though Grad-CAM is class-discriminative and localizes the relevant image regions, it lacks the ability to highlight fine-grained details the way pixel-space gradient visualization methods like Guided backpropagation, and Deconvolution do. Thus the authors combined Grad-CAM with Guided backpropagation. Thanks for reading this report until the end. I hope you find the callbacks introduced here helpful for your deep learning wizardry. Please feel free to reach out to me on Twitter(@ayushthakur0) for any feedback on this report. Thank you.
[ { "code": null, "e": 707, "s": 172, "text": "Training a classification model is interesting, but have you ever wondered how your model is making its predictions? Is your model actually looking at the dog in the image before classifying it as a dog with 98% accuracy? Interesting, isn’t it. In today’s report, we will explore why deep learning models need to be interpretable, and some interesting methods to peek under the hood of a deep learning model. Deep learning interpretability is a very exciting area of research and much progress is being made in this direction already." }, { "code": null, "e": 1141, "s": 707, "text": "So why should you care about interpretability? After all, the success of your business or your project is judged primarily by how good the accuracy of your model is. But in order to deploy our models in the real world, we need to consider other factors too. For instance, is racially biased? Or, what if it’s classifying humans with 97% accuracy, but while it classifies men with 99% accuracy, it only achieves 95% accuracy on women?" }, { "code": null, "e": 1381, "s": 1141, "text": "Understanding how a model makes its predictions can also help us debug your network. [Check out this blog post on ‘Debugging Neural Networks with PyTorch and W&B Using Gradients and Visualizations’ for some other techniques that can help]." }, { "code": null, "e": 2019, "s": 1381, "text": "At this point, we are all familiar with the concept that deep learning models make predictions based on the learned representation expressed in terms of other simpler representations. That is, deep learning allows us to build complex concepts out of simpler concepts. Here’s an amazing Distill Pub post to help you understand this concept better. We also know that these representations are learned while we train the model with our input data and the label, in case of some supervised learning task like image classification. One of the criticisms of this approach is that the learned features in a neural network are not interpretable." }, { "code": null, "e": 2148, "s": 2019, "text": "Today we’ll look at 2techniques that address this criticism and shed light into neural networks’ “black-box” nature of learning." }, { "code": null, "e": 2174, "s": 2148, "text": "Class Activation Map(CAM)" }, { "code": null, "e": 2187, "s": 2174, "text": "Gradient CAM" }, { "code": null, "e": 2713, "s": 2187, "text": "It has been observed that convolution units of various layers of a convolutional neural network act as an object detector even though no such prior about the location of the object is provided while training the network for a classification task. Even though convolution has this remarkable property, it is lost when we use a fully connected layer for the classification task. To avoid the use of a fully connected network some architectures like Network in Network(NiN) and GoogLeNet are fully convolutional neural networks." }, { "code": null, "e": 3162, "s": 2713, "text": "Global Average Pooling(GAP) is a very commonly used layer in such architectures. It is mainly used as a regularizer to prevent overfitting while training. The authors of Learning Deep Features for Discriminative Localization found out that by tweaking such an architecture, they can extend the advantages of GAP and can retain its localization ability until the last layer. Let’s try to quickly understand the procedure of generating CAM using GAP." }, { "code": null, "e": 3806, "s": 3162, "text": "The class activation map simply indicates the discriminative region in the image which the CNN uses to classify that image in a particular category. For this technique, the network consists of ConvNet and just before the Softmax layer(for multi-class classification), global average pooling is performed on the convolutional feature maps. The output of this layer is used as features for a fully-connected layer that produces the desired classification output. Given this simple connectivity structure, we can identify the importance of the image regions by projecting back the weights of the output layer on to the convolutional feature maps." }, { "code": null, "e": 3837, "s": 3806, "text": "Let’s try to implement this. 😄" }, { "code": null, "e": 4146, "s": 3837, "text": "Suppose you have built your deep classifier with Conv blocks and a few fully connected layers. We will have to modify this architecture such that there aren’t any fully connected layers. We will use the GlobalAveragePooling2D layer between the output layer (softmax/sigmoid) and the last convolutional block." }, { "code": null, "e": 4314, "s": 4146, "text": "The CAMmodel provides a required modification to our cat and dog classifier. Here I am using pre-trained VGG16 model to simulate my already trained cat-dog classifier." }, { "code": null, "e": 4784, "s": 4314, "text": "def CAMmodel(): ## Simulating my pretrained dog and cat classifier. vgg = VGG16(include_top=False, weights='imagenet') vgg.trainable = False ## Flatten the layer so that it's not nested in the sequential model. vgg_flat = flatten_model(vgg) ## Insert GAP vgg_flat.append(keras.layers.GlobalAveragePooling2D()) vgg_flat.append(keras.layers.Dense(1, activation='sigmoid')) model = keras.models.Sequential(vgg_flat) return model" }, { "code": null, "e": 5152, "s": 4784, "text": "A simple utility flatten_model returns the list of layers in my pre-trained model. This is done so that the layers are not nested when modified using Sequential model and the last convolutional layer can be accessed and used as an output. I appended GlobalAveragePooling2D and Dense in the returned array from flatten_model. Finally, the Sequential model is returned." }, { "code": null, "e": 5440, "s": 5152, "text": "def flatten_model(model_nested): ''' Utility to flatten pretrained model ''' layers_flat = [] for layer in model_nested.layers: try: layers_flat.extend(layer.layers) except AttributeError: layers_flat.append(layer) return layers_flat" }, { "code": null, "e": 5507, "s": 5440, "text": "Next we call model.build() with the appropriate model input shape." }, { "code": null, "e": 5611, "s": 5507, "text": "keras.backend.clear_session()model = CAMmodel()model.build((None, None, None, 3)) # Notemodel.summary()" }, { "code": null, "e": 5791, "s": 5611, "text": "Since a new layer was introduced, we have to retrain the model. But we don’t need to retrain the entire model. We can freeze the convolutional blocks by using vgg.trainable=False." }, { "code": null, "e": 5805, "s": 5791, "text": "Observations:" }, { "code": null, "e": 5994, "s": 5805, "text": "There is a decline in the model performance in terms of both training and validation accuracy. The optimal train and validation accuracy that I achieved was 99.01% and 95.67% respectively." }, { "code": null, "e": 6106, "s": 5994, "text": "Thus for the implementation of CAM, we have to modify our architecture and thus a decline in model performance." }, { "code": null, "e": 6213, "s": 6106, "text": "In the __init__for the CAM class, we initialize cammodel. Notice there are two outputs from this cammodel:" }, { "code": null, "e": 6274, "s": 6213, "text": "Output from the last convolutional layer (block5_conv3 here)" }, { "code": null, "e": 6314, "s": 6274, "text": "The model prediction (softmax/sigmoid)." }, { "code": null, "e": 7572, "s": 6314, "text": "class CAM: def __init__(self, model, layerName): self.model = model self.layerName = layerName ## Prepare cammodel last_conv_layer = self.model.get_layer(self.layerName).output self.cammodel = keras.models.Model(inputs=self.model.input, outputs=[last_conv_layer, self.model.output]) def compute_heatmap(self, image, classIdx): ## Get the output of last conv layer and model prediction [conv_outputs, predictions] = self.cammodel.predict(image) conv_outputs = conv_outputs[0, :, :, :] conv_outputs = np.rollaxis(conv_outputs, 2) ## Get class weights between class_weights = self.model.layers[-1].get_weights()[0] ## Create the class activation map. caml = np.zeros(shape = conv_outputs.shape[1:3], dtype=np.float32) for i, w in enumerate(class_weights[:]): caml += w * conv_outputs[i, :, :] caml /= np.max(caml) caml = cv2.resize(caml, (image.shape[1], image.shape[2])) ## Prepare heat map heatmap = cv2.applyColorMap(np.uint8(255*caml), cv2.COLORMAP_JET) heatmap[np.where(caml < 0.2)] = 0 return heatmap def overlay_heatmap(self, heatmap, image): img = heatmap*0.5 + image img = img*255 img = img.astype('uint8') return (heatmap, img)" }, { "code": null, "e": 7731, "s": 7572, "text": "The compute_heatmap method is responsible for generating the heatmap which is the discriminative region used by CNN to identify the category (class of image)." }, { "code": null, "e": 7849, "s": 7731, "text": "cammodel.predict() on the input image will give the feature map of the last convolutional layer of shape (1,7,7,512)." }, { "code": null, "e": 7915, "s": 7849, "text": "We also extract the weights of the output layer of shape (512,1)." }, { "code": null, "e": 8057, "s": 7915, "text": "Finally, the dot product of the extracted weights from the final layer and the feature map is calculated to produce the class activation map." }, { "code": null, "e": 8322, "s": 8057, "text": "Now we wrap everything in a callback. The CamLogger callback integrates wandb.log() method to log the generated activation maps onto the W&B run page. The heatmap returned from the CAM is finally overlayed on the original image by calling overlay_heatmap() method." }, { "code": null, "e": 8686, "s": 8322, "text": "We can draw lot of conclusions from the the plots as shown below. 👇 Note the examples chart contains validation images along with their prediction scores. If the prediction score is greater than 0.5, the network classifies the image as a dog, otherwise as a cat. While CAM charts have their corresponding class activation maps. Let's go through some observations:" }, { "code": null, "e": 8847, "s": 8686, "text": "The model is classifying the images as dogs by looking at the facial region in the image. For some images it’s able to look at the entire body, except the paws." }, { "code": null, "e": 8934, "s": 8847, "text": "The model is classifying the images as cats by looking at the ears, paws and whiskers." }, { "code": null, "e": 9123, "s": 8934, "text": "For a misclassified image the model is not looking at where it should be looking. Thus by using CAM we are able to interpret the reason behind this misclassification, which is really cool." }, { "code": null, "e": 9457, "s": 9123, "text": "Why is that? Even though the ears, paws and whiskers are present in the image why did it look at something else. One reason I can think of is that since we haven’t fine tuned our pretrained VGG16 on our cat-dog dataset, the CNN as feature extractor is not entirely familiar with the patterns (distributions) appearing in our dataset." }, { "code": null, "e": 9685, "s": 9457, "text": "When multiple instances of the same class are present in the image, the model looks only at one of them. But that is okay, given that we are not concerned about object detection. Note that the confidence is low because of this." }, { "code": null, "e": 9702, "s": 9685, "text": "Other use cases:" }, { "code": null, "e": 10070, "s": 9702, "text": "CAM can be used for a weakly supervised object localization task. The authors of the linked paper tested the ability of the CAM for a localization task on the ILSVRC 2014 benchmark dataset. The technique was able to achieve 37.1% top-5 error for object localization on this dataset, which is close to the 34.2% top-5 error achieved by a fully supervised CNN approach." }, { "code": null, "e": 10123, "s": 10070, "text": "Even though CAM was amazing it had some limitations:" }, { "code": null, "e": 10175, "s": 10123, "text": "The model needs to be modified in order to use CAM." }, { "code": null, "e": 10253, "s": 10175, "text": "The modified model needs to be retrained, which is computationally expensive." }, { "code": null, "e": 10431, "s": 10253, "text": "Since fully connected Dense layers are removed. the model performance will surely suffer. This means the prediction score doesn’t give the actual picture of the model’s ability." }, { "code": null, "e": 10576, "s": 10431, "text": "The use case was bound by architectural constraints, i.e., architectures performing GAP over convolutional maps immediately before output layer." }, { "code": null, "e": 10615, "s": 10576, "text": "What makes a good visual explanation?:" }, { "code": null, "e": 10733, "s": 10615, "text": "Certainly the technique should localize the class in the image. We saw this in CAM and it was worked remarkable good." }, { "code": null, "e": 10819, "s": 10733, "text": "Finer details should be captured, i.e., the activation map should be high resolution." }, { "code": null, "e": 11230, "s": 10819, "text": "Thus the authors of Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization, a really amazing paper, came up with modifications to CAM and previous approaches. Their approach uses the gradients of any target prediction flowing into the final convolutional layer to produce a coarse localization map highlighting the important regions in the image for predicting the class of the image." }, { "code": null, "e": 11408, "s": 11230, "text": "Thus Grad-CAM is a strict generalization over CAM. Beside overcoming the limitations of CAM it’s applicable to different deep learning tasks involving CNNs. It is applicable to:" }, { "code": null, "e": 11493, "s": 11408, "text": "CNNs with fully-connected layers (e.g. VGG) without any modification to the network." }, { "code": null, "e": 11549, "s": 11493, "text": "CNNs used for structured outputs like image captioning." }, { "code": null, "e": 11681, "s": 11549, "text": "CNNs used in tasks with multi-modal inputs like visual Q&A or reinforcement learning, without architectural changes or re-training." }, { "code": null, "e": 11704, "s": 11681, "text": "Let’s implement this 😄" }, { "code": null, "e": 11827, "s": 11704, "text": "We will focus on the image classification task. Unlike CAM we don’t have to modify our model for this task and retrain it." }, { "code": null, "e": 11941, "s": 11827, "text": "I have used a VGG16 model pretrained on ImageNet as my base model and I'm simulating Transfer Learning with this." }, { "code": null, "e": 12092, "s": 11941, "text": "The layers of the baseline model are turned to non-trainable by using vgg.trainable = False. Note how I have used fully connected layers in the model." }, { "code": null, "e": 12615, "s": 12092, "text": "def catdogmodel(): inp = keras.layers.Input(shape=(224,224,3)) vgg = tf.keras.applications.VGG16(include_top=False, weights='imagenet', input_tensor=inp, input_shape=(224,224,3)) vgg.trainable = False x = vgg.get_layer('block5_pool').output x = tf.keras.layers.GlobalAveragePooling2D()(x) x = keras.layers.Dense(64, activation='relu')(x) output = keras.layers.Dense(1, activation='sigmoid')(x) model = tf.keras.models.Model(inputs = inp, outputs=output) return model" }, { "code": null, "e": 12967, "s": 12615, "text": "You will find the class GradCAM in the linked notebook. This is a modified implementation from Grad-CAM: Visualize class activation maps with Keras, TensorFlow, and Deep Learning, an amazing blog post, by Adrian Rosebrook of PyImageSearch.com. I would highly suggest checking out the step by step implementation of the GradCAM class in that blog post." }, { "code": null, "e": 12999, "s": 12967, "text": "I made two modifications to it:" }, { "code": null, "e": 13414, "s": 12999, "text": "While doing transfer learning, that is, if your target (last) convolutional layer is non trainable, tape.gradient(loss, convOutputs) will return None. This is because tape.gradient() by default does not trace non-trainable variables/layers. Thus to use that layer for computing your gradients you need to allow GradientTape to watch it by calling tape.watch() on the target layer output (tensor). Hence the change," }, { "code": null, "e": 13609, "s": 13414, "text": "with tf.GradientTape() as tape: tape.watch(self.gradModel.get_layer(self.layerName).output) inputs = tf.cast(image, tf.float32) (convOutputs, predictions) = self.gradModel(inputs)" }, { "code": null, "e": 13843, "s": 13609, "text": "The original implementation didn’t account for binary classification. The original authors also talked about softmax-ing the output. So in order to train a simple cat and dog classifier, I made a small modification. Hence the change," }, { "code": null, "e": 13969, "s": 13843, "text": "if len(predictions)==1: # Binary Classification loss = predictions[0] else: loss = predictions[:, classIdx]" }, { "code": null, "e": 14087, "s": 13969, "text": "The GRADCAM class can be used after the model is trained or as a callback. Here's a small excerpt from his blog post." }, { "code": null, "e": 14315, "s": 14087, "text": "The third point motivated me to work on this project. I built a custom callback around this GRADCAM implementation and used wandb.log() to log the activation maps. Thus by using this callback you can use GradCAM while training." }, { "code": null, "e": 14426, "s": 14315, "text": "Given we’re working with a simple dataset I have only trained for few epochs and the model seems to work well." }, { "code": null, "e": 14462, "s": 14426, "text": "Here’s the GradCAM custom callback." }, { "code": null, "e": 15626, "s": 14462, "text": "class GRADCamLogger(tf.keras.callbacks.Callback): def __init__(self, validation_data, layer_name): super(GRADCamLogger, self).__init__() self.validation_data = validation_data self.layer_name = layer_name def on_epoch_end(self, logs, epoch): images = [] grad_cam = [] ## Initialize GRADCam Class cam = GradCAM(model, self.layer_name) for image in self.validation_data: image = np.expand_dims(image, 0) pred = model.predict(image) classIDx = np.argmax(pred[0]) ## Compute Heatmap heatmap = cam.compute_heatmap(image, classIDx) image = image.reshape(image.shape[1:]) image = image*255 image = image.astype(np.uint8) ## Overlay heatmap on original image heatmap = cv2.resize(heatmap, (image.shape[0],image.shape[1])) (heatmap, output) = cam.overlay_heatmap(heatmap, image, alpha=0.5) images.append(image) grad_cam.append(output) wandb.log({\"images\": [wandb.Image(image) for image in images]}) wandb.log({\"gradcam\": [wandb.Image(cam) for cam in grad_cam]})" }, { "code": null, "e": 15953, "s": 15626, "text": "GradCAM being a strict generalization over CAM, should be preferred over CAM. To understand the theoretical underpinnings of this technique I recommend reading Demystifying Convolutional Neural Networks using GradCam by Divyanshu Mishra or simply reading the linked paper. A couple interesting conclusions we can draw include:" }, { "code": null, "e": 16054, "s": 15953, "text": "The model looks at the face of the dogs to classify them correctly, while I am unsure about the cat." }, { "code": null, "e": 16210, "s": 16054, "text": "The model is able to localize multiple instances of the class in an image, i.e. the prediction score is accounting for multiple dogs and cats in the image." }, { "code": null, "e": 17066, "s": 16210, "text": "Class Activation Maps and Grad-CAMs are a few approaches that introduce some explainability/interpretability into deep learning models, and are quite widely used. What’s most fascinating about these techniques is the ability to perform the object localization task, even without training the model with a location prior. GradCAM, when used for image captioning, can help us understand what region in the image is used to generate a certain word. When used for a Visual Q&A task, it can help us understand why the model came to a particular answer. Even though Grad-CAM is class-discriminative and localizes the relevant image regions, it lacks the ability to highlight fine-grained details the way pixel-space gradient visualization methods like Guided backpropagation, and Deconvolution do. Thus the authors combined Grad-CAM with Guided backpropagation." } ]
How to search a pickle file in Python? - GeeksforGeeks
02 Feb, 2021 Prerequisites: pickle file Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script Pickle serializes a single object at a time, and reads back a single object — the pickled data is recorded in sequence on the file. If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you’ve written). After de-serializing the first object, the file-pointer is at the beginning of the next object — if you simply call pickle.load again, it will read that next object — do that until the end of the file. dump()– used to write a pickled representation of obj to the open file object file. Syntax: pickle.dump(obj, file, protocol = None, *, fix_imports = True) load()– used to read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified. Syntax: pickle.load(file, *, fix_imports = True, encoding = “ASCII”, errors = “strict”) seek(0)- Pickle records can be concatenated into a file, so yes, you can just pickle.load(f) multiple times, but the files themselves are not indexed in a way that would let you seek into a given record. What your f.seek(0) is doing is seeking into the third byte in the file, which is in the middle of a pickle record, and thus is unpicklable. If you need random access, you might want to look into the built-in shelve module which builds a dictionary-like interface on top of pickle using a database file module. truncate()- changes the file size Given below is the implantation for adding to a pickle file. Program: Python3 import pickle print("GFG") def write_file(): f = open("travel.txt", "wb") op = 'y' while op == 'y': Travelcode = int(input("enter the travel id")) Place = input("Enter the Place") Travellers = int(input("Enter the number of travellers")) buses = int(input("Enter the number of buses")) pickle.dump([Travelcode, Place, Travellers, buses], f) op = input("Dp you want to continue> (y or n)") f.close() print("entering the details of passengers in the pickle file")write_file() After the pickle file is created and loaded with data successfully, searching can be performed. Import module Open pickle file Take some element to base search upon Display result if found Program: Python3 import pickle print("GFG") def search_file(): f = open("travel.txt", 'rb') t_code = int(input("Enter the travel code to traveller : ")) while True: try: L = pickle.load(f) if L[0] == t_code: print("Place", L[1], "\t\t Travellers :", L[2], "\t\t Buses :", L[3]) break except EOFError: print("Completed reading details") f.close() print("entering the details of passengers in the pickle file")write_file() print("Search the file using the passenger Code")search_file() Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Feb, 2021" }, { "code": null, "e": 24320, "s": 24292, "text": "Prerequisites: pickle file " }, { "code": null, "e": 24783, "s": 24320, "text": "Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script" }, { "code": null, "e": 24915, "s": 24783, "text": "Pickle serializes a single object at a time, and reads back a single object — the pickled data is recorded in sequence on the file." }, { "code": null, "e": 25046, "s": 24915, "text": "If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you’ve written)." }, { "code": null, "e": 25248, "s": 25046, "text": "After de-serializing the first object, the file-pointer is at the beginning of the next object — if you simply call pickle.load again, it will read that next object — do that until the end of the file." }, { "code": null, "e": 25332, "s": 25248, "text": "dump()– used to write a pickled representation of obj to the open file object file." }, { "code": null, "e": 25340, "s": 25332, "text": "Syntax:" }, { "code": null, "e": 25403, "s": 25340, "text": "pickle.dump(obj, file, protocol = None, *, fix_imports = True)" }, { "code": null, "e": 25544, "s": 25403, "text": "load()– used to read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified." }, { "code": null, "e": 25552, "s": 25544, "text": "Syntax:" }, { "code": null, "e": 25632, "s": 25552, "text": "pickle.load(file, *, fix_imports = True, encoding = “ASCII”, errors = “strict”)" }, { "code": null, "e": 26147, "s": 25632, "text": "seek(0)- Pickle records can be concatenated into a file, so yes, you can just pickle.load(f) multiple times, but the files themselves are not indexed in a way that would let you seek into a given record. What your f.seek(0) is doing is seeking into the third byte in the file, which is in the middle of a pickle record, and thus is unpicklable. If you need random access, you might want to look into the built-in shelve module which builds a dictionary-like interface on top of pickle using a database file module." }, { "code": null, "e": 26181, "s": 26147, "text": "truncate()- changes the file size" }, { "code": null, "e": 26242, "s": 26181, "text": "Given below is the implantation for adding to a pickle file." }, { "code": null, "e": 26251, "s": 26242, "text": "Program:" }, { "code": null, "e": 26259, "s": 26251, "text": "Python3" }, { "code": "import pickle print(\"GFG\") def write_file(): f = open(\"travel.txt\", \"wb\") op = 'y' while op == 'y': Travelcode = int(input(\"enter the travel id\")) Place = input(\"Enter the Place\") Travellers = int(input(\"Enter the number of travellers\")) buses = int(input(\"Enter the number of buses\")) pickle.dump([Travelcode, Place, Travellers, buses], f) op = input(\"Dp you want to continue> (y or n)\") f.close() print(\"entering the details of passengers in the pickle file\")write_file()", "e": 26804, "s": 26259, "text": null }, { "code": null, "e": 26900, "s": 26804, "text": "After the pickle file is created and loaded with data successfully, searching can be performed." }, { "code": null, "e": 26914, "s": 26900, "text": "Import module" }, { "code": null, "e": 26931, "s": 26914, "text": "Open pickle file" }, { "code": null, "e": 26969, "s": 26931, "text": "Take some element to base search upon" }, { "code": null, "e": 26993, "s": 26969, "text": "Display result if found" }, { "code": null, "e": 27002, "s": 26993, "text": "Program:" }, { "code": null, "e": 27010, "s": 27002, "text": "Python3" }, { "code": "import pickle print(\"GFG\") def search_file(): f = open(\"travel.txt\", 'rb') t_code = int(input(\"Enter the travel code to traveller : \")) while True: try: L = pickle.load(f) if L[0] == t_code: print(\"Place\", L[1], \"\\t\\t Travellers :\", L[2], \"\\t\\t Buses :\", L[3]) break except EOFError: print(\"Completed reading details\") f.close() print(\"entering the details of passengers in the pickle file\")write_file() print(\"Search the file using the passenger Code\")search_file()", "e": 27675, "s": 27010, "text": null }, { "code": null, "e": 27683, "s": 27675, "text": "Output:" }, { "code": null, "e": 27698, "s": 27683, "text": "python-utility" }, { "code": null, "e": 27705, "s": 27698, "text": "Python" }, { "code": null, "e": 27803, "s": 27705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27835, "s": 27803, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27891, "s": 27835, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27933, "s": 27891, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27975, "s": 27933, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28030, "s": 27975, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28052, "s": 28030, "text": "Defaultdict in Python" }, { "code": null, "e": 28091, "s": 28052, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28122, "s": 28091, "text": "Python | os.path.join() method" }, { "code": null, "e": 28151, "s": 28122, "text": "Create a directory in Python" } ]
Node.js http2.connect() Method - GeeksforGeeks
18 Nov, 2020 The http2.connect() is an inbuilt application programming interface of class http2 within the http2 module which is used to return a ClientHttp2Session instance. Syntax: const http2.connect(authority[, options][, listener]) Parameters: This method takes the following argument as a parameter: authority: It is the URL representing a remote HTTP/2 server to connect to. options: It can be maxDeflateDynamicTableSize, maxSettings, maxSessionMemory, etc option can be used according to need. listener: It is the one time listener of the ‘connect’ event. Return Value: This method returns the object of the ClientHttp2Session instance. How to generate a Private key and Public certificate? 1. Filename: Private key Open notepad and copy-paste the following key and save the file as private-key.pem -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5 HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu 0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5 JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC -----END RSA PRIVATE KEY----- 2. Filename: Public certificate Open notepad and copy-paste the following key and save the file as public-cert.pem -----BEGIN CERTIFICATE----- MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG 9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC hWF6W2H9+MAlU7yvtmCQQuZmfQ== -----END CERTIFICATE----- Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// http2.connect() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); stream.end('world'); // Stopping the server // by using the close() method server.close(() => { console.log("server closed"); })}); server.listen(8000); // Creating and initializing client// by using http2.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request({ ':method': 'GET', ':path': '/' }); req.on('response', (responseHeaders) => { console.log("status : " + responseHeaders[":status"]);}); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\n)/gm,""));}); req.on('end', () => { client.close(() => { console.log("client closed"); })}); Run the index.js file using the following command: node index.js Output: status : 200 Received: hello Received: world client closed server closed Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// http2.connect() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.end('world'); // Stopping the server // by using the close() method server.close(() => { console.log("server closed"); })}); server.listen(8000); // Creating and initializing client// by using http2.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request({ ':method': 'GET', ':path': '/' }); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\n)/gm,""));}); req.on('end', () => { client.close(() => { console.log("client closed"); })}); Run the index.js file using the following command: node index.js Output: Received: world client closed server closed Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http2.html#http2_http2_connect_authority_options_listener Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Express.js req.params Property JWT Authentication with Node.js Difference between npm i and npm ci in Node.js Mongoose Populate() Method Roadmap to Become a Web Developer in 2022 How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript
[ { "code": null, "e": 25002, "s": 24974, "text": "\n18 Nov, 2020" }, { "code": null, "e": 25164, "s": 25002, "text": "The http2.connect() is an inbuilt application programming interface of class http2 within the http2 module which is used to return a ClientHttp2Session instance." }, { "code": null, "e": 25172, "s": 25164, "text": "Syntax:" }, { "code": null, "e": 25227, "s": 25172, "text": "const http2.connect(authority[, options][, listener])\n" }, { "code": null, "e": 25296, "s": 25227, "text": "Parameters: This method takes the following argument as a parameter:" }, { "code": null, "e": 25372, "s": 25296, "text": "authority: It is the URL representing a remote HTTP/2 server to connect to." }, { "code": null, "e": 25492, "s": 25372, "text": "options: It can be maxDeflateDynamicTableSize, maxSettings, maxSessionMemory, etc option can be used according to need." }, { "code": null, "e": 25554, "s": 25492, "text": "listener: It is the one time listener of the ‘connect’ event." }, { "code": null, "e": 25635, "s": 25554, "text": "Return Value: This method returns the object of the ClientHttp2Session instance." }, { "code": null, "e": 25689, "s": 25635, "text": "How to generate a Private key and Public certificate?" }, { "code": null, "e": 25797, "s": 25689, "text": "1. Filename: Private key Open notepad and copy-paste the following key and save the file as private-key.pem" }, { "code": null, "e": 26685, "s": 25797, "text": "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg\nJKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5\nHcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB\nAoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu\no0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT\nVwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu\n0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ\nfBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ\nsZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC\nTlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy\nGBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5\nJFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m\nnUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC\n-----END RSA PRIVATE KEY-----\n" }, { "code": null, "e": 26800, "s": 26685, "text": "2. Filename: Public certificate Open notepad and copy-paste the following key and save the file as public-cert.pem" }, { "code": null, "e": 27728, "s": 26800, "text": "-----BEGIN CERTIFICATE-----\nMIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC\nSU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV\nBAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG\n9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw\nOTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw\nDgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM\nUm9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB\nnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm\nDhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi\nQK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC\nkwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX\nbXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG\nBfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC\nhWF6W2H9+MAlU7yvtmCQQuZmfQ==\n-----END CERTIFICATE-----" }, { "code": null, "e": 27758, "s": 27728, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 27769, "s": 27758, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// http2.connect() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); stream.end('world'); // Stopping the server // by using the close() method server.close(() => { console.log(\"server closed\"); })}); server.listen(8000); // Creating and initializing client// by using http2.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request({ ':method': 'GET', ':path': '/' }); req.on('response', (responseHeaders) => { console.log(\"status : \" + responseHeaders[\":status\"]);}); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\\n)/gm,\"\"));}); req.on('end', () => { client.close(() => { console.log(\"client closed\"); })});", "e": 28970, "s": 27769, "text": null }, { "code": null, "e": 29021, "s": 28970, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 29035, "s": 29021, "text": "node index.js" }, { "code": null, "e": 29043, "s": 29035, "text": "Output:" }, { "code": null, "e": 29117, "s": 29043, "text": "status : 200\nReceived: hello\nReceived: world\nclient closed\nserver closed\n" }, { "code": null, "e": 29147, "s": 29117, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 29158, "s": 29147, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// http2.connect() method const http2 = require('http2');const fs = require('fs'); // Private key and public certificate for accessconst options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem'),}; // Creating and initializing server// by using http2.createServer() methodconst server = http2.createServer(options); server.on('stream', (stream, requestHeaders) => { stream.end('world'); // Stopping the server // by using the close() method server.close(() => { console.log(\"server closed\"); })}); server.listen(8000); // Creating and initializing client// by using http2.connect() methodconst client = http2.connect( 'http://localhost:8000'); const req = client.request({ ':method': 'GET', ':path': '/' }); req.on('data', (data) => { console.log('Received: %s ', data.toString().replace(/(\\n)/gm,\"\"));}); req.on('end', () => { client.close(() => { console.log(\"client closed\"); })});", "e": 30151, "s": 29158, "text": null }, { "code": null, "e": 30202, "s": 30151, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 30216, "s": 30202, "text": "node index.js" }, { "code": null, "e": 30224, "s": 30216, "text": "Output:" }, { "code": null, "e": 30269, "s": 30224, "text": "Received: world\nclient closed\nserver closed\n" }, { "code": null, "e": 30384, "s": 30269, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http2.html#http2_http2_connect_authority_options_listener" }, { "code": null, "e": 30400, "s": 30384, "text": "Node.js-Methods" }, { "code": null, "e": 30408, "s": 30400, "text": "Node.js" }, { "code": null, "e": 30425, "s": 30408, "text": "Web Technologies" }, { "code": null, "e": 30523, "s": 30425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30532, "s": 30523, "text": "Comments" }, { "code": null, "e": 30545, "s": 30532, "text": "Old Comments" }, { "code": null, "e": 30582, "s": 30545, "text": "Express.js express.Router() Function" }, { "code": null, "e": 30613, "s": 30582, "text": "Express.js req.params Property" }, { "code": null, "e": 30645, "s": 30613, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 30692, "s": 30645, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 30719, "s": 30692, "text": "Mongoose Populate() Method" }, { "code": null, "e": 30761, "s": 30719, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30811, "s": 30761, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30873, "s": 30811, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30916, "s": 30873, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML - <style> tag
The HTML <style> tag is used for declaring style sheets within the head of your HTML document. NONE <head> <style type="text/css"> h1 { color:#F1F1F1 } </style> </head> For more detail on <style> tag please check HTML Styles chapter. Specifies the direction of the text Document wide identifier Sets the language code. Sets the language code. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2469, "s": 2374, "text": "The HTML <style> tag is used for declaring style sheets within the head of your HTML document." }, { "code": null, "e": 2474, "s": 2469, "text": "NONE" }, { "code": null, "e": 2557, "s": 2474, "text": "<head>\n\n <style type=\"text/css\">\n h1 { color:#F1F1F1 }\n </style>\n\n</head>" }, { "code": null, "e": 2622, "s": 2557, "text": "For more detail on <style> tag please check HTML Styles chapter." }, { "code": null, "e": 2658, "s": 2622, "text": "Specifies the direction of the text" }, { "code": null, "e": 2683, "s": 2658, "text": "Document wide identifier" }, { "code": null, "e": 2707, "s": 2683, "text": "Sets the language code." }, { "code": null, "e": 2731, "s": 2707, "text": "Sets the language code." }, { "code": null, "e": 2764, "s": 2731, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 2778, "s": 2764, "text": " Anadi Sharma" }, { "code": null, "e": 2813, "s": 2778, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2827, "s": 2813, "text": " Anadi Sharma" }, { "code": null, "e": 2862, "s": 2827, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2879, "s": 2862, "text": " Frahaan Hussain" }, { "code": null, "e": 2914, "s": 2879, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2945, "s": 2914, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 2978, "s": 2945, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3009, "s": 2978, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3044, "s": 3009, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3075, "s": 3044, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3082, "s": 3075, "text": " Print" }, { "code": null, "e": 3093, "s": 3082, "text": " Add Notes" } ]
Angular10 TitleCasePipe - GeeksforGeeks
30 Apr, 2021 In this article, we are going to see what is TitleCasePipe in Angular 10 and how to use it. TitleCasePipe is used to Transforms all the text to titlecase. Syntax: {{ value | TitleCasePipe }} NgModule: Module used by TitleCasePipe is: CommonModule Approach: Create the angular app to be used There is no need for any import for the TitleCasePipe to be used In app.component.ts define the variables that takes the TitleCasePipe value. In app.component.html use the above syntax with ‘|’ symbol to make TitleCasePipe element. Serve the angular app using ng serve to see the output Input value: value: it takes a string value. Example 1: app.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Key Value object value : string = 'geeksforgeeks'; } app.component.html <b> <div> titlecase value is : {{value | titlecase}} </div></b> Output: Example 2: app.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Key Value object value : string = 'geeksforgeeks'; } app.component.html <b> <div> CamelCase value is : {{value}} </div> <div> TitleCase value is : {{value |titlecase}} </div></b> Output: Reference: https://angular.io/api/common/TitleCasePipe Angular10 AngularJS-Basics AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component 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": 25109, "s": 25081, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25201, "s": 25109, "text": "In this article, we are going to see what is TitleCasePipe in Angular 10 and how to use it." }, { "code": null, "e": 25264, "s": 25201, "text": "TitleCasePipe is used to Transforms all the text to titlecase." }, { "code": null, "e": 25272, "s": 25264, "text": "Syntax:" }, { "code": null, "e": 25300, "s": 25272, "text": "{{ value | TitleCasePipe }}" }, { "code": null, "e": 25343, "s": 25300, "text": "NgModule: Module used by TitleCasePipe is:" }, { "code": null, "e": 25356, "s": 25343, "text": "CommonModule" }, { "code": null, "e": 25367, "s": 25356, "text": "Approach: " }, { "code": null, "e": 25401, "s": 25367, "text": "Create the angular app to be used" }, { "code": null, "e": 25466, "s": 25401, "text": "There is no need for any import for the TitleCasePipe to be used" }, { "code": null, "e": 25543, "s": 25466, "text": "In app.component.ts define the variables that takes the TitleCasePipe value." }, { "code": null, "e": 25633, "s": 25543, "text": "In app.component.html use the above syntax with ‘|’ symbol to make TitleCasePipe element." }, { "code": null, "e": 25688, "s": 25633, "text": "Serve the angular app using ng serve to see the output" }, { "code": null, "e": 25701, "s": 25688, "text": "Input value:" }, { "code": null, "e": 25733, "s": 25701, "text": "value: it takes a string value." }, { "code": null, "e": 25744, "s": 25733, "text": "Example 1:" }, { "code": null, "e": 25761, "s": 25744, "text": "app.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Key Value object value : string = 'geeksforgeeks'; }", "e": 25982, "s": 25761, "text": null }, { "code": null, "e": 26001, "s": 25982, "text": "app.component.html" }, { "code": "<b> <div> titlecase value is : {{value | titlecase}} </div></b>", "e": 26070, "s": 26001, "text": null }, { "code": null, "e": 26078, "s": 26070, "text": "Output:" }, { "code": null, "e": 26089, "s": 26078, "text": "Example 2:" }, { "code": null, "e": 26106, "s": 26089, "text": "app.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Key Value object value : string = 'geeksforgeeks'; }", "e": 26327, "s": 26106, "text": null }, { "code": null, "e": 26346, "s": 26327, "text": "app.component.html" }, { "code": "<b> <div> CamelCase value is : {{value}} </div> <div> TitleCase value is : {{value |titlecase}} </div></b>", "e": 26463, "s": 26346, "text": null }, { "code": null, "e": 26471, "s": 26463, "text": "Output:" }, { "code": null, "e": 26526, "s": 26471, "text": "Reference: https://angular.io/api/common/TitleCasePipe" }, { "code": null, "e": 26536, "s": 26526, "text": "Angular10" }, { "code": null, "e": 26553, "s": 26536, "text": "AngularJS-Basics" }, { "code": null, "e": 26563, "s": 26553, "text": "AngularJS" }, { "code": null, "e": 26580, "s": 26563, "text": "Web Technologies" }, { "code": null, "e": 26678, "s": 26580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26687, "s": 26678, "text": "Comments" }, { "code": null, "e": 26700, "s": 26687, "text": "Old Comments" }, { "code": null, "e": 26744, "s": 26700, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26808, "s": 26744, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 26861, "s": 26808, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 26885, "s": 26861, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 26920, "s": 26885, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26962, "s": 26920, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26995, "s": 26962, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27038, "s": 26995, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27100, "s": 27038, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
C# | Getting index of the specified value in a SortedList object - GeeksforGeeks
01 Feb, 2019 SortedList.IndexOfValue(Object) Method is used to get the zero-based index of the first occurrence of the specified value in a SortedList object. Syntax: public virtual int IndexOfValue (object value); Here, value is the Value which is to be located in the SortedList object. The value can be null. Return Value: This method return the zero-based index of the first occurrence of the value parameter, if the value is found in the SortedList object otherwise it returns -1. Below programs illustrate the use of above-discussed method: Example 1: // C# code to get the zero-based index // of the first occurrence of the specified// value in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Rohit"); mylist.Add("Third", "Mohit"); //taking value "Rohit" twice // but it give the first occurrence mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // printing the keys and values of mylist Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write("\nThe index of value 'Rohit' is: "); // getting the index of value "Rohit" Console.Write(mylist.IndexOfValue("Rohit")); // getting the index of value which is // not present in mylist so it will // return -1 Console.Write("\nThe index of value 'Kirti' is: "); Console.Write(mylist.IndexOfValue("Kirti")); }} Output: Index Keys Values [0] Fifth Manish [1] First Ram [2] Fourth Rohit [3] Second Shyam [4] Third Mohit The index of value 'Rohit' is: 2 The index of value 'Kirti' is: -1 Example 2: // C# code to get the zero-based index // of the first occurrence of the specified// value in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("1", "C++"); mylist.Add("2", "Java"); mylist.Add("3", "DSA"); // taking a value null mylist.Add("4", null); mylist.Add("5", "C#"); // printing the keys and values of mylist Console.WriteLine("Index \t\t Keys \t\tValues"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine("[{0}]\t\t{1}\t\t{2}", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write("\nThe index of value 'null' is: "); // getting the index of value "null" // it will give ArgumentNullException Console.Write(mylist.IndexOfValue(null)); }} Output: Index Keys Values [0] 1 C++ [1] 2 Java [2] 3 DSA [3] 4 [4] 5 C# The index of value 'null' is: 3 Note: The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change. The values of the elements of the SortedList are compared to the specified value using the Equals method. This method uses a linear search; therefore, this method is an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.indexofvalue?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-SortedList CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24448, "s": 24302, "text": "SortedList.IndexOfValue(Object) Method is used to get the zero-based index of the first occurrence of the specified value in a SortedList object." }, { "code": null, "e": 24456, "s": 24448, "text": "Syntax:" }, { "code": null, "e": 24504, "s": 24456, "text": "public virtual int IndexOfValue (object value);" }, { "code": null, "e": 24601, "s": 24504, "text": "Here, value is the Value which is to be located in the SortedList object. The value can be null." }, { "code": null, "e": 24775, "s": 24601, "text": "Return Value: This method return the zero-based index of the first occurrence of the value parameter, if the value is found in the SortedList object otherwise it returns -1." }, { "code": null, "e": 24836, "s": 24775, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 24847, "s": 24836, "text": "Example 1:" }, { "code": "// C# code to get the zero-based index // of the first occurrence of the specified// value in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Rohit\"); mylist.Add(\"Third\", \"Mohit\"); //taking value \"Rohit\" twice // but it give the first occurrence mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // printing the keys and values of mylist Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write(\"\\nThe index of value 'Rohit' is: \"); // getting the index of value \"Rohit\" Console.Write(mylist.IndexOfValue(\"Rohit\")); // getting the index of value which is // not present in mylist so it will // return -1 Console.Write(\"\\nThe index of value 'Kirti' is: \"); Console.Write(mylist.IndexOfValue(\"Kirti\")); }}", "e": 26200, "s": 24847, "text": null }, { "code": null, "e": 26208, "s": 26200, "text": "Output:" }, { "code": null, "e": 26463, "s": 26208, "text": "Index Keys Values\n[0] Fifth Manish\n[1] First Ram\n[2] Fourth Rohit\n[3] Second Shyam\n[4] Third Mohit\n\nThe index of value 'Rohit' is: 2\nThe index of value 'Kirti' is: -1\n" }, { "code": null, "e": 26474, "s": 26463, "text": "Example 2:" }, { "code": "// C# code to get the zero-based index // of the first occurrence of the specified// value in a SortedList objectusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"1\", \"C++\"); mylist.Add(\"2\", \"Java\"); mylist.Add(\"3\", \"DSA\"); // taking a value null mylist.Add(\"4\", null); mylist.Add(\"5\", \"C#\"); // printing the keys and values of mylist Console.WriteLine(\"Index \\t\\t Keys \\t\\tValues\"); for (int i = 0; i < mylist.Count; i++) { Console.WriteLine(\"[{0}]\\t\\t{1}\\t\\t{2}\", i, mylist.GetKey(i), mylist.GetByIndex(i)); } Console.Write(\"\\nThe index of value 'null' is: \"); // getting the index of value \"null\" // it will give ArgumentNullException Console.Write(mylist.IndexOfValue(null)); }}", "e": 27556, "s": 26474, "text": null }, { "code": null, "e": 27564, "s": 27556, "text": "Output:" }, { "code": null, "e": 27750, "s": 27564, "text": "Index Keys Values\n[0] 1 C++\n[1] 2 Java\n[2] 3 DSA\n[3] 4 \n[4] 5 C#\n\nThe index of value 'null' is: 3\n" }, { "code": null, "e": 27756, "s": 27750, "text": "Note:" }, { "code": null, "e": 28050, "s": 27756, "text": "The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. So, the index of a specific key/value pair may change." }, { "code": null, "e": 28156, "s": 28050, "text": "The values of the elements of the SortedList are compared to the specified value using the Equals method." }, { "code": null, "e": 28253, "s": 28156, "text": "This method uses a linear search; therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 28264, "s": 28253, "text": "Reference:" }, { "code": null, "e": 28375, "s": 28264, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.indexofvalue?view=netframework-4.7.2" }, { "code": null, "e": 28404, "s": 28375, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 28434, "s": 28404, "text": "CSharp-Collections-SortedList" }, { "code": null, "e": 28448, "s": 28434, "text": "CSharp-method" }, { "code": null, "e": 28451, "s": 28448, "text": "C#" }, { "code": null, "e": 28549, "s": 28451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28572, "s": 28549, "text": "Extension Method in C#" }, { "code": null, "e": 28600, "s": 28572, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28640, "s": 28600, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28683, "s": 28640, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28699, "s": 28683, "text": "C# | List Class" }, { "code": null, "e": 28716, "s": 28699, "text": "C# | Inheritance" }, { "code": null, "e": 28738, "s": 28716, "text": "Partial Classes in C#" }, { "code": null, "e": 28778, "s": 28738, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28803, "s": 28778, "text": "Lambda Expressions in C#" } ]
iText - Markup Annotation
In this chapter, we will see how to add text markup annotation to a PDF document using iText library. You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. To use text annotation in your PDF document, you need to create an object of PdfTextAnnotation class and add this to the PdfPage. Following are the steps to use text annotation in the PDF document. The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created. Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below. // Creating a PdfWriter String dest = "C:/itextExamples/markupAnnotation.pdf"; PdfWriter writer = new PdfWriter(dest); When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified. The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor. Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below. // Creating a PdfDocument PdfDocument pdfDoc = new PdfDocument(writer); Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class. The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument. Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below. // Creating a Document Document document = new Document(pdfDoc); The PdfAnnotation class of the package com.itextpdf.kernel.pdf.annot represents the superclass of all the annotations. Among its derived classes, PdfTextMarkupAnnotation class represents the text markup annotation. Create an object of this class as shown below. // Creating a PdfTextMarkupAnnotation object Rectangle rect = new Rectangle(105, 790, 64, 10); float[] floatArray = new float[]{169, 790, 105, 790, 169, 800, 105, 800}; PdfAnnotation annotation = PdfTextMarkupAnnotation.createHighLight(rect,floatArray); Set color to the annotation using the setColor() method of the PdfAnnotation class. To this method, pass the color object representing the color of the annotation as a parameter. // Setting color to the annotation annotation.setColor(Color.YELLOW); Set the title and contents of the annotation using the setTitle() and setContents() methods of the PdfAnnotation class respectively. // Setting title to the annotation annotation.setTitle(new PdfString("Hello!")); // Setting contents to the annotation annotation.setContents(new PdfString("Hi welcome to Tutorialspoint")); Create a new PdfPage class using the addNewPage() method of the PdfDocument class and add the above created annotation using the addAnnotation() method of PdfPage class, as shown below. // Creating a new Pdfpage PdfPage pdfPage = pdfDoc.addNewPage(); // Adding annotation to a page in a PDF pdfPage.addAnnotation(annotation); Close the document using the close() method of the Document class, as shown below. // Closing the document document.close(); The following Java program demonstrates how to add text markup annotation to a PDF document using the iText library. It creates a PDF document with the name markupAnnotation.pdf, adds a text markup annotation to it, and saves it in the path C:/itextExamples/ Save this code in a file with the name MarkupAnnotation.java. import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfString; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.annot.PdfAnnotation; import com.itextpdf.kernel.pdf.annot.PdfTextMarkupAnnotation; import com.itextpdf.layout.Document; public class MarkupAnnotation { public static void main(String args[]) throws Exception { // Creating a PdfDocument object String file = "C:/itextExamples/markupAnnotation.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); // Creating a Document object Document doc = new Document(pdfDoc); // Creating a PdfTextMarkupAnnotation object Rectangle rect = new Rectangle(105, 790, 64, 10); float[] floatArray = new float[]{169, 790, 105, 790, 169, 800, 105, 800}; PdfAnnotation annotation = PdfTextMarkupAnnotation.createHighLight(rect,floatArray); // Setting color to the annotation annotation.setColor(Color.YELLOW); // Setting title to the annotation annotation.setTitle(new PdfString("Hello!")); // Setting contents to the annotation annotation.setContents(new PdfString("Hi welcome to Tutorialspoint")); // Creating a new Pdfpage PdfPage pdfPage = pdfDoc.addNewPage(); // Adding annotation to a page in a PDF pdfPage.addAnnotation(annotation); // Closing the document doc.close(); System.out.println("Annotation added successfully"); } } Compile and execute the saved Java file from the Command prompt using the following commands − javac MarkupAnnotation.java java MarkupAnnotation Upon execution, the above program creates a PDF document displaying the following message. Annotation added successfully If you verify the specified path, you can find the created PDF document as shown below. Print Add Notes Bookmark this page
[ { "code": null, "e": 2470, "s": 2368, "text": "In this chapter, we will see how to add text markup annotation to a PDF document using iText library." }, { "code": null, "e": 2779, "s": 2470, "text": "You can create an empty PDF Document by instantiating the Document class. While instantiating this class, you need to pass a PdfDocument object as a parameter to its constructor. To use text annotation in your PDF document, you need to create an object of PdfTextAnnotation class and add this to the PdfPage." }, { "code": null, "e": 2847, "s": 2779, "text": "Following are the steps to use text annotation in the PDF document." }, { "code": null, "e": 3076, "s": 2847, "text": "The PdfWriter class represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the path of the file where the PDF is to be created." }, { "code": null, "e": 3225, "s": 3076, "text": "Instantiate the PdfWriter class by passing a string value (representing the path where you need to create a PDF) to its constructor, as shown below." }, { "code": null, "e": 3348, "s": 3225, "text": "// Creating a PdfWriter \nString dest = \"C:/itextExamples/markupAnnotation.pdf\"; \nPdfWriter writer = new PdfWriter(dest); \n" }, { "code": null, "e": 3488, "s": 3348, "text": "When an object of this type is passed to a PdfDocument (class), every element added to this document will be written to the file specified." }, { "code": null, "e": 3740, "s": 3488, "text": "The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To instantiate this class (in writing mode), you need to pass an object of the class PdfWriter to its constructor." }, { "code": null, "e": 3842, "s": 3740, "text": "Instantiate the PdfDocument class by passing the PdfWriter object to its constructor, as shown below." }, { "code": null, "e": 3918, "s": 3842, "text": "// Creating a PdfDocument \nPdfDocument pdfDoc = new PdfDocument(writer); \n" }, { "code": null, "e": 4089, "s": 3918, "text": "Once a PdfDocument object is created, you can add various elements like page, font, file attachment, and event handler using the respective methods provided by its class." }, { "code": null, "e": 4283, "s": 4089, "text": "The Document class of the package com.itextpdf.layout is the root element while creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument." }, { "code": null, "e": 4408, "s": 4283, "text": "Instantiate the Document class by passing the object of the class PdfDocument created in the previous steps, as shown below." }, { "code": null, "e": 4478, "s": 4408, "text": "// Creating a Document \nDocument document = new Document(pdfDoc); \n" }, { "code": null, "e": 4597, "s": 4478, "text": "The PdfAnnotation class of the package com.itextpdf.kernel.pdf.annot represents the superclass of all the annotations." }, { "code": null, "e": 4740, "s": 4597, "text": "Among its derived classes, PdfTextMarkupAnnotation class represents the text markup annotation. Create an object of this class as shown below." }, { "code": null, "e": 4997, "s": 4740, "text": "// Creating a PdfTextMarkupAnnotation object \nRectangle rect = new Rectangle(105, 790, 64, 10); \nfloat[] floatArray = new float[]{169, 790, 105, 790, 169, 800, 105, 800};\nPdfAnnotation annotation = PdfTextMarkupAnnotation.createHighLight(rect,floatArray);\n" }, { "code": null, "e": 5176, "s": 4997, "text": "Set color to the annotation using the setColor() method of the PdfAnnotation class. To this method, pass the color object representing the color of the annotation as a parameter." }, { "code": null, "e": 5248, "s": 5176, "text": "// Setting color to the annotation \nannotation.setColor(Color.YELLOW);\n" }, { "code": null, "e": 5381, "s": 5248, "text": "Set the title and contents of the annotation using the setTitle() and setContents() methods of the PdfAnnotation class respectively." }, { "code": null, "e": 5584, "s": 5381, "text": "// Setting title to the annotation \nannotation.setTitle(new PdfString(\"Hello!\")); \n\n// Setting contents to the annotation \nannotation.setContents(new PdfString(\"Hi welcome to Tutorialspoint\")); \n" }, { "code": null, "e": 5770, "s": 5584, "text": "Create a new PdfPage class using the addNewPage() method of the PdfDocument class and add the above created annotation using the addAnnotation() method of PdfPage class, as shown below." }, { "code": null, "e": 5923, "s": 5770, "text": "// Creating a new Pdfpage \nPdfPage pdfPage = pdfDoc.addNewPage(); \n\n// Adding annotation to a page in a PDF \npdfPage.addAnnotation(annotation); \n" }, { "code": null, "e": 6006, "s": 5923, "text": "Close the document using the close() method of the Document class, as shown below." }, { "code": null, "e": 6051, "s": 6006, "text": "// Closing the document \ndocument.close(); \n" }, { "code": null, "e": 6310, "s": 6051, "text": "The following Java program demonstrates how to add text markup annotation to a PDF document using the iText library. It creates a PDF document with the name markupAnnotation.pdf, adds a text markup annotation to it, and saves it in the path C:/itextExamples/" }, { "code": null, "e": 6372, "s": 6310, "text": "Save this code in a file with the name MarkupAnnotation.java." }, { "code": null, "e": 8190, "s": 6372, "text": "import com.itextpdf.kernel.color.Color; \nimport com.itextpdf.kernel.geom.Rectangle; \nimport com.itextpdf.kernel.pdf.PdfDocument; \nimport com.itextpdf.kernel.pdf.PdfPage; \nimport com.itextpdf.kernel.pdf.PdfString; \nimport com.itextpdf.kernel.pdf.PdfWriter; \nimport com.itextpdf.kernel.pdf.annot.PdfAnnotation; \nimport com.itextpdf.kernel.pdf.annot.PdfTextMarkupAnnotation;\nimport com.itextpdf.layout.Document; \n\npublic class MarkupAnnotation { \n public static void main(String args[]) throws Exception { \n // Creating a PdfDocument object \n String file = \"C:/itextExamples/markupAnnotation.pdf\"; \n PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file)); \n \n // Creating a Document object \n Document doc = new Document(pdfDoc); \n \n // Creating a PdfTextMarkupAnnotation object \n Rectangle rect = new Rectangle(105, 790, 64, 10); \n float[] floatArray = new float[]{169, 790, 105, 790, 169, 800, 105, 800};\n PdfAnnotation annotation = \n PdfTextMarkupAnnotation.createHighLight(rect,floatArray);\n \n // Setting color to the annotation \n annotation.setColor(Color.YELLOW); \n \n // Setting title to the annotation \n annotation.setTitle(new PdfString(\"Hello!\"));\n \n // Setting contents to the annotation \n annotation.setContents(new PdfString(\"Hi welcome to Tutorialspoint\"));\n \n // Creating a new Pdfpage\n PdfPage pdfPage = pdfDoc.addNewPage();\n \n // Adding annotation to a page in a PDF \n pdfPage.addAnnotation(annotation);\n \n // Closing the document\n doc.close(); \n \n System.out.println(\"Annotation added successfully\"); \n } \n} " }, { "code": null, "e": 8285, "s": 8190, "text": "Compile and execute the saved Java file from the Command prompt using the following commands −" }, { "code": null, "e": 8338, "s": 8285, "text": "javac MarkupAnnotation.java \njava MarkupAnnotation \n" }, { "code": null, "e": 8429, "s": 8338, "text": "Upon execution, the above program creates a PDF document displaying the following message." }, { "code": null, "e": 8460, "s": 8429, "text": "Annotation added successfully\n" }, { "code": null, "e": 8548, "s": 8460, "text": "If you verify the specified path, you can find the created PDF document as shown below." }, { "code": null, "e": 8555, "s": 8548, "text": " Print" }, { "code": null, "e": 8566, "s": 8555, "text": " Add Notes" } ]
jQuery UI | Date Picker
03 Aug, 2021 A date-picker of jQuery UI is used to provide a calendar to the user to select the date from a Calendar. This date picker usually connected to a text-box so user selection of date from the calendar can be transferred to the textbox. We will use the CDN link for different libraries and styles. To display any jQuery UI widget, we have to use the link of jQuery and jQuery UI. We will also use style property and used the theme Cupertino for our calendar. You can change the theme to match your style requirements. <link href=’https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css’ rel=’stylesheet’> Example 1: This example display a date picker. <!DOCTYPE html><html> <head> <title> jQuery UI | Date Picker </title> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" > </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" > </script></head> <body> Date: <input type="text" id="my_date_picker"> <script> $(document).ready(function() { $(function() { $( "#my_date_picker" ).datepicker(); }); }) </script></body> </html> Output: Default Date Selected: By default today’s date is selected in the calendar. However, we can change the default date by assigning the value to the default date. Example 2: <!DOCTYPE html><html> <head> <title> jQuery UI | Date Picker </title> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" > </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" > </script></head> <body> Date: <input type="text" id="my_date_picker"> <script> $(function() { $( "#my_date_picker" ).datepicker({ defaultDate:"09/22/2019" }); }); </script></body> </html> Output: Managing the date format: While displaying the calendar we can manage the date format. We can use the following jQuery code in the script section to get the result. <script>$(function() { $( "#my_date_picker" ).datepicker({ dateFormat: 'dd-mm-yy', defaultDate:"24-09-2019" });});</script> Managing the Weekday: By default, the first day of the week is displayed from Sunday ( firstDay=0 ). We can change the starting day by changing the value of firstDay. <script>$(function() { $( "#my_date_picker" ).datepicker({ firstDay:2 // Tuesday is first day });});</script> Updating Month and Year: Based on our requirement we can add options for the users to select Month and Year. <script>$(function() { $( "#my_date_picker" ).datepicker({ changeMonth: true, changeYear: true });});</script> Maximum and Minimum dates to Select: We can restrict the user selection of Dates from the calendar by assigning a Maximum and Minimum Date value. $(function() { $( "#my_date_picker" ).datepicker({ maxDate:'+3d', minDate: '-4d' });}); We have two calendars, one calendar is to choose the start date and the other one is to choose end date in the calendar. It can be used for hotel booking where we have to select check-in Date and check-out date. The following conditions must be met for such arrangements. Once the start date is selected, the end date can’t be before the start date Once the end date is selected, the start date can’t be after the end date End date can’t be changed to before start date Start date can’t be changed to after end date. Dates which can’t be selected should be disabled for selection in the above cases. Before using two interlocked calendars we will learn how to set Minimum selectable date and Maximum selectable date.minDate: Minimum Selectable date. maxDate: Maximum Selectable Date. There is one example at the end of the previous article on DatePicker. Here it is again. Interlocking of two CalendarsChange function of Calendar:We will be using the change function to trigger the event. We will set the minDate for the End Calendar whenever the change function of Start Calendar is triggered.Similarly, we will set the maxDate for the Start Calendar when ever change function of End Calendar is triggered.getDate()This method returns the selected date of the calendar. Here is an example var my_date = $( "#my_calendar" ).datepicker( "getDate" ); We will use this to get the dates selected by the user.Now we will give the user two calendars to select the start date and end date. <!DOCTYPE html><html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <style> .ui-datepicker { width: 12em; } h1{ color:green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> Start Date: <input type="text" id="my_date_picker1"> End Date: <input type="text" id="my_date_picker2"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $(function() { $("#my_date_picker1").datepicker({}); }); $(function() { $("#my_date_picker2").datepicker({}); }); $('#my_date_picker1').change(function() { startDate = $(this).datepicker('getDate'); $("#my_date_picker2").datepicker("option", "minDate", startDate); }) $('#my_date_picker2').change(function() { endDate = $(this).datepicker('getDate'); $("#my_date_picker1").datepicker("option", "maxDate", endDate); }) }) </script> </center></body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. mayeshmohapatra jQuery-Misc HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Aug, 2021" }, { "code": null, "e": 285, "s": 52, "text": "A date-picker of jQuery UI is used to provide a calendar to the user to select the date from a Calendar. This date picker usually connected to a text-box so user selection of date from the calendar can be transferred to the textbox." }, { "code": null, "e": 566, "s": 285, "text": "We will use the CDN link for different libraries and styles. To display any jQuery UI widget, we have to use the link of jQuery and jQuery UI. We will also use style property and used the theme Cupertino for our calendar. You can change the theme to match your style requirements." }, { "code": null, "e": 685, "s": 566, "text": "<link href=’https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css’ rel=’stylesheet’>" }, { "code": null, "e": 732, "s": 685, "text": "Example 1: This example display a date picker." }, { "code": "<!DOCTYPE html><html> <head> <title> jQuery UI | Date Picker </title> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\" > </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\" > </script></head> <body> Date: <input type=\"text\" id=\"my_date_picker\"> <script> $(document).ready(function() { $(function() { $( \"#my_date_picker\" ).datepicker(); }); }) </script></body> </html>", "e": 1428, "s": 732, "text": null }, { "code": null, "e": 1436, "s": 1428, "text": "Output:" }, { "code": null, "e": 1596, "s": 1436, "text": "Default Date Selected: By default today’s date is selected in the calendar. However, we can change the default date by assigning the value to the default date." }, { "code": null, "e": 1607, "s": 1596, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> jQuery UI | Date Picker </title> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\" > </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\" > </script></head> <body> Date: <input type=\"text\" id=\"my_date_picker\"> <script> $(function() { $( \"#my_date_picker\" ).datepicker({ defaultDate:\"09/22/2019\" }); }); </script></body> </html>", "e": 2285, "s": 1607, "text": null }, { "code": null, "e": 2293, "s": 2285, "text": "Output:" }, { "code": null, "e": 2458, "s": 2293, "text": "Managing the date format: While displaying the calendar we can manage the date format. We can use the following jQuery code in the script section to get the result." }, { "code": "<script>$(function() { $( \"#my_date_picker\" ).datepicker({ dateFormat: 'dd-mm-yy', defaultDate:\"24-09-2019\" });});</script>", "e": 2602, "s": 2458, "text": null }, { "code": null, "e": 2769, "s": 2602, "text": "Managing the Weekday: By default, the first day of the week is displayed from Sunday ( firstDay=0 ). We can change the starting day by changing the value of firstDay." }, { "code": "<script>$(function() { $( \"#my_date_picker\" ).datepicker({ firstDay:2 // Tuesday is first day });});</script>", "e": 2892, "s": 2769, "text": null }, { "code": null, "e": 3001, "s": 2892, "text": "Updating Month and Year: Based on our requirement we can add options for the users to select Month and Year." }, { "code": "<script>$(function() { $( \"#my_date_picker\" ).datepicker({ changeMonth: true, changeYear: true });});</script>", "e": 3132, "s": 3001, "text": null }, { "code": null, "e": 3278, "s": 3132, "text": "Maximum and Minimum dates to Select: We can restrict the user selection of Dates from the calendar by assigning a Maximum and Minimum Date value." }, { "code": "$(function() { $( \"#my_date_picker\" ).datepicker({ maxDate:'+3d', minDate: '-4d' });});", "e": 3386, "s": 3278, "text": null }, { "code": null, "e": 3658, "s": 3386, "text": "We have two calendars, one calendar is to choose the start date and the other one is to choose end date in the calendar. It can be used for hotel booking where we have to select check-in Date and check-out date. The following conditions must be met for such arrangements." }, { "code": null, "e": 3735, "s": 3658, "text": "Once the start date is selected, the end date can’t be before the start date" }, { "code": null, "e": 3809, "s": 3735, "text": "Once the end date is selected, the start date can’t be after the end date" }, { "code": null, "e": 3856, "s": 3809, "text": "End date can’t be changed to before start date" }, { "code": null, "e": 3903, "s": 3856, "text": "Start date can’t be changed to after end date." }, { "code": null, "e": 3986, "s": 3903, "text": "Dates which can’t be selected should be disabled for selection in the above cases." }, { "code": null, "e": 4259, "s": 3986, "text": "Before using two interlocked calendars we will learn how to set Minimum selectable date and Maximum selectable date.minDate: Minimum Selectable date. maxDate: Maximum Selectable Date. There is one example at the end of the previous article on DatePicker. Here it is again." }, { "code": null, "e": 4676, "s": 4259, "text": "Interlocking of two CalendarsChange function of Calendar:We will be using the change function to trigger the event. We will set the minDate for the End Calendar whenever the change function of Start Calendar is triggered.Similarly, we will set the maxDate for the Start Calendar when ever change function of End Calendar is triggered.getDate()This method returns the selected date of the calendar. Here is an example" }, { "code": "var my_date = $( \"#my_calendar\" ).datepicker( \"getDate\" );", "e": 4735, "s": 4676, "text": null }, { "code": null, "e": 4869, "s": 4735, "text": "We will use this to get the dates selected by the user.Now we will give the user two calendars to select the start date and end date." }, { "code": "<!DOCTYPE html><html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'> <style> .ui-datepicker { width: 12em; } h1{ color:green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> Start Date: <input type=\"text\" id=\"my_date_picker1\"> End Date: <input type=\"text\" id=\"my_date_picker2\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(function() { $(\"#my_date_picker1\").datepicker({}); }); $(function() { $(\"#my_date_picker2\").datepicker({}); }); $('#my_date_picker1').change(function() { startDate = $(this).datepicker('getDate'); $(\"#my_date_picker2\").datepicker(\"option\", \"minDate\", startDate); }) $('#my_date_picker2').change(function() { endDate = $(this).datepicker('getDate'); $(\"#my_date_picker1\").datepicker(\"option\", \"maxDate\", endDate); }) }) </script> </center></body> </html>", "e": 6343, "s": 4869, "text": null }, { "code": null, "e": 6351, "s": 6343, "text": "Output:" }, { "code": null, "e": 6619, "s": 6351, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 6635, "s": 6619, "text": "mayeshmohapatra" }, { "code": null, "e": 6647, "s": 6635, "text": "jQuery-Misc" }, { "code": null, "e": 6652, "s": 6647, "text": "HTML" }, { "code": null, "e": 6659, "s": 6652, "text": "JQuery" }, { "code": null, "e": 6676, "s": 6659, "text": "Web Technologies" }, { "code": null, "e": 6703, "s": 6676, "text": "Web technologies Questions" }, { "code": null, "e": 6708, "s": 6703, "text": "HTML" } ]
JavaScript | Assignment operators
02 Jun, 2020 The Assignment operator is equal (=) which assigns the value of right-hand operand to its left-hand operand. That is if a = b assigns the value of b to a. The simple assignment operator is used to assigning a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example. Syntax: data=value Examples: // Lets take some variables x=10 y=20 x=y // Here, x is equal to 20 y=x // Here, y is equal to 10 There are so many assignment operator as shown in the table with the description:th a+=b a=a+b a-=b a=a-b a*=b a=a*b a/=b a=a/b a%=b a=a%b a**=b a=a**b a<<=b a=a<<b a>>=b a=a>>b a&=b a=a&b a|=b a=a | b a^=b a=a^b Addition Assignment: This operator adds the value to the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. In case if concatenation then we use the string as an operand. Example: Javascript <script> let a = 2; const b= 3; // Expected output: 2 document.write(a); document.write('</br>'); // Expected output: 4 document.write(a = b + 1);</script> Output: 2 4 Subtraction Assignment: This operator subtracts the value of the right operand from a variable and assigns the result to the variable. Example: Javascript <script> let yoo=4; document.write(foo=yoo-1); // 4-1 </script> Output: 3 Multiplication Assignment: This operator multiplies a variable by the value of the right operand and assigns the result to the variable. Example: Javascript <script> let yoo=5; document.write(yoo=yoo*2); // 5*2 </script> Output: 10 Division Assignment: This operator divides a variable by the value of the right operand and assigns the result to the variable. Example: Javascript <script> let yoo=10; const moo=2; document.write(yoo=yoo/moo); // 10/2 document.write("</br>"); document.write(yoo/=0); // Infinity </script> Output: 5 Infinity Remainder Assignment: This operator divides a variable by the value of the right operand and assigns the remainder to the variable. Example: Javascript <script> let yoo=50; document.write(yoo%=10); //zero </script> Output: 0 Exponentiation Assignment: This operator raises the value of a variable to the power of the right operand. Example: Javascript <script> let yoo=2; const moo=2; // 2 raise to the power 2 document.write(yoo**moo); </script> Output: 4 Left Shift Assignment: This operator moves the specified amount of bits to the left and assigns the result to the variable. Example: Javascript <script> var yoo=5; // 101 // 20(In Binary 10100) document.write(yoo<<=2);</script> Output: 20 Right Shift Assignment: This operator moves the specified amount of bits to the right and assigns the result to the variable. Example: Javascript <script> var yoo=5; document.write(yoo>>=2); // 001 </script> Output: 1 Binary AND Assignment: This operator uses the binary representation of both operands, does a bitwise AND operation on them, and assigns the result to the variable. Example: Javascript <script> var yoo=5; document.write(yoo&=2); // 000 </script> Output: 0 Binary OR Assignment: This operator uses the binary representation of both operands, does a bitwise OR operation on them, and assigns the result to the variable. Example: Javascript <script> var yoo=5; // 7(In binary: 111) document.write(yoo|=2); </script> Output: 7 This operator uses the binary representation of both operands, does a bitwise XOR operation on them, and assigns the result to the variable. Example: Javascript <script> var yoo=5; document.write(yoo^=2); // 111 </script> Output: 7 javascript-basics Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 184, "s": 28, "text": "The Assignment operator is equal (=) which assigns the value of right-hand operand to its left-hand operand. That is if a = b assigns the value of b to a." }, { "code": null, "e": 436, "s": 184, "text": "The simple assignment operator is used to assigning a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example." }, { "code": null, "e": 444, "s": 436, "text": "Syntax:" }, { "code": null, "e": 455, "s": 444, "text": "data=value" }, { "code": null, "e": 465, "s": 455, "text": "Examples:" }, { "code": null, "e": 564, "s": 465, "text": "// Lets take some variables\nx=10\ny=20\n\nx=y // Here, x is equal to 20\ny=x // Here, y is equal to 10" }, { "code": null, "e": 648, "s": 564, "text": "There are so many assignment operator as shown in the table with the description:th" }, { "code": null, "e": 653, "s": 648, "text": "a+=b" }, { "code": null, "e": 659, "s": 653, "text": "a=a+b" }, { "code": null, "e": 664, "s": 659, "text": "a-=b" }, { "code": null, "e": 670, "s": 664, "text": "a=a-b" }, { "code": null, "e": 675, "s": 670, "text": "a*=b" }, { "code": null, "e": 681, "s": 675, "text": "a=a*b" }, { "code": null, "e": 686, "s": 681, "text": "a/=b" }, { "code": null, "e": 692, "s": 686, "text": "a=a/b" }, { "code": null, "e": 697, "s": 692, "text": "a%=b" }, { "code": null, "e": 703, "s": 697, "text": "a=a%b" }, { "code": null, "e": 709, "s": 703, "text": "a**=b" }, { "code": null, "e": 716, "s": 709, "text": "a=a**b" }, { "code": null, "e": 722, "s": 716, "text": "a<<=b" }, { "code": null, "e": 729, "s": 722, "text": "a=a<<b" }, { "code": null, "e": 735, "s": 729, "text": "a>>=b" }, { "code": null, "e": 742, "s": 735, "text": "a=a>>b" }, { "code": null, "e": 747, "s": 742, "text": "a&=b" }, { "code": null, "e": 753, "s": 747, "text": "a=a&b" }, { "code": null, "e": 758, "s": 753, "text": "a|=b" }, { "code": null, "e": 766, "s": 758, "text": "a=a | b" }, { "code": null, "e": 771, "s": 766, "text": "a^=b" }, { "code": null, "e": 777, "s": 771, "text": "a=a^b" }, { "code": null, "e": 1094, "s": 777, "text": "Addition Assignment: This operator adds the value to the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. In case if concatenation then we use the string as an operand." }, { "code": null, "e": 1103, "s": 1094, "text": "Example:" }, { "code": null, "e": 1114, "s": 1103, "text": "Javascript" }, { "code": "<script> let a = 2; const b= 3; // Expected output: 2 document.write(a); document.write('</br>'); // Expected output: 4 document.write(a = b + 1);</script>", "e": 1277, "s": 1114, "text": null }, { "code": null, "e": 1285, "s": 1277, "text": "Output:" }, { "code": null, "e": 1289, "s": 1285, "text": "2\n4" }, { "code": null, "e": 1425, "s": 1289, "text": "Subtraction Assignment: This operator subtracts the value of the right operand from a variable and assigns the result to the variable." }, { "code": null, "e": 1434, "s": 1425, "text": "Example:" }, { "code": null, "e": 1445, "s": 1434, "text": "Javascript" }, { "code": "<script> let yoo=4; document.write(foo=yoo-1); // 4-1 </script>", "e": 1514, "s": 1445, "text": null }, { "code": null, "e": 1522, "s": 1514, "text": "Output:" }, { "code": null, "e": 1524, "s": 1522, "text": "3" }, { "code": null, "e": 1661, "s": 1524, "text": "Multiplication Assignment: This operator multiplies a variable by the value of the right operand and assigns the result to the variable." }, { "code": null, "e": 1670, "s": 1661, "text": "Example:" }, { "code": null, "e": 1681, "s": 1670, "text": "Javascript" }, { "code": "<script> let yoo=5; document.write(yoo=yoo*2); // 5*2 </script>", "e": 1750, "s": 1681, "text": null }, { "code": null, "e": 1758, "s": 1750, "text": "Output:" }, { "code": null, "e": 1761, "s": 1758, "text": "10" }, { "code": null, "e": 1889, "s": 1761, "text": "Division Assignment: This operator divides a variable by the value of the right operand and assigns the result to the variable." }, { "code": null, "e": 1898, "s": 1889, "text": "Example:" }, { "code": null, "e": 1909, "s": 1898, "text": "Javascript" }, { "code": "<script> let yoo=10; const moo=2; document.write(yoo=yoo/moo); // 10/2 document.write(\"</br>\"); document.write(yoo/=0); // Infinity </script>", "e": 2070, "s": 1909, "text": null }, { "code": null, "e": 2078, "s": 2070, "text": "Output:" }, { "code": null, "e": 2089, "s": 2078, "text": "5\nInfinity" }, { "code": null, "e": 2221, "s": 2089, "text": "Remainder Assignment: This operator divides a variable by the value of the right operand and assigns the remainder to the variable." }, { "code": null, "e": 2230, "s": 2221, "text": "Example:" }, { "code": null, "e": 2241, "s": 2230, "text": "Javascript" }, { "code": "<script> let yoo=50; document.write(yoo%=10); //zero </script>", "e": 2309, "s": 2241, "text": null }, { "code": null, "e": 2317, "s": 2309, "text": "Output:" }, { "code": null, "e": 2319, "s": 2317, "text": "0" }, { "code": null, "e": 2426, "s": 2319, "text": "Exponentiation Assignment: This operator raises the value of a variable to the power of the right operand." }, { "code": null, "e": 2435, "s": 2426, "text": "Example:" }, { "code": null, "e": 2446, "s": 2435, "text": "Javascript" }, { "code": "<script> let yoo=2; const moo=2; // 2 raise to the power 2 document.write(yoo**moo); </script>", "e": 2554, "s": 2446, "text": null }, { "code": null, "e": 2562, "s": 2554, "text": "Output:" }, { "code": null, "e": 2564, "s": 2562, "text": "4" }, { "code": null, "e": 2688, "s": 2564, "text": "Left Shift Assignment: This operator moves the specified amount of bits to the left and assigns the result to the variable." }, { "code": null, "e": 2697, "s": 2688, "text": "Example:" }, { "code": null, "e": 2708, "s": 2697, "text": "Javascript" }, { "code": "<script> var yoo=5; // 101 // 20(In Binary 10100) document.write(yoo<<=2);</script>", "e": 2794, "s": 2708, "text": null }, { "code": null, "e": 2802, "s": 2794, "text": "Output:" }, { "code": null, "e": 2805, "s": 2802, "text": "20" }, { "code": null, "e": 2931, "s": 2805, "text": "Right Shift Assignment: This operator moves the specified amount of bits to the right and assigns the result to the variable." }, { "code": null, "e": 2940, "s": 2931, "text": "Example:" }, { "code": null, "e": 2951, "s": 2940, "text": "Javascript" }, { "code": "<script> var yoo=5; document.write(yoo>>=2); // 001 </script>", "e": 3016, "s": 2951, "text": null }, { "code": null, "e": 3024, "s": 3016, "text": "Output:" }, { "code": null, "e": 3026, "s": 3024, "text": "1" }, { "code": null, "e": 3190, "s": 3026, "text": "Binary AND Assignment: This operator uses the binary representation of both operands, does a bitwise AND operation on them, and assigns the result to the variable." }, { "code": null, "e": 3199, "s": 3190, "text": "Example:" }, { "code": null, "e": 3210, "s": 3199, "text": "Javascript" }, { "code": "<script> var yoo=5; document.write(yoo&=2); // 000 </script>", "e": 3274, "s": 3210, "text": null }, { "code": null, "e": 3282, "s": 3274, "text": "Output:" }, { "code": null, "e": 3284, "s": 3282, "text": "0" }, { "code": null, "e": 3446, "s": 3284, "text": "Binary OR Assignment: This operator uses the binary representation of both operands, does a bitwise OR operation on them, and assigns the result to the variable." }, { "code": null, "e": 3455, "s": 3446, "text": "Example:" }, { "code": null, "e": 3466, "s": 3455, "text": "Javascript" }, { "code": "<script> var yoo=5; // 7(In binary: 111) document.write(yoo|=2); </script>", "e": 3544, "s": 3466, "text": null }, { "code": null, "e": 3552, "s": 3544, "text": "Output:" }, { "code": null, "e": 3554, "s": 3552, "text": "7" }, { "code": null, "e": 3696, "s": 3554, "text": " This operator uses the binary representation of both operands, does a bitwise XOR operation on them, and assigns the result to the variable." }, { "code": null, "e": 3705, "s": 3696, "text": "Example:" }, { "code": null, "e": 3716, "s": 3705, "text": "Javascript" }, { "code": "<script> var yoo=5; document.write(yoo^=2); // 111 </script>", "e": 3780, "s": 3716, "text": null }, { "code": null, "e": 3788, "s": 3780, "text": "Output:" }, { "code": null, "e": 3790, "s": 3788, "text": "7" }, { "code": null, "e": 3808, "s": 3790, "text": "javascript-basics" }, { "code": null, "e": 3815, "s": 3808, "text": "Picked" }, { "code": null, "e": 3826, "s": 3815, "text": "JavaScript" } ]
How to Get Current Date and Time in SQL?
08 Oct, 2021 In this article, we will show to get the current date and time in SQL. In SQL whenever we need to insert and fetching the Current date and time. So For finding to Current Date and Time in SQL have some Predefined function. We will Implement a few methods here. With the Help of the below function. GETDATE() function is mostly used to find the current Date. It will return the DATETIME data type. This means it will Return the Current date with the current Time. Query: Select GetDate() AS 'CurrentDATETime'; Output: CURRENT_TIMESTAMP: It is also used to find current TIMESTAMP means current Date and Time. The CURRENT_TIMESTAMP function can be used the same that the GETDATE() function is used CURRENT_TIMESTAMP returns the same result as GETDATE(). Query: Select CURRENT_TIMESTAMP AS "CURRENTTIMESTAMP"; Output: SYSDATETIME(): SYSDATETIME() function is also used to get the current TIME of the System on which the instance of SQL Server is running. SYSDATETIME() function provides more fractional seconds precision compared to the GETDATE() function. We can fetch the TIME part from the DATE and TIME value returned from the SYSDATETIME() function as below: Query: SELECT SYSDATETIME() 'Current TIME using SYSDATETIME()' Output: We can extract the time part from GETDATE() or CURRENT_TIMESTAMP(). Query: SELECT CONVERT(VARCHAR(8), GETDATE(),108)'hh:mi:ss' Output: Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 328, "s": 28, "text": "In this article, we will show to get the current date and time in SQL. In SQL whenever we need to insert and fetching the Current date and time. So For finding to Current Date and Time in SQL have some Predefined function. We will Implement a few methods here. With the Help of the below function. " }, { "code": null, "e": 493, "s": 328, "text": "GETDATE() function is mostly used to find the current Date. It will return the DATETIME data type. This means it will Return the Current date with the current Time." }, { "code": null, "e": 500, "s": 493, "text": "Query:" }, { "code": null, "e": 539, "s": 500, "text": "Select GetDate() AS 'CurrentDATETime';" }, { "code": null, "e": 547, "s": 539, "text": "Output:" }, { "code": null, "e": 566, "s": 547, "text": "CURRENT_TIMESTAMP:" }, { "code": null, "e": 782, "s": 566, "text": "It is also used to find current TIMESTAMP means current Date and Time. The CURRENT_TIMESTAMP function can be used the same that the GETDATE() function is used CURRENT_TIMESTAMP returns the same result as GETDATE(). " }, { "code": null, "e": 789, "s": 782, "text": "Query:" }, { "code": null, "e": 838, "s": 789, "text": "Select CURRENT_TIMESTAMP AS \"CURRENTTIMESTAMP\"; " }, { "code": null, "e": 846, "s": 838, "text": "Output:" }, { "code": null, "e": 862, "s": 846, "text": "SYSDATETIME(): " }, { "code": null, "e": 1193, "s": 862, "text": "SYSDATETIME() function is also used to get the current TIME of the System on which the instance of SQL Server is running. SYSDATETIME() function provides more fractional seconds precision compared to the GETDATE() function. We can fetch the TIME part from the DATE and TIME value returned from the SYSDATETIME() function as below:" }, { "code": null, "e": 1200, "s": 1193, "text": "Query:" }, { "code": null, "e": 1256, "s": 1200, "text": "SELECT SYSDATETIME() 'Current TIME using SYSDATETIME()'" }, { "code": null, "e": 1264, "s": 1256, "text": "Output:" }, { "code": null, "e": 1333, "s": 1264, "text": " We can extract the time part from GETDATE() or CURRENT_TIMESTAMP()." }, { "code": null, "e": 1340, "s": 1333, "text": "Query:" }, { "code": null, "e": 1392, "s": 1340, "text": "SELECT CONVERT(VARCHAR(8), GETDATE(),108)'hh:mi:ss'" }, { "code": null, "e": 1400, "s": 1392, "text": "Output:" }, { "code": null, "e": 1409, "s": 1402, "text": "Picked" }, { "code": null, "e": 1420, "s": 1409, "text": "SQL-Server" }, { "code": null, "e": 1424, "s": 1420, "text": "SQL" }, { "code": null, "e": 1428, "s": 1424, "text": "SQL" } ]
GATE | GATE CS 2018 | Question 32
14 Nov, 2018 Consider a long-lived TCP session with an end-to-end bandwidth of 1 Gbps (= 109 bits-per-second). The session starts with a sequence number of 1234. The minimum time (in seconds, rounded to the closest integer) before this sequence number can be used again is _______ . Note – This was Numerical Type question. (A) 34(B) 4.30(C) 43(D) None of theseAnswer: (A)Explanation: As sequence number field of TCP is 32 bits, so there are total 232 unique sequence number are possible (from 0 to 232-1), which is limit of TCP data. But if you want to send data more than 232 bytes in TCP, then you need to repeat this procedure after sending 232 bytes of data or unique sequence numbers. This concept is known as wrap around which allow sending unlimited data using TCP. Therefore, question is asking for wrap around time which is equal to pass all unique sequences first, i.e., 232, TCP assigns 1 sequence number to each byte of data. Twrap−around = (Total data) / (Bandwidth) = (232 bytes) / (109 bits per second) = (232 * 8 bits) / (109 bits per second) = 34.35 seconds = 34 (in seconds) GATE’ answer is same as either ceiling value or floor value (i.e., 34 and 35 both are correct). So, option (A) is correct.Quiz of this Question GATE CS 2018 GATE-GATE CS 2018 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Nov, 2018" }, { "code": null, "e": 298, "s": 28, "text": "Consider a long-lived TCP session with an end-to-end bandwidth of 1 Gbps (= 109 bits-per-second). The session starts with a sequence number of 1234. The minimum time (in seconds, rounded to the closest integer) before this sequence number can be used again is _______ ." }, { "code": null, "e": 339, "s": 298, "text": "Note – This was Numerical Type question." }, { "code": null, "e": 550, "s": 339, "text": "(A) 34(B) 4.30(C) 43(D) None of theseAnswer: (A)Explanation: As sequence number field of TCP is 32 bits, so there are total 232 unique sequence number are possible (from 0 to 232-1), which is limit of TCP data." }, { "code": null, "e": 789, "s": 550, "text": "But if you want to send data more than 232 bytes in TCP, then you need to repeat this procedure after sending 232 bytes of data or unique sequence numbers. This concept is known as wrap around which allow sending unlimited data using TCP." }, { "code": null, "e": 954, "s": 789, "text": "Therefore, question is asking for wrap around time which is equal to pass all unique sequences first, i.e., 232, TCP assigns 1 sequence number to each byte of data." }, { "code": null, "e": 1112, "s": 954, "text": "Twrap−around = (Total data) / (Bandwidth)\n= (232 bytes) / (109 bits per second) \n= (232 * 8 bits) / (109 bits per second) \n= 34.35 seconds = 34 (in seconds) " }, { "code": null, "e": 1208, "s": 1112, "text": "GATE’ answer is same as either ceiling value or floor value (i.e., 34 and 35 both are correct)." }, { "code": null, "e": 1256, "s": 1208, "text": "So, option (A) is correct.Quiz of this Question" }, { "code": null, "e": 1269, "s": 1256, "text": "GATE CS 2018" }, { "code": null, "e": 1287, "s": 1269, "text": "GATE-GATE CS 2018" }, { "code": null, "e": 1292, "s": 1287, "text": "GATE" } ]
dmidecode command in Linux with Examples
15 May, 2019 dmidecode also referred as Desktop Management Interface table decoder, record data from DMI table and produce it in human readable format. dmidecode command is used when the user want to retrieve system’s hardware related information such as Processor, RAM(DIMMs), BIOS detail, Memory, Serial numbers etc. of Linux system in a readable format. dmidecode command not only displays the system’s current hardware configuration but also the maximum supported CPU and memory. Syntax: dmidecode [OPTIONS] However, in some Linux/Unix system, it may require root permission in order to run dmidecode command, like the present Linux system which is being used to run the following command require root privilege. Example 1: Running a simple dmidecode command to get hardware information. Example 2: To get information about Processor. Example 3: To get BIOS information. Options: -d, –dev-mem FILE: This option is used to read memory from device FILE, where FILE is the file name being used. By default it is /dev/mem. -h, –help: Display help and exit. -q, –quiet: This option is used to print less verbose output. -s, –string KEYWORD: Only display the value of the given DMI string. Suppose if we want to know the value of processor-frequency, we can use the following command along with the keyword(processor-frequency). -t, –type TYPE: This option is helpful when we only want to display the entries of a given type. With the help of DMI type id, we can get particular information about a hardware component. Type ids are equivalent to the keyword thus we can either use the type id’s # or we can use the entire keyword to get the information related to that keyword. Type keywords are not case sensitive.Example 1: To get information about Baseboard we can execute any of the following commands.sudo dmidecode -t baseboardorsudo dmidecode -t 2orsudo dmidecode --type baseboardExample 2: To get information about Chassis. Example 1: To get information about Baseboard we can execute any of the following commands. sudo dmidecode -t baseboard or sudo dmidecode -t 2 or sudo dmidecode --type baseboard Example 2: To get information about Chassis. -u, –dump: Mostly used in debugging processes. This option is used when don’t want to decode the entries rather we want them to be dumped in hexadecimal form. –dump-bin FILE: This option comes handy when we don’t want dmidecode to decode the entries but to dump the DMI information to a binary file. The file is the name of the file that is to be used. –from-dump FILE: This option Read the DMI data from a given binary file. -V, –version: Display the version and exit. linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2019" }, { "code": null, "e": 499, "s": 28, "text": "dmidecode also referred as Desktop Management Interface table decoder, record data from DMI table and produce it in human readable format. dmidecode command is used when the user want to retrieve system’s hardware related information such as Processor, RAM(DIMMs), BIOS detail, Memory, Serial numbers etc. of Linux system in a readable format. dmidecode command not only displays the system’s current hardware configuration but also the maximum supported CPU and memory." }, { "code": null, "e": 507, "s": 499, "text": "Syntax:" }, { "code": null, "e": 527, "s": 507, "text": "dmidecode [OPTIONS]" }, { "code": null, "e": 732, "s": 527, "text": "However, in some Linux/Unix system, it may require root permission in order to run dmidecode command, like the present Linux system which is being used to run the following command require root privilege." }, { "code": null, "e": 807, "s": 732, "text": "Example 1: Running a simple dmidecode command to get hardware information." }, { "code": null, "e": 854, "s": 807, "text": "Example 2: To get information about Processor." }, { "code": null, "e": 890, "s": 854, "text": "Example 3: To get BIOS information." }, { "code": null, "e": 899, "s": 890, "text": "Options:" }, { "code": null, "e": 1038, "s": 899, "text": "-d, –dev-mem FILE: This option is used to read memory from device FILE, where FILE is the file name being used. By default it is /dev/mem." }, { "code": null, "e": 1072, "s": 1038, "text": "-h, –help: Display help and exit." }, { "code": null, "e": 1134, "s": 1072, "text": "-q, –quiet: This option is used to print less verbose output." }, { "code": null, "e": 1342, "s": 1134, "text": "-s, –string KEYWORD: Only display the value of the given DMI string. Suppose if we want to know the value of processor-frequency, we can use the following command along with the keyword(processor-frequency)." }, { "code": null, "e": 1944, "s": 1342, "text": "-t, –type TYPE: This option is helpful when we only want to display the entries of a given type. With the help of DMI type id, we can get particular information about a hardware component. Type ids are equivalent to the keyword thus we can either use the type id’s # or we can use the entire keyword to get the information related to that keyword. Type keywords are not case sensitive.Example 1: To get information about Baseboard we can execute any of the following commands.sudo dmidecode -t baseboardorsudo dmidecode -t 2orsudo dmidecode --type baseboardExample 2: To get information about Chassis." }, { "code": null, "e": 2036, "s": 1944, "text": "Example 1: To get information about Baseboard we can execute any of the following commands." }, { "code": null, "e": 2064, "s": 2036, "text": "sudo dmidecode -t baseboard" }, { "code": null, "e": 2067, "s": 2064, "text": "or" }, { "code": null, "e": 2087, "s": 2067, "text": "sudo dmidecode -t 2" }, { "code": null, "e": 2090, "s": 2087, "text": "or" }, { "code": null, "e": 2122, "s": 2090, "text": "sudo dmidecode --type baseboard" }, { "code": null, "e": 2167, "s": 2122, "text": "Example 2: To get information about Chassis." }, { "code": null, "e": 2326, "s": 2167, "text": "-u, –dump: Mostly used in debugging processes. This option is used when don’t want to decode the entries rather we want them to be dumped in hexadecimal form." }, { "code": null, "e": 2520, "s": 2326, "text": "–dump-bin FILE: This option comes handy when we don’t want dmidecode to decode the entries but to dump the DMI information to a binary file. The file is the name of the file that is to be used." }, { "code": null, "e": 2593, "s": 2520, "text": "–from-dump FILE: This option Read the DMI data from a given binary file." }, { "code": null, "e": 2637, "s": 2593, "text": "-V, –version: Display the version and exit." }, { "code": null, "e": 2651, "s": 2637, "text": "linux-command" }, { "code": null, "e": 2671, "s": 2651, "text": "Linux-misc-commands" }, { "code": null, "e": 2682, "s": 2671, "text": "Linux-Unix" } ]
Neural Networks | A beginners guide
21 Apr, 2022 Neural networks are artificial systems that were inspired by biological neural networks. These systems learn to perform tasks by being exposed to various datasets and examples without any task-specific rules. The idea is that the system generates identifying characteristics from the data they have been passed without being programmed with a pre-programmed understanding of these datasets. Neural networks are based on computational models for threshold logic. Threshold logic is a combination of algorithms and mathematics. Neural networks are based either on the study of the brain or on the application of neural networks to artificial intelligence. The work has led to improvements in finite automata theory. Components of a typical neural network involve neurons, connections, weights, biases, propagation function, and a learning rule. Neurons will receive an input from predecessor neurons that have an activation , threshold , an activation function f, and an output function . Connections consist of connections, weights and biases which rules how neuron transfers output to neuron . Propagation computes the input and outputs the output and sums the predecessor neurons function with the weight. The learning rule modifies the weights and thresholds of the variables in the network. Supervised vs Unsupervised Learning:Neural networks learn via supervised learning; Supervised machine learning involves an input variable x and output variable y. The algorithm learns from a training dataset. With each correct answers, algorithms iteratively make predictions on the data. The learning stops when the algorithm reaches an acceptable level of performance.Unsupervised machine learning has input data X and no corresponding output variables. The goal is to model the underlying structure of the data for understanding more about the data. The keywords for supervised machine learning are classification and regression. For unsupervised machine learning, the keywords are clustering and association. Evolution of Neural Networks:Hebbian learning deals with neural plasticity. Hebbian learning is unsupervised and deals with long term potentiation. Hebbian learning deals with pattern recognition and exclusive-or circuits; deals with if-then rules. Back propagation solved the exclusive-or issue that Hebbian learning could not handle. This also allowed for multi-layer networks to be feasible and efficient. If an error was found, the error was solved at each layer by modifying the weights at each node. This led to the development of support vector machines, linear classifiers, and max-pooling. The vanishing gradient problem affects feedforward networks that use back propagation and recurrent neural network. This is known as deep-learning. Hardware-based designs are used for biophysical simulation and neurotrophic computing. They have large scale component analysis and convolution creates new class of neural computing with analog. This also solved back-propagation for many-layered feedforward neural networks. Convolutional networks are used for alternating between convolutional layers and max-pooling layers with connected layers (fully or sparsely connected) with a final classification layer. The learning is done without unsupervised pre-training. Each filter is equivalent to a weights vector that has to be trained. The shift variance has to be guaranteed to dealing with small and large neural networks. This is being resolved in Development Networks. There are seven types of neural networks that can be used. The first is a multilayer perceptron which has three or more layers and uses a nonlinear activation function. The second is the convolutional neural network that uses a variation of the multilayer perceptrons. The third is the recursive neural network that uses weights to make structured predictions. The fourth is a recurrent neural network that makes connections between the neurons in a directed cycle. The long short-term memory neural network uses the recurrent neural network architecture and does not use activation function. The final two are sequence to sequence modules which uses two recurrent networks and shallow neural networks which produces a vector space from an amount of text. These neural networks are applications of the basic neural network demonstrated below. For the example, the neural network will work with three vectors: a vector of attributes X, a vector of classes Y, and a vector of weights W. The code will use 100 iterations to fit the attributes to the classes. The predictions are generated, weighed, and then outputted after iterating through the vector of weights W. The neural network handles back propagation. Examples: Input : X { 2.6, 3.1, 3.0, 3.4, 2.1, 2.5, 2.6, 1.3, 4.9, 0.1, 0.3, 2.3,}; y {1, 1, 1}; W {0.3, 0.4, 0.6}; Output : 0.990628 0.984596 0.994117 Below is the implementations: import numpy as np # array of any amount of numbers. n = mX = np.array([[1, 2, 3], [3, 4, 1], [2, 5, 3]]) # multiplicationy = np.array([[.5, .3, .2]]) # transpose of yy = y.T # sigma valuesigm = 2 # find the deltadelt = np.random.random((3, 3)) - 1 for j in range(100): # find matrix 1. 100 layers. m1 = (y - (1/(1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt))))))*((1/( 1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt)))))*(1-(1/( 1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt))))))) # find matrix 2 m2 = m1.dot(delt.T) * ((1/(1 + np.exp(-(np.dot(X, sigm))))) * (1-(1/(1 + np.exp(-(np.dot(X, sigm))))))) # find delta delt = delt + (1/(1 + np.exp(-(np.dot(X, sigm))))).T.dot(m1) # find sigma sigm = sigm + (X.T.dot(m2)) # print output from the matrixprint(1/(1 + np.exp(-(np.dot(X, sigm))))) [[ 0.99999294 0.99999379 0.99999353] [ 0.99999987 0.99999989 0.99999988] [ 1. 1. 1. ]] Limitations:The neural network is for a supervised model. It does not handle unsupervised machine learning and does not cluster and associate data. It also lacks a level of accuracy that will be found in more computationally expensive neural network. Based on Andrew Trask’s neural network. Also, the neural network does not work with any matrices where X’s number of rows and columns do not match Y and W’s number of rows. The next steps would be to create an unsupervised neural network and to increase computational power for the supervised model with more iterations and threading. Resources: http://neuralnetworksanddeeplearning.com https://skymind.ai/wiki/neural-network http://pages.cs.wisc.edu/~bolo/shipyard/neural/local.html https://iamtrask.github.io/2015/07/12/basic-python-network/ Picked Technical Scripter 2018 Advanced Computer Subject Machine Learning Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Apr, 2022" }, { "code": null, "e": 443, "s": 52, "text": "Neural networks are artificial systems that were inspired by biological neural networks. These systems learn to perform tasks by being exposed to various datasets and examples without any task-specific rules. The idea is that the system generates identifying characteristics from the data they have been passed without being programmed with a pre-programmed understanding of these datasets." }, { "code": null, "e": 766, "s": 443, "text": "Neural networks are based on computational models for threshold logic. Threshold logic is a combination of algorithms and mathematics. Neural networks are based either on the study of the brain or on the application of neural networks to artificial intelligence. The work has led to improvements in finite automata theory." }, { "code": null, "e": 1348, "s": 766, "text": "Components of a typical neural network involve neurons, connections, weights, biases, propagation function, and a learning rule. Neurons will receive an input from predecessor neurons that have an activation , threshold , an activation function f, and an output function . Connections consist of connections, weights and biases which rules how neuron transfers output to neuron . Propagation computes the input and outputs the output and sums the predecessor neurons function with the weight. The learning rule modifies the weights and thresholds of the variables in the network." }, { "code": null, "e": 2061, "s": 1348, "text": "Supervised vs Unsupervised Learning:Neural networks learn via supervised learning; Supervised machine learning involves an input variable x and output variable y. The algorithm learns from a training dataset. With each correct answers, algorithms iteratively make predictions on the data. The learning stops when the algorithm reaches an acceptable level of performance.Unsupervised machine learning has input data X and no corresponding output variables. The goal is to model the underlying structure of the data for understanding more about the data. The keywords for supervised machine learning are classification and regression. For unsupervised machine learning, the keywords are clustering and association." }, { "code": null, "e": 2310, "s": 2061, "text": "Evolution of Neural Networks:Hebbian learning deals with neural plasticity. Hebbian learning is unsupervised and deals with long term potentiation. Hebbian learning deals with pattern recognition and exclusive-or circuits; deals with if-then rules." }, { "code": null, "e": 2808, "s": 2310, "text": "Back propagation solved the exclusive-or issue that Hebbian learning could not handle. This also allowed for multi-layer networks to be feasible and efficient. If an error was found, the error was solved at each layer by modifying the weights at each node. This led to the development of support vector machines, linear classifiers, and max-pooling. The vanishing gradient problem affects feedforward networks that use back propagation and recurrent neural network. This is known as deep-learning." }, { "code": null, "e": 3083, "s": 2808, "text": "Hardware-based designs are used for biophysical simulation and neurotrophic computing. They have large scale component analysis and convolution creates new class of neural computing with analog. This also solved back-propagation for many-layered feedforward neural networks." }, { "code": null, "e": 3533, "s": 3083, "text": "Convolutional networks are used for alternating between convolutional layers and max-pooling layers with connected layers (fully or sparsely connected) with a final classification layer. The learning is done without unsupervised pre-training. Each filter is equivalent to a weights vector that has to be trained. The shift variance has to be guaranteed to dealing with small and large neural networks. This is being resolved in Development Networks." }, { "code": null, "e": 3592, "s": 3533, "text": "There are seven types of neural networks that can be used." }, { "code": null, "e": 3702, "s": 3592, "text": "The first is a multilayer perceptron which has three or more layers and uses a nonlinear activation function." }, { "code": null, "e": 3802, "s": 3702, "text": "The second is the convolutional neural network that uses a variation of the multilayer perceptrons." }, { "code": null, "e": 3894, "s": 3802, "text": "The third is the recursive neural network that uses weights to make structured predictions." }, { "code": null, "e": 4126, "s": 3894, "text": "The fourth is a recurrent neural network that makes connections between the neurons in a directed cycle. The long short-term memory neural network uses the recurrent neural network architecture and does not use activation function." }, { "code": null, "e": 4376, "s": 4126, "text": "The final two are sequence to sequence modules which uses two recurrent networks and shallow neural networks which produces a vector space from an amount of text. These neural networks are applications of the basic neural network demonstrated below." }, { "code": null, "e": 4742, "s": 4376, "text": "For the example, the neural network will work with three vectors: a vector of attributes X, a vector of classes Y, and a vector of weights W. The code will use 100 iterations to fit the attributes to the classes. The predictions are generated, weighed, and then outputted after iterating through the vector of weights W. The neural network handles back propagation." }, { "code": null, "e": 4752, "s": 4742, "text": "Examples:" }, { "code": null, "e": 4912, "s": 4752, "text": "Input :\nX { 2.6, 3.1, 3.0,\n 3.4, 2.1, 2.5,\n 2.6, 1.3, 4.9, \n 0.1, 0.3, 2.3,};\ny {1, 1, 1};\nW {0.3, 0.4, 0.6}; \n\nOutput :\n0.990628 \n0.984596 \n0.994117 " }, { "code": null, "e": 4942, "s": 4912, "text": "Below is the implementations:" }, { "code": "import numpy as np # array of any amount of numbers. n = mX = np.array([[1, 2, 3], [3, 4, 1], [2, 5, 3]]) # multiplicationy = np.array([[.5, .3, .2]]) # transpose of yy = y.T # sigma valuesigm = 2 # find the deltadelt = np.random.random((3, 3)) - 1 for j in range(100): # find matrix 1. 100 layers. m1 = (y - (1/(1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt))))))*((1/( 1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt)))))*(1-(1/( 1 + np.exp(-(np.dot((1/(1 + np.exp( -(np.dot(X, sigm))))), delt))))))) # find matrix 2 m2 = m1.dot(delt.T) * ((1/(1 + np.exp(-(np.dot(X, sigm))))) * (1-(1/(1 + np.exp(-(np.dot(X, sigm))))))) # find delta delt = delt + (1/(1 + np.exp(-(np.dot(X, sigm))))).T.dot(m1) # find sigma sigm = sigm + (X.T.dot(m2)) # print output from the matrixprint(1/(1 + np.exp(-(np.dot(X, sigm)))))", "e": 6006, "s": 4942, "text": null }, { "code": null, "e": 6125, "s": 6006, "text": "[[ 0.99999294 0.99999379 0.99999353]\n [ 0.99999987 0.99999989 0.99999988]\n [ 1. 1. 1. ]]\n" }, { "code": null, "e": 6549, "s": 6125, "text": "Limitations:The neural network is for a supervised model. It does not handle unsupervised machine learning and does not cluster and associate data. It also lacks a level of accuracy that will be found in more computationally expensive neural network. Based on Andrew Trask’s neural network. Also, the neural network does not work with any matrices where X’s number of rows and columns do not match Y and W’s number of rows." }, { "code": null, "e": 6711, "s": 6549, "text": "The next steps would be to create an unsupervised neural network and to increase computational power for the supervised model with more iterations and threading." }, { "code": null, "e": 6722, "s": 6711, "text": "Resources:" }, { "code": null, "e": 6763, "s": 6722, "text": "http://neuralnetworksanddeeplearning.com" }, { "code": null, "e": 6802, "s": 6763, "text": "https://skymind.ai/wiki/neural-network" }, { "code": null, "e": 6860, "s": 6802, "text": "http://pages.cs.wisc.edu/~bolo/shipyard/neural/local.html" }, { "code": null, "e": 6920, "s": 6860, "text": "https://iamtrask.github.io/2015/07/12/basic-python-network/" }, { "code": null, "e": 6927, "s": 6920, "text": "Picked" }, { "code": null, "e": 6951, "s": 6927, "text": "Technical Scripter 2018" }, { "code": null, "e": 6977, "s": 6951, "text": "Advanced Computer Subject" }, { "code": null, "e": 6994, "s": 6977, "text": "Machine Learning" }, { "code": null, "e": 7013, "s": 6994, "text": "Technical Scripter" }, { "code": null, "e": 7030, "s": 7013, "text": "Machine Learning" } ]
OpenCV C++ Program to blur an image
20 Apr, 2022 The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) Compile command: g++ -w article.cpp -o article `pkg-config –libs opencv` (3) Run command: ./article (4) The image bat.jpg has to be in the same directory as the code. Before you run the code, please make sure that you have OpenCV installed on your system. // Title: OpenCV C++ Program to blur an image. // Import the core header file #include <opencv2/core/core.hpp> // core - a compact module defining basic data structures, // including the dense multi-dimensional array Mat and // basic functions used by all other modules. // highgui - an easy-to-use interface to video // capturing, image and video codecs, as well // as simple UI capabilities. #include <opencv2/highgui/highgui.hpp> // imgproc - an image processing module that // includes linear and non-linear image filtering, // geometrical image transformations (resize, affine // and perspective warping, generic table-based // remapping) color space conversion, histograms, // and so on. #include <opencv2/imgproc/imgproc.hpp> // The stdio.h header defines three variable types, // several macros, and various functions for performing // input and output. #include <stdio.h> #include <iostream> // Namespace where all the C++ OpenCV functionality resides using namespace cv; using namespace std; // We can also use 'namespace std' if need be. int main() // Main function { // read the image data in the file "MyPic.JPG" and // store it in 'img' Mat image = imread("bat.jpg", CV_LOAD_IMAGE_UNCHANGED); // Mat object is a basic image container. // imread: first argument denotes the image to be loaded // the second arguments specifies the image format. // CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as is // CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image as an // intensity one // CV_LOAD_IMAGE_COLOR (>0) loads the image in the // BGR format // If the second argument is not specified, it is // implied CV_LOAD_IMAGE_COLOR // Check for no data if (! image.data ) { cout << "Could not open or find the image.\n"; return -1; // unsuccessful } // Function to blur the image // first argument: input source // second argument: output source // third argument: blurring kernel size blur(image,image,Size(10,10)); // Create a window // first argument: name of the window // second argument: flag- types: // WINDOW_NORMAL If this is set, the user can resize the // window. // WINDOW_AUTOSIZE If this is set, the window size is // automatically adjusted to fit the // displayed image() ), and you cannot // change the window size manually. // WINDOW_OPENGL If this is set, the window will be // created with OpenGL support. namedWindow( "bat", CV_WINDOW_AUTOSIZE ); // Displays an image in the specified window. // first argument: name of the window // second argument: image to be shown(Mat object) imshow( "bat", image ); waitKey(0); // Wait infinite time for a keypress return 0; // Return from the main function } To Run the program in the Windows, VISUAL STUDIO you can use following approach: The idea is to first use a function called cvtColor to convert the input image into Grayscale image, then we will convert that Grayscale image to Blurred Image using a function GaussianBlur. SYNTAX: cvtColor(source_image, destination_image, code); GaussianBlur(source_image, destination_image, kernel-size, sigmaX); PARAMETERS: cvtColor is the in-built function in the C++ that is used to convert one color space(number of channels) to another using the color space conversion code. Color space conversion code are easily accessible and are pre-defined. You can learn more about them over here. GaussianBlur takes Grayscale image as input and returns a blurred image. Kernel size is used to define how much we want the kernel to affect the pixels in our image. Now kernel is the matrix of pixels in the image, so when we define kernel size it will first pickup an anchor(a center point) and then it will affect the pixels in its neighborhood. In a 3*3 matrix only the neighborhood pixel’s will be affected while in a 10*10 matrix will affect the pixels in range of 10*10 matrix from the center. SigmaX: A variable of the type double representing the Gaussian kernel standard deviation in X direction. Implementation of the above approach. C++ #include <iostream>#include <opencv2/highgui.hpp>#include <opencv2/imgcodecs.hpp>#include <opencv2/imgproc.hpp> using namespace std;using namespace cv; void main() // we can use int main as well just don't forget // to add return 0 in the end{ string path = "Resources/face.jpeg"; Mat img = imread(path); Mat imgGray, Blur_img; //Defining Output Image matrix cvtColor(img, imgGray, COLOR_BGR2GRAY); // To convert image to // grayscale image GaussianBlur(img, Blur_img, Size(7, 7), 5, 0); // Now finally adding blur to the image imshow("Image", img); // Image before the conversion imshow("GrayImage",imgGray); // After Conversion to GrayScale imshow("Blurimg", Blur_img); // Blurred Image waitKey(0); // wait for keystroke} OUTPUT: Original image GrayScale Image: GrayImage Blur Image: Blurred Image OpenCV Python Program to Blur Image About the Author: Aditya Prakash is an undergraduate student at Indian Institute of Information Technology, Vadodara. He primarily codes in C++. The motto for him is: So far so good. He plays cricket, watches superhero movies, football and is a big fan of answering questions. If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. codex47 sweetyty Image-Processing C++ Project CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Apr, 2022" }, { "code": null, "e": 481, "s": 54, "text": "The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) Compile command: g++ -w article.cpp -o article `pkg-config –libs opencv` (3) Run command: ./article (4) The image bat.jpg has to be in the same directory as the code. Before you run the code, please make sure that you have OpenCV installed on your system. " }, { "code": null, "e": 3441, "s": 481, "text": "// Title: OpenCV C++ Program to blur an image.\n// Import the core header file\n#include <opencv2/core/core.hpp> \n\n// core - a compact module defining basic data structures,\n// including the dense multi-dimensional array Mat and \n// basic functions used by all other modules.\n\n// highgui - an easy-to-use interface to video \n// capturing, image and video codecs, as well\n// as simple UI capabilities.\n#include <opencv2/highgui/highgui.hpp>\n\n// imgproc - an image processing module that \n// includes linear and non-linear image filtering,\n// geometrical image transformations (resize, affine\n// and perspective warping, generic table-based \n// remapping) color space conversion, histograms, \n// and so on.\n#include <opencv2/imgproc/imgproc.hpp>\n\n// The stdio.h header defines three variable types, \n// several macros, and various functions for performing\n// input and output.\n#include <stdio.h>\n#include <iostream>\n\n// Namespace where all the C++ OpenCV functionality resides\nusing namespace cv;\n\nusing namespace std;\n\n// We can also use 'namespace std' if need be.\n\nint main() // Main function\n{\n // read the image data in the file \"MyPic.JPG\" and \n // store it in 'img'\n Mat image = imread(\"bat.jpg\", CV_LOAD_IMAGE_UNCHANGED); \n \n // Mat object is a basic image container.\n // imread: first argument denotes the image to be loaded\n // the second arguments specifies the image format.\n // CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as is\n // CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image as an\n // intensity one\n // CV_LOAD_IMAGE_COLOR (>0) loads the image in the \n // BGR format\n // If the second argument is not specified, it is \n // implied CV_LOAD_IMAGE_COLOR\n\n // Check for no data\n if (! image.data ) \n {\n cout << \"Could not open or find the image.\\n\";\n return -1; // unsuccessful\n }\n \n // Function to blur the image\n // first argument: input source\n // second argument: output source\n // third argument: blurring kernel size\n blur(image,image,Size(10,10)); \n\n // Create a window\n // first argument: name of the window\n // second argument: flag- types:\n // WINDOW_NORMAL If this is set, the user can resize the \n // window.\n // WINDOW_AUTOSIZE If this is set, the window size is \n // automatically adjusted to fit the \n // displayed image() ), and you cannot \n // change the window size manually.\n // WINDOW_OPENGL If this is set, the window will be\n // created with OpenGL support.\n namedWindow( \"bat\", CV_WINDOW_AUTOSIZE ); \n\n // Displays an image in the specified window.\n // first argument: name of the window\n // second argument: image to be shown(Mat object)\n imshow( \"bat\", image ); \n\n waitKey(0); // Wait infinite time for a keypress\n \n return 0; // Return from the main function\n}" }, { "code": null, "e": 3524, "s": 3441, "text": " To Run the program in the Windows, VISUAL STUDIO you can use following approach:" }, { "code": null, "e": 3716, "s": 3524, "text": "The idea is to first use a function called cvtColor to convert the input image into Grayscale image, then we will convert that Grayscale image to Blurred Image using a function GaussianBlur." }, { "code": null, "e": 3726, "s": 3716, "text": "SYNTAX: " }, { "code": null, "e": 3775, "s": 3726, "text": "cvtColor(source_image, destination_image, code);" }, { "code": null, "e": 3843, "s": 3775, "text": "GaussianBlur(source_image, destination_image, kernel-size, sigmaX);" }, { "code": null, "e": 3855, "s": 3843, "text": "PARAMETERS:" }, { "code": null, "e": 4122, "s": 3855, "text": "cvtColor is the in-built function in the C++ that is used to convert one color space(number of channels) to another using the color space conversion code. Color space conversion code are easily accessible and are pre-defined. You can learn more about them over here." }, { "code": null, "e": 4197, "s": 4122, "text": "GaussianBlur takes Grayscale image as input and returns a blurred image. " }, { "code": null, "e": 4624, "s": 4197, "text": "Kernel size is used to define how much we want the kernel to affect the pixels in our image. Now kernel is the matrix of pixels in the image, so when we define kernel size it will first pickup an anchor(a center point) and then it will affect the pixels in its neighborhood. In a 3*3 matrix only the neighborhood pixel’s will be affected while in a 10*10 matrix will affect the pixels in range of 10*10 matrix from the center." }, { "code": null, "e": 4730, "s": 4624, "text": "SigmaX: A variable of the type double representing the Gaussian kernel standard deviation in X direction." }, { "code": null, "e": 4768, "s": 4730, "text": "Implementation of the above approach." }, { "code": null, "e": 4772, "s": 4768, "text": "C++" }, { "code": "#include <iostream>#include <opencv2/highgui.hpp>#include <opencv2/imgcodecs.hpp>#include <opencv2/imgproc.hpp> using namespace std;using namespace cv; void main() // we can use int main as well just don't forget // to add return 0 in the end{ string path = \"Resources/face.jpeg\"; Mat img = imread(path); Mat imgGray, Blur_img; //Defining Output Image matrix cvtColor(img, imgGray, COLOR_BGR2GRAY); // To convert image to // grayscale image GaussianBlur(img, Blur_img, Size(7, 7), 5, 0); // Now finally adding blur to the image imshow(\"Image\", img); // Image before the conversion imshow(\"GrayImage\",imgGray); // After Conversion to GrayScale imshow(\"Blurimg\", Blur_img); // Blurred Image waitKey(0); // wait for keystroke}", "e": 5599, "s": 4772, "text": null }, { "code": null, "e": 5607, "s": 5599, "text": "OUTPUT:" }, { "code": null, "e": 5622, "s": 5607, "text": "Original image" }, { "code": null, "e": 5639, "s": 5622, "text": "GrayScale Image:" }, { "code": null, "e": 5649, "s": 5639, "text": "GrayImage" }, { "code": null, "e": 5661, "s": 5649, "text": "Blur Image:" }, { "code": null, "e": 5675, "s": 5661, "text": "Blurred Image" }, { "code": null, "e": 5713, "s": 5675, "text": "OpenCV Python Program to Blur Image " }, { "code": null, "e": 5732, "s": 5713, "text": "About the Author: " }, { "code": null, "e": 5798, "s": 5734, "text": "Aditya Prakash is an undergraduate student at Indian Institute " }, { "code": null, "e": 5994, "s": 5798, "text": "of Information Technology, Vadodara. He primarily codes in C++. The motto for him is: So far so good. He plays cricket, watches superhero movies, football and is a big fan of answering questions." }, { "code": null, "e": 6099, "s": 5996, "text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks." }, { "code": null, "e": 6110, "s": 6102, "text": "codex47" }, { "code": null, "e": 6119, "s": 6110, "text": "sweetyty" }, { "code": null, "e": 6136, "s": 6119, "text": "Image-Processing" }, { "code": null, "e": 6140, "s": 6136, "text": "C++" }, { "code": null, "e": 6148, "s": 6140, "text": "Project" }, { "code": null, "e": 6152, "s": 6148, "text": "CPP" }, { "code": null, "e": 6250, "s": 6152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6293, "s": 6250, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6327, "s": 6293, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 6352, "s": 6327, "text": "unordered_map in C++ STL" }, { "code": null, "e": 6406, "s": 6352, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6430, "s": 6406, "text": "Sorting a vector in C++" }, { "code": null, "e": 6479, "s": 6430, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6534, "s": 6479, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 6567, "s": 6534, "text": "Working with zip files in Python" }, { "code": null, "e": 6589, "s": 6567, "text": "XML parsing in Python" } ]
Why is iterating over a dictionary slow in Python?
22 Jul, 2021 In this article, we are going to discuss why is iterating over a dict so slow in Python? Before coming to any conclusion lets have a look at the performance difference between NumPy arrays and dictionaries in python: Python # import modulesimport numpy as npimport sys # compute numpy performancedef np_performance(): array = np.empty(100000000) for i in range(100000000): array[i] = i print("SIZE : ", sys.getsizeof(array)/1024.0**2, "MiB") # compute dictionary performancedef dict_performance(): dic = dict() for i in range(100000000): dic[i] = i print("SIZE : ", sys.getsizeof(dic)/1024.0**2, "MiB") In the above Python Script we have two functions : np_performance: This function creates an empty NumPy array for 10,00,000 elements and iterates over the entire array updating individual element’s value to the iterator location (‘i’ in this case)dict_performance: This function creates an empty Dictionary for 10,00,000 elements and iterates over the entire dictionary updating individual element’s value to the iterator location (‘i’ in this case) np_performance: This function creates an empty NumPy array for 10,00,000 elements and iterates over the entire array updating individual element’s value to the iterator location (‘i’ in this case) dict_performance: This function creates an empty Dictionary for 10,00,000 elements and iterates over the entire dictionary updating individual element’s value to the iterator location (‘i’ in this case) And finally, a sys.getsizeof() function call to calculate the memory usage by respective data structures. Now we call both these functions, and to measure the time taken by each function we use %time function which gives us the Time execution of a Python statement or expression. %time function can be used both as a line and cell magic: In the inline mode, you can time a single-line statement (though multiple ones can be chained using semicolons).In cell mode, you can time the cell body (a directly following statement raises an error). In the inline mode, you can time a single-line statement (though multiple ones can be chained using semicolons). In cell mode, you can time the cell body (a directly following statement raises an error). Calling these functions from inline mode using %time method : Python3 # compute time taken%time np_performance() Output: Python3 # compute time taken%time dict_performance() Output: As we can see there is quite a difference in Wall time between iterating on a NumPy array and a python dictionary. This difference in performance is due to the internal working differences between arrays and dictionaries as after Python 3.6, Dictionaries in python are based on a hybrid of HashTables and an array of elements. So whenever we take out/delete an entry from the dictionary, rather than deleting a key from that particular location, it allows the next key to be replaced by deleted key’s position. What python dictionary does is replace the value from the hash array with a dummy value representing null. So upon traversing when you encounter these dummy null values it keeps on iterating till it finds the next real-valued key. Since there may be lots of empty spaces we’ll be traversing on without any real benefits and hence Dictionaries are generally slower than their array/list counterparts. For large-sized Datasets, memory access would be the bottleneck. Dictionaries are mutable, and take up more memory than arrays or (named) tuples (when organized efficiently, not duplicating type information). Picked python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 245, "s": 28, "text": "In this article, we are going to discuss why is iterating over a dict so slow in Python? Before coming to any conclusion lets have a look at the performance difference between NumPy arrays and dictionaries in python:" }, { "code": null, "e": 252, "s": 245, "text": "Python" }, { "code": "# import modulesimport numpy as npimport sys # compute numpy performancedef np_performance(): array = np.empty(100000000) for i in range(100000000): array[i] = i print(\"SIZE : \", sys.getsizeof(array)/1024.0**2, \"MiB\") # compute dictionary performancedef dict_performance(): dic = dict() for i in range(100000000): dic[i] = i print(\"SIZE : \", sys.getsizeof(dic)/1024.0**2, \"MiB\")", "e": 705, "s": 252, "text": null }, { "code": null, "e": 756, "s": 705, "text": "In the above Python Script we have two functions :" }, { "code": null, "e": 1155, "s": 756, "text": "np_performance: This function creates an empty NumPy array for 10,00,000 elements and iterates over the entire array updating individual element’s value to the iterator location (‘i’ in this case)dict_performance: This function creates an empty Dictionary for 10,00,000 elements and iterates over the entire dictionary updating individual element’s value to the iterator location (‘i’ in this case)" }, { "code": null, "e": 1352, "s": 1155, "text": "np_performance: This function creates an empty NumPy array for 10,00,000 elements and iterates over the entire array updating individual element’s value to the iterator location (‘i’ in this case)" }, { "code": null, "e": 1555, "s": 1352, "text": "dict_performance: This function creates an empty Dictionary for 10,00,000 elements and iterates over the entire dictionary updating individual element’s value to the iterator location (‘i’ in this case)" }, { "code": null, "e": 1661, "s": 1555, "text": "And finally, a sys.getsizeof() function call to calculate the memory usage by respective data structures." }, { "code": null, "e": 1893, "s": 1661, "text": "Now we call both these functions, and to measure the time taken by each function we use %time function which gives us the Time execution of a Python statement or expression. %time function can be used both as a line and cell magic:" }, { "code": null, "e": 2096, "s": 1893, "text": "In the inline mode, you can time a single-line statement (though multiple ones can be chained using semicolons).In cell mode, you can time the cell body (a directly following statement raises an error)." }, { "code": null, "e": 2209, "s": 2096, "text": "In the inline mode, you can time a single-line statement (though multiple ones can be chained using semicolons)." }, { "code": null, "e": 2300, "s": 2209, "text": "In cell mode, you can time the cell body (a directly following statement raises an error)." }, { "code": null, "e": 2362, "s": 2300, "text": "Calling these functions from inline mode using %time method :" }, { "code": null, "e": 2370, "s": 2362, "text": "Python3" }, { "code": "# compute time taken%time np_performance()", "e": 2413, "s": 2370, "text": null }, { "code": null, "e": 2421, "s": 2413, "text": "Output:" }, { "code": null, "e": 2429, "s": 2421, "text": "Python3" }, { "code": "# compute time taken%time dict_performance()", "e": 2474, "s": 2429, "text": null }, { "code": null, "e": 2482, "s": 2474, "text": "Output:" }, { "code": null, "e": 2597, "s": 2482, "text": "As we can see there is quite a difference in Wall time between iterating on a NumPy array and a python dictionary." }, { "code": null, "e": 3224, "s": 2597, "text": "This difference in performance is due to the internal working differences between arrays and dictionaries as after Python 3.6, Dictionaries in python are based on a hybrid of HashTables and an array of elements. So whenever we take out/delete an entry from the dictionary, rather than deleting a key from that particular location, it allows the next key to be replaced by deleted key’s position. What python dictionary does is replace the value from the hash array with a dummy value representing null. So upon traversing when you encounter these dummy null values it keeps on iterating till it finds the next real-valued key." }, { "code": null, "e": 3393, "s": 3224, "text": "Since there may be lots of empty spaces we’ll be traversing on without any real benefits and hence Dictionaries are generally slower than their array/list counterparts." }, { "code": null, "e": 3602, "s": 3393, "text": "For large-sized Datasets, memory access would be the bottleneck. Dictionaries are mutable, and take up more memory than arrays or (named) tuples (when organized efficiently, not duplicating type information)." }, { "code": null, "e": 3609, "s": 3602, "text": "Picked" }, { "code": null, "e": 3621, "s": 3609, "text": "python-dict" }, { "code": null, "e": 3628, "s": 3621, "text": "Python" }, { "code": null, "e": 3640, "s": 3628, "text": "python-dict" } ]
Program for cube sum of first n natural numbers
22 Jun, 2022 Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples : Input : n = 5 Output : 225 13 + 23 + 33 + 43 + 53 = 225 Input : n = 7 Output : 784 13 + 23 + 33 + 43 + 53 + 63 + 73 = 784 A simple solution is to one by one add terms. C++ Java Python3 C# PHP Javascript // Simple C++ program to find sum of series// with cubes of first n natural numbers#include <iostream>using namespace std; /* Returns the sum of series */int sumOfSeries(int n){ int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;} // Simple Java program to find sum of series// with cubes of first n natural numbers import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> # Simple Python program to find sum of series# with cubes of first n natural numbers # Returns the sum of seriesdef sumOfSeries(n): sum = 0 for i in range(1, n + 1): sum += i * i*i return sum # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)> // Simple C# program to find sum of series// with cubes of first n natural numbersusing System; class GFG { /* Returns the sum of series */ static int sumOfSeries(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum; } // Driver Function public static void Main() { int n = 5; Console.Write(sumOfSeries(n)); }}// This code is contributed by// Smitha Dinesh Semwal <?php// Simple PHP program to find sum of series// with cubes of first n natural numbers // Returns the sum of seriesfunction sumOfSeries( $n){ $sum = 0; for ($x = 1; $x <= $n; $x++) $sum += $x * $x * $x; return $sum;} // Driver code$n = 5;echo sumOfSeries($n); // This Code is contributed by vt_m.?> <script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ let sum = 0; for (let x = 1; x <= n; x++) sum += x * x * x; return sum;} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code contributed by aashish1995 </script> Output : 225 Time Complexity: O(n) Auxiliary Space: O(1)An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 For n = 5 sum by formula is (5*(5 + 1 ) / 2)) ^ 2 = (5*6/2) ^ 2 = (15) ^ 2 = 225 For n = 7, sum by formula is (7*(7 + 1 ) / 2)) ^ 2 = (7*8/2) ^ 2 = (28) ^ 2 = 784 C++ Java Python3 C# PHP Javascript // A formula based C++ program to find sum// of series with cubes of first n natural// numbers#include <iostream>using namespace std; int sumOfSeries(int n){ int x = (n * (n + 1) / 2); return x * x;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;} // A formula based Java program to find sum// of series with cubes of first n natural// numbers import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> # A formula based Python program to find sum# of series with cubes of first n natural# numbers # Returns the sum of seriesdef sumOfSeries(n): x = (n * (n + 1) / 2) return (int)(x * x) # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)> // A formula based C# program to// find sum of series with cubes// of first n natural numbersusing System; class GFG { // Returns the sum of series public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void Main() { int n = 5; Console.Write(sumOfSeries(n)); }} // Code Contributed by nitin mittal. <?php// A formula based PHP program to find sum// of series with cubes of first n natural// numbers function sumOfSeries($n){ $x = ($n * ($n + 1) / 2); return $x * $x;} // Driver Function$n = 5;echo sumOfSeries($n); // This code is contributed by vt_m.?> <script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ x = (n * (n + 1) / 2) return (x * x)} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code is contributed by sravan kumar </script> Output: 225 Time Complexity: O(1) Auxiliary Space: O(1)How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. Let the formula be true for n = k-1. Sum of first (k-1) natural numbers = [((k - 1) * k)/2]2 Sum of first k natural numbers = = Sum of (k-1) numbers + k3 = [((k - 1) * k)/2]2 + k3 = [k2(k2 - 2k + 1) + 4k3]/4 = [k4 + 2k3 + k2]/4 = k2(k2 + 2k + 1)/4 = [k*(k+1)/2]2 The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. C++ Java Python3 C# PHP Javascript // Efficient CPP program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be with in// limits.#include <iostream>using namespace std; // Returns sum of first n natural// numbersint sumOfSeries(int n){ int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x;} // Driver codeint main(){ int n = 5; cout << sumOfSeries(n); return 0;} // Efficient Java program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be with in// limits.import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }}// Code Contributed by Mohit Gupta_OMG <(0_o)> # Efficient Python program to find sum of cubes# of first n natural numbers that avoids# overflow if result is going to be with in# limits. # Returns the sum of seriesdef sumOfSeries(n): x = 0 if n % 2 == 0 : x = (n / 2) * (n + 1) else: x = ((n + 1) / 2) * n return (int)(x * x) # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)> // Efficient C# program to find sum of// cubes of first n natural numbers// that avoids overflow if result is// going to be with in limits.using System; class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x; } // Driver code static public void Main () { int n = 5; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by Ajit. <?php// Efficient PHP program to// find sum of cubes of first // n natural numbers that avoids// overflow if result is going// to be with in limits. // Returns sum of first n// natural numbersfunction sumOfSeries($n){ $x; if ($n % 2 == 0) $x = ($n / 2) * ($n + 1); else $x = (($n + 1) / 2) * $n; return $x * $x;} // Driver code$n = 5;echo sumOfSeries($n); // This code is contributed by vt_m.?> <script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ x=0 if (n % 2 == 0) x = (n / 2) * (n + 1) else x = ((n + 1) / 2) * n return (x * x)} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code contributed by sravan </script> Output: 225 Time complexity: O(1) since performing constant operations Auxiliary Space: O(1)This article is contributed by R_Raj. 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. Smitha Dinesh Semwal nitin mittal jit_t vt_m aashish1995 sravankumar8128 surinderdawra388 kumargaurav97520 maths-cube number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 136, "s": 52, "text": "Print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term.Examples : " }, { "code": null, "e": 260, "s": 136, "text": "Input : n = 5\nOutput : 225\n13 + 23 + 33 + 43 + 53 = 225\n\nInput : n = 7\nOutput : 784\n13 + 23 + 33 + 43 + 53 + \n63 + 73 = 784" }, { "code": null, "e": 310, "s": 262, "text": "A simple solution is to one by one add terms. " }, { "code": null, "e": 314, "s": 310, "text": "C++" }, { "code": null, "e": 319, "s": 314, "text": "Java" }, { "code": null, "e": 327, "s": 319, "text": "Python3" }, { "code": null, "e": 330, "s": 327, "text": "C#" }, { "code": null, "e": 334, "s": 330, "text": "PHP" }, { "code": null, "e": 345, "s": 334, "text": "Javascript" }, { "code": "// Simple C++ program to find sum of series// with cubes of first n natural numbers#include <iostream>using namespace std; /* Returns the sum of series */int sumOfSeries(int n){ int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;}", "e": 697, "s": 345, "text": null }, { "code": "// Simple Java program to find sum of series// with cubes of first n natural numbers import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 1206, "s": 697, "text": null }, { "code": "# Simple Python program to find sum of series# with cubes of first n natural numbers # Returns the sum of seriesdef sumOfSeries(n): sum = 0 for i in range(1, n + 1): sum += i * i*i return sum # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 1515, "s": 1206, "text": null }, { "code": "// Simple C# program to find sum of series// with cubes of first n natural numbersusing System; class GFG { /* Returns the sum of series */ static int sumOfSeries(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum += x * x * x; return sum; } // Driver Function public static void Main() { int n = 5; Console.Write(sumOfSeries(n)); }}// This code is contributed by// Smitha Dinesh Semwal", "e": 1977, "s": 1515, "text": null }, { "code": "<?php// Simple PHP program to find sum of series// with cubes of first n natural numbers // Returns the sum of seriesfunction sumOfSeries( $n){ $sum = 0; for ($x = 1; $x <= $n; $x++) $sum += $x * $x * $x; return $sum;} // Driver code$n = 5;echo sumOfSeries($n); // This Code is contributed by vt_m.?>", "e": 2294, "s": 1977, "text": null }, { "code": "<script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ let sum = 0; for (let x = 1; x <= n; x++) sum += x * x * x; return sum;} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code contributed by aashish1995 </script>", "e": 2660, "s": 2294, "text": null }, { "code": null, "e": 2670, "s": 2660, "text": "Output : " }, { "code": null, "e": 2674, "s": 2670, "text": "225" }, { "code": null, "e": 2696, "s": 2674, "text": "Time Complexity: O(n)" }, { "code": null, "e": 2810, "s": 2696, "text": "Auxiliary Space: O(1)An efficient solution is to use direct mathematical formula which is (n ( n + 1 ) / 2) ^ 2 " }, { "code": null, "e": 3048, "s": 2810, "text": "For n = 5 sum by formula is\n (5*(5 + 1 ) / 2)) ^ 2\n = (5*6/2) ^ 2\n = (15) ^ 2\n = 225\n\nFor n = 7, sum by formula is\n (7*(7 + 1 ) / 2)) ^ 2\n = (7*8/2) ^ 2\n = (28) ^ 2\n = 784" }, { "code": null, "e": 3054, "s": 3050, "text": "C++" }, { "code": null, "e": 3059, "s": 3054, "text": "Java" }, { "code": null, "e": 3067, "s": 3059, "text": "Python3" }, { "code": null, "e": 3070, "s": 3067, "text": "C#" }, { "code": null, "e": 3074, "s": 3070, "text": "PHP" }, { "code": null, "e": 3085, "s": 3074, "text": "Javascript" }, { "code": "// A formula based C++ program to find sum// of series with cubes of first n natural// numbers#include <iostream>using namespace std; int sumOfSeries(int n){ int x = (n * (n + 1) / 2); return x * x;} // Driver Functionint main(){ int n = 5; cout << sumOfSeries(n); return 0;}", "e": 3376, "s": 3085, "text": null }, { "code": "// A formula based Java program to find sum// of series with cubes of first n natural// numbers import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 3847, "s": 3376, "text": null }, { "code": "# A formula based Python program to find sum# of series with cubes of first n natural# numbers # Returns the sum of seriesdef sumOfSeries(n): x = (n * (n + 1) / 2) return (int)(x * x) # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 4131, "s": 3847, "text": null }, { "code": "// A formula based C# program to// find sum of series with cubes// of first n natural numbersusing System; class GFG { // Returns the sum of series public static int sumOfSeries(int n) { int x = (n * (n + 1) / 2); return x * x; } // Driver Function public static void Main() { int n = 5; Console.Write(sumOfSeries(n)); }} // Code Contributed by nitin mittal.", "e": 4558, "s": 4131, "text": null }, { "code": "<?php// A formula based PHP program to find sum// of series with cubes of first n natural// numbers function sumOfSeries($n){ $x = ($n * ($n + 1) / 2); return $x * $x;} // Driver Function$n = 5;echo sumOfSeries($n); // This code is contributed by vt_m.?>", "e": 4819, "s": 4558, "text": null }, { "code": "<script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ x = (n * (n + 1) / 2) return (x * x)} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code is contributed by sravan kumar </script>", "e": 5142, "s": 4819, "text": null }, { "code": null, "e": 5152, "s": 5142, "text": "Output: " }, { "code": null, "e": 5156, "s": 5152, "text": "225" }, { "code": null, "e": 5178, "s": 5156, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5381, "s": 5178, "text": "Auxiliary Space: O(1)How does this formula work? We can prove the formula using mathematical induction. We can easily see that the formula holds true for n = 1 and n = 2. Let this be true for n = k-1. " }, { "code": null, "e": 5719, "s": 5381, "text": "Let the formula be true for n = k-1.\nSum of first (k-1) natural numbers = \n [((k - 1) * k)/2]2\n\nSum of first k natural numbers = \n = Sum of (k-1) numbers + k3\n = [((k - 1) * k)/2]2 + k3\n = [k2(k2 - 2k + 1) + 4k3]/4\n = [k4 + 2k3 + k2]/4\n = k2(k2 + 2k + 1)/4\n = [k*(k+1)/2]2" }, { "code": null, "e": 5884, "s": 5719, "text": "The above program causes overflow, even if result is not beyond integer limit. Like previous post, we can avoid overflow upto some extent by doing division first. " }, { "code": null, "e": 5888, "s": 5884, "text": "C++" }, { "code": null, "e": 5893, "s": 5888, "text": "Java" }, { "code": null, "e": 5901, "s": 5893, "text": "Python3" }, { "code": null, "e": 5904, "s": 5901, "text": "C#" }, { "code": null, "e": 5908, "s": 5904, "text": "PHP" }, { "code": null, "e": 5919, "s": 5908, "text": "Javascript" }, { "code": "// Efficient CPP program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be with in// limits.#include <iostream>using namespace std; // Returns sum of first n natural// numbersint sumOfSeries(int n){ int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x;} // Driver codeint main(){ int n = 5; cout << sumOfSeries(n); return 0;}", "e": 6362, "s": 5919, "text": null }, { "code": "// Efficient Java program to find sum of cubes// of first n natural numbers that avoids// overflow if result is going to be with in// limits.import java.util.*;import java.lang.*;class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x; } // Driver Function public static void main(String[] args) { int n = 5; System.out.println(sumOfSeries(n)); }}// Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 6959, "s": 6362, "text": null }, { "code": "# Efficient Python program to find sum of cubes# of first n natural numbers that avoids# overflow if result is going to be with in# limits. # Returns the sum of seriesdef sumOfSeries(n): x = 0 if n % 2 == 0 : x = (n / 2) * (n + 1) else: x = ((n + 1) / 2) * n return (int)(x * x) # Driver Functionn = 5print(sumOfSeries(n)) # Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 7365, "s": 6959, "text": null }, { "code": "// Efficient C# program to find sum of// cubes of first n natural numbers// that avoids overflow if result is// going to be with in limits.using System; class GFG { /* Returns the sum of series */ public static int sumOfSeries(int n) { int x; if (n % 2 == 0) x = (n / 2) * (n + 1); else x = ((n + 1) / 2) * n; return x * x; } // Driver code static public void Main () { int n = 5; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by Ajit.", "e": 7919, "s": 7365, "text": null }, { "code": "<?php// Efficient PHP program to// find sum of cubes of first // n natural numbers that avoids// overflow if result is going// to be with in limits. // Returns sum of first n// natural numbersfunction sumOfSeries($n){ $x; if ($n % 2 == 0) $x = ($n / 2) * ($n + 1); else $x = (($n + 1) / 2) * $n; return $x * $x;} // Driver code$n = 5;echo sumOfSeries($n); // This code is contributed by vt_m.?>", "e": 8340, "s": 7919, "text": null }, { "code": "<script> // Simple javascript program to find sum of series// with cubes of first n natural numbers /* Returns the sum of series */function sumOfSeries( n){ x=0 if (n % 2 == 0) x = (n / 2) * (n + 1) else x = ((n + 1) / 2) * n return (x * x)} // Driven Program let n = 5; document.write(sumOfSeries(n)); // This code contributed by sravan </script>", "e": 8728, "s": 8340, "text": null }, { "code": null, "e": 8738, "s": 8728, "text": "Output: " }, { "code": null, "e": 8742, "s": 8738, "text": "225" }, { "code": null, "e": 8801, "s": 8742, "text": "Time complexity: O(1) since performing constant operations" }, { "code": null, "e": 9236, "s": 8801, "text": "Auxiliary Space: O(1)This article is contributed by R_Raj. 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": 9257, "s": 9236, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 9270, "s": 9257, "text": "nitin mittal" }, { "code": null, "e": 9276, "s": 9270, "text": "jit_t" }, { "code": null, "e": 9281, "s": 9276, "text": "vt_m" }, { "code": null, "e": 9293, "s": 9281, "text": "aashish1995" }, { "code": null, "e": 9309, "s": 9293, "text": "sravankumar8128" }, { "code": null, "e": 9326, "s": 9309, "text": "surinderdawra388" }, { "code": null, "e": 9343, "s": 9326, "text": "kumargaurav97520" }, { "code": null, "e": 9354, "s": 9343, "text": "maths-cube" }, { "code": null, "e": 9368, "s": 9354, "text": "number-theory" }, { "code": null, "e": 9381, "s": 9368, "text": "Mathematical" }, { "code": null, "e": 9395, "s": 9381, "text": "number-theory" }, { "code": null, "e": 9408, "s": 9395, "text": "Mathematical" } ]
Python program to check whether the string is Symmetrical or Palindrome
25 Sep, 2021 Given a string. the task is to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a string appears same when read forward or backward. Example: Input: khokho Output: The entered string is symmetrical The entered string is not palindrome Input:amaama Output: The entered string is symmetrical The entered string is palindrome Approach 1: The approach is very naive. In the case of palindrome, a loop is run to the mid of the string and the first and last characters are matched. If the characters are not similar then the loop breaks and the string is not palindrome otherwise the string is a palindrome. In the case of symmetry, if the string length is even then the string is broken into two halves and the loop is run, checking the characters of the strings of both the half. If the characters are not similar then the loops break and the string is not symmetrical otherwise the string is symmetrical. If the string length is odd then the string is broken into two halves in such a way that the middle element is left unchecked, and the above same step is repeated. Below is the implementation. Python3 # Python program to demonstrate# symmetry and palindrome of the# string # Function to check whether the# string is palindrome or notdef palindrome(a): # finding the mid, start # and last index of the string mid = (len(a)-1)//2 #you can remove the -1 or you add <= sign in line 21 start = 0 #so that you can compare the middle elements also. last = len(a)-1 flag = 0 # A loop till the mid of the # string while(start <= mid): # comparing letters from right # from the letters from left if (a[start]== a[last]): start += 1 last -= 1 else: flag = 1 break; # Checking the flag variable to # check if the string is palindrome # or not if flag == 0: print("The entered string is palindrome") else: print("The entered string is not palindrome") # Function to check whether the# string is symmetrical or not def symmetry(a): n = len(a) flag = 0 # Check if the string's length # is odd or even if n%2: mid = n//2 +1 else: mid = n//2 start1 = 0 start2 = mid while(start1 < mid and start2 < n): if (a[start1]== a[start2]): start1 = start1 + 1 start2 = start2 + 1 else: flag = 1 break # Checking the flag variable to # check if the string is symmetrical # or not if flag == 0: print("The entered string is symmetrical") else: print("The entered string is not symmetrical") # Driver codestring = 'amaama'palindrome(string)symmetry(string) The entered string is palindrome The entered string is symmetrical Approach 2: We use slicing in this method. Python3 string = 'amaama'half = int(len(string) / 2) if len(string) % 2 == 0: # even first_str = string[:half] second_str = string[half:]else: # odd first_str = string[:half] second_str = string[half+1:] # symmetricif first_str == second_str: print(string, 'string is symmertical')else: print(string, 'string is not symmertical') # palindromeif first_str == second_str[::-1]: # ''.join(reversed(second_str)) [slower] print(string, 'string is palindrome')else: print(string, 'string is not palindrome') amaama string is symmertical amaama string is palindrome anjali pardeshi sumitgumber28 aashishpaliwal1999 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Sep, 2021" }, { "code": null, "e": 387, "s": 52, "text": "Given a string. the task is to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a string appears same when read forward or backward." }, { "code": null, "e": 397, "s": 387, "text": "Example: " }, { "code": null, "e": 580, "s": 397, "text": "Input: khokho\nOutput: \nThe entered string is symmetrical\nThe entered string is not palindrome\n\nInput:amaama\nOutput:\nThe entered string is symmetrical\nThe entered string is palindrome" }, { "code": null, "e": 1323, "s": 580, "text": "Approach 1: The approach is very naive. In the case of palindrome, a loop is run to the mid of the string and the first and last characters are matched. If the characters are not similar then the loop breaks and the string is not palindrome otherwise the string is a palindrome. In the case of symmetry, if the string length is even then the string is broken into two halves and the loop is run, checking the characters of the strings of both the half. If the characters are not similar then the loops break and the string is not symmetrical otherwise the string is symmetrical. If the string length is odd then the string is broken into two halves in such a way that the middle element is left unchecked, and the above same step is repeated." }, { "code": null, "e": 1352, "s": 1323, "text": "Below is the implementation." }, { "code": null, "e": 1360, "s": 1352, "text": "Python3" }, { "code": "# Python program to demonstrate# symmetry and palindrome of the# string # Function to check whether the# string is palindrome or notdef palindrome(a): # finding the mid, start # and last index of the string mid = (len(a)-1)//2 #you can remove the -1 or you add <= sign in line 21 start = 0 #so that you can compare the middle elements also. last = len(a)-1 flag = 0 # A loop till the mid of the # string while(start <= mid): # comparing letters from right # from the letters from left if (a[start]== a[last]): start += 1 last -= 1 else: flag = 1 break; # Checking the flag variable to # check if the string is palindrome # or not if flag == 0: print(\"The entered string is palindrome\") else: print(\"The entered string is not palindrome\") # Function to check whether the# string is symmetrical or not def symmetry(a): n = len(a) flag = 0 # Check if the string's length # is odd or even if n%2: mid = n//2 +1 else: mid = n//2 start1 = 0 start2 = mid while(start1 < mid and start2 < n): if (a[start1]== a[start2]): start1 = start1 + 1 start2 = start2 + 1 else: flag = 1 break # Checking the flag variable to # check if the string is symmetrical # or not if flag == 0: print(\"The entered string is symmetrical\") else: print(\"The entered string is not symmetrical\") # Driver codestring = 'amaama'palindrome(string)symmetry(string)", "e": 3068, "s": 1360, "text": null }, { "code": null, "e": 3136, "s": 3068, "text": "The entered string is palindrome\nThe entered string is symmetrical\n" }, { "code": null, "e": 3148, "s": 3136, "text": "Approach 2:" }, { "code": null, "e": 3179, "s": 3148, "text": "We use slicing in this method." }, { "code": null, "e": 3187, "s": 3179, "text": "Python3" }, { "code": "string = 'amaama'half = int(len(string) / 2) if len(string) % 2 == 0: # even first_str = string[:half] second_str = string[half:]else: # odd first_str = string[:half] second_str = string[half+1:] # symmetricif first_str == second_str: print(string, 'string is symmertical')else: print(string, 'string is not symmertical') # palindromeif first_str == second_str[::-1]: # ''.join(reversed(second_str)) [slower] print(string, 'string is palindrome')else: print(string, 'string is not palindrome')", "e": 3708, "s": 3187, "text": null }, { "code": null, "e": 3766, "s": 3708, "text": "amaama string is symmertical\namaama string is palindrome\n" }, { "code": null, "e": 3782, "s": 3766, "text": "anjali pardeshi" }, { "code": null, "e": 3796, "s": 3782, "text": "sumitgumber28" }, { "code": null, "e": 3815, "s": 3796, "text": "aashishpaliwal1999" }, { "code": null, "e": 3838, "s": 3815, "text": "Python string-programs" }, { "code": null, "e": 3845, "s": 3838, "text": "Python" }, { "code": null, "e": 3861, "s": 3845, "text": "Python Programs" } ]
Command Line Arguments in Golang
17 May, 2020 Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program. In Golang, we have a package called as os package that contains an array called as “Args”. Args is an array of string that contains all the command line arguments passed. The first argument will be always the program name as shown below. Example 1: Try to use offline compiler for better results. Save the below file as cmdargs1.go // Golang program to show how// to use command-line argumentspackage main import ( "fmt" "os") func main() { // The first argument // is always program name myProgramName := os.Args[0] // it will display // the program name fmt.Println(myProgramName)} Output: Here, you can see it is showing the program name with full path. Basically you can call this as Os Filepath output. If you will run the program with some dummy arguments then that will also print as a program name. Example 2: Save the below file as cmdargs2.go // Golang program to show how// to use command-line argumentspackage main import ( "fmt" "os") func main() { // The first argument // is always program name myProgramName := os.Args[0] // this will take 4 // command line arguments cmdArgs := os.Args[4] // getting the arguments // with normal indexing gettingArgs := os.Args[2] toGetAllArgs := os.Args[1:] // it will display // the program name fmt.Println(myProgramName) fmt.Println(cmdArgs) fmt.Println(gettingArgs) fmt.Println(toGetAllArgs)} Output: Picked Go Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Data Types in Go Golang Maps Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2020" }, { "code": null, "e": 253, "s": 54, "text": "Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program." }, { "code": null, "e": 424, "s": 253, "text": "In Golang, we have a package called as os package that contains an array called as “Args”. Args is an array of string that contains all the command line arguments passed." }, { "code": null, "e": 491, "s": 424, "text": "The first argument will be always the program name as shown below." }, { "code": null, "e": 585, "s": 491, "text": "Example 1: Try to use offline compiler for better results. Save the below file as cmdargs1.go" }, { "code": "// Golang program to show how// to use command-line argumentspackage main import ( \"fmt\" \"os\") func main() { // The first argument // is always program name myProgramName := os.Args[0] // it will display // the program name fmt.Println(myProgramName)}", "e": 872, "s": 585, "text": null }, { "code": null, "e": 1095, "s": 872, "text": "Output: Here, you can see it is showing the program name with full path. Basically you can call this as Os Filepath output. If you will run the program with some dummy arguments then that will also print as a program name." }, { "code": null, "e": 1141, "s": 1095, "text": "Example 2: Save the below file as cmdargs2.go" }, { "code": "// Golang program to show how// to use command-line argumentspackage main import ( \"fmt\" \"os\") func main() { // The first argument // is always program name myProgramName := os.Args[0] // this will take 4 // command line arguments cmdArgs := os.Args[4] // getting the arguments // with normal indexing gettingArgs := os.Args[2] toGetAllArgs := os.Args[1:] // it will display // the program name fmt.Println(myProgramName) fmt.Println(cmdArgs) fmt.Println(gettingArgs) fmt.Println(toGetAllArgs)}", "e": 1720, "s": 1141, "text": null }, { "code": null, "e": 1728, "s": 1720, "text": "Output:" }, { "code": null, "e": 1735, "s": 1728, "text": "Picked" }, { "code": null, "e": 1747, "s": 1735, "text": "Go Language" }, { "code": null, "e": 1763, "s": 1747, "text": "Write From Home" }, { "code": null, "e": 1861, "s": 1763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1912, "s": 1861, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 1959, "s": 1912, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 1972, "s": 1959, "text": "Arrays in Go" }, { "code": null, "e": 1989, "s": 1972, "text": "Data Types in Go" }, { "code": null, "e": 2001, "s": 1989, "text": "Golang Maps" }, { "code": null, "e": 2037, "s": 2001, "text": "Convert integer to string in Python" }, { "code": null, "e": 2073, "s": 2037, "text": "Convert string to integer in Python" }, { "code": null, "e": 2134, "s": 2073, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2150, "s": 2134, "text": "Python infinity" } ]
Python Input Methods for Competitive Programming
28 Jan, 2022 Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. Online coding platforms, if C/C++ limit provided is X. Usually, in Java time provided is 2X and Python, it’s 5X.To improve the speed of code execution for input/output intensive problems, languages have various input and output procedures. An Example Problem : Consider a question of finding the sum of N numbers inputted from the user. Input a number N. Input N numbers are separated by a single space in a line. Examples: Input : 5 1 2 3 4 5 Output : 15 Different Python solutions for the above Problem : Normal Method Python: (Python 2.7) 1. raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns. 2. print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. Python3 # basic method of input output# input Nn = int(input()) # input the arrayarr = [int(x) for x in input().split()] # initialize variablesummation = 0 # calculate sumfor x in arr: summation += x # print answerprint(summation) A bit faster method using inbuilt stdin, stdout: (Python 2.7) 1. sys.stdin on the other hand is a File Object. It is like creating any other file object one could create to read input from the file. In this case, the file will be a standard input buffer. 2. stdout.write(‘D\n’) is faster than print ‘D’. 3. Even faster is to write all once by stdout.write(“”.join(list-comprehension)) but this makes memory usage dependent on the size of the input. Python3 # import inbuilt standard input outputfrom sys import stdin, stdout # suppose a function called main() and# all the operations are performeddef main(): # input via readline method n = stdin.readline() # array input similar method arr = [int(x) for x in stdin.readline().split()] #initialize variable summation = 0 # calculate sum for x in arr: summation += x # could use inbuilt summation = sum(arr) # print answer via write # write method writes only # string operations # so we need to convert any # data into string for input stdout.write(str(summation)) # call the main methodif __name__ == "__main__": main() The difference in time: Timing summary (100k lines each) ——————————– Print : 6.040 s Write to file : 0.122 s Print with Stdout : 0.121 s As we have seen till now that taking input from the standard system and giving output to the standard system is always a good idea to improve the efficiency of the code which is always a need in Competitive programming. But wait! would you like to write these long lines every time when you need them? Then, what’s the benefit of using Python. Let’s discuss the solution to this problem. What we can do is let’s create separate functions for taking inputs of various types and just call them whenever you need them. Suppose the input is of the following form 5 7 19 20 and we want separate variables to reference them. what we want is: a = 5 b = 7 c = 19 d = 20 so, we can create a function named as get_ints() as follows: Python3 import sysdef get_ints(): return map(int, sys.stdin.readline().strip().split()) a,b,c,d = get_ints() Now you don’t have to write this line again and again. You just have to call the get_ints() function in order to take input in this form. In the function get_ints we are using the map function. Suppose the input is of the following form 1 2 3 4 5 6 7 8 and we want that a single variable will hold the whole list of integers. What we want is : Arr = [1, 2, 3, 4, 5, 6, 7, 8] So, here we will create a function named get_list() as follows: Python3 import sysdef get_ints(): return list(map(int, sys.stdin.readline().strip().split())) Arr = get_ints() Now you don’t have to write this line again and again. You just have to call the get_ints() function in order to take input in this form Suppose the input is of the following form GeeksforGeeks is the best platform to practice Coding. and we want that a single reference variable will hold this string. What we want is : string = "GeeksforGeeks if the best platform to practice coding." So, here we will create a function named get_string() as follows: Python3 import sysdef get_string(): return sys.stdin.readline().strip() string = get_string() Now you don’t have to write this line again and again. You just have to call the get_string() function in order to take input in this formAdding a buffered pipe io: (Python 2.7) 1. Simply, adding the buffered IO code before your submission code to make the output faster. 2. The benefit of io.BytesIO objects is that they implement a common interface (commonly known as a ‘file-like’ object). BytesIO objects have an internal pointer and for every call to read(n) the pointer advances. 3. The atexit module provides a simple interface to register functions to be called when a program closes down normally. The sys module also provides a hook, sys.exitfunc, but only one function can be registered there. The atexit registry can be used by multiple modules and libraries simultaneously. Python3 # template begins##################################### # import libraries for input/ output handling# on generic levelimport atexit, io, sys # A stream implementation using an in-memory bytes# buffer. It inherits BufferedIOBase.buffer = io.BytesIO()sys.stdout = buffer # print via here@atexit.registerdef write(): sys.stdout.write(buffer.getvalue()) ###################################### template ends # normal method followed# input Nn = int(input()) # input the arrayarr = [int(x) for x in input().split()] # initialize variablesummation = 0 # calculate sumfor x in arr: summation += x # print answerprint(summation) While handling a large amount of data usually, the normal method fails to execute within the time limit. Method 2 helps in maintaining a large amount of I/O data. Method 3 is the fastest. Usually, handling of input data files greater than 2 or 3 MBs is helped via methods 2 and 3.Note: above mention codes are in Python 2.7, to use in Python 3.X versions. Simply replace the raw_input() with Python 3.X’s input() syntax. Rest should work fine.References: 1.More About Input in Python 2.7 2.Output via sys library and other commands. 3.Input via sys library and other commands. 4. Python atexit Module docs.This article is contributed by Shubham Saxena. 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. HARSHGUPTA5 chaudhary_19 gnishantkja yeshwanthtalwar ddeevviissaavviittaa amartyaghoshgfg Competitive Programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jan, 2022" }, { "code": null, "e": 430, "s": 54, "text": "Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. Online coding platforms, if C/C++ limit provided is X. Usually, in Java time provided is 2X and Python, it’s 5X.To improve the speed of code execution for input/output intensive problems, languages have various input and output procedures. " }, { "code": null, "e": 606, "s": 430, "text": "An Example Problem : Consider a question of finding the sum of N numbers inputted from the user. Input a number N. Input N numbers are separated by a single space in a line. " }, { "code": null, "e": 617, "s": 606, "text": "Examples: " }, { "code": null, "e": 650, "s": 617, "text": "Input : \n5\n1 2 3 4 5\nOutput :\n15" }, { "code": null, "e": 702, "s": 650, "text": "Different Python solutions for the above Problem : " }, { "code": null, "e": 1011, "s": 702, "text": "Normal Method Python: (Python 2.7) 1. raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns. 2. print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. " }, { "code": null, "e": 1019, "s": 1011, "text": "Python3" }, { "code": "# basic method of input output# input Nn = int(input()) # input the arrayarr = [int(x) for x in input().split()] # initialize variablesummation = 0 # calculate sumfor x in arr: summation += x # print answerprint(summation)", "e": 1249, "s": 1019, "text": null }, { "code": null, "e": 1700, "s": 1249, "text": "A bit faster method using inbuilt stdin, stdout: (Python 2.7) 1. sys.stdin on the other hand is a File Object. It is like creating any other file object one could create to read input from the file. In this case, the file will be a standard input buffer. 2. stdout.write(‘D\\n’) is faster than print ‘D’. 3. Even faster is to write all once by stdout.write(“”.join(list-comprehension)) but this makes memory usage dependent on the size of the input. " }, { "code": null, "e": 1708, "s": 1700, "text": "Python3" }, { "code": "# import inbuilt standard input outputfrom sys import stdin, stdout # suppose a function called main() and# all the operations are performeddef main(): # input via readline method n = stdin.readline() # array input similar method arr = [int(x) for x in stdin.readline().split()] #initialize variable summation = 0 # calculate sum for x in arr: summation += x # could use inbuilt summation = sum(arr) # print answer via write # write method writes only # string operations # so we need to convert any # data into string for input stdout.write(str(summation)) # call the main methodif __name__ == \"__main__\": main() ", "e": 2390, "s": 1708, "text": null }, { "code": null, "e": 2416, "s": 2390, "text": "The difference in time: " }, { "code": null, "e": 2529, "s": 2416, "text": "Timing summary (100k lines each) ——————————– Print : 6.040 s Write to file : 0.122 s Print with Stdout : 0.121 s" }, { "code": null, "e": 3047, "s": 2529, "text": "As we have seen till now that taking input from the standard system and giving output to the standard system is always a good idea to improve the efficiency of the code which is always a need in Competitive programming. But wait! would you like to write these long lines every time when you need them? Then, what’s the benefit of using Python. Let’s discuss the solution to this problem. What we can do is let’s create separate functions for taking inputs of various types and just call them whenever you need them. " }, { "code": null, "e": 3092, "s": 3047, "text": "Suppose the input is of the following form " }, { "code": null, "e": 3102, "s": 3092, "text": "5 7 19 20" }, { "code": null, "e": 3171, "s": 3102, "text": "and we want separate variables to reference them. what we want is: " }, { "code": null, "e": 3197, "s": 3171, "text": "a = 5\nb = 7\nc = 19\nd = 20" }, { "code": null, "e": 3260, "s": 3197, "text": "so, we can create a function named as get_ints() as follows: " }, { "code": null, "e": 3268, "s": 3260, "text": "Python3" }, { "code": "import sysdef get_ints(): return map(int, sys.stdin.readline().strip().split()) a,b,c,d = get_ints()", "e": 3369, "s": 3268, "text": null }, { "code": null, "e": 3563, "s": 3369, "text": "Now you don’t have to write this line again and again. You just have to call the get_ints() function in order to take input in this form. In the function get_ints we are using the map function." }, { "code": null, "e": 3607, "s": 3563, "text": "Suppose the input is of the following form " }, { "code": null, "e": 3623, "s": 3607, "text": "1 2 3 4 5 6 7 8" }, { "code": null, "e": 3716, "s": 3623, "text": "and we want that a single variable will hold the whole list of integers. What we want is : " }, { "code": null, "e": 3747, "s": 3716, "text": "Arr = [1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 3813, "s": 3747, "text": "So, here we will create a function named get_list() as follows: " }, { "code": null, "e": 3821, "s": 3813, "text": "Python3" }, { "code": "import sysdef get_ints(): return list(map(int, sys.stdin.readline().strip().split())) Arr = get_ints()", "e": 3924, "s": 3821, "text": null }, { "code": null, "e": 4062, "s": 3924, "text": "Now you don’t have to write this line again and again. You just have to call the get_ints() function in order to take input in this form " }, { "code": null, "e": 4107, "s": 4062, "text": "Suppose the input is of the following form " }, { "code": null, "e": 4162, "s": 4107, "text": "GeeksforGeeks is the best platform to practice Coding." }, { "code": null, "e": 4250, "s": 4162, "text": "and we want that a single reference variable will hold this string. What we want is : " }, { "code": null, "e": 4316, "s": 4250, "text": "string = \"GeeksforGeeks if the best platform to practice coding.\"" }, { "code": null, "e": 4383, "s": 4316, "text": "So, here we will create a function named get_string() as follows: " }, { "code": null, "e": 4391, "s": 4383, "text": "Python3" }, { "code": "import sysdef get_string(): return sys.stdin.readline().strip() string = get_string()", "e": 4477, "s": 4391, "text": null }, { "code": null, "e": 5266, "s": 4477, "text": "Now you don’t have to write this line again and again. You just have to call the get_string() function in order to take input in this formAdding a buffered pipe io: (Python 2.7) 1. Simply, adding the buffered IO code before your submission code to make the output faster. 2. The benefit of io.BytesIO objects is that they implement a common interface (commonly known as a ‘file-like’ object). BytesIO objects have an internal pointer and for every call to read(n) the pointer advances. 3. The atexit module provides a simple interface to register functions to be called when a program closes down normally. The sys module also provides a hook, sys.exitfunc, but only one function can be registered there. The atexit registry can be used by multiple modules and libraries simultaneously. " }, { "code": null, "e": 5274, "s": 5266, "text": "Python3" }, { "code": "# template begins##################################### # import libraries for input/ output handling# on generic levelimport atexit, io, sys # A stream implementation using an in-memory bytes# buffer. It inherits BufferedIOBase.buffer = io.BytesIO()sys.stdout = buffer # print via here@atexit.registerdef write(): sys.stdout.write(buffer.getvalue()) ###################################### template ends # normal method followed# input Nn = int(input()) # input the arrayarr = [int(x) for x in input().split()] # initialize variablesummation = 0 # calculate sumfor x in arr: summation += x # print answerprint(summation)", "e": 5900, "s": 5274, "text": null }, { "code": null, "e": 6929, "s": 5900, "text": "While handling a large amount of data usually, the normal method fails to execute within the time limit. Method 2 helps in maintaining a large amount of I/O data. Method 3 is the fastest. Usually, handling of input data files greater than 2 or 3 MBs is helped via methods 2 and 3.Note: above mention codes are in Python 2.7, to use in Python 3.X versions. Simply replace the raw_input() with Python 3.X’s input() syntax. Rest should work fine.References: 1.More About Input in Python 2.7 2.Output via sys library and other commands. 3.Input via sys library and other commands. 4. Python atexit Module docs.This article is contributed by Shubham Saxena. 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": 6941, "s": 6929, "text": "HARSHGUPTA5" }, { "code": null, "e": 6954, "s": 6941, "text": "chaudhary_19" }, { "code": null, "e": 6966, "s": 6954, "text": "gnishantkja" }, { "code": null, "e": 6982, "s": 6966, "text": "yeshwanthtalwar" }, { "code": null, "e": 7003, "s": 6982, "text": "ddeevviissaavviittaa" }, { "code": null, "e": 7019, "s": 7003, "text": "amartyaghoshgfg" }, { "code": null, "e": 7043, "s": 7019, "text": "Competitive Programming" }, { "code": null, "e": 7050, "s": 7043, "text": "Python" } ]
Python String upper()
03 Dec, 2020 upper() method converts all lowercase characters in a string into uppercase characters and returns it Syntax : string.upper() Parameters : The upper() method doesn’t take any parameters. Returns : returns a uppercased string of the given string CODE 1: String with only alphabetic characters # Python3 program to show the# working of upper() functiontext = 'geeKs For geEkS' print("Original String:")print(text) # upper() function to convert # string to upper_caseprint("\nConverted String:")print(text.upper()) Output : Original String: geeKs For geEkS Converted String: GEEKS FOR GEEKS CODE 2: String with alphanumeric characters # Python3 program to show the# working of upper() functiontext = 'g3Ek5 f0r gE3K5' print("Original String:")print(text) # upper() function to convert # string to upper_caseprint("\nConverted String:")print(text.upper()) Output : Original String: g3Ek5 f0r gE3K5 Converted String: G3EK5 F0R GE3K5 Application: One of the common application of upper() method is to check if the two strings are same or not # Python3 program to show the# working of upper() functiontext1 = 'geeks fOr geeks' text2 = 'gEeKS fOR GeeKs' # Comparison of strings using # upper() methodif(text1.upper() == text2.upper()): print("Strings are same")else: print("Strings are not same") Output: Strings are same python-string Python-string-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2020" }, { "code": null, "e": 130, "s": 28, "text": "upper() method converts all lowercase characters in a string into uppercase characters and returns it" }, { "code": null, "e": 139, "s": 130, "text": "Syntax :" }, { "code": null, "e": 155, "s": 139, "text": "string.upper()\n" }, { "code": null, "e": 168, "s": 155, "text": "Parameters :" }, { "code": null, "e": 216, "s": 168, "text": "The upper() method doesn’t take any parameters." }, { "code": null, "e": 226, "s": 216, "text": "Returns :" }, { "code": null, "e": 275, "s": 226, "text": "returns a uppercased string of the given string\n" }, { "code": null, "e": 322, "s": 275, "text": "CODE 1: String with only alphabetic characters" }, { "code": "# Python3 program to show the# working of upper() functiontext = 'geeKs For geEkS' print(\"Original String:\")print(text) # upper() function to convert # string to upper_caseprint(\"\\nConverted String:\")print(text.upper())", "e": 544, "s": 322, "text": null }, { "code": null, "e": 553, "s": 544, "text": "Output :" }, { "code": null, "e": 621, "s": 553, "text": "Original String:\ngeeKs For geEkS\n\nConverted String:\nGEEKS FOR GEEKS" }, { "code": null, "e": 665, "s": 621, "text": "CODE 2: String with alphanumeric characters" }, { "code": "# Python3 program to show the# working of upper() functiontext = 'g3Ek5 f0r gE3K5' print(\"Original String:\")print(text) # upper() function to convert # string to upper_caseprint(\"\\nConverted String:\")print(text.upper())", "e": 887, "s": 665, "text": null }, { "code": null, "e": 896, "s": 887, "text": "Output :" }, { "code": null, "e": 965, "s": 896, "text": "Original String:\ng3Ek5 f0r gE3K5\n\nConverted String:\nG3EK5 F0R GE3K5\n" }, { "code": null, "e": 1073, "s": 965, "text": "Application: One of the common application of upper() method is to check if the two strings are same or not" }, { "code": "# Python3 program to show the# working of upper() functiontext1 = 'geeks fOr geeks' text2 = 'gEeKS fOR GeeKs' # Comparison of strings using # upper() methodif(text1.upper() == text2.upper()): print(\"Strings are same\")else: print(\"Strings are not same\")", "e": 1335, "s": 1073, "text": null }, { "code": null, "e": 1343, "s": 1335, "text": "Output:" }, { "code": null, "e": 1360, "s": 1343, "text": "Strings are same" }, { "code": null, "e": 1374, "s": 1360, "text": "python-string" }, { "code": null, "e": 1398, "s": 1374, "text": "Python-string-functions" }, { "code": null, "e": 1405, "s": 1398, "text": "Python" } ]
Remove a given word from a String
18 Nov, 2019 Given a String and a Word, the task is remove that Word from the String. Examples: Input: String = "Geeks For Geeks", Word = "For" Output: "Geeks Geeks" Input: String = "A computer Science Portal", Word = "Geeks" Output: "A computer Science Portal" Approach : In Java, this can be done using String replaceAll method by replacing given word with a blank space. Below is the solution to the above problem: C++ Java C# // C++ program to remove// a given word from a string #include <bits/stdc++.h>using namespace std; string removeWord(string str, string word) { // Check if the word is present in string // If found, remove it using removeAll() if (str.find(word) != string::npos) { size_t p = -1; // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle string tempWord = word + " "; while ((p = str.find(word)) != string::npos) str.replace(p, tempWord.length(), ""); // To cover the edge case // if the word is at the // end of the string tempWord = " " + word; while ((p = str.find(word)) != string::npos) str.replace(p, tempWord.length(), ""); } // Return the resultant string return str;} // Driver Codeint main(int argc, char const *argv[]) { // Test Case 1: // If the word is in the middle string string1 = "Geeks for Geeks."; string word1 = "for"; // Test Case 2: // If the word is at the beginning string string2 = "for Geeks Geeks."; string word2 = "for"; // Test Case 3: // If the word is at the end string string3 = "Geeks Geeks for."; string word3 = "for"; // Test Case 4: // If the word is not present string string4 = "A computer Science Portal."; string word4 = "Geeks"; // Test case 1 cout << "String: " << string1 << "\nWord: " << word1 << "\nResult String: " << removeWord(string1, word1) << endl; // Test case 2 cout << "\nString: " << string2 << "\nWord: " << word2 << "\nResult String: " << removeWord(string2, word2) << endl; // Test case 3 cout << "\nString: " << string3 << "\nWord: " << word3 << "\nResult String: " << removeWord(string3, word3) << endl; // Test case 4 cout << "\nString: " << string4 << "\nWord: " << word4 << "\nResult String: " << removeWord(string4, word4) << endl; return 0;} // This code is contributed by// sanjeev2552 // Java program to remove// a given word from a stringpublic class GFG { public static String removeWord(String string, String word) { // Check if the word is present in string // If found, remove it using removeAll() if (string.contains(word)) { // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle String tempWord = word + " "; string = string.replaceAll(tempWord, ""); // To cover the edge case // if the word is at the // end of the string tempWord = " " + word; string = string.replaceAll(tempWord, ""); } // Return the resultant string return string; } public static void main(String args[]) { // Test Case 1: // If the word is in the middle String string1 = "Geeks for Geeks."; String word1 = "for"; // Test Case 2: // If the word is at the beginning String string2 = "for Geeks Geeks."; String word2 = "for"; // Test Case 3: // If the word is at the end String string3 = "Geeks Geeks for."; String word3 = "for"; // Test Case 4: // If the word is not present String string4 = "A computer Science Portal."; String word4 = "Geeks"; // Test case 1 System.out.println("String: " + string1 + "\nWord: " + word1 + "\nResult String: " + removeWord(string1, word1)); // Test case 2 System.out.println("\nString: " + string2 + "\nWord: " + word2 + "\nResult String: " + removeWord(string2, word2)); // Test case 3 System.out.println("\nString: " + string3 + "\nWord: " + word3 + "\nResult String: " + removeWord(string3, word3)); // Test case 4 System.out.println("\nString: " + string4 + "\nWord: " + word4 + "\nResult String: " + removeWord(string4, word4)); }} // C# program to remove// a given word from a stringusing System; class GFG { public static String removeWord(String str, String word) { // Check if the word is present in string // If found, remove it using removeAll() if (str.Contains(word)) { // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle String tempWord = word + " "; str = str.Replace(tempWord, ""); // To cover the edge case // if the word is at the // end of the string tempWord = " " + word; str = str.Replace(tempWord, ""); } // Return the resultant string return str; } // Driver code public static void Main(String []args) { // Test Case 1: // If the word is in the middle String string1 = "Geeks for Geeks."; String word1 = "for"; // Test Case 2: // If the word is at the beginning String string2 = "for Geeks Geeks."; String word2 = "for"; // Test Case 3: // If the word is at the end String string3 = "Geeks Geeks for."; String word3 = "for"; // Test Case 4: // If the word is not present String string4 = "A computer Science Portal."; String word4 = "Geeks"; // Test case 1 Console.WriteLine("String: " + string1 + "\nWord: " + word1 + "\nResult String: " + removeWord(string1, word1)); // Test case 2 Console.WriteLine("\nString: " + string2 + "\nWord: " + word2 + "\nResult String: " + removeWord(string2, word2)); // Test case 3 Console.WriteLine("\nString: " + string3 + "\nWord: " + word3 + "\nResult String: " + removeWord(string3, word3)); // Test case 4 Console.WriteLine("\nString: " + string4 + "\nWord: " + word4 + "\nResult String: " + removeWord(string4, word4)); }} // This code contributed by Rajput-Ji String: Geeks for Geeks. Word: for Result String: Geeks Geeks. String: for Geeks Geeks. Word: for Result String: Geeks Geeks. String: Geeks Geeks for. Word: for Result String: Geeks Geeks. String: A computer Science Portal. Word: Geeks Result String: A computer Science Portal. Rajput-Ji sanjeev2552 Java-String-Programs Java-Strings Java Java Programs Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Nov, 2019" }, { "code": null, "e": 125, "s": 52, "text": "Given a String and a Word, the task is remove that Word from the String." }, { "code": null, "e": 135, "s": 125, "text": "Examples:" }, { "code": null, "e": 303, "s": 135, "text": "Input: String = \"Geeks For Geeks\", Word = \"For\"\nOutput: \"Geeks Geeks\"\n\nInput: String = \"A computer Science Portal\", Word = \"Geeks\"\nOutput: \"A computer Science Portal\"\n" }, { "code": null, "e": 415, "s": 303, "text": "Approach : In Java, this can be done using String replaceAll method by replacing given word with a blank space." }, { "code": null, "e": 459, "s": 415, "text": "Below is the solution to the above problem:" }, { "code": null, "e": 463, "s": 459, "text": "C++" }, { "code": null, "e": 468, "s": 463, "text": "Java" }, { "code": null, "e": 471, "s": 468, "text": "C#" }, { "code": "// C++ program to remove// a given word from a string #include <bits/stdc++.h>using namespace std; string removeWord(string str, string word) { // Check if the word is present in string // If found, remove it using removeAll() if (str.find(word) != string::npos) { size_t p = -1; // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle string tempWord = word + \" \"; while ((p = str.find(word)) != string::npos) str.replace(p, tempWord.length(), \"\"); // To cover the edge case // if the word is at the // end of the string tempWord = \" \" + word; while ((p = str.find(word)) != string::npos) str.replace(p, tempWord.length(), \"\"); } // Return the resultant string return str;} // Driver Codeint main(int argc, char const *argv[]) { // Test Case 1: // If the word is in the middle string string1 = \"Geeks for Geeks.\"; string word1 = \"for\"; // Test Case 2: // If the word is at the beginning string string2 = \"for Geeks Geeks.\"; string word2 = \"for\"; // Test Case 3: // If the word is at the end string string3 = \"Geeks Geeks for.\"; string word3 = \"for\"; // Test Case 4: // If the word is not present string string4 = \"A computer Science Portal.\"; string word4 = \"Geeks\"; // Test case 1 cout << \"String: \" << string1 << \"\\nWord: \" << word1 << \"\\nResult String: \" << removeWord(string1, word1) << endl; // Test case 2 cout << \"\\nString: \" << string2 << \"\\nWord: \" << word2 << \"\\nResult String: \" << removeWord(string2, word2) << endl; // Test case 3 cout << \"\\nString: \" << string3 << \"\\nWord: \" << word3 << \"\\nResult String: \" << removeWord(string3, word3) << endl; // Test case 4 cout << \"\\nString: \" << string4 << \"\\nWord: \" << word4 << \"\\nResult String: \" << removeWord(string4, word4) << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 2564, "s": 471, "text": null }, { "code": "// Java program to remove// a given word from a stringpublic class GFG { public static String removeWord(String string, String word) { // Check if the word is present in string // If found, remove it using removeAll() if (string.contains(word)) { // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle String tempWord = word + \" \"; string = string.replaceAll(tempWord, \"\"); // To cover the edge case // if the word is at the // end of the string tempWord = \" \" + word; string = string.replaceAll(tempWord, \"\"); } // Return the resultant string return string; } public static void main(String args[]) { // Test Case 1: // If the word is in the middle String string1 = \"Geeks for Geeks.\"; String word1 = \"for\"; // Test Case 2: // If the word is at the beginning String string2 = \"for Geeks Geeks.\"; String word2 = \"for\"; // Test Case 3: // If the word is at the end String string3 = \"Geeks Geeks for.\"; String word3 = \"for\"; // Test Case 4: // If the word is not present String string4 = \"A computer Science Portal.\"; String word4 = \"Geeks\"; // Test case 1 System.out.println(\"String: \" + string1 + \"\\nWord: \" + word1 + \"\\nResult String: \" + removeWord(string1, word1)); // Test case 2 System.out.println(\"\\nString: \" + string2 + \"\\nWord: \" + word2 + \"\\nResult String: \" + removeWord(string2, word2)); // Test case 3 System.out.println(\"\\nString: \" + string3 + \"\\nWord: \" + word3 + \"\\nResult String: \" + removeWord(string3, word3)); // Test case 4 System.out.println(\"\\nString: \" + string4 + \"\\nWord: \" + word4 + \"\\nResult String: \" + removeWord(string4, word4)); }}", "e": 4863, "s": 2564, "text": null }, { "code": "// C# program to remove// a given word from a stringusing System; class GFG { public static String removeWord(String str, String word) { // Check if the word is present in string // If found, remove it using removeAll() if (str.Contains(word)) { // To cover the case // if the word is at the // beginning of the string // or anywhere in the middle String tempWord = word + \" \"; str = str.Replace(tempWord, \"\"); // To cover the edge case // if the word is at the // end of the string tempWord = \" \" + word; str = str.Replace(tempWord, \"\"); } // Return the resultant string return str; } // Driver code public static void Main(String []args) { // Test Case 1: // If the word is in the middle String string1 = \"Geeks for Geeks.\"; String word1 = \"for\"; // Test Case 2: // If the word is at the beginning String string2 = \"for Geeks Geeks.\"; String word2 = \"for\"; // Test Case 3: // If the word is at the end String string3 = \"Geeks Geeks for.\"; String word3 = \"for\"; // Test Case 4: // If the word is not present String string4 = \"A computer Science Portal.\"; String word4 = \"Geeks\"; // Test case 1 Console.WriteLine(\"String: \" + string1 + \"\\nWord: \" + word1 + \"\\nResult String: \" + removeWord(string1, word1)); // Test case 2 Console.WriteLine(\"\\nString: \" + string2 + \"\\nWord: \" + word2 + \"\\nResult String: \" + removeWord(string2, word2)); // Test case 3 Console.WriteLine(\"\\nString: \" + string3 + \"\\nWord: \" + word3 + \"\\nResult String: \" + removeWord(string3, word3)); // Test case 4 Console.WriteLine(\"\\nString: \" + string4 + \"\\nWord: \" + word4 + \"\\nResult String: \" + removeWord(string4, word4)); }} // This code contributed by Rajput-Ji", "e": 7165, "s": 4863, "text": null }, { "code": null, "e": 7447, "s": 7165, "text": "String: Geeks for Geeks.\nWord: for\nResult String: Geeks Geeks.\n\nString: for Geeks Geeks.\nWord: for\nResult String: Geeks Geeks.\n\nString: Geeks Geeks for.\nWord: for\nResult String: Geeks Geeks.\n\nString: A computer Science Portal.\nWord: Geeks\nResult String: A computer Science Portal.\n" }, { "code": null, "e": 7457, "s": 7447, "text": "Rajput-Ji" }, { "code": null, "e": 7469, "s": 7457, "text": "sanjeev2552" }, { "code": null, "e": 7490, "s": 7469, "text": "Java-String-Programs" }, { "code": null, "e": 7503, "s": 7490, "text": "Java-Strings" }, { "code": null, "e": 7508, "s": 7503, "text": "Java" }, { "code": null, "e": 7522, "s": 7508, "text": "Java Programs" }, { "code": null, "e": 7535, "s": 7522, "text": "Java-Strings" }, { "code": null, "e": 7540, "s": 7535, "text": "Java" } ]
GATE CS 2018 - GeeksforGeeks
22 Nov, 2021 What is the area of the circle which has the diagonal of the square as its diameter if the area of square is ' d ' ? πd πd2 (1/4) πd2 (1/2)πd One important observation to solve the question : Diagonal of Square = Diameter of Circle. Let side of square be x. From Pythogorous theorem. Diagonal = √(2*x*x) We know area of square = x * x = d Diameter = Diagonal = √(2*d) Radius = √(d/2) Area of Circle = π * √(d/2) * √(d/2) = 1/2 * π * d Let total males and females be 60x and 40x respectively. Total number of people = (60x + 40x) Total number of people who attended : 0.8(60x + 40x) = 80x Let y males attended. It is given all 1females attended 40x + y = 80x y = 40x which is same as females. If pqr ≠ 0 and p^(-x) = 1/q, q^(-y) = 1/r, r^(-z) = 1/p, find the value of the product xyz ? -1 1 / pqr 1 pqr Taking logs of given three values, we get 1/q = p-x -------(1) 1/r = q-y -------(2) 1/p = r-z -------(3) 1/q = p-x = r-xz [Putting value of p from (3)] = q-xyz [Putting value of r from (2)] = 1 / qxyz On comparing power of q both sides, we get xyz = 1 So, option (C) is correct. Let there be x total men. Total amount paid = x * 750 * 8/9 + (300 - x)*1000*2/3 = x*2000/3 + 300*1000*2/3 - x*2000/3 = 200000 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 29498, "s": 29470, "text": "\n22 Nov, 2021" }, { "code": null, "e": 29615, "s": 29498, "text": "What is the area of the circle which has the diagonal of the square as its diameter if the area of square is ' d ' ?" }, { "code": null, "e": 29618, "s": 29615, "text": "πd" }, { "code": null, "e": 29622, "s": 29618, "text": "πd2" }, { "code": null, "e": 29632, "s": 29622, "text": "(1/4) πd2" }, { "code": null, "e": 29640, "s": 29632, "text": "(1/2)πd" }, { "code": null, "e": 29942, "s": 29640, "text": "One important observation to solve \nthe question :\n\nDiagonal of Square = Diameter of Circle.\n\nLet side of square be x. \n\nFrom Pythogorous theorem.\nDiagonal = √(2*x*x)\n\nWe know area of square = x * x = d\n\nDiameter = Diagonal = √(2*d)\n\nRadius = √(d/2)\nArea of Circle = π * √(d/2) * √(d/2) = 1/2 * π * d" }, { "code": null, "e": 30223, "s": 29942, "text": "Let total males and females be 60x and\n40x respectively.\n\nTotal number of people = (60x + 40x)\nTotal number of people who attended : \n 0.8(60x + 40x) = 80x\n\nLet y males attended. It is given all \n1females attended \n\n40x + y = 80x\ny = 40x which is same as females.\n" }, { "code": null, "e": 30317, "s": 30223, "text": "If pqr ≠ 0 and p^(-x) = 1/q, q^(-y) = 1/r, r^(-z) = 1/p, find the value of the product xyz ?" }, { "code": null, "e": 30320, "s": 30317, "text": "-1" }, { "code": null, "e": 30328, "s": 30320, "text": "1 / pqr" }, { "code": null, "e": 30330, "s": 30328, "text": "1" }, { "code": null, "e": 30334, "s": 30330, "text": "pqr" }, { "code": null, "e": 30376, "s": 30334, "text": "Taking logs of given three values, we get" }, { "code": null, "e": 30601, "s": 30376, "text": "1/q = p-x -------(1)\n1/r = q-y -------(2)\n1/p = r-z -------(3)\n\n1/q = p-x\n = r-xz [Putting value of p from (3)]\n = q-xyz [Putting value of r from (2)]\n = 1 / qxyz\n\nOn comparing power of q both sides, we get xyz = 1" }, { "code": null, "e": 30628, "s": 30601, "text": "So, option (C) is correct." }, { "code": null, "e": 30792, "s": 30628, "text": "Let there be x total men.\n\nTotal amount paid = x * 750 * 8/9 + (300 - x)*1000*2/3\n = x*2000/3 + 300*1000*2/3 - x*2000/3\n = 200000" } ]