title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Image classification from scratch in keras. Beginner friendly, intermediate exciting and expert refreshing. | by Rising Odegua | Towards Data Science
Last weekend I was thinking out loud . what if I had a really really small data set of images that I captured myself and wanted to teach a computer to recognize or distinguish between some specified categories. Let’s say I have a few thousand images and I want to train a model to automatically detect one class from another. Would I be able to train a deep neural network to successfully classify these images since I have such little data? Well, after doing some research, I found out that having to train deep neural network with little data was a common situation people encountered in the field of computer vision. well let’s face it, not everyone has access to big data like the Googs or the Faces, and some data are very difficult to obtain. But I also found out that the solution to this problem was quite easy. So today I’m going to walk you through training a Convolutional Neural Network using that little Image data you have to get a really good classifier which will have an accuracy of about 81%. In this post, I introduced a really powerful technique called transfer learning that helps us increase our accuracy up to about 95%. Alright you can go out and start gathering your data. I’ll be using an existing data set of dogs and cats available on the Kaggle platform. — -Yes, I’m lazy. I can’t get my own data. Kaggle is the home of data science and machine learning practitioners worldwide. They host some of the biggest data science competitions and it is a great place for getting open source data as well as learning from winning experts. Well, I feel I should say this. If you’re from Africa, we have a new platform called Zindi which is like Kaggle but fine tuned to the Africa society. It contains data sets that are collected from African businesses and organisation. This is a big step in preventing bias in AI, and Zindi is a great platform. So watch out for the Zindians, we’re coming. Okay, back to getting the data. We head over to this page on Kaggle. Here we have two options, we can either download the data and train our model locally on our Laptop or we can use Kaggle kernels which gives us more compute power, access to a GPU, and almost all the libraries pre-installed for machine learning and deep learning. I don’t know about you, but I’d rather go with Kaggle kernels unless I have a GPU. If you can afford a GPU or you’re a gamaic [I totally made up that word] and already have a GPU and you want to train your model on your PC because you love your PC too much , then you can follow this tutorial or this one on setting up your own deep learning work station. For the rest of the lazy-or-cannot-currently-afford-a-GP-us, let’s head over to Kaggle and start this engine. Clicking on the link, we teleport here. Note: It is generally a good idea to read the data description when you visit a Kaggle competition page. Next, click on Kernels then the blue New Kernel button on the top right corner, this will ask you to Select Kernel Type. Pick Notebook so we can do some interactive programming. If you don’t know what a Notebook is or need to refresh your notebooking skills, here and here are great sites with tutorials on Jupyter Notebook. Clicking on Notebook creates a new private kernel for you and automatically adds the dogs vs cats dataset to your file path — in the cloud of course. Give your Kernel a name and put on your super power (GPU) for faster compute time. Now that our kernel is ready, let’s import some of the libraries we’re going to use. Type the following code and press shift Enter to run the cell. cv2 cv2 also called OpenCV, is an image and video processing library available in Python and many other high level programming languages. It is used for all sorts of image and video analysis, like facial recognition and detection, license plate reading, photo editing, advanced robotic vision, optical character recognition, and a whole lot more. In this tutorial, we are going to use it in reading and resizing our Images.NumPy is the most popular mathematical library in Python. It makes working and computing large, multi-dimensional arrays and matrices super easy and fast. It has a large collection of high-level mathematical functions to operate on these arrays.Pandas pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.Matplotlib is a plotting library for the Python. It can be used for plotting lines, bar-chart, graphs, histograms and even displaying Images.%matplotlib inline is a command that makes our plots appear in the notebook.os is an inbuilt python package for accessing your computer and file system. It can be used to display content in directories, create new folders and even delete folders.random will help us create random numbers which will be used when we split or shuffle our data set.gc short for garbage collector is an important tool for manually cleaning and deleting unnecessary variables. We’ll actively use this on Kaggle kernels because the free memory allocated to us may get full since we are working on Image datasets. cv2 cv2 also called OpenCV, is an image and video processing library available in Python and many other high level programming languages. It is used for all sorts of image and video analysis, like facial recognition and detection, license plate reading, photo editing, advanced robotic vision, optical character recognition, and a whole lot more. In this tutorial, we are going to use it in reading and resizing our Images. NumPy is the most popular mathematical library in Python. It makes working and computing large, multi-dimensional arrays and matrices super easy and fast. It has a large collection of high-level mathematical functions to operate on these arrays. Pandas pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. Matplotlib is a plotting library for the Python. It can be used for plotting lines, bar-chart, graphs, histograms and even displaying Images. %matplotlib inline is a command that makes our plots appear in the notebook. os is an inbuilt python package for accessing your computer and file system. It can be used to display content in directories, create new folders and even delete folders. random will help us create random numbers which will be used when we split or shuffle our data set. gc short for garbage collector is an important tool for manually cleaning and deleting unnecessary variables. We’ll actively use this on Kaggle kernels because the free memory allocated to us may get full since we are working on Image datasets. After importing the necessary libraries, we read our Images in to memory. The data is stored as Zip files in our kernel. We can see three files: sample submission.csv This is a csv (comma seperated value) file that is used for making submission after training your model and testing it on the test files given to you. Since this competition is over, we cannot make submissions, so we’ll ignore this file.test.zipThis file contains the Images we’re going to test our models on after training, to know if our model has learnt to differentiate dogs from cats.train.zipThis is the food for our model. It contains the data we’re going to use to teach our model what a dog or a cat looks like. sample submission.csv This is a csv (comma seperated value) file that is used for making submission after training your model and testing it on the test files given to you. Since this competition is over, we cannot make submissions, so we’ll ignore this file. test.zipThis file contains the Images we’re going to test our models on after training, to know if our model has learnt to differentiate dogs from cats. train.zipThis is the food for our model. It contains the data we’re going to use to teach our model what a dog or a cat looks like. Now to access our training Images, we’re going to use the os package which we imported earlier. Note: All data file paths on kaggle start with the root directory ../input. for example the file path to the train data in this kernel will be ../input/train Here we create a file path to our train and test dataHere we create two variables train_dogs and train_cats. One for all dog images and the other for cat images. We write a list comprehension that uses the command os.listdir() to get all the images in the train data zip file and retrieve all images with dog in their name. ** We do the same for cat images.We get our test images too.The train data set contains a total of 25,000 images, but since we are experimenting working with a small data set and we obviously have access to little computational power, we’re going to extract only 2000 images from both classes. ** 2000 dog images and 2000 cat images, making a training data set of 4000 images.So we grab the first 2000 images from the train_dogs and train_cats, then concatenate them into one train set called train_imgs.VERY IMPORTANT! we randomly shuffle the train_imgs .Here we do some cleaning. As you may have noticed, we now have train_imgs meaning train_dogs and train_cats variables are useless and taking unnecessary space. If we don’t delete them, we might run out of memory when we start training our model. Here we create a file path to our train and test data Here we create two variables train_dogs and train_cats. One for all dog images and the other for cat images. We write a list comprehension that uses the command os.listdir() to get all the images in the train data zip file and retrieve all images with dog in their name. ** We do the same for cat images. We get our test images too. The train data set contains a total of 25,000 images, but since we are experimenting working with a small data set and we obviously have access to little computational power, we’re going to extract only 2000 images from both classes. ** 2000 dog images and 2000 cat images, making a training data set of 4000 images.So we grab the first 2000 images from the train_dogs and train_cats, then concatenate them into one train set called train_imgs. VERY IMPORTANT! we randomly shuffle the train_imgs . Here we do some cleaning. As you may have noticed, we now have train_imgs meaning train_dogs and train_cats variables are useless and taking unnecessary space. If we don’t delete them, we might run out of memory when we start training our model. Okay, lets view some images in our train_imgs. Import an image plotting module from matplotlibRun a for loop to plot the first three images in train_imgs Import an image plotting module from matplotlib Run a for loop to plot the first three images in train_imgs Remember its a random list, but luckily when I ran the code the first three images was made up to two dogs and one cat and notice that they have different dimensions. In the next code block we’re going resize the images using the cv2 module.First let’s declare the new dimensions we want to use. Here I’m using 150 by 150 for height and width and 3 channels. A colored Image is made up of 3 channels, i.e 3 arrays of red, green and blue pixel values. We could use 1 channel which would read our images in gray-scale format (black and white). Now, lets write a little function that helps also read and then resize our images to the height and width stated above. Create a new variable X which will hold the new training set and y which will hold our training labels. (1 if the image is a dog and 0 if it is a cat)we read our images one after the other and resize them with the cv2 commands.We append 1 to y if the image is a dog and 0 if it is a cat. Create a new variable X which will hold the new training set and y which will hold our training labels. (1 if the image is a dog and 0 if it is a cat) we read our images one after the other and resize them with the cv2 commands. We append 1 to y if the image is a dog and 0 if it is a cat. Now, let’s call our function and process the images. X, y = read_and_process_image(train_imgs) X is now an array of image pixel values and y is a list of labels. Let’s preview the first image in X. And that my friend is a dog image. Or we can say what our computer calls a dog. Wait! how did I know its a dog? well, lets look at the corresponding value in the label list y. Well, remember we said lets 1 and 0 represent dogs and cats respectively. Still don’t believe me. Then, let’s plot the first 5 arrays of X. We can’t plot the images in X with the mpimg module of matplotlib.image above because these are now arrays of pixels not raw jpg files. So we should use the imshow() command. Now that we’re confident that our training set contains the appropriate images of dogs and cats, let’s look at our labels. Remember we have a total of 4000 images (2000 dogs and 2000 cats), therefore our label list y should contain 2000 of 1s and 2000 of 0s. Let’s plot this and confirm. We import seaborn package, another plotting package built on top of matplotlib that gives very beautiful plots.Remember we are neat people and we don’t wait for the garbage man to do the cleaning for us. So we delete the train_imgs, since it has already been converted to an array and saved in X.X and y are currently of type list (list of python array), we will convert these to numpy array so we can feed it into our model.Plot a colorful diagram to confirm the number of classes in our y label variable We import seaborn package, another plotting package built on top of matplotlib that gives very beautiful plots. Remember we are neat people and we don’t wait for the garbage man to do the cleaning for us. So we delete the train_imgs, since it has already been converted to an array and saved in X. X and y are currently of type list (list of python array), we will convert these to numpy array so we can feed it into our model. Plot a colorful diagram to confirm the number of classes in our y label variable Great! we have 2000 classes of both dogs and cats. Let’s move on. Next let’s check the shape of our data. Always check and confirm the shapes of your data, it is super important. We can see that our image is a tensor of rank 4, or we could say a 4 dimensional array with dimensions 4000 x 150 x 150 x 3 which correspond to the batch size, height, width and channels respectively. The shape of our image array is important for the keras model we’re going to build. The model takes as input an array of ( height, width,channels) Now that our data is ready (X,y) we could start training, but first we have to do something that is very important, which is to split our data into train and validation set. This is one of the most important things to do before you start training your model. For splitting, we’re going to use a handy function from a popular machine learning package in python called sklearn. Imports train_test_split from sklearnWe tell the function we want 20% of the data to be assigned to the validation set and the other 80% to the train set.Here we print the shape of the new train and validation set Imports train_test_split from sklearn We tell the function we want 20% of the data to be assigned to the validation set and the other 80% to the train set. Here we print the shape of the new train and validation set Next, we’re going to declare some important variables that will be used when training our model. Yes, we’re still cleaning.get the length of the train and validation set. Yes, we’re still cleaning. get the length of the train and validation set. Wheeeeeew....Now its time to create our model. We are going to use a Convolutional Neural Network (convnet) to train our model. Convets are currently the standard when it comes to Computer Vision problems. They have always outperform other types of neural network in any image problem. New to convnets? At the end of this post, there are good links to sites where you can learn all about them. In creating our model we’re going to use KERAS. According to wikipedia... Keras is an open source neural network library written in Python. It is capable of running on top of TensorFlow, Microsoft Cognitive Toolkit, or Theano. Designed to enable fast experimentation with deep neural networks, it focuses on being user-friendly, modular, and extensible. First let’s import the neccessary keras modules we are going to use Here we import keras layers module which contains different types of layers used in deep learning such as:** Convolutional layer (Mostly used in computer vision)** Pooling layer (also used in computer vision)** Recurrent layer (Mostly used in sequential and time series modelling)** Embedding layers (Mostly used in Natural Language processing)** Normalization layers ** and many moreHere we import keras models which contains two types:**Sequential model which we’ll be using in this tutorial and**The model with the Functional APIHere we import keras optimizer, a module that contains different types of back propagation algorithm for training our model. Some of these optimizers are:**sgd (stochastic gradient descent)**rmsprop (root mean square propagation)**Adams**Adagrad**AdadeltaHere we import one of the most important function (ImageDataGenerator) used when working with a small data set. More on this below. Here we import keras layers module which contains different types of layers used in deep learning such as:** Convolutional layer (Mostly used in computer vision)** Pooling layer (also used in computer vision)** Recurrent layer (Mostly used in sequential and time series modelling)** Embedding layers (Mostly used in Natural Language processing)** Normalization layers ** and many more Here we import keras models which contains two types:**Sequential model which we’ll be using in this tutorial and**The model with the Functional API Here we import keras optimizer, a module that contains different types of back propagation algorithm for training our model. Some of these optimizers are:**sgd (stochastic gradient descent)**rmsprop (root mean square propagation)**Adams**Adagrad**Adadelta Here we import one of the most important function (ImageDataGenerator) used when working with a small data set. More on this below. Now lets create our Network architecture. We are going to follow a popular, effective and simple architecture called the VGGnet Network architecture is just the way we arrange our convolution layers We are going to use a small vggnet, but you can see below that our filter size increases as we go down layers. 32 → 64 →128 →512 — and final layer is 1 Here we create a sequential model. This tells keras to stack all layers sequentially.Here we create the first layer by calling the .add() function on the model we created and pass the type of layer we want — a Conv2D layer. This first layer is called the input layer and has some important parameters we need to set.** filter size [32]: This is the size of the output dimension (i.e. the number of output filters in the convolution)** kernel_size [3,3]: This specifies the height and width of the 2D convolution window.** activation [‘relu’]: We select an activation function also called non-linearity to be used by our neural network. ReLU (Rectified Linear Unit) is the most common activation function used today, other variations are leaky ReLU and eLU.** input shape [150,150,3]: Remember the dimensions we resized our images to? 150 by 150 right? we pass that here including the channel of 3. We do not pass the first dimension of 4000 because that is the batch dimension.Here we add a MaxPool2D layer. Its function is to reduce the spatial size of the incoming features and therefore helps reduce the number of parameters and computation in the network, thereby helping to reduce overfitting. Here we create a sequential model. This tells keras to stack all layers sequentially. Here we create the first layer by calling the .add() function on the model we created and pass the type of layer we want — a Conv2D layer. This first layer is called the input layer and has some important parameters we need to set.** filter size [32]: This is the size of the output dimension (i.e. the number of output filters in the convolution)** kernel_size [3,3]: This specifies the height and width of the 2D convolution window.** activation [‘relu’]: We select an activation function also called non-linearity to be used by our neural network. ReLU (Rectified Linear Unit) is the most common activation function used today, other variations are leaky ReLU and eLU.** input shape [150,150,3]: Remember the dimensions we resized our images to? 150 by 150 right? we pass that here including the channel of 3. We do not pass the first dimension of 4000 because that is the batch dimension. Here we add a MaxPool2D layer. Its function is to reduce the spatial size of the incoming features and therefore helps reduce the number of parameters and computation in the network, thereby helping to reduce overfitting. Overfitting happens when our model memorizes the training data. The model will perform excellently at training time but fail at test time. Here we add a Flatten layer. A conv2D layers extract and learn spatial features which are then passed to a dense layer after it has been flattened. This is the work of the flatten layer.Here we add a Dropout layer with value 0.5. Dropout randomly drops some layers in a neural networks and then learns with the reduced network. This way, the network learns to be independent and not reliable on a single layer. Bottom-line is that it helps in overfitting.0.5 means to randomly drop half of the layers.The last layer has an output size of 1 and a different activation function called sigmoid. This is because we’re trying to detect if an image is a dog or a cat. i.e we want the model to output a probability of how sure an image is a dog and not a cat, that means we want a probability score where higher values means the classifier believes the image is a dog and lower values means it is a cat.The sigmoid is perfect for this because it takes in a set of numbers and returns a probability distribution in the range of 0 to 1. Here we add a Flatten layer. A conv2D layers extract and learn spatial features which are then passed to a dense layer after it has been flattened. This is the work of the flatten layer. Here we add a Dropout layer with value 0.5. Dropout randomly drops some layers in a neural networks and then learns with the reduced network. This way, the network learns to be independent and not reliable on a single layer. Bottom-line is that it helps in overfitting.0.5 means to randomly drop half of the layers. The last layer has an output size of 1 and a different activation function called sigmoid. This is because we’re trying to detect if an image is a dog or a cat. i.e we want the model to output a probability of how sure an image is a dog and not a cat, that means we want a probability score where higher values means the classifier believes the image is a dog and lower values means it is a cat.The sigmoid is perfect for this because it takes in a set of numbers and returns a probability distribution in the range of 0 to 1. We can preview the arrangement and parameter size of our convnet by calling the Keras function .summary() on the model object. We can see the number of parameters we want to train (3 million-plus) and the general arrangement of the different layers. The next step is to compile our model. We pass three parameters to the model.compile() command Loss [‘binary_crossentropy’]: We specify a loss function that our optimizer will minimize. In this case, since we’re working with a two-class problem, we use binary cross-entropy loss.Remember the optimizers we defined earlier? we’re going to use one of them called the rmsprop. This is not a fixed choice, it is part of a process called hyperparameter tuning which may be the difference between a world-class model and a naive one.Here we specify which metric we want to use in measuring our model’s performance after training. We want to know if our model is doing well or not. Since we’re doing a classification problem, the accuracy metric (acc) is a good choice. Note: The metric you use in measuring the performance of your model will depend on the type of problem you’re dealing with. Loss [‘binary_crossentropy’]: We specify a loss function that our optimizer will minimize. In this case, since we’re working with a two-class problem, we use binary cross-entropy loss. Remember the optimizers we defined earlier? we’re going to use one of them called the rmsprop. This is not a fixed choice, it is part of a process called hyperparameter tuning which may be the difference between a world-class model and a naive one. Here we specify which metric we want to use in measuring our model’s performance after training. We want to know if our model is doing well or not. Since we’re doing a classification problem, the accuracy metric (acc) is a good choice. Note: The metric you use in measuring the performance of your model will depend on the type of problem you’re dealing with. Finally, before we start training our model we need to perform some Normalization. i.e scale our image pixel values to have a unit standard deviation and a mean of 0. We’ll use an important module in Keras called ImageDataGenerator which performs some important functions when we’re feeding Images into our model during training. But...but what is an ImageDataGenerator? According to the creator of Keras François Chollet, Keras ImageDataGenerator() lets us quickly set-up python generators that automatically turn image files into preprocessed tensors that can be fed directly into models during training. It performs the following functions for us easily:1. Decode the JPEG content to RGB grids of pixels.2. Convert these into floating-point tensors.3. Rescale the pixel values (between 0 and 255) to the [0, 1] interval ( neural networks perform better with normalize data).4. It helps us easily augment images. (An important feature we’ll be using since we’re training on a small data set). Okay, let’s create our ImageDataGenerator object. We’re going to create two generators, one for the training set and the other for our validation set. We pass the rescale option to the ImageDataGenerator object. The rescale=1./255 option is a very IMPORTANT parameter. It normalizes the image pixel values to have zero mean and standard deviation of 1. It helps your model to generally learn and update its parameters efficiently.The second set of options is Image augmentation. They tell the ImageDataGenerator to randomly apply some transformation to the Image. This will help to augment our data-set and improve generalization.Here we also create an ImageDataGenerator object for our validation set. Note: we don’t do data augmentation here. We only perform rescale. We pass the rescale option to the ImageDataGenerator object. The rescale=1./255 option is a very IMPORTANT parameter. It normalizes the image pixel values to have zero mean and standard deviation of 1. It helps your model to generally learn and update its parameters efficiently. The second set of options is Image augmentation. They tell the ImageDataGenerator to randomly apply some transformation to the Image. This will help to augment our data-set and improve generalization. Here we also create an ImageDataGenerator object for our validation set. Note: we don’t do data augmentation here. We only perform rescale. Now that we have the ImageDataGenerator objects, let's create python generators from them by passing our train and validation set. We call the .flow( ) method on the data generators we created above passing in the data and label set. X_train and y_train for training then X_val and y_val for validation.The batch size tells the data generator to only take the specified batch(32 in our case) of Images at a time.Now we train our network by calling .fit( ) method on the model and passing some parameters. The first parameter is the training set ImageDataGenerator object [train_generator].Here we specify the number of steps per epoch. This tells our model how many images we want to process before making a gradient update to our loss function.A total of 3200 images divided by the batch size of 32 will give us 100 steps. This means we going to make a total of 100 gradient update to our model in one pass through the entire training set.An epoch is a full-cycle or pass through the entire training set. In our case, an epoch is reached when we make 100 gradient updates as specified by our steps_per_epoch parameter. Epochs = 64, means we want to go over our training data 64 times and each time we will make gradient updates 100 times.We pass in our validation data generator.We set the step size here too. I’m going to use the same step size as stated above. We call the .flow( ) method on the data generators we created above passing in the data and label set. X_train and y_train for training then X_val and y_val for validation.The batch size tells the data generator to only take the specified batch(32 in our case) of Images at a time. Now we train our network by calling .fit( ) method on the model and passing some parameters. The first parameter is the training set ImageDataGenerator object [train_generator]. Here we specify the number of steps per epoch. This tells our model how many images we want to process before making a gradient update to our loss function.A total of 3200 images divided by the batch size of 32 will give us 100 steps. This means we going to make a total of 100 gradient update to our model in one pass through the entire training set. An epoch is a full-cycle or pass through the entire training set. In our case, an epoch is reached when we make 100 gradient updates as specified by our steps_per_epoch parameter. Epochs = 64, means we want to go over our training data 64 times and each time we will make gradient updates 100 times. We pass in our validation data generator. We set the step size here too. I’m going to use the same step size as stated above. Run the cell to start training....This will take a while. Go disturb someone on twitter... Well after just 64 epochs, I got an accuracy of roughly 80%. Not bad for a model we trained from scratch with very little data. Maybe increasing the number of epochs and playing with some hyperparameters like batch size and the optimizer will help improve this score. I ‘ll leave that to you to explore. Next, we save our model, with the simple Keras function shown below, this way we can re-use it anytime instead of training again when rerunning our notebook. #Save the modelmodel.save_weights('model_wieghts.h5')model.save('model_keras.h5') We’ll plot some graphs of the accuracy and the loss in both the train and validation set to see if we can get some insights. After training a Keras model, it always calculates and saves the metric we specified when we compiled our model in a variable called history. We can extract these values and plot them.Note: The history object contains all the updates that happened during training.Here we simply get the size of our epoch from the number of values in the ‘acc’ list.Here we plot the accuracy against the epoch size.Here we plot the loss against the epoch size. After training a Keras model, it always calculates and saves the metric we specified when we compiled our model in a variable called history. We can extract these values and plot them.Note: The history object contains all the updates that happened during training. Here we simply get the size of our epoch from the number of values in the ‘acc’ list. Here we plot the accuracy against the epoch size. Here we plot the loss against the epoch size. So what can we take away from this plot? The first thing to note is that we’re not overfitting as the train and validation accuracy are pretty close and following each other.We can also notice that the accuracy keeps increasing as the epoch increases, giving us the intuition that increasing the epoch size will likely give us a higher accuracy. The first thing to note is that we’re not overfitting as the train and validation accuracy are pretty close and following each other. We can also notice that the accuracy keeps increasing as the epoch increases, giving us the intuition that increasing the epoch size will likely give us a higher accuracy. We’re still not overfitting as both train and validation loss are trending down closely just like the accuracy plot above and the loss will likely go lower if we increase the epoch size.. So there, you’ve got some intuition. Now try increasing the epoch size and play around with some hyperparameters. Before I conclude this tutorial we’re going to test our model on some Images from the test set. We perform the same pre-processing we did on the train and validation set. We read and convert the first 10 images in our test set to a list of array.Note: y_test will be empty because the test set has no label.We convert the list of array to one big numpy array.We create a test ImageDataGenerator and perform normalization only.Note: We do not augment the test set . We read and convert the first 10 images in our test set to a list of array.Note: y_test will be empty because the test set has no label. We convert the list of array to one big numpy array. We create a test ImageDataGenerator and perform normalization only.Note: We do not augment the test set . Now we’ll create a simple for loop, that iterates over the Images from the generator to make predictions. Then we’ll plot the results. Create a list to hold the labels we are going to generate.We set the figure size of the images we’re going to plot.Here we make a prediction on that particular image provided by the ImageDataGenerator by calling the .predict( ) method on our trained model.The pred variable is a probability of how sure the model is that the current image is a dog. Since we gave dogs a label of 1, a high probability — at least greater than average 0.5 — means our model is very confident that the image is a Dog, otherwise it is a cat.So we simply create an if -else statement that appends the string ‘Dog’ if the probability is greater than 0.5 otherwise it appends ‘cat’ to the text_label.We do this so we can add a title to the image when we plot it.Here we add a subplot so we can plot multiple images.Here we add the predicted class as a title to the image plot.We finally plot the image. Create a list to hold the labels we are going to generate. We set the figure size of the images we’re going to plot. Here we make a prediction on that particular image provided by the ImageDataGenerator by calling the .predict( ) method on our trained model. The pred variable is a probability of how sure the model is that the current image is a dog. Since we gave dogs a label of 1, a high probability — at least greater than average 0.5 — means our model is very confident that the image is a Dog, otherwise it is a cat.So we simply create an if -else statement that appends the string ‘Dog’ if the probability is greater than 0.5 otherwise it appends ‘cat’ to the text_label.We do this so we can add a title to the image when we plot it. Here we add a subplot so we can plot multiple images. Here we add the predicted class as a title to the image plot. We finally plot the image. Let’s see how our model performed on previously unseen images. Well....our model got one wrong from five images. I didn’t say it was at its best....at least not yet. Wheeeew.... it’s been a long post, but I guess it was worth it. In this next tutorial, we improved our model to achieve an accuracy of about 95% by using a pre-trained network. A process called Transfer Learning. Well, bye for now and happy coding. Link to this notebook on Github. Some amazing post and write-ups on CNN and Keras. CS231n Convolutional Neural Networks for Visual Recognition. Deep learning with python by Francois Chollet the creator of Keras. Convolution Neural network basics. A great medium post on CNN. An Intuitive guide to CNN | medium post. Keras tutorial. Questions, comments and contributions are welcome. Connect with me on twitter . Connect with me on Instagram.
[ { "code": null, "e": 211, "s": 172, "text": "Last weekend I was thinking out loud ." }, { "code": null, "e": 383, "s": 211, "text": "what if I had a really really small data set of images that I captured myself and wanted to teach a computer to recognize or distinguish between some specified categories." }, { "code": null, "e": 614, "s": 383, "text": "Let’s say I have a few thousand images and I want to train a model to automatically detect one class from another. Would I be able to train a deep neural network to successfully classify these images since I have such little data?" }, { "code": null, "e": 792, "s": 614, "text": "Well, after doing some research, I found out that having to train deep neural network with little data was a common situation people encountered in the field of computer vision." }, { "code": null, "e": 921, "s": 792, "text": "well let’s face it, not everyone has access to big data like the Googs or the Faces, and some data are very difficult to obtain." }, { "code": null, "e": 1183, "s": 921, "text": "But I also found out that the solution to this problem was quite easy. So today I’m going to walk you through training a Convolutional Neural Network using that little Image data you have to get a really good classifier which will have an accuracy of about 81%." }, { "code": null, "e": 1316, "s": 1183, "text": "In this post, I introduced a really powerful technique called transfer learning that helps us increase our accuracy up to about 95%." }, { "code": null, "e": 1370, "s": 1316, "text": "Alright you can go out and start gathering your data." }, { "code": null, "e": 1499, "s": 1370, "text": "I’ll be using an existing data set of dogs and cats available on the Kaggle platform. — -Yes, I’m lazy. I can’t get my own data." }, { "code": null, "e": 1731, "s": 1499, "text": "Kaggle is the home of data science and machine learning practitioners worldwide. They host some of the biggest data science competitions and it is a great place for getting open source data as well as learning from winning experts." }, { "code": null, "e": 2040, "s": 1731, "text": "Well, I feel I should say this. If you’re from Africa, we have a new platform called Zindi which is like Kaggle but fine tuned to the Africa society. It contains data sets that are collected from African businesses and organisation. This is a big step in preventing bias in AI, and Zindi is a great platform." }, { "code": null, "e": 2085, "s": 2040, "text": "So watch out for the Zindians, we’re coming." }, { "code": null, "e": 2418, "s": 2085, "text": "Okay, back to getting the data. We head over to this page on Kaggle. Here we have two options, we can either download the data and train our model locally on our Laptop or we can use Kaggle kernels which gives us more compute power, access to a GPU, and almost all the libraries pre-installed for machine learning and deep learning." }, { "code": null, "e": 2501, "s": 2418, "text": "I don’t know about you, but I’d rather go with Kaggle kernels unless I have a GPU." }, { "code": null, "e": 2774, "s": 2501, "text": "If you can afford a GPU or you’re a gamaic [I totally made up that word] and already have a GPU and you want to train your model on your PC because you love your PC too much , then you can follow this tutorial or this one on setting up your own deep learning work station." }, { "code": null, "e": 2884, "s": 2774, "text": "For the rest of the lazy-or-cannot-currently-afford-a-GP-us, let’s head over to Kaggle and start this engine." }, { "code": null, "e": 2924, "s": 2884, "text": "Clicking on the link, we teleport here." }, { "code": null, "e": 3029, "s": 2924, "text": "Note: It is generally a good idea to read the data description when you visit a Kaggle competition page." }, { "code": null, "e": 3207, "s": 3029, "text": "Next, click on Kernels then the blue New Kernel button on the top right corner, this will ask you to Select Kernel Type. Pick Notebook so we can do some interactive programming." }, { "code": null, "e": 3354, "s": 3207, "text": "If you don’t know what a Notebook is or need to refresh your notebooking skills, here and here are great sites with tutorials on Jupyter Notebook." }, { "code": null, "e": 3504, "s": 3354, "text": "Clicking on Notebook creates a new private kernel for you and automatically adds the dogs vs cats dataset to your file path — in the cloud of course." }, { "code": null, "e": 3587, "s": 3504, "text": "Give your Kernel a name and put on your super power (GPU) for faster compute time." }, { "code": null, "e": 3735, "s": 3587, "text": "Now that our kernel is ready, let’s import some of the libraries we’re going to use. Type the following code and press shift Enter to run the cell." }, { "code": null, "e": 5356, "s": 3735, "text": "cv2 cv2 also called OpenCV, is an image and video processing library available in Python and many other high level programming languages. It is used for all sorts of image and video analysis, like facial recognition and detection, license plate reading, photo editing, advanced robotic vision, optical character recognition, and a whole lot more. In this tutorial, we are going to use it in reading and resizing our Images.NumPy is the most popular mathematical library in Python. It makes working and computing large, multi-dimensional arrays and matrices super easy and fast. It has a large collection of high-level mathematical functions to operate on these arrays.Pandas pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.Matplotlib is a plotting library for the Python. It can be used for plotting lines, bar-chart, graphs, histograms and even displaying Images.%matplotlib inline is a command that makes our plots appear in the notebook.os is an inbuilt python package for accessing your computer and file system. It can be used to display content in directories, create new folders and even delete folders.random will help us create random numbers which will be used when we split or shuffle our data set.gc short for garbage collector is an important tool for manually cleaning and deleting unnecessary variables. We’ll actively use this on Kaggle kernels because the free memory allocated to us may get full since we are working on Image datasets." }, { "code": null, "e": 5780, "s": 5356, "text": "cv2 cv2 also called OpenCV, is an image and video processing library available in Python and many other high level programming languages. It is used for all sorts of image and video analysis, like facial recognition and detection, license plate reading, photo editing, advanced robotic vision, optical character recognition, and a whole lot more. In this tutorial, we are going to use it in reading and resizing our Images." }, { "code": null, "e": 6026, "s": 5780, "text": "NumPy is the most popular mathematical library in Python. It makes working and computing large, multi-dimensional arrays and matrices super easy and fast. It has a large collection of high-level mathematical functions to operate on these arrays." }, { "code": null, "e": 6249, "s": 6026, "text": "Pandas pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series." }, { "code": null, "e": 6391, "s": 6249, "text": "Matplotlib is a plotting library for the Python. It can be used for plotting lines, bar-chart, graphs, histograms and even displaying Images." }, { "code": null, "e": 6468, "s": 6391, "text": "%matplotlib inline is a command that makes our plots appear in the notebook." }, { "code": null, "e": 6639, "s": 6468, "text": "os is an inbuilt python package for accessing your computer and file system. It can be used to display content in directories, create new folders and even delete folders." }, { "code": null, "e": 6739, "s": 6639, "text": "random will help us create random numbers which will be used when we split or shuffle our data set." }, { "code": null, "e": 6984, "s": 6739, "text": "gc short for garbage collector is an important tool for manually cleaning and deleting unnecessary variables. We’ll actively use this on Kaggle kernels because the free memory allocated to us may get full since we are working on Image datasets." }, { "code": null, "e": 7105, "s": 6984, "text": "After importing the necessary libraries, we read our Images in to memory. The data is stored as Zip files in our kernel." }, { "code": null, "e": 7129, "s": 7105, "text": "We can see three files:" }, { "code": null, "e": 7672, "s": 7129, "text": "sample submission.csv This is a csv (comma seperated value) file that is used for making submission after training your model and testing it on the test files given to you. Since this competition is over, we cannot make submissions, so we’ll ignore this file.test.zipThis file contains the Images we’re going to test our models on after training, to know if our model has learnt to differentiate dogs from cats.train.zipThis is the food for our model. It contains the data we’re going to use to teach our model what a dog or a cat looks like." }, { "code": null, "e": 7932, "s": 7672, "text": "sample submission.csv This is a csv (comma seperated value) file that is used for making submission after training your model and testing it on the test files given to you. Since this competition is over, we cannot make submissions, so we’ll ignore this file." }, { "code": null, "e": 8085, "s": 7932, "text": "test.zipThis file contains the Images we’re going to test our models on after training, to know if our model has learnt to differentiate dogs from cats." }, { "code": null, "e": 8217, "s": 8085, "text": "train.zipThis is the food for our model. It contains the data we’re going to use to teach our model what a dog or a cat looks like." }, { "code": null, "e": 8313, "s": 8217, "text": "Now to access our training Images, we’re going to use the os package which we imported earlier." }, { "code": null, "e": 8471, "s": 8313, "text": "Note: All data file paths on kaggle start with the root directory ../input. for example the file path to the train data in this kernel will be ../input/train" }, { "code": null, "e": 9598, "s": 8471, "text": "Here we create a file path to our train and test dataHere we create two variables train_dogs and train_cats. One for all dog images and the other for cat images. We write a list comprehension that uses the command os.listdir() to get all the images in the train data zip file and retrieve all images with dog in their name. ** We do the same for cat images.We get our test images too.The train data set contains a total of 25,000 images, but since we are experimenting working with a small data set and we obviously have access to little computational power, we’re going to extract only 2000 images from both classes. ** 2000 dog images and 2000 cat images, making a training data set of 4000 images.So we grab the first 2000 images from the train_dogs and train_cats, then concatenate them into one train set called train_imgs.VERY IMPORTANT! we randomly shuffle the train_imgs .Here we do some cleaning. As you may have noticed, we now have train_imgs meaning train_dogs and train_cats variables are useless and taking unnecessary space. If we don’t delete them, we might run out of memory when we start training our model." }, { "code": null, "e": 9652, "s": 9598, "text": "Here we create a file path to our train and test data" }, { "code": null, "e": 9957, "s": 9652, "text": "Here we create two variables train_dogs and train_cats. One for all dog images and the other for cat images. We write a list comprehension that uses the command os.listdir() to get all the images in the train data zip file and retrieve all images with dog in their name. ** We do the same for cat images." }, { "code": null, "e": 9985, "s": 9957, "text": "We get our test images too." }, { "code": null, "e": 10431, "s": 9985, "text": "The train data set contains a total of 25,000 images, but since we are experimenting working with a small data set and we obviously have access to little computational power, we’re going to extract only 2000 images from both classes. ** 2000 dog images and 2000 cat images, making a training data set of 4000 images.So we grab the first 2000 images from the train_dogs and train_cats, then concatenate them into one train set called train_imgs." }, { "code": null, "e": 10484, "s": 10431, "text": "VERY IMPORTANT! we randomly shuffle the train_imgs ." }, { "code": null, "e": 10730, "s": 10484, "text": "Here we do some cleaning. As you may have noticed, we now have train_imgs meaning train_dogs and train_cats variables are useless and taking unnecessary space. If we don’t delete them, we might run out of memory when we start training our model." }, { "code": null, "e": 10777, "s": 10730, "text": "Okay, lets view some images in our train_imgs." }, { "code": null, "e": 10884, "s": 10777, "text": "Import an image plotting module from matplotlibRun a for loop to plot the first three images in train_imgs" }, { "code": null, "e": 10932, "s": 10884, "text": "Import an image plotting module from matplotlib" }, { "code": null, "e": 10992, "s": 10932, "text": "Run a for loop to plot the first three images in train_imgs" }, { "code": null, "e": 11159, "s": 10992, "text": "Remember its a random list, but luckily when I ran the code the first three images was made up to two dogs and one cat and notice that they have different dimensions." }, { "code": null, "e": 11351, "s": 11159, "text": "In the next code block we’re going resize the images using the cv2 module.First let’s declare the new dimensions we want to use. Here I’m using 150 by 150 for height and width and 3 channels." }, { "code": null, "e": 11534, "s": 11351, "text": "A colored Image is made up of 3 channels, i.e 3 arrays of red, green and blue pixel values. We could use 1 channel which would read our images in gray-scale format (black and white)." }, { "code": null, "e": 11654, "s": 11534, "text": "Now, lets write a little function that helps also read and then resize our images to the height and width stated above." }, { "code": null, "e": 11942, "s": 11654, "text": "Create a new variable X which will hold the new training set and y which will hold our training labels. (1 if the image is a dog and 0 if it is a cat)we read our images one after the other and resize them with the cv2 commands.We append 1 to y if the image is a dog and 0 if it is a cat." }, { "code": null, "e": 12093, "s": 11942, "text": "Create a new variable X which will hold the new training set and y which will hold our training labels. (1 if the image is a dog and 0 if it is a cat)" }, { "code": null, "e": 12171, "s": 12093, "text": "we read our images one after the other and resize them with the cv2 commands." }, { "code": null, "e": 12232, "s": 12171, "text": "We append 1 to y if the image is a dog and 0 if it is a cat." }, { "code": null, "e": 12285, "s": 12232, "text": "Now, let’s call our function and process the images." }, { "code": null, "e": 12327, "s": 12285, "text": "X, y = read_and_process_image(train_imgs)" }, { "code": null, "e": 12430, "s": 12327, "text": "X is now an array of image pixel values and y is a list of labels. Let’s preview the first image in X." }, { "code": null, "e": 12606, "s": 12430, "text": "And that my friend is a dog image. Or we can say what our computer calls a dog. Wait! how did I know its a dog? well, lets look at the corresponding value in the label list y." }, { "code": null, "e": 12680, "s": 12606, "text": "Well, remember we said lets 1 and 0 represent dogs and cats respectively." }, { "code": null, "e": 12921, "s": 12680, "text": "Still don’t believe me. Then, let’s plot the first 5 arrays of X. We can’t plot the images in X with the mpimg module of matplotlib.image above because these are now arrays of pixels not raw jpg files. So we should use the imshow() command." }, { "code": null, "e": 13209, "s": 12921, "text": "Now that we’re confident that our training set contains the appropriate images of dogs and cats, let’s look at our labels. Remember we have a total of 4000 images (2000 dogs and 2000 cats), therefore our label list y should contain 2000 of 1s and 2000 of 0s. Let’s plot this and confirm." }, { "code": null, "e": 13715, "s": 13209, "text": "We import seaborn package, another plotting package built on top of matplotlib that gives very beautiful plots.Remember we are neat people and we don’t wait for the garbage man to do the cleaning for us. So we delete the train_imgs, since it has already been converted to an array and saved in X.X and y are currently of type list (list of python array), we will convert these to numpy array so we can feed it into our model.Plot a colorful diagram to confirm the number of classes in our y label variable" }, { "code": null, "e": 13827, "s": 13715, "text": "We import seaborn package, another plotting package built on top of matplotlib that gives very beautiful plots." }, { "code": null, "e": 14013, "s": 13827, "text": "Remember we are neat people and we don’t wait for the garbage man to do the cleaning for us. So we delete the train_imgs, since it has already been converted to an array and saved in X." }, { "code": null, "e": 14143, "s": 14013, "text": "X and y are currently of type list (list of python array), we will convert these to numpy array so we can feed it into our model." }, { "code": null, "e": 14224, "s": 14143, "text": "Plot a colorful diagram to confirm the number of classes in our y label variable" }, { "code": null, "e": 14290, "s": 14224, "text": "Great! we have 2000 classes of both dogs and cats. Let’s move on." }, { "code": null, "e": 14403, "s": 14290, "text": "Next let’s check the shape of our data. Always check and confirm the shapes of your data, it is super important." }, { "code": null, "e": 14604, "s": 14403, "text": "We can see that our image is a tensor of rank 4, or we could say a 4 dimensional array with dimensions 4000 x 150 x 150 x 3 which correspond to the batch size, height, width and channels respectively." }, { "code": null, "e": 14751, "s": 14604, "text": "The shape of our image array is important for the keras model we’re going to build. The model takes as input an array of ( height, width,channels)" }, { "code": null, "e": 15010, "s": 14751, "text": "Now that our data is ready (X,y) we could start training, but first we have to do something that is very important, which is to split our data into train and validation set. This is one of the most important things to do before you start training your model." }, { "code": null, "e": 15127, "s": 15010, "text": "For splitting, we’re going to use a handy function from a popular machine learning package in python called sklearn." }, { "code": null, "e": 15341, "s": 15127, "text": "Imports train_test_split from sklearnWe tell the function we want 20% of the data to be assigned to the validation set and the other 80% to the train set.Here we print the shape of the new train and validation set" }, { "code": null, "e": 15379, "s": 15341, "text": "Imports train_test_split from sklearn" }, { "code": null, "e": 15497, "s": 15379, "text": "We tell the function we want 20% of the data to be assigned to the validation set and the other 80% to the train set." }, { "code": null, "e": 15557, "s": 15497, "text": "Here we print the shape of the new train and validation set" }, { "code": null, "e": 15654, "s": 15557, "text": "Next, we’re going to declare some important variables that will be used when training our model." }, { "code": null, "e": 15728, "s": 15654, "text": "Yes, we’re still cleaning.get the length of the train and validation set." }, { "code": null, "e": 15755, "s": 15728, "text": "Yes, we’re still cleaning." }, { "code": null, "e": 15803, "s": 15755, "text": "get the length of the train and validation set." }, { "code": null, "e": 15850, "s": 15803, "text": "Wheeeeeew....Now its time to create our model." }, { "code": null, "e": 16089, "s": 15850, "text": "We are going to use a Convolutional Neural Network (convnet) to train our model. Convets are currently the standard when it comes to Computer Vision problems. They have always outperform other types of neural network in any image problem." }, { "code": null, "e": 16197, "s": 16089, "text": "New to convnets? At the end of this post, there are good links to sites where you can learn all about them." }, { "code": null, "e": 16245, "s": 16197, "text": "In creating our model we’re going to use KERAS." }, { "code": null, "e": 16271, "s": 16245, "text": "According to wikipedia..." }, { "code": null, "e": 16551, "s": 16271, "text": "Keras is an open source neural network library written in Python. It is capable of running on top of TensorFlow, Microsoft Cognitive Toolkit, or Theano. Designed to enable fast experimentation with deep neural networks, it focuses on being user-friendly, modular, and extensible." }, { "code": null, "e": 16619, "s": 16551, "text": "First let’s import the neccessary keras modules we are going to use" }, { "code": null, "e": 17538, "s": 16619, "text": "Here we import keras layers module which contains different types of layers used in deep learning such as:** Convolutional layer (Mostly used in computer vision)** Pooling layer (also used in computer vision)** Recurrent layer (Mostly used in sequential and time series modelling)** Embedding layers (Mostly used in Natural Language processing)** Normalization layers ** and many moreHere we import keras models which contains two types:**Sequential model which we’ll be using in this tutorial and**The model with the Functional APIHere we import keras optimizer, a module that contains different types of back propagation algorithm for training our model. Some of these optimizers are:**sgd (stochastic gradient descent)**rmsprop (root mean square propagation)**Adams**Adagrad**AdadeltaHere we import one of the most important function (ImageDataGenerator) used when working with a small data set. More on this below." }, { "code": null, "e": 17923, "s": 17538, "text": "Here we import keras layers module which contains different types of layers used in deep learning such as:** Convolutional layer (Mostly used in computer vision)** Pooling layer (also used in computer vision)** Recurrent layer (Mostly used in sequential and time series modelling)** Embedding layers (Mostly used in Natural Language processing)** Normalization layers ** and many more" }, { "code": null, "e": 18072, "s": 17923, "text": "Here we import keras models which contains two types:**Sequential model which we’ll be using in this tutorial and**The model with the Functional API" }, { "code": null, "e": 18328, "s": 18072, "text": "Here we import keras optimizer, a module that contains different types of back propagation algorithm for training our model. Some of these optimizers are:**sgd (stochastic gradient descent)**rmsprop (root mean square propagation)**Adams**Adagrad**Adadelta" }, { "code": null, "e": 18460, "s": 18328, "text": "Here we import one of the most important function (ImageDataGenerator) used when working with a small data set. More on this below." }, { "code": null, "e": 18588, "s": 18460, "text": "Now lets create our Network architecture. We are going to follow a popular, effective and simple architecture called the VGGnet" }, { "code": null, "e": 18659, "s": 18588, "text": "Network architecture is just the way we arrange our convolution layers" }, { "code": null, "e": 18770, "s": 18659, "text": "We are going to use a small vggnet, but you can see below that our filter size increases as we go down layers." }, { "code": null, "e": 18811, "s": 18770, "text": "32 → 64 →128 →512 — and final layer is 1" }, { "code": null, "e": 20010, "s": 18811, "text": "Here we create a sequential model. This tells keras to stack all layers sequentially.Here we create the first layer by calling the .add() function on the model we created and pass the type of layer we want — a Conv2D layer. This first layer is called the input layer and has some important parameters we need to set.** filter size [32]: This is the size of the output dimension (i.e. the number of output filters in the convolution)** kernel_size [3,3]: This specifies the height and width of the 2D convolution window.** activation [‘relu’]: We select an activation function also called non-linearity to be used by our neural network. ReLU (Rectified Linear Unit) is the most common activation function used today, other variations are leaky ReLU and eLU.** input shape [150,150,3]: Remember the dimensions we resized our images to? 150 by 150 right? we pass that here including the channel of 3. We do not pass the first dimension of 4000 because that is the batch dimension.Here we add a MaxPool2D layer. Its function is to reduce the spatial size of the incoming features and therefore helps reduce the number of parameters and computation in the network, thereby helping to reduce overfitting." }, { "code": null, "e": 20096, "s": 20010, "text": "Here we create a sequential model. This tells keras to stack all layers sequentially." }, { "code": null, "e": 20989, "s": 20096, "text": "Here we create the first layer by calling the .add() function on the model we created and pass the type of layer we want — a Conv2D layer. This first layer is called the input layer and has some important parameters we need to set.** filter size [32]: This is the size of the output dimension (i.e. the number of output filters in the convolution)** kernel_size [3,3]: This specifies the height and width of the 2D convolution window.** activation [‘relu’]: We select an activation function also called non-linearity to be used by our neural network. ReLU (Rectified Linear Unit) is the most common activation function used today, other variations are leaky ReLU and eLU.** input shape [150,150,3]: Remember the dimensions we resized our images to? 150 by 150 right? we pass that here including the channel of 3. We do not pass the first dimension of 4000 because that is the batch dimension." }, { "code": null, "e": 21211, "s": 20989, "text": "Here we add a MaxPool2D layer. Its function is to reduce the spatial size of the incoming features and therefore helps reduce the number of parameters and computation in the network, thereby helping to reduce overfitting." }, { "code": null, "e": 21350, "s": 21211, "text": "Overfitting happens when our model memorizes the training data. The model will perform excellently at training time but fail at test time." }, { "code": null, "e": 22378, "s": 21350, "text": "Here we add a Flatten layer. A conv2D layers extract and learn spatial features which are then passed to a dense layer after it has been flattened. This is the work of the flatten layer.Here we add a Dropout layer with value 0.5. Dropout randomly drops some layers in a neural networks and then learns with the reduced network. This way, the network learns to be independent and not reliable on a single layer. Bottom-line is that it helps in overfitting.0.5 means to randomly drop half of the layers.The last layer has an output size of 1 and a different activation function called sigmoid. This is because we’re trying to detect if an image is a dog or a cat. i.e we want the model to output a probability of how sure an image is a dog and not a cat, that means we want a probability score where higher values means the classifier believes the image is a dog and lower values means it is a cat.The sigmoid is perfect for this because it takes in a set of numbers and returns a probability distribution in the range of 0 to 1." }, { "code": null, "e": 22565, "s": 22378, "text": "Here we add a Flatten layer. A conv2D layers extract and learn spatial features which are then passed to a dense layer after it has been flattened. This is the work of the flatten layer." }, { "code": null, "e": 22881, "s": 22565, "text": "Here we add a Dropout layer with value 0.5. Dropout randomly drops some layers in a neural networks and then learns with the reduced network. This way, the network learns to be independent and not reliable on a single layer. Bottom-line is that it helps in overfitting.0.5 means to randomly drop half of the layers." }, { "code": null, "e": 23408, "s": 22881, "text": "The last layer has an output size of 1 and a different activation function called sigmoid. This is because we’re trying to detect if an image is a dog or a cat. i.e we want the model to output a probability of how sure an image is a dog and not a cat, that means we want a probability score where higher values means the classifier believes the image is a dog and lower values means it is a cat.The sigmoid is perfect for this because it takes in a set of numbers and returns a probability distribution in the range of 0 to 1." }, { "code": null, "e": 23535, "s": 23408, "text": "We can preview the arrangement and parameter size of our convnet by calling the Keras function .summary() on the model object." }, { "code": null, "e": 23658, "s": 23535, "text": "We can see the number of parameters we want to train (3 million-plus) and the general arrangement of the different layers." }, { "code": null, "e": 23697, "s": 23658, "text": "The next step is to compile our model." }, { "code": null, "e": 23753, "s": 23697, "text": "We pass three parameters to the model.compile() command" }, { "code": null, "e": 24545, "s": 23753, "text": "Loss [‘binary_crossentropy’]: We specify a loss function that our optimizer will minimize. In this case, since we’re working with a two-class problem, we use binary cross-entropy loss.Remember the optimizers we defined earlier? we’re going to use one of them called the rmsprop. This is not a fixed choice, it is part of a process called hyperparameter tuning which may be the difference between a world-class model and a naive one.Here we specify which metric we want to use in measuring our model’s performance after training. We want to know if our model is doing well or not. Since we’re doing a classification problem, the accuracy metric (acc) is a good choice. Note: The metric you use in measuring the performance of your model will depend on the type of problem you’re dealing with." }, { "code": null, "e": 24730, "s": 24545, "text": "Loss [‘binary_crossentropy’]: We specify a loss function that our optimizer will minimize. In this case, since we’re working with a two-class problem, we use binary cross-entropy loss." }, { "code": null, "e": 24979, "s": 24730, "text": "Remember the optimizers we defined earlier? we’re going to use one of them called the rmsprop. This is not a fixed choice, it is part of a process called hyperparameter tuning which may be the difference between a world-class model and a naive one." }, { "code": null, "e": 25339, "s": 24979, "text": "Here we specify which metric we want to use in measuring our model’s performance after training. We want to know if our model is doing well or not. Since we’re doing a classification problem, the accuracy metric (acc) is a good choice. Note: The metric you use in measuring the performance of your model will depend on the type of problem you’re dealing with." }, { "code": null, "e": 25506, "s": 25339, "text": "Finally, before we start training our model we need to perform some Normalization. i.e scale our image pixel values to have a unit standard deviation and a mean of 0." }, { "code": null, "e": 25669, "s": 25506, "text": "We’ll use an important module in Keras called ImageDataGenerator which performs some important functions when we’re feeding Images into our model during training." }, { "code": null, "e": 25710, "s": 25669, "text": "But...but what is an ImageDataGenerator?" }, { "code": null, "e": 26335, "s": 25710, "text": "According to the creator of Keras François Chollet, Keras ImageDataGenerator() lets us quickly set-up python generators that automatically turn image files into preprocessed tensors that can be fed directly into models during training. It performs the following functions for us easily:1. Decode the JPEG content to RGB grids of pixels.2. Convert these into floating-point tensors.3. Rescale the pixel values (between 0 and 255) to the [0, 1] interval ( neural networks perform better with normalize data).4. It helps us easily augment images. (An important feature we’ll be using since we’re training on a small data set)." }, { "code": null, "e": 26486, "s": 26335, "text": "Okay, let’s create our ImageDataGenerator object. We’re going to create two generators, one for the training set and the other for our validation set." }, { "code": null, "e": 27105, "s": 26486, "text": "We pass the rescale option to the ImageDataGenerator object. The rescale=1./255 option is a very IMPORTANT parameter. It normalizes the image pixel values to have zero mean and standard deviation of 1. It helps your model to generally learn and update its parameters efficiently.The second set of options is Image augmentation. They tell the ImageDataGenerator to randomly apply some transformation to the Image. This will help to augment our data-set and improve generalization.Here we also create an ImageDataGenerator object for our validation set. Note: we don’t do data augmentation here. We only perform rescale." }, { "code": null, "e": 27385, "s": 27105, "text": "We pass the rescale option to the ImageDataGenerator object. The rescale=1./255 option is a very IMPORTANT parameter. It normalizes the image pixel values to have zero mean and standard deviation of 1. It helps your model to generally learn and update its parameters efficiently." }, { "code": null, "e": 27586, "s": 27385, "text": "The second set of options is Image augmentation. They tell the ImageDataGenerator to randomly apply some transformation to the Image. This will help to augment our data-set and improve generalization." }, { "code": null, "e": 27726, "s": 27586, "text": "Here we also create an ImageDataGenerator object for our validation set. Note: we don’t do data augmentation here. We only perform rescale." }, { "code": null, "e": 27857, "s": 27726, "text": "Now that we have the ImageDataGenerator objects, let's create python generators from them by passing our train and validation set." }, { "code": null, "e": 29090, "s": 27857, "text": "We call the .flow( ) method on the data generators we created above passing in the data and label set. X_train and y_train for training then X_val and y_val for validation.The batch size tells the data generator to only take the specified batch(32 in our case) of Images at a time.Now we train our network by calling .fit( ) method on the model and passing some parameters. The first parameter is the training set ImageDataGenerator object [train_generator].Here we specify the number of steps per epoch. This tells our model how many images we want to process before making a gradient update to our loss function.A total of 3200 images divided by the batch size of 32 will give us 100 steps. This means we going to make a total of 100 gradient update to our model in one pass through the entire training set.An epoch is a full-cycle or pass through the entire training set. In our case, an epoch is reached when we make 100 gradient updates as specified by our steps_per_epoch parameter. Epochs = 64, means we want to go over our training data 64 times and each time we will make gradient updates 100 times.We pass in our validation data generator.We set the step size here too. I’m going to use the same step size as stated above." }, { "code": null, "e": 29372, "s": 29090, "text": "We call the .flow( ) method on the data generators we created above passing in the data and label set. X_train and y_train for training then X_val and y_val for validation.The batch size tells the data generator to only take the specified batch(32 in our case) of Images at a time." }, { "code": null, "e": 29550, "s": 29372, "text": "Now we train our network by calling .fit( ) method on the model and passing some parameters. The first parameter is the training set ImageDataGenerator object [train_generator]." }, { "code": null, "e": 29902, "s": 29550, "text": "Here we specify the number of steps per epoch. This tells our model how many images we want to process before making a gradient update to our loss function.A total of 3200 images divided by the batch size of 32 will give us 100 steps. This means we going to make a total of 100 gradient update to our model in one pass through the entire training set." }, { "code": null, "e": 30202, "s": 29902, "text": "An epoch is a full-cycle or pass through the entire training set. In our case, an epoch is reached when we make 100 gradient updates as specified by our steps_per_epoch parameter. Epochs = 64, means we want to go over our training data 64 times and each time we will make gradient updates 100 times." }, { "code": null, "e": 30244, "s": 30202, "text": "We pass in our validation data generator." }, { "code": null, "e": 30328, "s": 30244, "text": "We set the step size here too. I’m going to use the same step size as stated above." }, { "code": null, "e": 30419, "s": 30328, "text": "Run the cell to start training....This will take a while. Go disturb someone on twitter..." }, { "code": null, "e": 30480, "s": 30419, "text": "Well after just 64 epochs, I got an accuracy of roughly 80%." }, { "code": null, "e": 30547, "s": 30480, "text": "Not bad for a model we trained from scratch with very little data." }, { "code": null, "e": 30687, "s": 30547, "text": "Maybe increasing the number of epochs and playing with some hyperparameters like batch size and the optimizer will help improve this score." }, { "code": null, "e": 30723, "s": 30687, "text": "I ‘ll leave that to you to explore." }, { "code": null, "e": 30881, "s": 30723, "text": "Next, we save our model, with the simple Keras function shown below, this way we can re-use it anytime instead of training again when rerunning our notebook." }, { "code": null, "e": 30963, "s": 30881, "text": "#Save the modelmodel.save_weights('model_wieghts.h5')model.save('model_keras.h5')" }, { "code": null, "e": 31088, "s": 30963, "text": "We’ll plot some graphs of the accuracy and the loss in both the train and validation set to see if we can get some insights." }, { "code": null, "e": 31532, "s": 31088, "text": "After training a Keras model, it always calculates and saves the metric we specified when we compiled our model in a variable called history. We can extract these values and plot them.Note: The history object contains all the updates that happened during training.Here we simply get the size of our epoch from the number of values in the ‘acc’ list.Here we plot the accuracy against the epoch size.Here we plot the loss against the epoch size." }, { "code": null, "e": 31797, "s": 31532, "text": "After training a Keras model, it always calculates and saves the metric we specified when we compiled our model in a variable called history. We can extract these values and plot them.Note: The history object contains all the updates that happened during training." }, { "code": null, "e": 31883, "s": 31797, "text": "Here we simply get the size of our epoch from the number of values in the ‘acc’ list." }, { "code": null, "e": 31933, "s": 31883, "text": "Here we plot the accuracy against the epoch size." }, { "code": null, "e": 31979, "s": 31933, "text": "Here we plot the loss against the epoch size." }, { "code": null, "e": 32020, "s": 31979, "text": "So what can we take away from this plot?" }, { "code": null, "e": 32325, "s": 32020, "text": "The first thing to note is that we’re not overfitting as the train and validation accuracy are pretty close and following each other.We can also notice that the accuracy keeps increasing as the epoch increases, giving us the intuition that increasing the epoch size will likely give us a higher accuracy." }, { "code": null, "e": 32459, "s": 32325, "text": "The first thing to note is that we’re not overfitting as the train and validation accuracy are pretty close and following each other." }, { "code": null, "e": 32631, "s": 32459, "text": "We can also notice that the accuracy keeps increasing as the epoch increases, giving us the intuition that increasing the epoch size will likely give us a higher accuracy." }, { "code": null, "e": 32819, "s": 32631, "text": "We’re still not overfitting as both train and validation loss are trending down closely just like the accuracy plot above and the loss will likely go lower if we increase the epoch size.." }, { "code": null, "e": 32933, "s": 32819, "text": "So there, you’ve got some intuition. Now try increasing the epoch size and play around with some hyperparameters." }, { "code": null, "e": 33029, "s": 32933, "text": "Before I conclude this tutorial we’re going to test our model on some Images from the test set." }, { "code": null, "e": 33104, "s": 33029, "text": "We perform the same pre-processing we did on the train and validation set." }, { "code": null, "e": 33398, "s": 33104, "text": "We read and convert the first 10 images in our test set to a list of array.Note: y_test will be empty because the test set has no label.We convert the list of array to one big numpy array.We create a test ImageDataGenerator and perform normalization only.Note: We do not augment the test set ." }, { "code": null, "e": 33535, "s": 33398, "text": "We read and convert the first 10 images in our test set to a list of array.Note: y_test will be empty because the test set has no label." }, { "code": null, "e": 33588, "s": 33535, "text": "We convert the list of array to one big numpy array." }, { "code": null, "e": 33694, "s": 33588, "text": "We create a test ImageDataGenerator and perform normalization only.Note: We do not augment the test set ." }, { "code": null, "e": 33829, "s": 33694, "text": "Now we’ll create a simple for loop, that iterates over the Images from the generator to make predictions. Then we’ll plot the results." }, { "code": null, "e": 34708, "s": 33829, "text": "Create a list to hold the labels we are going to generate.We set the figure size of the images we’re going to plot.Here we make a prediction on that particular image provided by the ImageDataGenerator by calling the .predict( ) method on our trained model.The pred variable is a probability of how sure the model is that the current image is a dog. Since we gave dogs a label of 1, a high probability — at least greater than average 0.5 — means our model is very confident that the image is a Dog, otherwise it is a cat.So we simply create an if -else statement that appends the string ‘Dog’ if the probability is greater than 0.5 otherwise it appends ‘cat’ to the text_label.We do this so we can add a title to the image when we plot it.Here we add a subplot so we can plot multiple images.Here we add the predicted class as a title to the image plot.We finally plot the image." }, { "code": null, "e": 34767, "s": 34708, "text": "Create a list to hold the labels we are going to generate." }, { "code": null, "e": 34825, "s": 34767, "text": "We set the figure size of the images we’re going to plot." }, { "code": null, "e": 34967, "s": 34825, "text": "Here we make a prediction on that particular image provided by the ImageDataGenerator by calling the .predict( ) method on our trained model." }, { "code": null, "e": 35450, "s": 34967, "text": "The pred variable is a probability of how sure the model is that the current image is a dog. Since we gave dogs a label of 1, a high probability — at least greater than average 0.5 — means our model is very confident that the image is a Dog, otherwise it is a cat.So we simply create an if -else statement that appends the string ‘Dog’ if the probability is greater than 0.5 otherwise it appends ‘cat’ to the text_label.We do this so we can add a title to the image when we plot it." }, { "code": null, "e": 35504, "s": 35450, "text": "Here we add a subplot so we can plot multiple images." }, { "code": null, "e": 35566, "s": 35504, "text": "Here we add the predicted class as a title to the image plot." }, { "code": null, "e": 35593, "s": 35566, "text": "We finally plot the image." }, { "code": null, "e": 35656, "s": 35593, "text": "Let’s see how our model performed on previously unseen images." }, { "code": null, "e": 35759, "s": 35656, "text": "Well....our model got one wrong from five images. I didn’t say it was at its best....at least not yet." }, { "code": null, "e": 35972, "s": 35759, "text": "Wheeeew.... it’s been a long post, but I guess it was worth it. In this next tutorial, we improved our model to achieve an accuracy of about 95% by using a pre-trained network. A process called Transfer Learning." }, { "code": null, "e": 36008, "s": 35972, "text": "Well, bye for now and happy coding." }, { "code": null, "e": 36041, "s": 36008, "text": "Link to this notebook on Github." }, { "code": null, "e": 36091, "s": 36041, "text": "Some amazing post and write-ups on CNN and Keras." }, { "code": null, "e": 36152, "s": 36091, "text": "CS231n Convolutional Neural Networks for Visual Recognition." }, { "code": null, "e": 36220, "s": 36152, "text": "Deep learning with python by Francois Chollet the creator of Keras." }, { "code": null, "e": 36255, "s": 36220, "text": "Convolution Neural network basics." }, { "code": null, "e": 36283, "s": 36255, "text": "A great medium post on CNN." }, { "code": null, "e": 36324, "s": 36283, "text": "An Intuitive guide to CNN | medium post." }, { "code": null, "e": 36340, "s": 36324, "text": "Keras tutorial." }, { "code": null, "e": 36391, "s": 36340, "text": "Questions, comments and contributions are welcome." }, { "code": null, "e": 36420, "s": 36391, "text": "Connect with me on twitter ." } ]
How to apply hover effect over button using SASS ? - GeeksforGeeks
14 Sep, 2021 Animation makes the user experience more beautiful and impressive. With the usage of HTML (HyperText Markup Language) elements and SASS ( Syntactically Awesome Stylesheet), we will design buttons that provide them with a colorful border and an animation effect. We will use Sass because it acts as a better substitute for CSS and a superset of CSS. Sass provides 100% compatibility to all browsers and provides a better syntax with a compiled CSS file. Sass provides two file extensions ‘SCSS‘ (Sassy Css) and ‘SASS‘ (Indented Syntax). We will use SCSS extension and various features of SCSS. Approach: We will introduce the button element and give the structure of the HTML page. We will use features of Sass to provide them with styling, border design using linear-gradient, and an animation effect. Step by step Implementation: Step 1: First, we will design simple buttons using a button tag of HTML. We will start by creating an HTML file. Inside the HTML head tag, we will include the meta links and external files to include fallback fonts. Inside the body tag, we will include attributes, classes and Id’s to provide them with designs and button tags to make it clickable. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="index.css"> <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@600&display=swap" rel="stylesheet"></head> <body> <div class="container"> <div class="border_btn1 border_btn1_animate"> <button class="container_button1 btn1-hover btn1-hover-animate"> Button 1 </button> </div> <div class="border_btn2 border_btn2_animate"> <button class="container_button2 btn2-hover btn2-hover-animate"> Button 2 </button> </div> </div></body></html> Step 2: We will create an SCSS file with a file extension .scss. We will include various features of SCSS. Variables that begins with a ‘$’ dollar sign and ends with a semicolon acts as a better tool to change the properties in a single place rather than searching in the entire code, Nesting include the parent class, and also we will use extend an element which helps to inherit the properties of an element. SCSS Code: index.scss /* Declaring variables */$range: 88vh;$background_color: #f3f3f3;$text-color: black; /* Declaring a mixin function by passing a actual argument */@mixin center($align) { display: flex; justify-content: center; align-items: center; flex-direction: $align;}*,*::before,*::after { padding: 0px; margin: 0px; box-sizing: inherit;} .container { /* Calling a mixin function name center by passing row as a information to it's actual argument */ @include center(row); /* Accessing variable using a '$' dollar sign */ height: $range; button { border: none; @include center(row); box-sizing: border-box; cursor: pointer; font-size: 21px; font-weight: bold; letter-spacing: 2px; width: 200px; height: 46px; background-color: $background_color; color: $text-color; font-family: "Cormorant", "Garamond"; margin-left: 23px; border-radius: 24px; } .border_btn1 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px; } .border_btn1_animate { background: linear-gradient( to left, red, orange, yellow, green, blue, indigo, violet ); } #{&}_button1 { margin-left: 0px; height: 44px; display: inline-block; position: relative; } .border_btn2 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px; } .border_btn2_animate { background: linear-gradient( to right, chartreuse, #6161fd, #fd31fd, #ffb03a, red ); } #{&}_button2 { /* Inheriting the properties of container_button1 */ @extend .container_button1; }}.btn1-hover:hover:before,.btn2-hover:hover:before { position: absolute; left: 0px; top: 0px; line-height: 2.1; min-width: 49px; font-size: 100%; border-radius: 24px; background: rgba(0, 0, 0, 0.1);} .btn1-hover:hover:before,.btn2-hover:hover:before { content: url("");}.btn1-hover-animate:hover:before,.btn2-hover-animate:hover:before { transition: width 0.5ms ease-in-out; animation: change 1s forwards 1;} @keyframes change { 0% { width: 1px; } 100% { width: 200px; }} Step 3: CSS or Cascading Style Sheets is compiled with SCSS. The best thing about SCSS is that it provides the Compiled CSS with browser support which makes it compatible across major browsers. We used CSS flexible box layout to make the buttons appear centered, linear-gradient to provide the border of the button with the touch of gradient followed by the direction ‘to left’ instructs the color to start. Animation and keyframes are used to display the effects when the cursor is over the button, added animation shorthand properties ‘animation: change 1s forwards 1‘ followed by animation-name – change, animation-delay-function: 1s, animation-fill-mode: forwards ( to stop the animation after the last keyframe ) animation-iteration-count-function: 1. When hovering the opacity of the background color of buttons, it will slightly increase the width from 1px to 200px depending upon the width of the button which is achieved by using the CSS keyframes. It’s not allowed to make any changes in the CSS file as it will automatically compile the SASS or SCSS file to CSS. Compiled CSS Code: index.css /* Declaring variables *//* Declaring a mixin function by passing a actual argument */*,*::before,*::after { padding: 0px; margin: 0px; box-sizing: inherit;} .container { /* Calling a mixin function name center by passing row as a information to it's actual argument */ display: flex; justify-content: center; align-items: center; flex-direction: row; /* Accessing variable using a '$' dollar sign */ height: 88vh;}.container button { border: none; display: flex; justify-content: center; align-items: center; flex-direction: row; box-sizing: border-box; cursor: pointer; font-size: 21px; font-weight: bold; letter-spacing: 2px; width: 200px; height: 46px; background-color: #f3f3f3; color: black; font-family: "Cormorant", "Garamond"; margin-left: 23px; border-radius: 24px;}.container .border_btn1 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px;}.container .border_btn1_animate { background: linear-gradient( to left, red, orange, yellow, green, blue, indigo, violet );}.container .container_button1,.container .container_button2 { margin-left: 0px; height: 44px; display: inline-block; position: relative;}.container .border_btn2 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px;}.container .border_btn2_animate { background: linear-gradient( to right, chartreuse, #6161fd, #fd31fd, #ffb03a, red );}.container .container_button2 { /* Inheriting the properties of container_button1 */} .btn1-hover:hover:before,.btn2-hover:hover:before { position: absolute; left: 0px; top: 0px; line-height: 2.1; min-width: 49px; font-size: 100%; border-radius: 24px; background: rgba(0, 0, 0, 0.1);} .btn1-hover:hover:before,.btn2-hover:hover:before { content: url("");} .btn1-hover-animate:hover:before,.btn2-hover-animate:hover:before { transition: width 0.5ms ease-in-out; animation: change 1s forwards 1;} @keyframes change { 0% { width: 1px; } 100% { width: 200px; }} Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions SASS CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24985, "s": 24957, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25579, "s": 24985, "text": "Animation makes the user experience more beautiful and impressive. With the usage of HTML (HyperText Markup Language) elements and SASS ( Syntactically Awesome Stylesheet), we will design buttons that provide them with a colorful border and an animation effect. We will use Sass because it acts as a better substitute for CSS and a superset of CSS. Sass provides 100% compatibility to all browsers and provides a better syntax with a compiled CSS file. Sass provides two file extensions ‘SCSS‘ (Sassy Css) and ‘SASS‘ (Indented Syntax). We will use SCSS extension and various features of SCSS." }, { "code": null, "e": 25789, "s": 25579, "text": "Approach: We will introduce the button element and give the structure of the HTML page. We will use features of Sass to provide them with styling, border design using linear-gradient, and an animation effect. " }, { "code": null, "e": 25818, "s": 25789, "text": "Step by step Implementation:" }, { "code": null, "e": 26167, "s": 25818, "text": "Step 1: First, we will design simple buttons using a button tag of HTML. We will start by creating an HTML file. Inside the HTML head tag, we will include the meta links and external files to include fallback fonts. Inside the body tag, we will include attributes, classes and Id’s to provide them with designs and button tags to make it clickable." }, { "code": null, "e": 26174, "s": 26169, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"index.css\"> <link href=\"https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@600&display=swap\" rel=\"stylesheet\"></head> <body> <div class=\"container\"> <div class=\"border_btn1 border_btn1_animate\"> <button class=\"container_button1 btn1-hover btn1-hover-animate\"> Button 1 </button> </div> <div class=\"border_btn2 border_btn2_animate\"> <button class=\"container_button2 btn2-hover btn2-hover-animate\"> Button 2 </button> </div> </div></body></html>", "e": 26989, "s": 26174, "text": null }, { "code": null, "e": 27401, "s": 26989, "text": "Step 2: We will create an SCSS file with a file extension .scss. We will include various features of SCSS. Variables that begins with a ‘$’ dollar sign and ends with a semicolon acts as a better tool to change the properties in a single place rather than searching in the entire code, Nesting include the parent class, and also we will use extend an element which helps to inherit the properties of an element. " }, { "code": null, "e": 27412, "s": 27401, "text": "SCSS Code:" }, { "code": null, "e": 27423, "s": 27412, "text": "index.scss" }, { "code": "/* Declaring variables */$range: 88vh;$background_color: #f3f3f3;$text-color: black; /* Declaring a mixin function by passing a actual argument */@mixin center($align) { display: flex; justify-content: center; align-items: center; flex-direction: $align;}*,*::before,*::after { padding: 0px; margin: 0px; box-sizing: inherit;} .container { /* Calling a mixin function name center by passing row as a information to it's actual argument */ @include center(row); /* Accessing variable using a '$' dollar sign */ height: $range; button { border: none; @include center(row); box-sizing: border-box; cursor: pointer; font-size: 21px; font-weight: bold; letter-spacing: 2px; width: 200px; height: 46px; background-color: $background_color; color: $text-color; font-family: \"Cormorant\", \"Garamond\"; margin-left: 23px; border-radius: 24px; } .border_btn1 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px; } .border_btn1_animate { background: linear-gradient( to left, red, orange, yellow, green, blue, indigo, violet ); } #{&}_button1 { margin-left: 0px; height: 44px; display: inline-block; position: relative; } .border_btn2 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px; } .border_btn2_animate { background: linear-gradient( to right, chartreuse, #6161fd, #fd31fd, #ffb03a, red ); } #{&}_button2 { /* Inheriting the properties of container_button1 */ @extend .container_button1; }}.btn1-hover:hover:before,.btn2-hover:hover:before { position: absolute; left: 0px; top: 0px; line-height: 2.1; min-width: 49px; font-size: 100%; border-radius: 24px; background: rgba(0, 0, 0, 0.1);} .btn1-hover:hover:before,.btn2-hover:hover:before { content: url(\"\");}.btn1-hover-animate:hover:before,.btn2-hover-animate:hover:before { transition: width 0.5ms ease-in-out; animation: change 1s forwards 1;} @keyframes change { 0% { width: 1px; } 100% { width: 200px; }}", "e": 29602, "s": 27423, "text": null }, { "code": null, "e": 29797, "s": 29602, "text": "Step 3: CSS or Cascading Style Sheets is compiled with SCSS. The best thing about SCSS is that it provides the Compiled CSS with browser support which makes it compatible across major browsers. " }, { "code": null, "e": 30362, "s": 29797, "text": "We used CSS flexible box layout to make the buttons appear centered, linear-gradient to provide the border of the button with the touch of gradient followed by the direction ‘to left’ instructs the color to start. Animation and keyframes are used to display the effects when the cursor is over the button, added animation shorthand properties ‘animation: change 1s forwards 1‘ followed by animation-name – change, animation-delay-function: 1s, animation-fill-mode: forwards ( to stop the animation after the last keyframe ) animation-iteration-count-function: 1. " }, { "code": null, "e": 30679, "s": 30362, "text": "When hovering the opacity of the background color of buttons, it will slightly increase the width from 1px to 200px depending upon the width of the button which is achieved by using the CSS keyframes. It’s not allowed to make any changes in the CSS file as it will automatically compile the SASS or SCSS file to CSS." }, { "code": null, "e": 30698, "s": 30679, "text": "Compiled CSS Code:" }, { "code": null, "e": 30708, "s": 30698, "text": "index.css" }, { "code": "/* Declaring variables *//* Declaring a mixin function by passing a actual argument */*,*::before,*::after { padding: 0px; margin: 0px; box-sizing: inherit;} .container { /* Calling a mixin function name center by passing row as a information to it's actual argument */ display: flex; justify-content: center; align-items: center; flex-direction: row; /* Accessing variable using a '$' dollar sign */ height: 88vh;}.container button { border: none; display: flex; justify-content: center; align-items: center; flex-direction: row; box-sizing: border-box; cursor: pointer; font-size: 21px; font-weight: bold; letter-spacing: 2px; width: 200px; height: 46px; background-color: #f3f3f3; color: black; font-family: \"Cormorant\", \"Garamond\"; margin-left: 23px; border-radius: 24px;}.container .border_btn1 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px;}.container .border_btn1_animate { background: linear-gradient( to left, red, orange, yellow, green, blue, indigo, violet );}.container .container_button1,.container .container_button2 { margin-left: 0px; height: 44px; display: inline-block; position: relative;}.container .border_btn2 { width: 200px; height: 44px; padding: 3px; border-radius: 41px; margin-left: 21px;}.container .border_btn2_animate { background: linear-gradient( to right, chartreuse, #6161fd, #fd31fd, #ffb03a, red );}.container .container_button2 { /* Inheriting the properties of container_button1 */} .btn1-hover:hover:before,.btn2-hover:hover:before { position: absolute; left: 0px; top: 0px; line-height: 2.1; min-width: 49px; font-size: 100%; border-radius: 24px; background: rgba(0, 0, 0, 0.1);} .btn1-hover:hover:before,.btn2-hover:hover:before { content: url(\"\");} .btn1-hover-animate:hover:before,.btn2-hover-animate:hover:before { transition: width 0.5ms ease-in-out; animation: change 1s forwards 1;} @keyframes change { 0% { width: 1px; } 100% { width: 200px; }}", "e": 32761, "s": 30708, "text": null }, { "code": null, "e": 32769, "s": 32761, "text": "Output:" }, { "code": null, "e": 32906, "s": 32769, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 32921, "s": 32906, "text": "CSS-Properties" }, { "code": null, "e": 32935, "s": 32921, "text": "CSS-Questions" }, { "code": null, "e": 32950, "s": 32935, "text": "HTML-Questions" }, { "code": null, "e": 32955, "s": 32950, "text": "SASS" }, { "code": null, "e": 32959, "s": 32955, "text": "CSS" }, { "code": null, "e": 32964, "s": 32959, "text": "HTML" }, { "code": null, "e": 32981, "s": 32964, "text": "Web Technologies" }, { "code": null, "e": 32986, "s": 32981, "text": "HTML" }, { "code": null, "e": 33084, "s": 32986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33093, "s": 33084, "text": "Comments" }, { "code": null, "e": 33106, "s": 33093, "text": "Old Comments" }, { "code": null, "e": 33143, "s": 33106, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33172, "s": 33143, "text": "Form validation using jQuery" }, { "code": null, "e": 33211, "s": 33172, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33253, "s": 33211, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33288, "s": 33253, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 33348, "s": 33288, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33409, "s": 33348, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33462, "s": 33409, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33512, "s": 33462, "text": "How to Insert Form Data into Database using PHP ?" } ]
How to stop a function during its execution in JavaScript?
To stop a function during its execution, use the concept of − document.getElementById().addEventListener(). Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <button type="button" id="call">Call the function</button> <button type="button" id="halt">Stop the function execution </button> <script> document.getElementById("call").addEventListener("click", callFunction); document.getElementById("halt").addEventListener("click", haltFunction); var timeValue = null; function callFunction() { timeValue = setInterval(function() { console.log("The call() is being executed...."); }, 1000); } function haltFunction() { clearInterval(timeValue); } </script> </body> </html> To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor. When you click Call the function button, it will execute the function. To stop the function, click Stop the function execution button. The snapshot is as follows −
[ { "code": null, "e": 1124, "s": 1062, "text": "To stop a function during its execution, use the concept of −" }, { "code": null, "e": 1170, "s": 1124, "text": "document.getElementById().addEventListener()." }, { "code": null, "e": 1181, "s": 1170, "text": " Live Demo" }, { "code": null, "e": 2133, "s": 1181, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<button type=\"button\" id=\"call\">Call the function</button>\n<button type=\"button\" id=\"halt\">Stop the function execution </button>\n<script>\n document.getElementById(\"call\").addEventListener(\"click\", callFunction);\n document.getElementById(\"halt\").addEventListener(\"click\", haltFunction);\n var timeValue = null;\n function callFunction() {\n timeValue = setInterval(function() {\n console.log(\"The call() is being executed....\");\n }, 1000);\n }\n function haltFunction() {\n clearInterval(timeValue);\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2294, "s": 2133, "text": "To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor." }, { "code": null, "e": 2429, "s": 2294, "text": "When you click Call the function button, it will execute the function. To stop the function, click Stop the function execution button." }, { "code": null, "e": 2458, "s": 2429, "text": "The snapshot is as follows −" } ]
Postman - Create Tests for CRUD
CRUD stands for Create, Retrieve, Update and Delete operations on any website opened in a browser. Whenever we launch an application, the retrieve operation is performed. On creating data, for example, adding a new user for a website, the create operation is performed. If we are modifying the information, for example, changing details of an existing customer in a website, the update operation is performed. Finally, to eliminate any information, for example, deleting a user in a website, the delete operation is carried out. To retrieve a resource from the server, the HTTP method − GET is used (discussed in details in the Chapter − Postman GET Requests). To create a resource in the server, the HTTP method − POST is used (discussed in details in the Chapter − Postman POST Requests). To modify a resource in the server, the HTTP method − PUT is used (discussed in details in the Chapter − Postman PUT Requests). To delete a resource in the server, the HTTP method − DELETE is used (discussed in details in the Chapter − Postman DELETE Requests). A Postman test is executed only if a request is successful. If a Response Body is not generated, it means our request is incorrect and we will not be able to execute any test to validate a Response. In Postman, tests are developed in JavaScript and can be developed using the JavaScript and Functional methods. Both the techniques are based on the language JavaScript. Follow the steps given below to develop tests in Javascript − Step 1 − Tests developed in the JavaScript method are mentioned within the Tests tab under the address bar. Step 2 − Add the below JavaScript verifications within the Tests tab − tests["Status Code should be 200"] = responseCode.code === 200 tests["Response time lesser than 10ms"] = responseTime<10 We can add one or more than one test for a particular request. Here, tests is a variable of type array which can hold data types− integer, string, Boolean and so on. The Status Code should be 200 and Response time lesser than 10ms are the names of the tests. It is recommended to give meaningful names to test. The responseCode.code is the response code obtained in the Response and the responseTime is the time taken to get the Response. Step 3 − Select the GET method and enter an endpoint then click on Send. Response In the Response, click on the Test Results tab − The Test Results tab shows the test which has passed in green and the test which has failed in red. The Test Results (1/2) means one out of the two tests has passed. Response shows the status as 200 OK and Response time as 129ms (the second test checks if the Response time is less than 10ms). Hence, the first test got passed and the second one failed along with the Assertion error. Follow the steps given below to develop a test in with functional method − Step 1 − Tests developed in the Functional method are mentioned within the Tests tab under the address bar. Step 2 − Add the below code within the Tests tab − pm.test["Status Code is 401"], function(){ pm.response.to.have.status(401) }) Here, pm.test is the function for the test being performed. Status Code is 401 and it is the name of the test which shall be visible in the Test Result after execution. The pm.response is used for obtaining the response and adding assertions on it to verify the header, code, status, and so on. Step 3 − Select the GET method and enter an endpoint then click on Send. Response In the Response, click on the Test Results tab − The Test Results tab shows the test in red as the test has failed. The Test Results (0/1) means zero out of the one test has passed. Response shows the status as 200 OK (the test checks if the response code is 401). Hence the test shows failed along with the Assertion error. 12 Lectures 1 hours Taurius Litvinavicius 25 Lectures 2 hours Anuja Jain 18 Lectures 2.5 hours Spotle Learn Print Add Notes Bookmark this page
[ { "code": null, "e": 2279, "s": 2108, "text": "CRUD stands for Create, Retrieve, Update and Delete operations on any website opened in a browser. Whenever we launch an application, the retrieve operation is performed." }, { "code": null, "e": 2518, "s": 2279, "text": "On creating data, for example, adding a new user for a website, the create operation is performed. If we are modifying the information, for example, changing details of an existing customer in a website, the update operation is performed." }, { "code": null, "e": 2637, "s": 2518, "text": "Finally, to eliminate any information, for example, deleting a user in a website, the delete operation is carried out." }, { "code": null, "e": 2899, "s": 2637, "text": "To retrieve a resource from the server, the HTTP method − GET is used (discussed in details in the Chapter − Postman GET Requests). To create a resource in the server, the HTTP method − POST is used (discussed in details in the Chapter − Postman POST Requests)." }, { "code": null, "e": 3161, "s": 2899, "text": "To modify a resource in the server, the HTTP method − PUT is used (discussed in details in the Chapter − Postman PUT Requests). To delete a resource in the server, the HTTP method − DELETE is used (discussed in details in the Chapter − Postman DELETE Requests)." }, { "code": null, "e": 3360, "s": 3161, "text": "A Postman test is executed only if a request is successful. If a Response Body is not generated, it means our request is incorrect and we will not be able to execute any test to validate a Response." }, { "code": null, "e": 3530, "s": 3360, "text": "In Postman, tests are developed in JavaScript and can be developed using the JavaScript and Functional methods. Both the techniques are based on the language JavaScript." }, { "code": null, "e": 3592, "s": 3530, "text": "Follow the steps given below to develop tests in Javascript −" }, { "code": null, "e": 3700, "s": 3592, "text": "Step 1 − Tests developed in the JavaScript method are mentioned within the Tests tab under the address bar." }, { "code": null, "e": 3771, "s": 3700, "text": "Step 2 − Add the below JavaScript verifications within the Tests tab −" }, { "code": null, "e": 3893, "s": 3771, "text": "tests[\"Status Code should be 200\"] = responseCode.code === 200\ntests[\"Response time lesser than 10ms\"] = responseTime<10\n" }, { "code": null, "e": 3956, "s": 3893, "text": "We can add one or more than one test for a particular request." }, { "code": null, "e": 4204, "s": 3956, "text": "Here, tests is a variable of type array which can hold data types− integer, string, Boolean and so on. The Status Code should be 200 and Response time lesser than 10ms are the names of the tests. It is recommended to give meaningful names to test." }, { "code": null, "e": 4332, "s": 4204, "text": "The responseCode.code is the response code obtained in the Response and the responseTime is the time taken to get the Response." }, { "code": null, "e": 4405, "s": 4332, "text": "Step 3 − Select the GET method and enter an endpoint then click on Send." }, { "code": null, "e": 4414, "s": 4405, "text": "Response" }, { "code": null, "e": 4463, "s": 4414, "text": "In the Response, click on the Test Results tab −" }, { "code": null, "e": 4629, "s": 4463, "text": "The Test Results tab shows the test which has passed in green and the test which has failed in red. The Test Results (1/2) means one out of the two tests has passed." }, { "code": null, "e": 4757, "s": 4629, "text": "Response shows the status as 200 OK and Response time as 129ms (the second test checks if the Response time is less than 10ms)." }, { "code": null, "e": 4848, "s": 4757, "text": "Hence, the first test got passed and the second one failed along with the Assertion error." }, { "code": null, "e": 4923, "s": 4848, "text": "Follow the steps given below to develop a test in with functional method −" }, { "code": null, "e": 5031, "s": 4923, "text": "Step 1 − Tests developed in the Functional method are mentioned within the Tests tab under the address bar." }, { "code": null, "e": 5082, "s": 5031, "text": "Step 2 − Add the below code within the Tests tab −" }, { "code": null, "e": 5162, "s": 5082, "text": "pm.test[\"Status Code is 401\"], function(){\n\tpm.response.to.have.status(401)\n})\n" }, { "code": null, "e": 5331, "s": 5162, "text": "Here, pm.test is the function for the test being performed. Status Code is 401 and it is the name of the test which shall be visible in the Test Result after execution." }, { "code": null, "e": 5457, "s": 5331, "text": "The pm.response is used for obtaining the response and adding assertions on it to verify the header, code, status, and so on." }, { "code": null, "e": 5530, "s": 5457, "text": "Step 3 − Select the GET method and enter an endpoint then click on Send." }, { "code": null, "e": 5539, "s": 5530, "text": "Response" }, { "code": null, "e": 5589, "s": 5539, "text": "In the Response, click on the Test Results tab −" }, { "code": null, "e": 5805, "s": 5589, "text": "The Test Results tab shows the test in red as the test has failed. The Test Results (0/1) means zero out of the one test has passed. Response shows the status as 200 OK (the test checks if the response code is 401)." }, { "code": null, "e": 5865, "s": 5805, "text": "Hence the test shows failed along with the Assertion error." }, { "code": null, "e": 5898, "s": 5865, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 5921, "s": 5898, "text": " Taurius Litvinavicius" }, { "code": null, "e": 5954, "s": 5921, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 5966, "s": 5954, "text": " Anuja Jain" }, { "code": null, "e": 6001, "s": 5966, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6015, "s": 6001, "text": " Spotle Learn" }, { "code": null, "e": 6022, "s": 6015, "text": " Print" }, { "code": null, "e": 6033, "s": 6022, "text": " Add Notes" } ]
Tk - Label Widget
A label widget is a common widget used in almost all Tk applications that is used to display simple text. The syntax for label widget is shown below − label labelName options The options available for the label widget are listed below in table − -background color Used to set background color for widget. -borderwidth width Used to draw with border in 3D effects. -font fontDescriptor Used to set font for widget. -foreground color Used to set foreground color for widget. -height number Used to set height for widget. -padx number Sets the padx for the widget. -pady number Sets the pady for the widget. -relief condition Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove. -text text Sets the text for the widget. -textvariable varName Variable associated with the widget. When the text of widget changes, the variable is set to text of widget. -width number Sets the width for widget. -justify alignment Sets the alignment of text, which can be left, center, or right. A simple example for label widget is shown below − #!/usr/bin/wish grid [label .myLabel -background red -foreground white -text "Hello World" -relief ridge -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -height 10 -width 35 -textvariable myvariable -justify left -underline 1] set myvariable "Test Hello" When we run the above program, we will get the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2201, "text": "A label widget is a common widget used in almost all Tk applications that is used to display simple text. The syntax for label widget is shown below −" }, { "code": null, "e": 2377, "s": 2352, "text": "label labelName options\n" }, { "code": null, "e": 2448, "s": 2377, "text": "The options available for the label widget are listed below in table −" }, { "code": null, "e": 2466, "s": 2448, "text": "-background color" }, { "code": null, "e": 2507, "s": 2466, "text": "Used to set background color for widget." }, { "code": null, "e": 2526, "s": 2507, "text": "-borderwidth width" }, { "code": null, "e": 2566, "s": 2526, "text": "Used to draw with border in 3D effects." }, { "code": null, "e": 2587, "s": 2566, "text": "-font fontDescriptor" }, { "code": null, "e": 2616, "s": 2587, "text": "Used to set font for widget." }, { "code": null, "e": 2634, "s": 2616, "text": "-foreground color" }, { "code": null, "e": 2675, "s": 2634, "text": "Used to set foreground color for widget." }, { "code": null, "e": 2690, "s": 2675, "text": "-height number" }, { "code": null, "e": 2721, "s": 2690, "text": "Used to set height for widget." }, { "code": null, "e": 2734, "s": 2721, "text": "-padx number" }, { "code": null, "e": 2764, "s": 2734, "text": "Sets the padx for the widget." }, { "code": null, "e": 2777, "s": 2764, "text": "-pady number" }, { "code": null, "e": 2807, "s": 2777, "text": "Sets the pady for the widget." }, { "code": null, "e": 2825, "s": 2807, "text": "-relief condition" }, { "code": null, "e": 2929, "s": 2825, "text": "Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove." }, { "code": null, "e": 2940, "s": 2929, "text": "-text text" }, { "code": null, "e": 2970, "s": 2940, "text": "Sets the text for the widget." }, { "code": null, "e": 2992, "s": 2970, "text": "-textvariable varName" }, { "code": null, "e": 3101, "s": 2992, "text": "Variable associated with the widget. When the text of widget changes, the variable is set to text of widget." }, { "code": null, "e": 3115, "s": 3101, "text": "-width number" }, { "code": null, "e": 3142, "s": 3115, "text": "Sets the width for widget." }, { "code": null, "e": 3161, "s": 3142, "text": "-justify alignment" }, { "code": null, "e": 3226, "s": 3161, "text": "Sets the alignment of text, which can be left, center, or right." }, { "code": null, "e": 3277, "s": 3226, "text": "A simple example for label widget is shown below −" }, { "code": null, "e": 3552, "s": 3277, "text": "#!/usr/bin/wish\n\ngrid [label .myLabel -background red -foreground white -text \"Hello World\" -relief ridge\n -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -height 10 -width 35 \n -textvariable myvariable -justify left -underline 1]\nset myvariable \"Test Hello\"" }, { "code": null, "e": 3618, "s": 3552, "text": "When we run the above program, we will get the following output −" }, { "code": null, "e": 3625, "s": 3618, "text": " Print" }, { "code": null, "e": 3636, "s": 3625, "text": " Add Notes" } ]
JavaScript | Replace multiple strings with multiple other strings - GeeksforGeeks
06 Jun, 2019 Given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using javascript.Below are the few methods to understand: replace() methodThis method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue) Parameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace the search value with.Return value:Returns a new string where the defines value(s) has been replaced by the new value. string.replace(searchVal, newvalue) Parameters: searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value. newvalue: This parameter is required. It specifies the value to replace the search value with. Return value:Returns a new string where the defines value(s) has been replaced by the new value. JavaScript Array join() MethodThis method adds the elements of an array into a string, and returns the string.The elements will be separated by a passed separator. The default separator is comma (, ).Syntax:array.join(separator) Parameters:separator: This parameter is optional. It specifies the separator to be used. If not used, the elements are separated with a commaReturn value:It returns a string, denoting the array values, separated by the defined separator.Example 1: This example uses the RegExp to replace the strings according to the object using the replace() method.<!DOCTYPE html> <html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;">GeeksForGeeks</h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; var Obj = { Lenovo: "Dell", Honor: "OnePlus", Samsung: "Lenovo" }; up.innerHTML = str; function GFG_Fun() { down.innerHTML = str.replace(/Lenovo|Honor|Samsung/gi, function(matched){ return Obj[matched]; }); } </script></body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example first creates a RegExp and then using the replace() method to replace the particular keywords with the new one.<!DOCTYPE HTML><html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; var Obj = { Lenovo: "Dell", Honor: "OnePlus", Samsung: "Lenovo" }; up.innerHTML = str; function GFG_Fun() { var RE = new RegExp(Object.keys(Obj).join("|"), "gi"); down.innerHTML = str.replace(RE, function(matched) { return Obj[matched]; }); } </script></body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes arrow_drop_upSave array.join(separator) Parameters: separator: This parameter is optional. It specifies the separator to be used. If not used, the elements are separated with a comma Return value:It returns a string, denoting the array values, separated by the defined separator. Example 1: This example uses the RegExp to replace the strings according to the object using the replace() method. <!DOCTYPE html> <html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;">GeeksForGeeks</h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; var Obj = { Lenovo: "Dell", Honor: "OnePlus", Samsung: "Lenovo" }; up.innerHTML = str; function GFG_Fun() { down.innerHTML = str.replace(/Lenovo|Honor|Samsung/gi, function(matched){ return Obj[matched]; }); } </script></body> </html> Output: Before clicking the button: After clicking the button: Example 2: This example first creates a RegExp and then using the replace() method to replace the particular keywords with the new one. <!DOCTYPE HTML><html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab."; var Obj = { Lenovo: "Dell", Honor: "OnePlus", Samsung: "Lenovo" }; up.innerHTML = str; function GFG_Fun() { var RE = new RegExp(Object.keys(Obj).join("|"), "gi"); down.innerHTML = str.replace(RE, function(matched) { return Obj[matched]; }); } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 30060, "s": 30032, "text": "\n06 Jun, 2019" }, { "code": null, "e": 30264, "s": 30060, "text": "Given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using javascript.Below are the few methods to understand:" }, { "code": null, "e": 30786, "s": 30264, "text": "replace() methodThis method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)\nParameters:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to replace the search value with.Return value:Returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 30823, "s": 30786, "text": "string.replace(searchVal, newvalue)\n" }, { "code": null, "e": 30835, "s": 30823, "text": "Parameters:" }, { "code": null, "e": 30964, "s": 30835, "text": "searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value." }, { "code": null, "e": 31059, "s": 30964, "text": "newvalue: This parameter is required. It specifies the value to replace the search value with." }, { "code": null, "e": 31156, "s": 31059, "text": "Return value:Returns a new string where the defines value(s) has been replaced by the new value." }, { "code": null, "e": 34072, "s": 31156, "text": "JavaScript Array join() MethodThis method adds the elements of an array into a string, and returns the string.The elements will be separated by a passed separator. The default separator is comma (, ).Syntax:array.join(separator)\nParameters:separator: This parameter is optional. It specifies the separator to be used. If not used, the elements are separated with a commaReturn value:It returns a string, denoting the array values, separated by the defined separator.Example 1: This example uses the RegExp to replace the strings according to the object using the replace() method.<!DOCTYPE html> <html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\">GeeksForGeeks</h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = \"I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.\"; var Obj = { Lenovo: \"Dell\", Honor: \"OnePlus\", Samsung: \"Lenovo\" }; up.innerHTML = str; function GFG_Fun() { down.innerHTML = str.replace(/Lenovo|Honor|Samsung/gi, function(matched){ return Obj[matched]; }); } </script></body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example first creates a RegExp and then using the replace() method to replace the particular keywords with the new one.<!DOCTYPE HTML><html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = \"I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.\"; var Obj = { Lenovo: \"Dell\", Honor: \"OnePlus\", Samsung: \"Lenovo\" }; up.innerHTML = str; function GFG_Fun() { var RE = new RegExp(Object.keys(Obj).join(\"|\"), \"gi\"); down.innerHTML = str.replace(RE, function(matched) { return Obj[matched]; }); } </script></body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34095, "s": 34072, "text": "array.join(separator)\n" }, { "code": null, "e": 34107, "s": 34095, "text": "Parameters:" }, { "code": null, "e": 34238, "s": 34107, "text": "separator: This parameter is optional. It specifies the separator to be used. If not used, the elements are separated with a comma" }, { "code": null, "e": 34335, "s": 34238, "text": "Return value:It returns a string, denoting the array values, separated by the defined separator." }, { "code": null, "e": 34450, "s": 34335, "text": "Example 1: This example uses the RegExp to replace the strings according to the object using the replace() method." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\">GeeksForGeeks</h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = \"I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.\"; var Obj = { Lenovo: \"Dell\", Honor: \"OnePlus\", Samsung: \"Lenovo\" }; up.innerHTML = str; function GFG_Fun() { down.innerHTML = str.replace(/Lenovo|Honor|Samsung/gi, function(matched){ return Obj[matched]; }); } </script></body> </html>", "e": 35440, "s": 34450, "text": null }, { "code": null, "e": 35448, "s": 35440, "text": "Output:" }, { "code": null, "e": 35476, "s": 35448, "text": "Before clicking the button:" }, { "code": null, "e": 35503, "s": 35476, "text": "After clicking the button:" }, { "code": null, "e": 35639, "s": 35503, "text": "Example 2: This example first creates a RegExp and then using the replace() method to replace the particular keywords with the new one." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Replace multiple strings with multiple other strings. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var str = \"I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.\"; var Obj = { Lenovo: \"Dell\", Honor: \"OnePlus\", Samsung: \"Lenovo\" }; up.innerHTML = str; function GFG_Fun() { var RE = new RegExp(Object.keys(Obj).join(\"|\"), \"gi\"); down.innerHTML = str.replace(RE, function(matched) { return Obj[matched]; }); } </script></body> </html>", "e": 36696, "s": 35639, "text": null }, { "code": null, "e": 36704, "s": 36696, "text": "Output:" }, { "code": null, "e": 36732, "s": 36704, "text": "Before clicking the button:" }, { "code": null, "e": 36759, "s": 36732, "text": "After clicking the button:" }, { "code": null, "e": 36777, "s": 36759, "text": "javascript-string" }, { "code": null, "e": 36788, "s": 36777, "text": "JavaScript" }, { "code": null, "e": 36805, "s": 36788, "text": "Web Technologies" }, { "code": null, "e": 36832, "s": 36805, "text": "Web technologies Questions" }, { "code": null, "e": 36930, "s": 36832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36939, "s": 36930, "text": "Comments" }, { "code": null, "e": 36952, "s": 36939, "text": "Old Comments" }, { "code": null, "e": 36997, "s": 36952, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37066, "s": 36997, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 37127, "s": 37066, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37199, "s": 37127, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37226, "s": 37199, "text": "File uploading in React.js" }, { "code": null, "e": 37268, "s": 37226, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 37301, "s": 37268, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37363, "s": 37301, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37406, "s": 37363, "text": "How to fetch data from an API in ReactJS ?" } ]
Stack and Array Implementation with Python and NodeJs | by Chamal Pradeep | Towards Data Science
We were discussed basic definitions of the Data structures and algorithms in the previous article. in this article, let’s dig deeper into the Data structure world, and especially, let’s get our hands dirty with a little bit for coding as well. Objectives of this article: Discuss Data types, built-in, and derived data types.Introduce Stack Derived Data StructureImplement and use Stack in Python {code} and NodeJs {code}Introduce Array Derived Data StructureImplement and use Stack in Python {code} and NodeJs {code} Discuss Data types, built-in, and derived data types. Introduce Stack Derived Data Structure Implement and use Stack in Python {code} and NodeJs {code} Introduce Array Derived Data Structure Implement and use Stack in Python {code} and NodeJs {code} Data structures are made from one or more Data objects. data objects represent the data that we are going to store using carefully designed data structures. Data types are identified as primary ways of classifying several types of data in a data structure such as string, character, integer, etc. There are two major data types in the programming world, namely build-in data types and Derived data types. These are the basic data types that programming languages are supporting. Mainly known as the primary data types in a particular programming language. These data types are implemented using one or more built-in (primary) data types. All data structures are developed based on such kind of derived data types. In this article, we will discuss Stack’s an Array's data structures with the implementation examples. The stack is an Abstract data type (ADT is a type for objects whose behavior is defined by a set of values and a set of operations) which is one of the main Data structures in programming languages, and for beginners, this is an easily understandable structure. LIFO (Last In First Out) is the main specialty of a stack. Like most of the data structures, the stack also represent real-world objects. For instance, a stack of coins, a stack of boxes, etc. A stack can be implemented using an array, a list, a pointer, etc. When it comes to a stack, there is a set of functions defined to use the stack efficiently in the programming context. Python implementation In python, we can use a list data type as a built-in data type to implement the stack data structure. {code}Please find the attached codebase in this Github link. NodeJs implementation In NodeJs, we can implement a stack data structure using the Array data type. {code} Please find the attached codebase in this Github link. Once you defined the stack class one of the main functionalities is push function. Here you will input an item to the top of the array. Algorithm to implement We can define an algorithm to implement the push operation in the stack class. Step 1 − Checks if the stack is full(assume that the list is implemented based on a dynamic array) for the given size or not.Step 2 − If the stack is full, print an errorStep 3 − If the stack is not full for the given maximum size, increase the top by one and point the pointer to the next empty space.Step 4 − Add a new element to the new empty space which is in the top of the stackStep 5 − Return success. The pop function will remove the topmost element from the stack, and the stack item count will be reduced by one. Even though it seems like the topmost element removed from the stack, still that element will not be completely removed, only the pointer will move to the below position. Algorithm to implement We can define an algorithm to implement the pop operation in the stack class. Step 1 − Checks if the stack is empty by looking at the array lengthStep 2 − If the stack is empty, print an error, exitStep 3 − If the stack is not empty, get the element which is pointing at the top of the stack.Step 4 − Decreases the size of the stack by 1, automatically the pointer of the top most item will changed to the below item.Step 5 − Returns success. The peek function will display the topmost element from the stack, and this operation will not remove the item from the stack like in the pop operation. Algorithm to implement We can define an algorithm to implement the peek operation in the stack class. the peek operation just returns the value at the top of the stack. Step 1 − Checks if the stack is empty by looking at the array lengthStep 2 − If the stack is empty, print an error, exitStep 3 − If the stack is not empty, get the element which is pointing at the top of the stack.Step 4 − Returns success. There are other functions like isEmpty(), isFull(), and printStackItems() which can be used as supportive functions that will help you to use the stack efficiently. Stack implementation and all supportive functional implementations will be found in this codebase. stack data structure Get your hands dirty with a stack data structure because we will use these data structures in the future when we are solving real-life problems in the algorithms section. The array is one of the most used data structures when programmers implementing their algorithms. One specialty of an array is that the array container should be in fixed size and all the elements should be in the same type. Apart from all the elements in the array should be in the same data type, array always starts from the 0th element (zero-indexed), and the size of the array means, how many elements can be stored in itself. In many data types, there are major operations(functionalities) that exist for the effective and efficient usage of that data type. In the array data type, there are five major operations exist. Add a new element to the given index is called the array insertion. We were able to implement inserting an element to the given index via python and nodejs programming language. Implementation of the array insert operation in nodejs Implementation of the array insert operation in python We can perform search operations on an array element based on either the value or an index. Search by index means, return the corresponding array element to the given index, and the search by value means to return the corresponding value the given index in the array. Implementation of the array insert operation in nodejs Implementation of the array insert operation in python Since the array is a fixed size data structure, delete an element from the given position in an array is a little bit tricky. You should adjust the new array by reducing the size of the array while you are deleting the given element. Please refer following code samples which explain how to delete a given element from an array with basic programming techniques. Implementation of the array insert operation in python Implementation of the array insert operation in Nodejs Array update is quite an easy operation that you just need to traverse through the given array until you find the required element to update. Please follow the following code samples to get more familiar with array update functionality. Implementation of the array update operation in nodejs — code Implementation of the array update operation in python — code Array traversal is nothing but print all the array elements in a sequence. Since the array is a zero-indexed data type, we can start to print array elements by traversal through the array structure from the zero position. Implementation of the array traversal operation in nodejs — code Implementation of the array traversal operation in python — code In conclusion, we have learned how to use the Stack and Array efficiently. Please find the following code segments to see how we can implement a stack and an array in python and nodejs. You will only need node installed in your machine and you are good to go. (node installation link) Start coding to get your hands dirty for the following lessons. FYI: when you trying to implement data structure operations, always remember on “Algorithm to implement” and think in that direction. This approach will help you to get a deep understanding of the entire workflow of data structure usage. In the next lesson, we will implement other derived data structures like a queue, linked list, doubly link list, and circular linked lists which are considered as highly important data structures to get a hand on before diving into algorithmic usage. For the Git repository cloning please click here See you with more lessons, happy coding!
[ { "code": null, "e": 291, "s": 47, "text": "We were discussed basic definitions of the Data structures and algorithms in the previous article. in this article, let’s dig deeper into the Data structure world, and especially, let’s get our hands dirty with a little bit for coding as well." }, { "code": null, "e": 319, "s": 291, "text": "Objectives of this article:" }, { "code": null, "e": 565, "s": 319, "text": "Discuss Data types, built-in, and derived data types.Introduce Stack Derived Data StructureImplement and use Stack in Python {code} and NodeJs {code}Introduce Array Derived Data StructureImplement and use Stack in Python {code} and NodeJs {code}" }, { "code": null, "e": 619, "s": 565, "text": "Discuss Data types, built-in, and derived data types." }, { "code": null, "e": 658, "s": 619, "text": "Introduce Stack Derived Data Structure" }, { "code": null, "e": 717, "s": 658, "text": "Implement and use Stack in Python {code} and NodeJs {code}" }, { "code": null, "e": 756, "s": 717, "text": "Introduce Array Derived Data Structure" }, { "code": null, "e": 815, "s": 756, "text": "Implement and use Stack in Python {code} and NodeJs {code}" }, { "code": null, "e": 1220, "s": 815, "text": "Data structures are made from one or more Data objects. data objects represent the data that we are going to store using carefully designed data structures. Data types are identified as primary ways of classifying several types of data in a data structure such as string, character, integer, etc. There are two major data types in the programming world, namely build-in data types and Derived data types." }, { "code": null, "e": 1371, "s": 1220, "text": "These are the basic data types that programming languages are supporting. Mainly known as the primary data types in a particular programming language." }, { "code": null, "e": 1631, "s": 1371, "text": "These data types are implemented using one or more built-in (primary) data types. All data structures are developed based on such kind of derived data types. In this article, we will discuss Stack’s an Array's data structures with the implementation examples." }, { "code": null, "e": 1952, "s": 1631, "text": "The stack is an Abstract data type (ADT is a type for objects whose behavior is defined by a set of values and a set of operations) which is one of the main Data structures in programming languages, and for beginners, this is an easily understandable structure. LIFO (Last In First Out) is the main specialty of a stack." }, { "code": null, "e": 2086, "s": 1952, "text": "Like most of the data structures, the stack also represent real-world objects. For instance, a stack of coins, a stack of boxes, etc." }, { "code": null, "e": 2272, "s": 2086, "text": "A stack can be implemented using an array, a list, a pointer, etc. When it comes to a stack, there is a set of functions defined to use the stack efficiently in the programming context." }, { "code": null, "e": 2294, "s": 2272, "text": "Python implementation" }, { "code": null, "e": 2396, "s": 2294, "text": "In python, we can use a list data type as a built-in data type to implement the stack data structure." }, { "code": null, "e": 2457, "s": 2396, "text": "{code}Please find the attached codebase in this Github link." }, { "code": null, "e": 2479, "s": 2457, "text": "NodeJs implementation" }, { "code": null, "e": 2557, "s": 2479, "text": "In NodeJs, we can implement a stack data structure using the Array data type." }, { "code": null, "e": 2619, "s": 2557, "text": "{code} Please find the attached codebase in this Github link." }, { "code": null, "e": 2755, "s": 2619, "text": "Once you defined the stack class one of the main functionalities is push function. Here you will input an item to the top of the array." }, { "code": null, "e": 2778, "s": 2755, "text": "Algorithm to implement" }, { "code": null, "e": 2857, "s": 2778, "text": "We can define an algorithm to implement the push operation in the stack class." }, { "code": null, "e": 3267, "s": 2857, "text": "Step 1 − Checks if the stack is full(assume that the list is implemented based on a dynamic array) for the given size or not.Step 2 − If the stack is full, print an errorStep 3 − If the stack is not full for the given maximum size, increase the top by one and point the pointer to the next empty space.Step 4 − Add a new element to the new empty space which is in the top of the stackStep 5 − Return success." }, { "code": null, "e": 3552, "s": 3267, "text": "The pop function will remove the topmost element from the stack, and the stack item count will be reduced by one. Even though it seems like the topmost element removed from the stack, still that element will not be completely removed, only the pointer will move to the below position." }, { "code": null, "e": 3575, "s": 3552, "text": "Algorithm to implement" }, { "code": null, "e": 3653, "s": 3575, "text": "We can define an algorithm to implement the pop operation in the stack class." }, { "code": null, "e": 4019, "s": 3653, "text": "Step 1 − Checks if the stack is empty by looking at the array lengthStep 2 − If the stack is empty, print an error, exitStep 3 − If the stack is not empty, get the element which is pointing at the top of the stack.Step 4 − Decreases the size of the stack by 1, automatically the pointer of the top most item will changed to the below item.Step 5 − Returns success." }, { "code": null, "e": 4172, "s": 4019, "text": "The peek function will display the topmost element from the stack, and this operation will not remove the item from the stack like in the pop operation." }, { "code": null, "e": 4195, "s": 4172, "text": "Algorithm to implement" }, { "code": null, "e": 4341, "s": 4195, "text": "We can define an algorithm to implement the peek operation in the stack class. the peek operation just returns the value at the top of the stack." }, { "code": null, "e": 4582, "s": 4341, "text": "Step 1 − Checks if the stack is empty by looking at the array lengthStep 2 − If the stack is empty, print an error, exitStep 3 − If the stack is not empty, get the element which is pointing at the top of the stack.Step 4 − Returns success." }, { "code": null, "e": 4747, "s": 4582, "text": "There are other functions like isEmpty(), isFull(), and printStackItems() which can be used as supportive functions that will help you to use the stack efficiently." }, { "code": null, "e": 4867, "s": 4747, "text": "Stack implementation and all supportive functional implementations will be found in this codebase. stack data structure" }, { "code": null, "e": 5038, "s": 4867, "text": "Get your hands dirty with a stack data structure because we will use these data structures in the future when we are solving real-life problems in the algorithms section." }, { "code": null, "e": 5263, "s": 5038, "text": "The array is one of the most used data structures when programmers implementing their algorithms. One specialty of an array is that the array container should be in fixed size and all the elements should be in the same type." }, { "code": null, "e": 5470, "s": 5263, "text": "Apart from all the elements in the array should be in the same data type, array always starts from the 0th element (zero-indexed), and the size of the array means, how many elements can be stored in itself." }, { "code": null, "e": 5665, "s": 5470, "text": "In many data types, there are major operations(functionalities) that exist for the effective and efficient usage of that data type. In the array data type, there are five major operations exist." }, { "code": null, "e": 5843, "s": 5665, "text": "Add a new element to the given index is called the array insertion. We were able to implement inserting an element to the given index via python and nodejs programming language." }, { "code": null, "e": 5898, "s": 5843, "text": "Implementation of the array insert operation in nodejs" }, { "code": null, "e": 5953, "s": 5898, "text": "Implementation of the array insert operation in python" }, { "code": null, "e": 6045, "s": 5953, "text": "We can perform search operations on an array element based on either the value or an index." }, { "code": null, "e": 6221, "s": 6045, "text": "Search by index means, return the corresponding array element to the given index, and the search by value means to return the corresponding value the given index in the array." }, { "code": null, "e": 6276, "s": 6221, "text": "Implementation of the array insert operation in nodejs" }, { "code": null, "e": 6331, "s": 6276, "text": "Implementation of the array insert operation in python" }, { "code": null, "e": 6694, "s": 6331, "text": "Since the array is a fixed size data structure, delete an element from the given position in an array is a little bit tricky. You should adjust the new array by reducing the size of the array while you are deleting the given element. Please refer following code samples which explain how to delete a given element from an array with basic programming techniques." }, { "code": null, "e": 6749, "s": 6694, "text": "Implementation of the array insert operation in python" }, { "code": null, "e": 6804, "s": 6749, "text": "Implementation of the array insert operation in Nodejs" }, { "code": null, "e": 7041, "s": 6804, "text": "Array update is quite an easy operation that you just need to traverse through the given array until you find the required element to update. Please follow the following code samples to get more familiar with array update functionality." }, { "code": null, "e": 7103, "s": 7041, "text": "Implementation of the array update operation in nodejs — code" }, { "code": null, "e": 7165, "s": 7103, "text": "Implementation of the array update operation in python — code" }, { "code": null, "e": 7387, "s": 7165, "text": "Array traversal is nothing but print all the array elements in a sequence. Since the array is a zero-indexed data type, we can start to print array elements by traversal through the array structure from the zero position." }, { "code": null, "e": 7452, "s": 7387, "text": "Implementation of the array traversal operation in nodejs — code" }, { "code": null, "e": 7517, "s": 7452, "text": "Implementation of the array traversal operation in python — code" }, { "code": null, "e": 7703, "s": 7517, "text": "In conclusion, we have learned how to use the Stack and Array efficiently. Please find the following code segments to see how we can implement a stack and an array in python and nodejs." }, { "code": null, "e": 7802, "s": 7703, "text": "You will only need node installed in your machine and you are good to go. (node installation link)" }, { "code": null, "e": 7866, "s": 7802, "text": "Start coding to get your hands dirty for the following lessons." }, { "code": null, "e": 8105, "s": 7866, "text": "FYI: when you trying to implement data structure operations, always remember on “Algorithm to implement” and think in that direction. This approach will help you to get a deep understanding of the entire workflow of data structure usage." }, { "code": null, "e": 8356, "s": 8105, "text": "In the next lesson, we will implement other derived data structures like a queue, linked list, doubly link list, and circular linked lists which are considered as highly important data structures to get a hand on before diving into algorithmic usage." }, { "code": null, "e": 8405, "s": 8356, "text": "For the Git repository cloning please click here" } ]
Java – String getBytes() Method
This method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. Here is the syntax of this method − public byte[] getBytes() This method returns the resultant byte array. import java.io.*; public class Test { public static void main(String args[]) { String Str1 = new String("Welcome to Tutorialspoint.com"); try { String Str2 = new String( Str1.getBytes( "UTF-8" )); System.out.println("Returned Value " + Str2 ); Str2 = new String (Str1.getBytes( "ISO-8859-1" )); System.out.println("Returned Value " + Str2 ); } catch ( UnsupportedEncodingException e) { System.out.println("Unsupported character set"); } } } This will produce the following result − Returned Value Welcome to Tutorialspoint.com Returned Value Welcome to Tutorialspoint.com 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2514, "s": 2377, "text": "This method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array." }, { "code": null, "e": 2550, "s": 2514, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2576, "s": 2550, "text": "public byte[] getBytes()\n" }, { "code": null, "e": 2622, "s": 2576, "text": "This method returns the resultant byte array." }, { "code": null, "e": 3146, "s": 2622, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str1 = new String(\"Welcome to Tutorialspoint.com\");\n \n try {\n String Str2 = new String( Str1.getBytes( \"UTF-8\" ));\n System.out.println(\"Returned Value \" + Str2 );\n Str2 = new String (Str1.getBytes( \"ISO-8859-1\" ));\n System.out.println(\"Returned Value \" + Str2 );\n } catch ( UnsupportedEncodingException e) {\n System.out.println(\"Unsupported character set\");\n }\n }\n}" }, { "code": null, "e": 3187, "s": 3146, "text": "This will produce the following result −" }, { "code": null, "e": 3278, "s": 3187, "text": "Returned Value Welcome to Tutorialspoint.com\nReturned Value Welcome to Tutorialspoint.com\n" }, { "code": null, "e": 3311, "s": 3278, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3327, "s": 3311, "text": " Malhar Lathkar" }, { "code": null, "e": 3360, "s": 3327, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3376, "s": 3360, "text": " Malhar Lathkar" }, { "code": null, "e": 3411, "s": 3376, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3425, "s": 3411, "text": " Anadi Sharma" }, { "code": null, "e": 3459, "s": 3425, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3473, "s": 3459, "text": " Tushar Kale" }, { "code": null, "e": 3510, "s": 3473, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3525, "s": 3510, "text": " Monica Mittal" }, { "code": null, "e": 3558, "s": 3525, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3577, "s": 3558, "text": " Arnab Chakraborty" }, { "code": null, "e": 3584, "s": 3577, "text": " Print" }, { "code": null, "e": 3595, "s": 3584, "text": " Add Notes" } ]
How to add/insert additional property to JSON string using Gson in Java?
The com.google.gson.JSonElement class represents an element of Json. We can use the toJsonTree() method of Gson class to serialize an object's representation as a tree of JsonElements. We can add/ insert an additional property to JSON string by using the getAsJsonObject() method of JSonElement. This method returns to get the element as JsonObject. public JsonObject getAsJsonObject() import com.google.gson.*; public class AddPropertyGsonTest { public static void main(String[] args) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print JSON Student student = new Student("Adithya"); String jsonStr = gson.toJson(student, Student.class); System.out.println("JSON String: \n" + jsonStr); JsonElement jsonElement = gson.toJsonTree(student); jsonElement.getAsJsonObject().addProperty("id", "115"); jsonStr = gson.toJson(jsonElement); System.out.println("JSON String after inserting additional property: \n" + jsonStr); } } // Student class class Student { private String name; public Student(String name) { this.name= name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } JSON String: { "name": "Adithya" } JSON String after inserting additional property: { "name": "Adithya", "id": "115" }
[ { "code": null, "e": 1412, "s": 1062, "text": "The com.google.gson.JSonElement class represents an element of Json. We can use the toJsonTree() method of Gson class to serialize an object's representation as a tree of JsonElements. We can add/ insert an additional property to JSON string by using the getAsJsonObject() method of JSonElement. This method returns to get the element as JsonObject." }, { "code": null, "e": 1448, "s": 1412, "text": "public JsonObject getAsJsonObject()" }, { "code": null, "e": 2303, "s": 1448, "text": "import com.google.gson.*;\npublic class AddPropertyGsonTest {\n public static void main(String[] args) {\n Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print JSON\n Student student = new Student(\"Adithya\");\n String jsonStr = gson.toJson(student, Student.class);\n System.out.println(\"JSON String: \\n\" + jsonStr);\n JsonElement jsonElement = gson.toJsonTree(student);\n jsonElement.getAsJsonObject().addProperty(\"id\", \"115\");\n jsonStr = gson.toJson(jsonElement);\n System.out.println(\"JSON String after inserting additional property: \\n\" + jsonStr);\n }\n}\n// Student class\nclass Student {\n private String name;\n public Student(String name) {\n this.name= name;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 2431, "s": 2303, "text": "JSON String:\n{\n \"name\": \"Adithya\"\n}\nJSON String after inserting additional property:\n{\n \"name\": \"Adithya\",\n \"id\": \"115\"\n}" } ]
K-Means Clustering. A simpler intuitive explanation. | by Abhishek Kumar | Towards Data Science
K-means is one of the simplest unsupervised learning algorithms. The algorithm follows a simple and easy way to group a given data set into a certain number of coherent subsets called as clusters. The idea is to find K centres, called as cluster centroids, one for each cluster, hence the name K-means clustering. On seeing a new example, the algorithm reports the closest cluster to which the example belongs based on a distance measure such as euclidean distance. Let’s consider an example for a better understanding — assume a social networking site wants to find groups (clusters) of people with like interests and direct relevant ads to them. One way to approach the problem is through clustering where the firm may use features such as pages liked, posts shared and places checked into to build a dataset and run it through a clustering algorithm to identify the relevant groups. One thing to note though is that, the dataset is unlabelled. A note on the notation. x_{i} means x subscript i, x_{^th} means x superscript th and x_{^th}{i} means x superscript th and subscript i. The K-means clustering algorithm begins with an initialisation step — called as the random initialisation step. The goal of this step is to randomly select a centroid, u_{i} i ∈ {1,2,3...K} for each of the K-clusters. These K centroids are then converged to an optimal value using an iterative algorithm. Each step of the iteration performs the following two steps — Cluster assignment Move centroid The cluster assignment step goes through each of the example x_{^i} in the dataset and assigns it to its closest cluster centroid based on a distance measure say euclidean distance. For the example discussed below one may say that — given an example, the cluster assignment step assigns it to a colour, green or yellow depending on the distance of that example from the cluster centroids. The move centroid step computes new cluster centroids by taking an average of the examples assigned to same cluster centroid. Alternatively, the average of all the points coloured yellow and green, give the new values for cluster centroids. Just to be clear this is the step responsible for convergence of randomly initialised cluster centroid to an optimal value. The algorithm continues until convergence — which is to say, until two subsequent iterations do not give nearly same values for cluster centroids. As discussed earlier that algorithm starts with random initialisation step — but random initialisation might lead to the algorithm getting stuck at a local optima. One way to improve our odds of ending up with better values for cluster centroids is to perform the random initialisation step multiple times and choose a set of values that leads to the minimum value of distortion cost function given by — The above cost function is computing the average of the squared distances between each of the training example, x_{^i} and the cluster to which it has been assigned, u_{^i}{c}. Squaring has been done to solely avoid square root arising due to euclidean distance. It is obvious that, smaller values of cost function correspond to better initialisation. This technique is effective for values of K≤10 but, it has been observed that for larger values of K, it does not make that significant a difference. For larger values of K, the K-means algorithm will pretty much converge to acceptable values of cluster centroids. Also, this method of optimising the random initialisation step is computationally expensive. Up until now, you must have developed an intuitive understanding of K-means clustering algorithm but there is one more aspect to be dealt with, the parameter K. Let’s take a look as to how we may know the number of clusters in which our data set needs to be divided. Elbow method can be used to find the optimal value of K. The method plots the number of clusters against the value of distortion cost function and chooses a value of K where the graph elbows out or has a sharp turn. But practically this method is not used as much, because when real world data is plotted the graph does not usually has a prominent elbow to pick a value of K. Unfortunately, there is no automatic way of picking up a value for K. Most of the times a value for the parameter K is manually picked by looking at the visualisations.
[ { "code": null, "e": 513, "s": 47, "text": "K-means is one of the simplest unsupervised learning algorithms. The algorithm follows a simple and easy way to group a given data set into a certain number of coherent subsets called as clusters. The idea is to find K centres, called as cluster centroids, one for each cluster, hence the name K-means clustering. On seeing a new example, the algorithm reports the closest cluster to which the example belongs based on a distance measure such as euclidean distance." }, { "code": null, "e": 994, "s": 513, "text": "Let’s consider an example for a better understanding — assume a social networking site wants to find groups (clusters) of people with like interests and direct relevant ads to them. One way to approach the problem is through clustering where the firm may use features such as pages liked, posts shared and places checked into to build a dataset and run it through a clustering algorithm to identify the relevant groups. One thing to note though is that, the dataset is unlabelled." }, { "code": null, "e": 1131, "s": 994, "text": "A note on the notation. x_{i} means x subscript i, x_{^th} means x superscript th and x_{^th}{i} means x superscript th and subscript i." }, { "code": null, "e": 1349, "s": 1131, "text": "The K-means clustering algorithm begins with an initialisation step — called as the random initialisation step. The goal of this step is to randomly select a centroid, u_{i} i ∈ {1,2,3...K} for each of the K-clusters." }, { "code": null, "e": 1498, "s": 1349, "text": "These K centroids are then converged to an optimal value using an iterative algorithm. Each step of the iteration performs the following two steps —" }, { "code": null, "e": 1517, "s": 1498, "text": "Cluster assignment" }, { "code": null, "e": 1531, "s": 1517, "text": "Move centroid" }, { "code": null, "e": 1920, "s": 1531, "text": "The cluster assignment step goes through each of the example x_{^i} in the dataset and assigns it to its closest cluster centroid based on a distance measure say euclidean distance. For the example discussed below one may say that — given an example, the cluster assignment step assigns it to a colour, green or yellow depending on the distance of that example from the cluster centroids." }, { "code": null, "e": 2285, "s": 1920, "text": "The move centroid step computes new cluster centroids by taking an average of the examples assigned to same cluster centroid. Alternatively, the average of all the points coloured yellow and green, give the new values for cluster centroids. Just to be clear this is the step responsible for convergence of randomly initialised cluster centroid to an optimal value." }, { "code": null, "e": 2432, "s": 2285, "text": "The algorithm continues until convergence — which is to say, until two subsequent iterations do not give nearly same values for cluster centroids." }, { "code": null, "e": 2596, "s": 2432, "text": "As discussed earlier that algorithm starts with random initialisation step — but random initialisation might lead to the algorithm getting stuck at a local optima." }, { "code": null, "e": 2836, "s": 2596, "text": "One way to improve our odds of ending up with better values for cluster centroids is to perform the random initialisation step multiple times and choose a set of values that leads to the minimum value of distortion cost function given by —" }, { "code": null, "e": 3188, "s": 2836, "text": "The above cost function is computing the average of the squared distances between each of the training example, x_{^i} and the cluster to which it has been assigned, u_{^i}{c}. Squaring has been done to solely avoid square root arising due to euclidean distance. It is obvious that, smaller values of cost function correspond to better initialisation." }, { "code": null, "e": 3546, "s": 3188, "text": "This technique is effective for values of K≤10 but, it has been observed that for larger values of K, it does not make that significant a difference. For larger values of K, the K-means algorithm will pretty much converge to acceptable values of cluster centroids. Also, this method of optimising the random initialisation step is computationally expensive." }, { "code": null, "e": 3813, "s": 3546, "text": "Up until now, you must have developed an intuitive understanding of K-means clustering algorithm but there is one more aspect to be dealt with, the parameter K. Let’s take a look as to how we may know the number of clusters in which our data set needs to be divided." }, { "code": null, "e": 4029, "s": 3813, "text": "Elbow method can be used to find the optimal value of K. The method plots the number of clusters against the value of distortion cost function and chooses a value of K where the graph elbows out or has a sharp turn." }, { "code": null, "e": 4189, "s": 4029, "text": "But practically this method is not used as much, because when real world data is plotted the graph does not usually has a prominent elbow to pick a value of K." } ]
MNIST Dataset Python Example Using CNN | by Cory Maklin | Towards Data Science
It’s only a matter of time before self-driving cars become widespread. This tremendous feat of engineering wouldn’t be possible without convolutional neural networks. The algorithm used by convolutional neural networks is better suited for visual image processing than the one used in traditional artificial neural networks. Convolutional neural networks are composed of convolutional layers and pooling layers. Convolutional layers take advantage of the fact that all images can be encoded in terms of 1s and 0s to create feature maps. A feature detector is simply a matrix, whose values correspond to a feature of the image (i.e. pointy ears, slit eyes...). The matrix overlays a section the image and performs bit-wise multiplication with all of the values at that location. The results of the bit-wise multiplications are summed and put in the corresponding location of the feature map. It then shifts to another section of the image and repeats the process until it has traversed the entire image. Pooling is a lot like convolution except we don’t make use of a feature detector. Instead we use max pooling. The process of max pooling consists in taking a highest value within the area of the feature map overlaid by the window (nxn matrix) and putting it in the corresponding location of the pooled feature map. Pooling is useful in that it reduces the size of the image making it easier to compute and detect patterns despite differences in spatial orientation. For example, suppose the number 4 coincided with the slit eyes of a cat. Whether the eyes of the cat were looking directly at the camera or off to the side when the picture was taken, max pooling may still come up with the same value. That’s enough background information, on to code. The proceeding example uses Keras, a high-level API to build and train models in TensorFlow. import kerasfrom keras.datasets import fashion_mnist from keras.layers import Dense, Activation, Flatten, Conv2D, MaxPooling2Dfrom keras.models import Sequentialfrom keras.utils import to_categoricalimport numpy as npimport matplotlib.pyplot as plt Run the following line of code to import our data set. (train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data() The Fashion MNIST data set contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here: When using a convolutional layer as the first layer to our model, we need to reshape our data to (n_images, x_shape, y_shape, channels). All you really need to know is that you should set channels to 1 for grayscale images and set channels to 3 when you have a set of RGB-images as input. train_X = train_X.reshape(-1, 28,28, 1)test_X = test_X.reshape(-1, 28,28, 1) Negative one is the same as specifying the total number of images in the training set. train_X.shapeOut[00]: (60000, 28, 28, 1) Modifying the values of each pixel such that they range from 0 to 1 will improve the rate at which our model learns. train_X = train_X.astype('float32')test_X = test_X.astype('float32')train_X = train_X / 255test_X = test_X / 255 Our model cannot work with categorical data directly. Ergo we must use one hot encoding. In one hot encoding, the digits 0 through 9 are represented as a set of nine zeros and a single one. The digit is determined by the location of the number 1. For example, you’d represent a 3 as [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]. train_Y_one_hot = to_categorical(train_Y)test_Y_one_hot = to_categorical(test_Y) Our convolutional layers will have 64 neurons (feature maps) and a 3x3 feature detector. In turn, our pooling layers will use max pooling with a 2x2 matrix. Convolutional neural networks are almost always proceeded by an artificial neural network. In Keras, a Dense layer implements the operation output = activation(dot(input, weight) + bias). The input to our artificial neural network must be in one dimension therefore we flatten it beforehand. model = Sequential()model.add(Conv2D(64, (3,3), input_shape=(28, 28, 1)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Conv2D(64, (3,3)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Flatten())model.add(Dense(64))model.add(Dense(10))model.add(Activation('softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy']) Since the algorithm involved in convolutional neural networks use matrices, you can benefit immensely from running TensorFlow on your GPU. If you’re training the model using a CPU, I wouldn’t recommend more than 10 epochs as it can take a while. The batch size must match the number of images going into our first convolutional layer. model.fit(train_X, train_Y_one_hot, batch_size=64, epochs=10 By the tenth epoch, we obtained an accuracy of 94% which is really good all things considered. Let’s see how well our model does at categorizing new images. test_loss, test_acc = model.evaluate(test_X, test_Y_one_hot)print('Test loss', test_loss)print('Test accuracy', test_acc)Out[]: Test loss 0.2947616615891457Out[]: Test accuracy 0.9006 As you can see, based off the test accuracy, we’ve slightly overfitted our model. Let’s take a look at the first prediction made by our model. predictions = model.predict(test_X)print(np.argmax(np.round(predictions[0])))Out[30]: 9 The number 9 has a matching class ofAnkle boot. Running the following code will display the first image. plt.imshow(test_X[0].reshape(28, 28), cmap = plt.cm.binary)plt.show() Our model correctly classified the first image in our testing data set.
[ { "code": null, "e": 584, "s": 172, "text": "It’s only a matter of time before self-driving cars become widespread. This tremendous feat of engineering wouldn’t be possible without convolutional neural networks. The algorithm used by convolutional neural networks is better suited for visual image processing than the one used in traditional artificial neural networks. Convolutional neural networks are composed of convolutional layers and pooling layers." }, { "code": null, "e": 1175, "s": 584, "text": "Convolutional layers take advantage of the fact that all images can be encoded in terms of 1s and 0s to create feature maps. A feature detector is simply a matrix, whose values correspond to a feature of the image (i.e. pointy ears, slit eyes...). The matrix overlays a section the image and performs bit-wise multiplication with all of the values at that location. The results of the bit-wise multiplications are summed and put in the corresponding location of the feature map. It then shifts to another section of the image and repeats the process until it has traversed the entire image." }, { "code": null, "e": 1641, "s": 1175, "text": "Pooling is a lot like convolution except we don’t make use of a feature detector. Instead we use max pooling. The process of max pooling consists in taking a highest value within the area of the feature map overlaid by the window (nxn matrix) and putting it in the corresponding location of the pooled feature map. Pooling is useful in that it reduces the size of the image making it easier to compute and detect patterns despite differences in spatial orientation." }, { "code": null, "e": 1876, "s": 1641, "text": "For example, suppose the number 4 coincided with the slit eyes of a cat. Whether the eyes of the cat were looking directly at the camera or off to the side when the picture was taken, max pooling may still come up with the same value." }, { "code": null, "e": 2019, "s": 1876, "text": "That’s enough background information, on to code. The proceeding example uses Keras, a high-level API to build and train models in TensorFlow." }, { "code": null, "e": 2268, "s": 2019, "text": "import kerasfrom keras.datasets import fashion_mnist from keras.layers import Dense, Activation, Flatten, Conv2D, MaxPooling2Dfrom keras.models import Sequentialfrom keras.utils import to_categoricalimport numpy as npimport matplotlib.pyplot as plt" }, { "code": null, "e": 2323, "s": 2268, "text": "Run the following line of code to import our data set." }, { "code": null, "e": 2386, "s": 2323, "text": "(train_X,train_Y), (test_X,test_Y) = fashion_mnist.load_data()" }, { "code": null, "e": 2563, "s": 2386, "text": "The Fashion MNIST data set contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here:" }, { "code": null, "e": 2852, "s": 2563, "text": "When using a convolutional layer as the first layer to our model, we need to reshape our data to (n_images, x_shape, y_shape, channels). All you really need to know is that you should set channels to 1 for grayscale images and set channels to 3 when you have a set of RGB-images as input." }, { "code": null, "e": 2929, "s": 2852, "text": "train_X = train_X.reshape(-1, 28,28, 1)test_X = test_X.reshape(-1, 28,28, 1)" }, { "code": null, "e": 3016, "s": 2929, "text": "Negative one is the same as specifying the total number of images in the training set." }, { "code": null, "e": 3057, "s": 3016, "text": "train_X.shapeOut[00]: (60000, 28, 28, 1)" }, { "code": null, "e": 3174, "s": 3057, "text": "Modifying the values of each pixel such that they range from 0 to 1 will improve the rate at which our model learns." }, { "code": null, "e": 3287, "s": 3174, "text": "train_X = train_X.astype('float32')test_X = test_X.astype('float32')train_X = train_X / 255test_X = test_X / 255" }, { "code": null, "e": 3602, "s": 3287, "text": "Our model cannot work with categorical data directly. Ergo we must use one hot encoding. In one hot encoding, the digits 0 through 9 are represented as a set of nine zeros and a single one. The digit is determined by the location of the number 1. For example, you’d represent a 3 as [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]." }, { "code": null, "e": 3683, "s": 3602, "text": "train_Y_one_hot = to_categorical(train_Y)test_Y_one_hot = to_categorical(test_Y)" }, { "code": null, "e": 4132, "s": 3683, "text": "Our convolutional layers will have 64 neurons (feature maps) and a 3x3 feature detector. In turn, our pooling layers will use max pooling with a 2x2 matrix. Convolutional neural networks are almost always proceeded by an artificial neural network. In Keras, a Dense layer implements the operation output = activation(dot(input, weight) + bias). The input to our artificial neural network must be in one dimension therefore we flatten it beforehand." }, { "code": null, "e": 4577, "s": 4132, "text": "model = Sequential()model.add(Conv2D(64, (3,3), input_shape=(28, 28, 1)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Conv2D(64, (3,3)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Flatten())model.add(Dense(64))model.add(Dense(10))model.add(Activation('softmax'))model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(),metrics=['accuracy'])" }, { "code": null, "e": 4912, "s": 4577, "text": "Since the algorithm involved in convolutional neural networks use matrices, you can benefit immensely from running TensorFlow on your GPU. If you’re training the model using a CPU, I wouldn’t recommend more than 10 epochs as it can take a while. The batch size must match the number of images going into our first convolutional layer." }, { "code": null, "e": 4973, "s": 4912, "text": "model.fit(train_X, train_Y_one_hot, batch_size=64, epochs=10" }, { "code": null, "e": 5130, "s": 4973, "text": "By the tenth epoch, we obtained an accuracy of 94% which is really good all things considered. Let’s see how well our model does at categorizing new images." }, { "code": null, "e": 5314, "s": 5130, "text": "test_loss, test_acc = model.evaluate(test_X, test_Y_one_hot)print('Test loss', test_loss)print('Test accuracy', test_acc)Out[]: Test loss 0.2947616615891457Out[]: Test accuracy 0.9006" }, { "code": null, "e": 5396, "s": 5314, "text": "As you can see, based off the test accuracy, we’ve slightly overfitted our model." }, { "code": null, "e": 5457, "s": 5396, "text": "Let’s take a look at the first prediction made by our model." }, { "code": null, "e": 5545, "s": 5457, "text": "predictions = model.predict(test_X)print(np.argmax(np.round(predictions[0])))Out[30]: 9" }, { "code": null, "e": 5593, "s": 5545, "text": "The number 9 has a matching class ofAnkle boot." }, { "code": null, "e": 5650, "s": 5593, "text": "Running the following code will display the first image." }, { "code": null, "e": 5720, "s": 5650, "text": "plt.imshow(test_X[0].reshape(28, 28), cmap = plt.cm.binary)plt.show()" } ]
AWT Scrollbar Class
Scrollbar control represents a scroll bar component in order to enable user to select from range of values. Following is the declaration for java.awt.Scrollbar class: public class Scrollbar extends Component implements Adjustable, Accessible Following are the fields for java.awt.Image class: static int HORIZONTAL --A constant that indicates a horizontal scroll bar. static int HORIZONTAL --A constant that indicates a horizontal scroll bar. static int VERTICAL --A constant that indicates a vertical scroll bar. static int VERTICAL --A constant that indicates a vertical scroll bar. Scrollbar() Constructs a new vertical scroll bar. Scrollbar(int orientation) Constructs a new scroll bar with the specified orientation. Scrollbar(int orientation, int value, int visible, int minimum, int maximum) Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values. void addAdjustmentListener(AdjustmentListener l) Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar. void addNotify() Creates the Scrollbar's peer. int getBlockIncrement() Gets the block increment of this scroll bar. int getLineIncrement() Deprecated. As of JDK version 1.1, replaced by getUnitIncrement(). int getMaximum() Gets the maximum value of this scroll bar. int getMinimum() Gets the minimum value of this scroll bar. int getOrientation() Returns the orientation of this scroll bar. int getPageIncrement() Deprecated. As of JDK version 1.1, replaced by getBlockIncrement(). int getUnitIncrement() Gets the unit increment for this scrollbar. int getValue() Gets the current value of this scroll bar. boolean getValueIsAdjusting() Returns true if the value is in the process of changing as a result of actions being taken by the user. int getVisible() Deprecated. As of JDK version 1.1, replaced by getVisibleAmount(). int getVisibleAmount() Gets the visible amount of this scroll bar. protected String paramString() Returns a string representing the state of this Scrollbar. protected void processAdjustmentEvent(AdjustmentEvent e) Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects. protected void processEvent(AWTEvent e) Processes events on this scroll bar. void removeAdjustmentListener(AdjustmentListener l) Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar. void setBlockIncrement(int v) Sets the block increment for this scroll bar. void setLineIncrement(int v) Deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int). void setMaximum(int newMaximum) Sets the maximum value of this scroll bar. void setMinimum(int newMinimum) Sets the minimum value of this scroll bar. void setOrientation(int orientation) Sets the orientation for this scroll bar. void setPageIncrement(int v) Deprecated. As of JDK version 1.1, replaced by setBlockIncrement(). void setUnitIncrement(int v) Sets the unit increment for this scroll bar. void setValue(int newValue) Sets the value of this scroll bar to the specified value. void setValueIsAdjusting(boolean b) Sets the valueIsAdjusting property. void setValues(int value, int visible, int minimum, int maximum) Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum. void setVisibleAmount(int newAmount) Sets the visible amount of this scroll bar. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Scrollbar. AdjustmentListener[] getAdjustmentListeners() Returns an array of all the adjustment listeners registered on this scrollbar. <T extends EventListener>T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Scrollbar. This class inherits methods from the following classes: java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showScrollbarDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showScrollbarDemo(){ headerLabel.setText("Control in action: Scrollbar"); final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL); final Scrollbar verticalScroller = new Scrollbar(); verticalScroller.setOrientation(Scrollbar.VERTICAL); horizontalScroller.setMaximum (100); horizontalScroller.setMinimum (1); verticalScroller.setMaximum (100); verticalScroller.setMinimum (1); horizontalScroller.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { statusLabel.setText("Horozontal: " +horizontalScroller.getValue() +" ,Vertical: " + verticalScroller.getValue()); } }); verticalScroller.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { statusLabel.setText("Horozontal: " +horizontalScroller.getValue() +" ,Vertical: "+ verticalScroller.getValue()); } }); controlPanel.add(horizontalScroller); controlPanel.add(verticalScroller); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1855, "s": 1747, "text": "Scrollbar control represents a scroll bar component in order to enable user to select from range of values." }, { "code": null, "e": 1914, "s": 1855, "text": "Following is the declaration for java.awt.Scrollbar class:" }, { "code": null, "e": 1998, "s": 1914, "text": "public class Scrollbar\n extends Component\n implements Adjustable, Accessible" }, { "code": null, "e": 2049, "s": 1998, "text": "Following are the fields for java.awt.Image class:" }, { "code": null, "e": 2125, "s": 2049, "text": "static int HORIZONTAL --A constant that indicates a horizontal scroll bar." }, { "code": null, "e": 2201, "s": 2125, "text": "static int HORIZONTAL --A constant that indicates a horizontal scroll bar." }, { "code": null, "e": 2273, "s": 2201, "text": "static int VERTICAL --A constant that indicates a vertical scroll bar." }, { "code": null, "e": 2345, "s": 2273, "text": "static int VERTICAL --A constant that indicates a vertical scroll bar." }, { "code": null, "e": 2358, "s": 2345, "text": "Scrollbar() " }, { "code": null, "e": 2396, "s": 2358, "text": "Constructs a new vertical scroll bar." }, { "code": null, "e": 2424, "s": 2396, "text": "Scrollbar(int orientation) " }, { "code": null, "e": 2484, "s": 2424, "text": "Constructs a new scroll bar with the specified orientation." }, { "code": null, "e": 2562, "s": 2484, "text": "Scrollbar(int orientation, int value, int visible, int minimum, int maximum) " }, { "code": null, "e": 2685, "s": 2562, "text": "Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values." }, { "code": null, "e": 2735, "s": 2685, "text": "void addAdjustmentListener(AdjustmentListener l) " }, { "code": null, "e": 2836, "s": 2735, "text": "Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar." }, { "code": null, "e": 2854, "s": 2836, "text": "void addNotify() " }, { "code": null, "e": 2884, "s": 2854, "text": "Creates the Scrollbar's peer." }, { "code": null, "e": 2909, "s": 2884, "text": "int getBlockIncrement() " }, { "code": null, "e": 2954, "s": 2909, "text": "Gets the block increment of this scroll bar." }, { "code": null, "e": 2978, "s": 2954, "text": "int getLineIncrement() " }, { "code": null, "e": 3046, "s": 2978, "text": " Deprecated. As of JDK version 1.1, replaced by getUnitIncrement()." }, { "code": null, "e": 3064, "s": 3046, "text": "int getMaximum() " }, { "code": null, "e": 3107, "s": 3064, "text": "Gets the maximum value of this scroll bar." }, { "code": null, "e": 3125, "s": 3107, "text": "int getMinimum() " }, { "code": null, "e": 3168, "s": 3125, "text": "Gets the minimum value of this scroll bar." }, { "code": null, "e": 3189, "s": 3168, "text": "int getOrientation()" }, { "code": null, "e": 3234, "s": 3189, "text": " Returns the orientation of this scroll bar." }, { "code": null, "e": 3258, "s": 3234, "text": "int getPageIncrement() " }, { "code": null, "e": 3326, "s": 3258, "text": "Deprecated. As of JDK version 1.1, replaced by getBlockIncrement()." }, { "code": null, "e": 3349, "s": 3326, "text": "int getUnitIncrement()" }, { "code": null, "e": 3393, "s": 3349, "text": "Gets the unit increment for this scrollbar." }, { "code": null, "e": 3409, "s": 3393, "text": "int getValue() " }, { "code": null, "e": 3452, "s": 3409, "text": "Gets the current value of this scroll bar." }, { "code": null, "e": 3460, "s": 3452, "text": "boolean" }, { "code": null, "e": 3483, "s": 3460, "text": "getValueIsAdjusting() " }, { "code": null, "e": 3587, "s": 3483, "text": "Returns true if the value is in the process of changing as a result of actions being taken by the user." }, { "code": null, "e": 3605, "s": 3587, "text": "int getVisible() " }, { "code": null, "e": 3672, "s": 3605, "text": "Deprecated. As of JDK version 1.1, replaced by getVisibleAmount()." }, { "code": null, "e": 3696, "s": 3672, "text": "int getVisibleAmount() " }, { "code": null, "e": 3740, "s": 3696, "text": "Gets the visible amount of this scroll bar." }, { "code": null, "e": 3772, "s": 3740, "text": "protected String paramString() " }, { "code": null, "e": 3831, "s": 3772, "text": "Returns a string representing the state of this Scrollbar." }, { "code": null, "e": 3889, "s": 3831, "text": "protected void processAdjustmentEvent(AdjustmentEvent e) " }, { "code": null, "e": 4011, "s": 3889, "text": "Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects." }, { "code": null, "e": 4052, "s": 4011, "text": "protected void processEvent(AWTEvent e) " }, { "code": null, "e": 4089, "s": 4052, "text": "Processes events on this scroll bar." }, { "code": null, "e": 4142, "s": 4089, "text": "void removeAdjustmentListener(AdjustmentListener l) " }, { "code": null, "e": 4265, "s": 4142, "text": "Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar." }, { "code": null, "e": 4296, "s": 4265, "text": "void setBlockIncrement(int v) " }, { "code": null, "e": 4342, "s": 4296, "text": "Sets the block increment for this scroll bar." }, { "code": null, "e": 4372, "s": 4342, "text": "void setLineIncrement(int v) " }, { "code": null, "e": 4442, "s": 4372, "text": "Deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int)." }, { "code": null, "e": 4475, "s": 4442, "text": "void setMaximum(int newMaximum) " }, { "code": null, "e": 4518, "s": 4475, "text": "Sets the maximum value of this scroll bar." }, { "code": null, "e": 4551, "s": 4518, "text": "void setMinimum(int newMinimum) " }, { "code": null, "e": 4594, "s": 4551, "text": "Sets the minimum value of this scroll bar." }, { "code": null, "e": 4632, "s": 4594, "text": "void setOrientation(int orientation) " }, { "code": null, "e": 4674, "s": 4632, "text": "Sets the orientation for this scroll bar." }, { "code": null, "e": 4704, "s": 4674, "text": "void setPageIncrement(int v) " }, { "code": null, "e": 4772, "s": 4704, "text": "Deprecated. As of JDK version 1.1, replaced by setBlockIncrement()." }, { "code": null, "e": 4802, "s": 4772, "text": "void setUnitIncrement(int v) " }, { "code": null, "e": 4847, "s": 4802, "text": "Sets the unit increment for this scroll bar." }, { "code": null, "e": 4876, "s": 4847, "text": "void setValue(int newValue) " }, { "code": null, "e": 4934, "s": 4876, "text": "Sets the value of this scroll bar to the specified value." }, { "code": null, "e": 4971, "s": 4934, "text": "void setValueIsAdjusting(boolean b) " }, { "code": null, "e": 5007, "s": 4971, "text": "Sets the valueIsAdjusting property." }, { "code": null, "e": 5073, "s": 5007, "text": "void setValues(int value, int visible, int minimum, int maximum) " }, { "code": null, "e": 5173, "s": 5073, "text": "Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum." }, { "code": null, "e": 5211, "s": 5173, "text": "void setVisibleAmount(int newAmount) " }, { "code": null, "e": 5255, "s": 5211, "text": "Sets the visible amount of this scroll bar." }, { "code": null, "e": 5297, "s": 5255, "text": "AccessibleContext getAccessibleContext() " }, { "code": null, "e": 5356, "s": 5297, "text": "Gets the AccessibleContext associated with this Scrollbar." }, { "code": null, "e": 5403, "s": 5356, "text": "AdjustmentListener[] getAdjustmentListeners() " }, { "code": null, "e": 5482, "s": 5403, "text": "Returns an array of all the adjustment listeners registered on this scrollbar." }, { "code": null, "e": 5548, "s": 5482, "text": "<T extends EventListener>T[] getListeners(Class<T> listenerType) " }, { "code": null, "e": 5642, "s": 5548, "text": "Returns an array of all the objects currently registered as FooListeners upon this Scrollbar." }, { "code": null, "e": 5698, "s": 5642, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 5717, "s": 5698, "text": "java.awt.Component" }, { "code": null, "e": 5736, "s": 5717, "text": "java.awt.Component" }, { "code": null, "e": 5753, "s": 5736, "text": "java.lang.Object" }, { "code": null, "e": 5770, "s": 5753, "text": "java.lang.Object" }, { "code": null, "e": 5884, "s": 5770, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 8429, "s": 5884, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showScrollbarDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showScrollbarDemo(){ \n headerLabel.setText(\"Control in action: Scrollbar\"); \n\n final Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);\n final Scrollbar verticalScroller = new Scrollbar();\n verticalScroller.setOrientation(Scrollbar.VERTICAL);\n horizontalScroller.setMaximum (100);\n horizontalScroller.setMinimum (1);\n verticalScroller.setMaximum (100);\n verticalScroller.setMinimum (1);\n\n horizontalScroller.addAdjustmentListener(new AdjustmentListener() {\n\n @Override\n public void adjustmentValueChanged(AdjustmentEvent e) {\n statusLabel.setText(\"Horozontal: \"\n +horizontalScroller.getValue() \n +\" ,Vertical: \"\n + verticalScroller.getValue());\n }\n });\n\n verticalScroller.addAdjustmentListener(new AdjustmentListener() {\n\n @Override\n public void adjustmentValueChanged(AdjustmentEvent e) {\n statusLabel.setText(\"Horozontal: \"\n +horizontalScroller.getValue() \n +\" ,Vertical: \"+ verticalScroller.getValue());\n }\n });\n\n controlPanel.add(horizontalScroller);\n controlPanel.add(verticalScroller);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 8520, "s": 8429, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 8576, "s": 8520, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 8673, "s": 8576, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 8723, "s": 8673, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 8751, "s": 8723, "text": "Verify the following output" }, { "code": null, "e": 8784, "s": 8751, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8792, "s": 8784, "text": " EduOLC" }, { "code": null, "e": 8799, "s": 8792, "text": " Print" }, { "code": null, "e": 8810, "s": 8799, "text": " Add Notes" } ]
Count minimum steps to get the given desired array - GeeksforGeeks
01 Apr, 2021 Consider an array with n elements and value of all the elements is zero. We can perform following operations on the array. Incremental operations:Choose 1 element from the array and increment its value by 1.Doubling operation: Double the values of all the elements of array. Incremental operations:Choose 1 element from the array and increment its value by 1. Doubling operation: Double the values of all the elements of array. We are given desired array target[] containing n elements. Compute and return the smallest possible number of the operations needed to change the array from all zeros to desired array.Examples: Input: target[] = {2, 3} Output: 4 To get the target array from {0, 0}, we first increment both elements by 1 (2 operations), then double the array (1 operation). Finally increment second element (1 more operation) Input: target[] = {2, 1} Output: 3 One of the optimal solution is to apply the incremental operation 2 times to first and once on second element. Input: target[] = {16, 16, 16} Output: 7 The output solution looks as follows. First apply an incremental operation to each element. Then apply the doubling operation four times. Total number of operations is 3+4 = 7 One important thing to note is that the task is to count the number of steps to get the given target array (not to convert zero array to target array). The idea is to follow reverse steps, i.e. to convert target to array of zeros. Below are steps. Take the target array first. Initialize result as 0. If all are even, divide all elements by 2 and increment result by 1. Find all odd elements, make them even by reducing them by 1. and for every reduction, increment result by 1. Finally, we get all zeros in target array. Below is the implementation of above algorithm. C++ Java Python3 C# PHP Javascript /* C++ program to count minimum number of operations to get the given target array */#include <bits/stdc++.h>using namespace std; // Returns count of minimum operations to convert a// zero array to target array with increment and// doubling operations.// This function computes count by doing reverse// steps, i.e., convert target to zero array.int countMinOperations(unsigned int target[], int n){ // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of target // don't become 0. while (1) { // To store count of zeroes in current // target array int zero_count = 0; int i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (target[i] & 1) break; // If 0, then increment zero_count else if (target[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (int j=0; j<n; j++) target[j] = target[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (int j=i; j<n; j++) { if (target[j] & 1) { target[j]--; result++; } } }} /* Driver program to test above functions*/int main(){ unsigned int arr[] = {16, 16, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum number of steps required to " "get the given target array is " << countMinOperations(arr, n); return 0;} /* Java program to count minimum number of operations to get the given arr array */ class Test{ static int arr[] = new int[]{16, 16, 16} ; // Returns count of minimum operations to convert a // zero array to arr array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert arr to zero array. static int countMinOperations(int n) { // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of arr // don't become 0. while (true) { // To store count of zeroes in current // arr array int zero_count = 0; int i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (int j=0; j<n; j++) arr[j] = arr[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (int j=i; j<n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver method to test the above function public static void main(String[] args) { System.out.println("Minimum number of steps required to \n" + "get the given target array is "+ countMinOperations(arr.length)); }} # Python3 program to count minimum number of# operations to get the given target array # Returns count of minimum operations to# convert a zero array to target array# with increment and doubling operations.# This function computes count by doing reverse# steps, i.e., convert target to zero array.def countMinOperations(target, n): # Initialize result (Count of minimum moves) result = 0; # Keep looping while all elements of # target don't become 0. while (True): # To store count of zeroes in # current target array zero_count = 0; # To find first odd element i = 0; while (i < n): # If odd number found if ((target[i] & 1) > 0): break; # If 0, then increment # zero_count elif (target[i] == 0): zero_count += 1; i += 1; # All numbers are 0 if (zero_count == n): return result; # All numbers are even if (i == n): # Divide the whole array by 2 # and increment result for j in range(n): target[j] = target[j] // 2; result += 1; # Make all odd numbers even by # subtracting one and increment result. for j in range(i, n): if (target[j] & 1): target[j] -= 1; result += 1; # Driver Codearr = [16, 16, 16];n = len(arr);print("Minimum number of steps required to", "\nget the given target array is", countMinOperations(arr, n)); # This code is contributed by mits // C# program to count minimum// number of operations to get// the given arr array */using System;class GFG { static int []arr = new int[]{16, 16, 16} ; // Returns count of minimum // operations to convert a // zero array to arr array // with increment and // doubling operations. // This function computes // count by doing reverse // steps, i.e., convert arr // to zero array. static int countMinOperations(int n) { // Initialize result // (Count of minimum moves) int result = 0; // Keep looping while all // elements of arr // don't become 0. while (true) { // To store count of zeroes // in current arr array int zero_count = 0; // To find first odd element int i; for (i = 0; i < n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment // zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for(int j = 0; j < n; j++) arr[j] = arr[j] / 2; result++; } // Make all odd numbers // even by subtracting // one and increment result. for(int j = i; j < n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver Code public static void Main() { Console.Write("Minimum number of steps required to \n" + "get the given target array is "+ countMinOperations(arr.Length)); }} // This code is contributed by nitin mittal. <?php// PHP program to count minimum// number of operations to get// the given target array // Returns count of minimum// operations to convert a// zero array to target array// with increment and doubling// operations.// This function computes// count by doing reverse// steps, i.e., convert target// to zero array.function countMinOperations($target, $n){ // Initialize result // (Count of minimum moves) $result = 0; // Keep looping while // all elements of target // don't become 0. while (1) { // To store count of // zeroes in current // target array $zero_count = 0; // To find first // odd element $i = 0; for($i = 0; $i < $n; $i++) { // If odd number found if ($target[$i] & 1) break; // If 0, then increment // zero_count else if ($target[$i] == 0) $zero_count++; } // All numbers are 0 if ($zero_count == $n) return $result; // All numbers are even if ($i == $n) { // Divide the whole array by 2 // and increment result for ($j = 0; $j < $n; $j++) $target[$j] = $target[$j] / 2; $result++; } // Make all odd numbers // even by subtracting // one and increment result. for ($j = $i; $j < $n; $j++) { if ($target[$j] & 1) { $target[$j]--; $result++; } } }} // Driver Code $arr= array(16, 16, 16); $n = sizeof($arr); echo "Minimum number of steps required to \n". "get the given target array is ". countMinOperations($arr, $n); // This code is contributed by mits?> <script> // JavaScript program to count minimum number of operations// to get the given arr array let arr = [16, 16, 16] ; // Returns count of minimum operations to convert a // zero array to arr array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert arr to zero array. function countMinOperations(n) { // Initialize result (Count of minimum moves) let result = 0; // Keep looping while all elements of arr // don't become 0. while (true) { // To store count of zeroes in current // arr array let zero_count = 0; let i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (let j=0; j<n; j++) arr[j] = arr[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (let j=i; j<n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver Code document.write("Minimum number of steps required to " + "<br/>" + "get the given target array is "+ countMinOperations(arr.length)); </script> Output : Minimum number of steps required to get the given target array is 7 YouTubeGeeksforGeeks501K subscribersCount minimum steps to get the given desired array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=AXlPTwCzpAo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal Mithun Kumar nidhi_biet chinmoy1997pal Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 41276, "s": 41248, "text": "\n01 Apr, 2021" }, { "code": null, "e": 41401, "s": 41276, "text": "Consider an array with n elements and value of all the elements is zero. We can perform following operations on the array. " }, { "code": null, "e": 41553, "s": 41401, "text": "Incremental operations:Choose 1 element from the array and increment its value by 1.Doubling operation: Double the values of all the elements of array." }, { "code": null, "e": 41638, "s": 41553, "text": "Incremental operations:Choose 1 element from the array and increment its value by 1." }, { "code": null, "e": 41706, "s": 41638, "text": "Doubling operation: Double the values of all the elements of array." }, { "code": null, "e": 41902, "s": 41706, "text": "We are given desired array target[] containing n elements. Compute and return the smallest possible number of the operations needed to change the array from all zeros to desired array.Examples: " }, { "code": null, "e": 42490, "s": 41902, "text": "Input: target[] = {2, 3}\nOutput: 4\nTo get the target array from {0, 0}, we \nfirst increment both elements by 1 (2 \noperations), then double the array (1 \noperation). Finally increment second\nelement (1 more operation)\n\nInput: target[] = {2, 1}\nOutput: 3\nOne of the optimal solution is to apply the \nincremental operation 2 times to first and \nonce on second element.\n\nInput: target[] = {16, 16, 16}\nOutput: 7\nThe output solution looks as follows. First \napply an incremental operation to each element. \nThen apply the doubling operation four times. \nTotal number of operations is 3+4 = 7" }, { "code": null, "e": 42740, "s": 42492, "text": "One important thing to note is that the task is to count the number of steps to get the given target array (not to convert zero array to target array). The idea is to follow reverse steps, i.e. to convert target to array of zeros. Below are steps." }, { "code": null, "e": 43023, "s": 42740, "text": "Take the target array first. \n\nInitialize result as 0. \n\nIf all are even, divide all elements by 2 \nand increment result by 1. \n\nFind all odd elements, make them even by \nreducing them by 1. and for every reduction,\nincrement result by 1.\n\nFinally, we get all zeros in target array." }, { "code": null, "e": 43073, "s": 43023, "text": "Below is the implementation of above algorithm. " }, { "code": null, "e": 43077, "s": 43073, "text": "C++" }, { "code": null, "e": 43082, "s": 43077, "text": "Java" }, { "code": null, "e": 43090, "s": 43082, "text": "Python3" }, { "code": null, "e": 43093, "s": 43090, "text": "C#" }, { "code": null, "e": 43097, "s": 43093, "text": "PHP" }, { "code": null, "e": 43108, "s": 43097, "text": "Javascript" }, { "code": "/* C++ program to count minimum number of operations to get the given target array */#include <bits/stdc++.h>using namespace std; // Returns count of minimum operations to convert a// zero array to target array with increment and// doubling operations.// This function computes count by doing reverse// steps, i.e., convert target to zero array.int countMinOperations(unsigned int target[], int n){ // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of target // don't become 0. while (1) { // To store count of zeroes in current // target array int zero_count = 0; int i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (target[i] & 1) break; // If 0, then increment zero_count else if (target[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (int j=0; j<n; j++) target[j] = target[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (int j=i; j<n; j++) { if (target[j] & 1) { target[j]--; result++; } } }} /* Driver program to test above functions*/int main(){ unsigned int arr[] = {16, 16, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Minimum number of steps required to \" \"get the given target array is \" << countMinOperations(arr, n); return 0;}", "e": 44895, "s": 43108, "text": null }, { "code": "/* Java program to count minimum number of operations to get the given arr array */ class Test{ static int arr[] = new int[]{16, 16, 16} ; // Returns count of minimum operations to convert a // zero array to arr array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert arr to zero array. static int countMinOperations(int n) { // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of arr // don't become 0. while (true) { // To store count of zeroes in current // arr array int zero_count = 0; int i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (int j=0; j<n; j++) arr[j] = arr[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (int j=i; j<n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"Minimum number of steps required to \\n\" + \"get the given target array is \"+ countMinOperations(arr.length)); }}", "e": 46929, "s": 44895, "text": null }, { "code": "# Python3 program to count minimum number of# operations to get the given target array # Returns count of minimum operations to# convert a zero array to target array# with increment and doubling operations.# This function computes count by doing reverse# steps, i.e., convert target to zero array.def countMinOperations(target, n): # Initialize result (Count of minimum moves) result = 0; # Keep looping while all elements of # target don't become 0. while (True): # To store count of zeroes in # current target array zero_count = 0; # To find first odd element i = 0; while (i < n): # If odd number found if ((target[i] & 1) > 0): break; # If 0, then increment # zero_count elif (target[i] == 0): zero_count += 1; i += 1; # All numbers are 0 if (zero_count == n): return result; # All numbers are even if (i == n): # Divide the whole array by 2 # and increment result for j in range(n): target[j] = target[j] // 2; result += 1; # Make all odd numbers even by # subtracting one and increment result. for j in range(i, n): if (target[j] & 1): target[j] -= 1; result += 1; # Driver Codearr = [16, 16, 16];n = len(arr);print(\"Minimum number of steps required to\", \"\\nget the given target array is\", countMinOperations(arr, n)); # This code is contributed by mits", "e": 48576, "s": 46929, "text": null }, { "code": "// C# program to count minimum// number of operations to get// the given arr array */using System;class GFG { static int []arr = new int[]{16, 16, 16} ; // Returns count of minimum // operations to convert a // zero array to arr array // with increment and // doubling operations. // This function computes // count by doing reverse // steps, i.e., convert arr // to zero array. static int countMinOperations(int n) { // Initialize result // (Count of minimum moves) int result = 0; // Keep looping while all // elements of arr // don't become 0. while (true) { // To store count of zeroes // in current arr array int zero_count = 0; // To find first odd element int i; for (i = 0; i < n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment // zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for(int j = 0; j < n; j++) arr[j] = arr[j] / 2; result++; } // Make all odd numbers // even by subtracting // one and increment result. for(int j = i; j < n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver Code public static void Main() { Console.Write(\"Minimum number of steps required to \\n\" + \"get the given target array is \"+ countMinOperations(arr.Length)); }} // This code is contributed by nitin mittal.", "e": 50766, "s": 48576, "text": null }, { "code": "<?php// PHP program to count minimum// number of operations to get// the given target array // Returns count of minimum// operations to convert a// zero array to target array// with increment and doubling// operations.// This function computes// count by doing reverse// steps, i.e., convert target// to zero array.function countMinOperations($target, $n){ // Initialize result // (Count of minimum moves) $result = 0; // Keep looping while // all elements of target // don't become 0. while (1) { // To store count of // zeroes in current // target array $zero_count = 0; // To find first // odd element $i = 0; for($i = 0; $i < $n; $i++) { // If odd number found if ($target[$i] & 1) break; // If 0, then increment // zero_count else if ($target[$i] == 0) $zero_count++; } // All numbers are 0 if ($zero_count == $n) return $result; // All numbers are even if ($i == $n) { // Divide the whole array by 2 // and increment result for ($j = 0; $j < $n; $j++) $target[$j] = $target[$j] / 2; $result++; } // Make all odd numbers // even by subtracting // one and increment result. for ($j = $i; $j < $n; $j++) { if ($target[$j] & 1) { $target[$j]--; $result++; } } }} // Driver Code $arr= array(16, 16, 16); $n = sizeof($arr); echo \"Minimum number of steps required to \\n\". \"get the given target array is \". countMinOperations($arr, $n); // This code is contributed by mits?>", "e": 52614, "s": 50766, "text": null }, { "code": "<script> // JavaScript program to count minimum number of operations// to get the given arr array let arr = [16, 16, 16] ; // Returns count of minimum operations to convert a // zero array to arr array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert arr to zero array. function countMinOperations(n) { // Initialize result (Count of minimum moves) let result = 0; // Keep looping while all elements of arr // don't become 0. while (true) { // To store count of zeroes in current // arr array let zero_count = 0; let i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (arr[i] % 2 == 1) break; // If 0, then increment zero_count else if (arr[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (let j=0; j<n; j++) arr[j] = arr[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (let j=i; j<n; j++) { if (arr[j] %2 == 1) { arr[j]--; result++; } } } } // Driver Code document.write(\"Minimum number of steps required to \" + \"<br/>\" + \"get the given target array is \"+ countMinOperations(arr.length)); </script>", "e": 54552, "s": 52614, "text": null }, { "code": null, "e": 54562, "s": 54552, "text": "Output : " }, { "code": null, "e": 54631, "s": 54562, "text": "Minimum number of steps required to \nget the given target array is 7" }, { "code": null, "e": 55482, "s": 54633, "text": "YouTubeGeeksforGeeks501K subscribersCount minimum steps to get the given desired array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:43•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=AXlPTwCzpAo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 55654, "s": 55482, "text": "This article is contributed by Shivam Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 55667, "s": 55654, "text": "nitin mittal" }, { "code": null, "e": 55680, "s": 55667, "text": "Mithun Kumar" }, { "code": null, "e": 55691, "s": 55680, "text": "nidhi_biet" }, { "code": null, "e": 55706, "s": 55691, "text": "chinmoy1997pal" }, { "code": null, "e": 55713, "s": 55706, "text": "Arrays" }, { "code": null, "e": 55726, "s": 55713, "text": "Mathematical" }, { "code": null, "e": 55733, "s": 55726, "text": "Arrays" }, { "code": null, "e": 55746, "s": 55733, "text": "Mathematical" }, { "code": null, "e": 55844, "s": 55746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55853, "s": 55844, "text": "Comments" }, { "code": null, "e": 55866, "s": 55853, "text": "Old Comments" }, { "code": null, "e": 55881, "s": 55866, "text": "Arrays in Java" }, { "code": null, "e": 55897, "s": 55881, "text": "Arrays in C/C++" }, { "code": null, "e": 55924, "s": 55897, "text": "Program for array rotation" }, { "code": null, "e": 55972, "s": 55924, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 56016, "s": 55972, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 56046, "s": 56016, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 56061, "s": 56046, "text": "C++ Data Types" }, { "code": null, "e": 56121, "s": 56061, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 56164, "s": 56121, "text": "Set in C++ Standard Template Library (STL)" } ]
Perl | oct() Function - GeeksforGeeks
25 Jun, 2019 oct() function in Perl converts the octal value passed to its respective decimal value. For example, oct(‘1015’) will return ‘525’. This function returns the resultant decimal value in the form of a string which can be used as a number because Perl automatically converts a string to a number in numeric contexts. If the passed parameter is not an octal number then the result will be 0. Syntax: oct(oct_value) Parameter:oct_value: Octal number which is to be converted to decimal Returns:the octal value converted to decimal value Example 1: #!/usr/bin/perl -w # Converting and printing # the decimal valueprint("oct(31) ", oct('31'), "\n");print("oct(50) ", oct('50'), "\n"); oct(31) 25 oct(50) 40 Example 2: #!/usr/bin/perl -w # Converting and printing # the decimal valueprint("oct(106) ", oct('106'), "\n");print("oct(125) ", oct('125'), "\n"); oct(106) 70 oct(125) 85 Perl-function Perl-Math-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | Data Types Perl Tutorial - Learn Perl With Examples Perl | Multidimensional Hashes Perl | Writing to a File Perl | File Handling Introduction Perl | Basic Syntax of a Perl Program Perl | Appending to a File Perl | Operators | Set - 1 Perl | index() Function Perl | Scope of Variables
[ { "code": null, "e": 24070, "s": 24042, "text": "\n25 Jun, 2019" }, { "code": null, "e": 24458, "s": 24070, "text": "oct() function in Perl converts the octal value passed to its respective decimal value. For example, oct(‘1015’) will return ‘525’. This function returns the resultant decimal value in the form of a string which can be used as a number because Perl automatically converts a string to a number in numeric contexts. If the passed parameter is not an octal number then the result will be 0." }, { "code": null, "e": 24481, "s": 24458, "text": "Syntax: oct(oct_value)" }, { "code": null, "e": 24551, "s": 24481, "text": "Parameter:oct_value: Octal number which is to be converted to decimal" }, { "code": null, "e": 24602, "s": 24551, "text": "Returns:the octal value converted to decimal value" }, { "code": null, "e": 24613, "s": 24602, "text": "Example 1:" }, { "code": "#!/usr/bin/perl -w # Converting and printing # the decimal valueprint(\"oct(31) \", oct('31'), \"\\n\");print(\"oct(50) \", oct('50'), \"\\n\");", "e": 24749, "s": 24613, "text": null }, { "code": null, "e": 24772, "s": 24749, "text": "oct(31) 25\noct(50) 40\n" }, { "code": null, "e": 24783, "s": 24772, "text": "Example 2:" }, { "code": "#!/usr/bin/perl -w # Converting and printing # the decimal valueprint(\"oct(106) \", oct('106'), \"\\n\");print(\"oct(125) \", oct('125'), \"\\n\");", "e": 24923, "s": 24783, "text": null }, { "code": null, "e": 24948, "s": 24923, "text": "oct(106) 70\noct(125) 85\n" }, { "code": null, "e": 24962, "s": 24948, "text": "Perl-function" }, { "code": null, "e": 24982, "s": 24962, "text": "Perl-Math-Functions" }, { "code": null, "e": 24987, "s": 24982, "text": "Perl" }, { "code": null, "e": 24992, "s": 24987, "text": "Perl" }, { "code": null, "e": 25090, "s": 24992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25099, "s": 25090, "text": "Comments" }, { "code": null, "e": 25112, "s": 25099, "text": "Old Comments" }, { "code": null, "e": 25130, "s": 25112, "text": "Perl | Data Types" }, { "code": null, "e": 25171, "s": 25130, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 25202, "s": 25171, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 25227, "s": 25202, "text": "Perl | Writing to a File" }, { "code": null, "e": 25261, "s": 25227, "text": "Perl | File Handling Introduction" }, { "code": null, "e": 25299, "s": 25261, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 25326, "s": 25299, "text": "Perl | Appending to a File" }, { "code": null, "e": 25353, "s": 25326, "text": "Perl | Operators | Set - 1" }, { "code": null, "e": 25377, "s": 25353, "text": "Perl | index() Function" } ]
XSLT Syntax
Let’s suppose we have the following sample XML file, students.xml, which is required to be transformed into a well-formatted HTML document. students.xml <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> We need to define an XSLT style sheet document for the above XML document to meet the following criteria − Page should have a title Students. Page should have a title Students. Page should have a table of student details. Page should have a table of student details. Columns should have following headers: Roll No, First Name, Last Name, Nick Name, Marks Columns should have following headers: Roll No, First Name, Last Name, Nick Name, Marks Table must contain details of the students accordingly. Table must contain details of the students accordingly. Create an XSLT document to meet the above requirements, name it as students.xsl and save it in the same location where students.xml lies. students.xsl <?xml version = "1.0" encoding = "UTF-8"?> <!-- xsl stylesheet declaration with xsl namespace: Namespace tells the xlst processor about which element is to be processed and which is used for output purpose only --> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <!-- xsl template declaration: template tells the xlst processor about the section of xml document which is to be formatted. It takes an XPath expression. In our case, it is matching document root element and will tell processor to process the entire document with this template. --> <xsl:template match = "/"> <!-- HTML tags Used for formatting purpose. Processor will skip them and browser will simply render them. --> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <!-- for-each processing instruction Looks for each element matching the XPath expression --> <xsl:for-each select="class/student"> <tr> <td> <!-- value-of processing instruction process the value of the element matching the XPath expression --> <xsl:value-of select = "@rollno"/> </td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Update student.xml document with the following xml-stylesheet tag. Set href value to students.xsl <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> ... </class> students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> Print Add Notes Bookmark this page
[ { "code": null, "e": 1899, "s": 1759, "text": "Let’s suppose we have the following sample XML file, students.xml, which is required to be transformed into a well-formatted HTML document." }, { "code": null, "e": 1912, "s": 1899, "text": "students.xml" }, { "code": null, "e": 2471, "s": 1912, "text": "<?xml version = \"1.0\"?>\n<class> \n <student rollno = \"393\">\n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks>\n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks>\n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 2578, "s": 2471, "text": "We need to define an XSLT style sheet document for the above XML document to meet the following criteria −" }, { "code": null, "e": 2613, "s": 2578, "text": "Page should have a title Students." }, { "code": null, "e": 2648, "s": 2613, "text": "Page should have a title Students." }, { "code": null, "e": 2693, "s": 2648, "text": "Page should have a table of student details." }, { "code": null, "e": 2738, "s": 2693, "text": "Page should have a table of student details." }, { "code": null, "e": 2826, "s": 2738, "text": "Columns should have following headers: Roll No, First Name, Last Name, Nick Name, Marks" }, { "code": null, "e": 2914, "s": 2826, "text": "Columns should have following headers: Roll No, First Name, Last Name, Nick Name, Marks" }, { "code": null, "e": 2970, "s": 2914, "text": "Table must contain details of the students accordingly." }, { "code": null, "e": 3026, "s": 2970, "text": "Table must contain details of the students accordingly." }, { "code": null, "e": 3164, "s": 3026, "text": "Create an XSLT document to meet the above requirements, name it as students.xsl and save it in the same location where students.xml lies." }, { "code": null, "e": 3177, "s": 3164, "text": "students.xsl" }, { "code": null, "e": 5266, "s": 3177, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!-- xsl stylesheet declaration with xsl namespace: \nNamespace tells the xlst processor about which \nelement is to be processed and which is used for output purpose only \n--> \n<xsl:stylesheet version = \"1.0\" \nxmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n<!-- xsl template declaration: \ntemplate tells the xlst processor about the section of xml \ndocument which is to be formatted. It takes an XPath expression. \nIn our case, it is matching document root element and will \ntell processor to process the entire document with this template. \n--> \n <xsl:template match = \"/\"> \n <!-- HTML tags \n Used for formatting purpose. Processor will skip them and browser \n will simply render them. \n --> \n\t\t\n <html> \n <body> \n <h2>Students</h2> \n\t\t\t\t\n <table border = \"1\"> \n <tr bgcolor = \"#9acd32\"> \n <th>Roll No</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Nick Name</th> \n <th>Marks</th> \n </tr> \n\t\t\t\t\n <!-- for-each processing instruction \n Looks for each element matching the XPath expression \n --> \n\t\t\t\t\n <xsl:for-each select=\"class/student\"> \n <tr> \n <td> \n <!-- value-of processing instruction \n process the value of the element matching the XPath expression \n --> \n <xsl:value-of select = \"@rollno\"/> \n </td> \n\t\t\t\t\t\t\n <td><xsl:value-of select = \"firstname\"/></td> \n <td><xsl:value-of select = \"lastname\"/></td> \n <td><xsl:value-of select = \"nickname\"/></td> \n <td><xsl:value-of select = \"marks\"/></td> \n\t\t\t\t\t\t\n </tr> \n </xsl:for-each> \n\t\t\t\t\t\n </table> \n </body> \n </html> \n </xsl:template> \n</xsl:stylesheet>" }, { "code": null, "e": 5364, "s": 5266, "text": "Update student.xml document with the following xml-stylesheet tag. Set href value to students.xsl" }, { "code": null, "e": 5473, "s": 5364, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n... \n</class> " }, { "code": null, "e": 5486, "s": 5473, "text": "students.xml" }, { "code": null, "e": 6111, "s": 5486, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class> " }, { "code": null, "e": 6118, "s": 6111, "text": " Print" }, { "code": null, "e": 6129, "s": 6118, "text": " Add Notes" } ]
Using Python to Monitor Social Distancing in a Public Area | by Aqeel Anwar | Towards Data Science
Note: Idea credits Landing AI Social-distancing is an important way to slow down the spread of infectious diseases. People are asked to limit their interactions with each other, reducing the chances of the disease being spread with physical or close contact. In the past decade, AI/Deep Learning has shown promising results in several daily life problems. Various daily life tasks have been automated with the help of AI. In this article, we will go through in detail how can one use python combined with deep learning and computer vision to monitor social distancing. The complete python code with installing instructions is available on GitHub Before we get into detail, let’s have a look at the final output. The video below is the result of using AI to monitor social distancing in a public area with already available street cameras. The rest of the article will be divided into three steps Step 1 — Installing the project Step 2 —Running the project Step 3 —Inputs and Outputs of the code Step 4— How does it work? Step 5— Suggested improvements It’s advisable to make a new virtual environment for this project and install the dependencies. Following steps can be taken to download get started with these project Clone the repository: The repository containing the code can be cloned using Clone the repository: The repository containing the code can be cloned using git clone https://github.com/aqeelanwar/SocialDistancingAI.git 2. Install required packages: The provided requirements.txt file can be used to install all the required packages. Use the following command cd SocialDistancingAIpip install –r requirements.txt This will install the required packages in the activated python environment. The code takes the video file path as input. The following command can be used to run the code cd SocialDistancingAIpython main.py --videopath "vid_short.mp4" Running main.py will open a window of the first frame in the video. At this point the code expects the user to mark 6 points by clicking appropriate positions on the frame. These points are necessary to provide a user perspective of the video. The first 4 among the 6 required points are used to mark the Region of Interest (ROI) where you want to monitor. Moreover, the lines marked by these points should be parallel in the real world as seen from above. For example, these lines could be the curbs of the road.These 4 points need to be provided in a pre-defined order which is the following. Point1 (bl): Bottom left Point2 (br): Bottom right Point3 (tl): Top left Point4 (tr): Top right The last two points are used to mark two points 6 feet apart in the region of interest. For example, this could be a person’s height (easier to mark on the frame) The gif below will help understand the points better The Code outputs The first output of the code is the original video with detected pedestrians in it. The pedestrians are localized with purple boxes. The second output of the code is localized pedestrian video from a top-down perspective (bird's eye view) in the region of interest that was marked by the user. Based on the bird's eye view and 6 feet distance points marked by the user, the algorithm calculates and reports the following parameters. 1. # 6ft violations: Number of times the pedestrians violated the 6 feet safe distance threshold 2. Stay-at-home Index: Quantifies how many people are staying at home as compared to the normal routine pedestrian traffic. 0% means that there is no change in the pedestrian traffic compared to normal days, 50% means half of the people are staying at home 3. Social-distancing Index: Quantifies the social distancing being maintained. 50% means half of the interactions violate the safe 6 feet distance criteria. Detecting distances between pedestrians from monocular images without any extra information is not possible. One way (not very accurate though) is to ask the user for specific inputs leading to a distance estimation between the pedestrians. If the user could mark two points on the frame that are 6 feet apart, using extrapolation, one could find the distance between different points on the frame. This would have been true if the camera was equidistant to all the points on the plane where the pedestrians were walking. The closer the pedestrians are to the camera the bigger they are. The closer the two points (which are the same number of pixels apart ) on the frame to the camera, the smaller is the actual distance between them. To cope with this issue, the code receives 4 points input from the user to mark two lines that are parallel seen from the above. The region marked by these 4 points are considered ROI (can be seen in yellow in the gif above). This polygon-shaped ROI is then warped into a rectangle which becomes the bird's eye view. This bird's eye view then has the property of points (which are the same number of pixels apart) being equidistant no matter where they are. All it needs is a multiplier that maps the distance between two points in pixels to distance in real life units (such as feet or meters). This is where the last two user input points come into play. Deep Learning is used to detect and localize the pedestrians which are then mapped to a bird's eye view projection of the camera as explained above. Once we have the coordinates of the pedestrians in the bird's eye view the social distancing parameters become straightforward. The complete block diagram of the algorithm can be seen below. The code could use a lot of improvements in several areas. A few are suggested below A more accurate approach of mapping the camera frame to a bird's eye viewThe code uses an existing multi-class classifier that was trained on 1000 classes from the COCO dataset. The code could use a re-trained classifier specifically trained for binary class (pedestrian, no-pedestrian).A more accurate way of calculating social distance parameters can be introduced. A more accurate approach of mapping the camera frame to a bird's eye view The code uses an existing multi-class classifier that was trained on 1000 classes from the COCO dataset. The code could use a re-trained classifier specifically trained for binary class (pedestrian, no-pedestrian). A more accurate way of calculating social distance parameters can be introduced. The algorithm can be used to analyze social distancing in a public area and carry out necessary actions to better deal with the pandemic. Automating the task will lead to effective actions taken in a short time hence equipping us better to deal with the situation. The complete code is available here at GitHub. Feel free to modify and improve it. Input Pedestrian video is taken from https://www.youtube.com/watch?v=aUdKzb4LGJI If this article was helpful to you, feel free to clap, share and respond to it. If you want to learn more about Machine Learning and Data Science, follow me @Aqeel Anwar or connect with me on LinkedIn.
[ { "code": null, "e": 202, "s": 172, "text": "Note: Idea credits Landing AI" }, { "code": null, "e": 431, "s": 202, "text": "Social-distancing is an important way to slow down the spread of infectious diseases. People are asked to limit their interactions with each other, reducing the chances of the disease being spread with physical or close contact." }, { "code": null, "e": 818, "s": 431, "text": "In the past decade, AI/Deep Learning has shown promising results in several daily life problems. Various daily life tasks have been automated with the help of AI. In this article, we will go through in detail how can one use python combined with deep learning and computer vision to monitor social distancing. The complete python code with installing instructions is available on GitHub" }, { "code": null, "e": 1011, "s": 818, "text": "Before we get into detail, let’s have a look at the final output. The video below is the result of using AI to monitor social distancing in a public area with already available street cameras." }, { "code": null, "e": 1068, "s": 1011, "text": "The rest of the article will be divided into three steps" }, { "code": null, "e": 1100, "s": 1068, "text": "Step 1 — Installing the project" }, { "code": null, "e": 1128, "s": 1100, "text": "Step 2 —Running the project" }, { "code": null, "e": 1167, "s": 1128, "text": "Step 3 —Inputs and Outputs of the code" }, { "code": null, "e": 1193, "s": 1167, "text": "Step 4— How does it work?" }, { "code": null, "e": 1224, "s": 1193, "text": "Step 5— Suggested improvements" }, { "code": null, "e": 1392, "s": 1224, "text": "It’s advisable to make a new virtual environment for this project and install the dependencies. Following steps can be taken to download get started with these project" }, { "code": null, "e": 1469, "s": 1392, "text": "Clone the repository: The repository containing the code can be cloned using" }, { "code": null, "e": 1546, "s": 1469, "text": "Clone the repository: The repository containing the code can be cloned using" }, { "code": null, "e": 1609, "s": 1546, "text": "git clone https://github.com/aqeelanwar/SocialDistancingAI.git" }, { "code": null, "e": 1750, "s": 1609, "text": "2. Install required packages: The provided requirements.txt file can be used to install all the required packages. Use the following command" }, { "code": null, "e": 1803, "s": 1750, "text": "cd SocialDistancingAIpip install –r requirements.txt" }, { "code": null, "e": 1880, "s": 1803, "text": "This will install the required packages in the activated python environment." }, { "code": null, "e": 1975, "s": 1880, "text": "The code takes the video file path as input. The following command can be used to run the code" }, { "code": null, "e": 2039, "s": 1975, "text": "cd SocialDistancingAIpython main.py --videopath \"vid_short.mp4\"" }, { "code": null, "e": 2283, "s": 2039, "text": "Running main.py will open a window of the first frame in the video. At this point the code expects the user to mark 6 points by clicking appropriate positions on the frame. These points are necessary to provide a user perspective of the video." }, { "code": null, "e": 2634, "s": 2283, "text": "The first 4 among the 6 required points are used to mark the Region of Interest (ROI) where you want to monitor. Moreover, the lines marked by these points should be parallel in the real world as seen from above. For example, these lines could be the curbs of the road.These 4 points need to be provided in a pre-defined order which is the following." }, { "code": null, "e": 2659, "s": 2634, "text": "Point1 (bl): Bottom left" }, { "code": null, "e": 2685, "s": 2659, "text": "Point2 (br): Bottom right" }, { "code": null, "e": 2707, "s": 2685, "text": "Point3 (tl): Top left" }, { "code": null, "e": 2730, "s": 2707, "text": "Point4 (tr): Top right" }, { "code": null, "e": 2893, "s": 2730, "text": "The last two points are used to mark two points 6 feet apart in the region of interest. For example, this could be a person’s height (easier to mark on the frame)" }, { "code": null, "e": 2946, "s": 2893, "text": "The gif below will help understand the points better" }, { "code": null, "e": 2963, "s": 2946, "text": "The Code outputs" }, { "code": null, "e": 3096, "s": 2963, "text": "The first output of the code is the original video with detected pedestrians in it. The pedestrians are localized with purple boxes." }, { "code": null, "e": 3257, "s": 3096, "text": "The second output of the code is localized pedestrian video from a top-down perspective (bird's eye view) in the region of interest that was marked by the user." }, { "code": null, "e": 3396, "s": 3257, "text": "Based on the bird's eye view and 6 feet distance points marked by the user, the algorithm calculates and reports the following parameters." }, { "code": null, "e": 3493, "s": 3396, "text": "1. # 6ft violations: Number of times the pedestrians violated the 6 feet safe distance threshold" }, { "code": null, "e": 3750, "s": 3493, "text": "2. Stay-at-home Index: Quantifies how many people are staying at home as compared to the normal routine pedestrian traffic. 0% means that there is no change in the pedestrian traffic compared to normal days, 50% means half of the people are staying at home" }, { "code": null, "e": 3907, "s": 3750, "text": "3. Social-distancing Index: Quantifies the social distancing being maintained. 50% means half of the interactions violate the safe 6 feet distance criteria." }, { "code": null, "e": 4643, "s": 3907, "text": "Detecting distances between pedestrians from monocular images without any extra information is not possible. One way (not very accurate though) is to ask the user for specific inputs leading to a distance estimation between the pedestrians. If the user could mark two points on the frame that are 6 feet apart, using extrapolation, one could find the distance between different points on the frame. This would have been true if the camera was equidistant to all the points on the plane where the pedestrians were walking. The closer the pedestrians are to the camera the bigger they are. The closer the two points (which are the same number of pixels apart ) on the frame to the camera, the smaller is the actual distance between them." }, { "code": null, "e": 5300, "s": 4643, "text": "To cope with this issue, the code receives 4 points input from the user to mark two lines that are parallel seen from the above. The region marked by these 4 points are considered ROI (can be seen in yellow in the gif above). This polygon-shaped ROI is then warped into a rectangle which becomes the bird's eye view. This bird's eye view then has the property of points (which are the same number of pixels apart) being equidistant no matter where they are. All it needs is a multiplier that maps the distance between two points in pixels to distance in real life units (such as feet or meters). This is where the last two user input points come into play." }, { "code": null, "e": 5577, "s": 5300, "text": "Deep Learning is used to detect and localize the pedestrians which are then mapped to a bird's eye view projection of the camera as explained above. Once we have the coordinates of the pedestrians in the bird's eye view the social distancing parameters become straightforward." }, { "code": null, "e": 5640, "s": 5577, "text": "The complete block diagram of the algorithm can be seen below." }, { "code": null, "e": 5725, "s": 5640, "text": "The code could use a lot of improvements in several areas. A few are suggested below" }, { "code": null, "e": 6093, "s": 5725, "text": "A more accurate approach of mapping the camera frame to a bird's eye viewThe code uses an existing multi-class classifier that was trained on 1000 classes from the COCO dataset. The code could use a re-trained classifier specifically trained for binary class (pedestrian, no-pedestrian).A more accurate way of calculating social distance parameters can be introduced." }, { "code": null, "e": 6167, "s": 6093, "text": "A more accurate approach of mapping the camera frame to a bird's eye view" }, { "code": null, "e": 6382, "s": 6167, "text": "The code uses an existing multi-class classifier that was trained on 1000 classes from the COCO dataset. The code could use a re-trained classifier specifically trained for binary class (pedestrian, no-pedestrian)." }, { "code": null, "e": 6463, "s": 6382, "text": "A more accurate way of calculating social distance parameters can be introduced." }, { "code": null, "e": 6811, "s": 6463, "text": "The algorithm can be used to analyze social distancing in a public area and carry out necessary actions to better deal with the pandemic. Automating the task will lead to effective actions taken in a short time hence equipping us better to deal with the situation. The complete code is available here at GitHub. Feel free to modify and improve it." }, { "code": null, "e": 6892, "s": 6811, "text": "Input Pedestrian video is taken from https://www.youtube.com/watch?v=aUdKzb4LGJI" } ]
Java Tutorial
Java is a popular programming language. Java is used to develop mobile apps, web apps, desktop apps, games and much more. Our "Try it Yourself" editor makes it easy to learn Java. You can edit Java code and view the result in your browser. public class Main { public static void main(String[] args) { System.out.println("Hello World"); } } Try it Yourself » Click on the "Run example" button to see how it works. We recommend reading this tutorial, in the sequence listed in the left menu. Java is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed. Insert the missing part of the code below to output "Hello World". public class MyClass { public static void main(String[] args) { ..("Hello World"); } } Start the Exercise Test your Java skills with a quiz. Start Java Quiz Learn by examples! This tutorial supplements all explanations with clarifying examples. See All Java Examples Java Keywords Java String Methods Java Math Methods Download Java from the official Java web site: https://www.oracle.com Get certified by completing the JAVA course 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": 40, "s": 0, "text": "Java is a popular programming language." }, { "code": null, "e": 123, "s": 40, "text": "Java is used to develop mobile apps, web apps, desktop apps, games and much \nmore." }, { "code": null, "e": 242, "s": 123, "text": "Our \"Try it Yourself\" editor makes it easy to learn Java. You can edit Java code and view the result \nin your browser." }, { "code": null, "e": 351, "s": 242, "text": "public class Main {\n public static void main(String[] args) {\n System.out.println(\"Hello World\");\n }\n}\n" }, { "code": null, "e": 371, "s": 351, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 426, "s": 371, "text": "Click on the \"Run example\" button to see how it works." }, { "code": null, "e": 503, "s": 426, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 644, "s": 503, "text": "Java is an object oriented language and some concepts may be new. Take breaks when needed, and go\nover the examples as many times as needed." }, { "code": null, "e": 711, "s": 644, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 807, "s": 711, "text": "public class MyClass {\n public static void main(String[] args) {\n ..(\"Hello World\");\n }\n}\n" }, { "code": null, "e": 826, "s": 807, "text": "Start the Exercise" }, { "code": null, "e": 861, "s": 826, "text": "Test your Java skills with a quiz." }, { "code": null, "e": 877, "s": 861, "text": "Start Java Quiz" }, { "code": null, "e": 965, "s": 877, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 987, "s": 965, "text": "See All Java Examples" }, { "code": null, "e": 1001, "s": 987, "text": "Java Keywords" }, { "code": null, "e": 1021, "s": 1001, "text": "Java String Methods" }, { "code": null, "e": 1039, "s": 1021, "text": "Java Math Methods" }, { "code": null, "e": 1109, "s": 1039, "text": "Download Java from the official Java web site:\nhttps://www.oracle.com" }, { "code": null, "e": 1153, "s": 1109, "text": "Get certified by completing the JAVA course" }, { "code": null, "e": 1186, "s": 1153, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1228, "s": 1186, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1335, "s": 1228, "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": 1354, "s": 1335, "text": "help@w3schools.com" } ]
Deep Learning Techniques for Text Classification | by Diardano Raihan | Towards Data Science
Text classification is one of the popular tasks in NLP that allows a program to classify free-text documents based on pre-defined classes. The classes can be based on topic, genre, or sentiment. Today’s emergence of large digital documents makes the text classification task more crucial, especially for companies to maximize their workflow or even profits. Recently, the progress of NLP research on text classification has arrived at the state-of-the-art (SOTA). It has achieved terrific results, showing Deep Learning methods as the cutting-edge technology to perform such tasks. Hence, the need to assess the performance of the SOTA deep learning models for text classification is essential not only for academic purposes but also for AI practitioners or professionals that need guidance and benchmark on similar projects. The experiment will evaluate the performance of some popular deep learning models, such as feedforward, recurrent, convolutional, and ensemble-based neural networks, on five text classification datasets. We will build each model on top of two separate feature extractions to capture information within the text. The result shows: the robustness of word embedding as a feature extractor to all the models in making a better final prediction. the effectiveness of the ensemble-based and temporal convolutional neural network in achieving good performances and even competing with the state-of-the-art benchmark models. MR. Movie Reviews — classifying a review as positive or negative [1]. Link SUBJ. Subjectivity — classifying a sentence as subjective or objective [2]. Link TREC. Text REtrieval Conference — classifying a question into six categories (a person, location, numeric information, etc.) [3]. Link CR. Customer Reviews — classifying a product review (cameras, MP3s, etc.) as positive or negative [4]. Link MPQA. Multi-Perspective Question Answering — opinion polarity detection [5]. Link To make things easy, we have prepared the datasets in the pickle format here. Shaojie Bai et al. [6] proposed a generic temporal convolutional network (TCN) as a dilated-causal version of CNN. It works as a strong alternative to recurrent architectures that can handle a long input sequence without suffering from vanishing or exploding gradient problems. If you care to learn more about the model blocks, you can refer to [6] and [7] for the implementation. The proposed TCN model is inspired by Christof Henkel [8], one of the grandmasters on Kaggle. The model consists of: Two TCN blocks stacked with the kernel size of 3 and dilation factors of 1, 2, and 4. The first TCN block contains 128 filters, and the second block uses 64 filters. The input features will be based on Word Embedding. Each block’s result will take the form of a sequence. The final sequence is then passed to two different global pooling layers. Next, both results are concatenated and passed into a dense layer of 16 neurons, and pass to the output. def tcn_model(kernel_size = 3, activation='relu', input_dim = None, output_dim=300, max_length = None, emb_matrix = None): inp = Input( shape=(max_length,)) x = Embedding(input_dim=input_dim, output_dim=output_dim, input_length=max_length, # Assign the embedding weight with word2vec embedding marix weights = [emb_matrix], # Set the weight to be not trainable (static) trainable = False)(inp) x = SpatialDropout1D(0.1)(x) x = TCN(128,dilations = [1, 2, 4], return_sequences=True, activation = activation, name = 'tcn1')(x) x = TCN(64,dilations = [1, 2, 4], return_sequences=True, activation = activation, name = 'tcn2')(x) avg_pool = GlobalAveragePooling1D()(x) max_pool = GlobalMaxPooling1D()(x) conc = concatenate([avg_pool, max_pool]) conc = Dense(16, activation="relu")(conc) conc = Dropout(0.1)(conc) outp = Dense(1, activation="sigmoid")(conc) model = Model(inputs=inp, outputs=outp) model.compile( loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) return model K. Kowsari et al. [9] introduced a novel deep learning technique for classification called Random Multimodel Deep Learning (RMDL). The model can be used for any classification task. The figure below illustrates an architecture using deep RNN, deep CNN, and deep feedforward neural network (DNN). In this project, we implement an ensemble learning-based model by combining 1D CNN with a single Bidirectional GRU (BiGRU). The 1D CNN has been proven to work well on text classification despite only a little parameter tuning [10]. On the other hand, BiGRU works well on temporal data by taking both earlier and later information in the sequence. We will see how this combination affects the model accuracy in the experiment. def ensemble_CNN_BiGRU(filters = 100, kernel_size = 3, activation='relu', input_dim = None, output_dim=300, max_length = None, emb_matrix = None): # Channel 1D CNN input1 = Input(shape=(max_length,)) embeddding1 = Embedding(input_dim=input_dim, output_dim=output_dim, input_length=max_length, input_shape=(max_length, ), # Assign the embedding weight with word2vec embedding marix weights = [emb_matrix], # Set the weight to be not trainable (static) trainable = False)(input1) conv1 = Conv1D(filters=filters, kernel_size=kernel_size, activation='relu', kernel_constraint= MaxNorm( max_value=3, axis=[0,1]))(embeddding1) pool1 = MaxPool1D(pool_size=2, strides=2)(conv1) flat1 = Flatten()(pool1) drop1 = Dropout(0.5)(flat1) dense1 = Dense(10, activation='relu')(drop1) drop1 = Dropout(0.5)(dense1) out1 = Dense(1, activation='sigmoid')(drop1) # Channel BiGRU input2 = Input(shape=(max_length,)) embeddding2 = Embedding(input_dim=input_dim, output_dim=output_dim, input_length=max_length, input_shape=(max_length, ), # Assign the embedding weight with word2vec embedding marix weights = [emb_matrix], # Set the weight to be not trainable (static) trainable = False, mask_zero=True)(input2) gru2 = Bidirectional(GRU(64))(embeddding2) drop2 = Dropout(0.5)(gru2) out2 = Dense(1, activation='sigmoid')(drop2) # Merge merged = concatenate([out1, out2]) # Interpretation outputs = Dense(1, activation='sigmoid')(merged) model = Model(inputs=[input1, input2], outputs=outputs) # Compile model.compile( loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model To compare the performance, we will also evaluate other popular models such as: SNN. A shallow neural network. edRVFL. Ensemble deep random vector functional link neural network. 1D CNN. Our baseline model representing a neural network with a one-dimensional convolution and pooling layers. (Stacked) BiGRU/BiLSTM. Bidirectional Gated Recurrent Unit / Long Short-Term Memory. Its stacked version means we add another bidirectional block to the network. To sum up, we will build deep learning models using two different feature extractions on five text classification datasets as follows: WE-rand. The model uses an embedding layer where the word vectors are randomly initialized and corrected during training WE-static. The model uses pre-trained word embedding called Word2Vec with 300-dimensional vectors. The vectors are kept static during training. The vectors for unknown words are randomly initialized using a generic normal distribution. WE-dynamic. Same as above, but the vectors are modified during training, not static. WE-avg. The model uses the average of vectors from the pre-trained word embedding to get the input context. Hence, the size of input features will be the same as the size of the vector dimension used in the Word2Vec, 300. Bag-of-Words (BoW). It represents text as the number of word occurrences within a document before feeding It to the model. We will use four word-scoring options: binary, count, freq, and TF-IDF. The benchmarks used in this work are: CNN-multichannel (Yoon Kim, 2014) [10] SuBiLSTM (Siddhartha Brahma, 2018) [11] SuBiLSTM-Tied (Siddhartha Brahma, 2018) [11] USE_T+CNN (Cer et al., 2018) [12] We will use accuracy and rank as comparison metrics. The rank will be calculated based on the accuracy of each dataset. In the case there are ties, we average their ranks. Table 8 shows the final comparison for each model performance. We also include the SOTA benchmark models (at the bottom) for further observation. Note that we only include the best results for the models that use the bag-of-words and average word embedding (SNN and edRVFL), From Table 8, we can calculate the average accuracy margin of the models to the baseline (1D CNN-rand) on the 5 datasets as follows: In Figure 5, the green bar represents the benchmark model. The purple bar depicts the top six proposed models that beat the baseline. Finally, the red bar is the proposed model with the lowest accuracy margin. The minus (-) sign indicates the model has much lower accuracy than higher ones in all datasets with the baseline as the reference. From there, we can calculate the average rank values and visualize the result as shown below: The models with BoW in this experiment cannot do much despite having so many hyperparameter tuning. The large numbers of text data will make the vocabulary of BoW extensive. Hence, the input features will be in sparse form, presenting a bit of information over many zeros. This text representation makes the model harder to train to achieve a better result. Unless we specify the vocabulary size not big enough or work with a small corpus, BoW cannot be a reliable option. On the other hand, the models perform better when using word embedding. By only taking the average of Word2Vec to obtain N-dimensional feature inputs, the model can have a very steep increase in accuracy up to 10%. For example, both edRVFL and SNN suddenly jump from 75.2 and 76.2 to 83.6 and 85.8 in the TREC dataset. These results prove the importance of word embedding as a default feature extractor. Figure 7 illustrates the effect of different word embedding modes on the model performance. As expected, the static word embedding using pre-trained Word2Vec always performs better. The static mode can help any models predict classes more accurately up to a 3% average accuracy increase than the random mode. The dynamic vector representation model will fine-tune the parameters initialized by Word2Vec vectors to learn the meaningful context for each task. Ideally, it will result in better performance than the static one. However, that is not always the case. Although the model can still improve, the change is not significant. In some cases, a model can even have lower accuracy. In Figure 7, the dynamic mode slightly lowers the overall model performance on TREC and MPQA datasets. In Table 8, although BiGRU-dynamic offers better performance than its static version in the SUBJ dataset, it decreases performance on the other datasets. This is because the vectors adjust to a specific dataset that can overfit and change the original context derived from Word2Vec. If we use word embedding, TCN is more effective than RNN-based models like LSTM or GRU. In four of five datasets, TCN outclasses all the RNN architectures with an excellent accuracy margin. On the other dataset, the TCN accuracy is still high and close to the highest ones. TCN-static and -dynamic sit as the top models, followed by BiLSTM-static, BiGRU-static, and Stacked BiGRU-static. Simply put, TCN is the best model not only compared to the RNN family but also to the other models in capturing information to make a stable prediction. The only type of model that can challenge TCN in this experiment is the ensemble-based model. As expected, the ensemble models generally outperform the single-based models in almost all the classification tasks. The ensemble model’s static version provides better performance in 3 out of 5 datasets. The key to ensemble learning is that the candidate models need to be proven to work well on the given task. In this case, the 1D CNN and BiRNN are great models to combine for text classification. The result encourages us to experiment combining a potent model, such as TCN, with other existing good deep learning models in the future. Finally, Table 9 summarizes the best models in this series of experiments. We use the average accuracy margin in Figure 5 and the average rank values in Figure 6 to compare the top six performing models for classifying text. We can see that the static version of TCN and Ensemble models emerge as the best. Next, the TCN-dynamic follows as the best model joining the group as the top three. In the end, TCN and ensemble-based models dominate other configurations to perform text classification tasks, making them the best recommend architectures for future application and research. This project has demonstrated a comprehensive experiment focusing on building deep learning models using two different feature extractions on five text classification datasets. In conclusion, the followings are the essential insights: Any model built on top of word embedding causes the model to perform exceptionally well. Using a pre-trained word embedding such as Word2Vec can increase the model accuracy with a high margin. TCN is an excellent alternative to recurrent architecture and has been proven effective in classifying text data. The ensemble learning-based model can help make better predictions than a single model trained independently. TCN and Ensemble CNN-GRU models are the best performing algorithms we obtained in this series of text classification tasks. We recommend some suggestions for future experiments as follows: An ensemble-based model with TCN. Perform text classification tasks using TCN combined with other good models such as 1D CNN and BiGRU in ensemble-based learning to see if it can challenge the benchmarks even more Kernel size and filters. Explore these two hyperparameters by extending the kernel sizes between 1 to 10 with more or fewer filters in CNN or TCN to see how it affects the model performance. Deeper network. Any neural network with more hidden layers typically will do better in any task. Explore the deeper version of CNN, RNN, and TCN to see how it affects the existing performance. Use GloVe and FastText. Explore other pre-trained word embedding options such as GloVe and FastText with static and dynamic modes and compare the result to Word2Vec. Thank you, Diardano RaihanLinkedIn Profile Note: Everything you have seen is documented in my GitHub repository. For those who are curious about the full code, please do have a visit 👍. [1] B. Pang, L. Lee, “Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales”, In Proceedings of ACL’05, 2005. [2] B. Pang, L. Lee, “A sentimental education: Sentiment analysis using subjectivity summarization based on minimum cuts”, In Proceedings of the 42nd Meeting of the Association for Computational Linguistics (ACL’04), 2004. [3] X. Li, D. Roth, “Learning question classifiers”, In Proceedings of COLING ’02, 2002. [4] M. Hu, B. Liu, “Mining and summarizing customer reviews”, In Proceedings of KDD ’04, 2004. [5] J. Wiebe, T. Wilson, and C. Cardie, “Annotating expressions of opinions and emotions in language”, Language Resources and Evaluation, 39(2):165–210, 2005. [6] S. bai, J. Kolter, and V. Koltun, “An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling”, arXiv, April, 2018. [7] P. Rémy, “Keras TCN”, GitHub https://github.com/philipperemy/keras-tcn, January. 2021. [8] C. Henkel, “Temporal Convolutional Network”, Kaggle, https://www.kaggle.com/christofhenkel/temporal-convolutional-network, February, 2021. [9] K. Kowsari, M. Heidarysafa, D. E. Brown, K. J. Meimandi, and L. E. Barnes, “Random Multimodel Deep Learning for Classification”, arXiv, April, 2018. [10] Y. Kim, “Convolutional Neural Networks for Sentence Classification,” Association for Computational Linguistics, October, 2014. [11] S. Brahma, “Improved Sentence Modeling using Suffix Bidirectional LSTM”, arXiv, September, 2018. [12] D. Cer, Y. Yang, S. Kong, N. Hua, N. Limtiaco, R. S. John, N. Constant, M. Guajardo-Cespedes, S. Yuan, C. Tar, Y. Sung, B. Strope, R. Kurzweil, “Universal Sentence Encoder”, arXiv, April, 2018.
[ { "code": null, "e": 530, "s": 172, "text": "Text classification is one of the popular tasks in NLP that allows a program to classify free-text documents based on pre-defined classes. The classes can be based on topic, genre, or sentiment. Today’s emergence of large digital documents makes the text classification task more crucial, especially for companies to maximize their workflow or even profits." }, { "code": null, "e": 754, "s": 530, "text": "Recently, the progress of NLP research on text classification has arrived at the state-of-the-art (SOTA). It has achieved terrific results, showing Deep Learning methods as the cutting-edge technology to perform such tasks." }, { "code": null, "e": 998, "s": 754, "text": "Hence, the need to assess the performance of the SOTA deep learning models for text classification is essential not only for academic purposes but also for AI practitioners or professionals that need guidance and benchmark on similar projects." }, { "code": null, "e": 1310, "s": 998, "text": "The experiment will evaluate the performance of some popular deep learning models, such as feedforward, recurrent, convolutional, and ensemble-based neural networks, on five text classification datasets. We will build each model on top of two separate feature extractions to capture information within the text." }, { "code": null, "e": 1328, "s": 1310, "text": "The result shows:" }, { "code": null, "e": 1439, "s": 1328, "text": "the robustness of word embedding as a feature extractor to all the models in making a better final prediction." }, { "code": null, "e": 1615, "s": 1439, "text": "the effectiveness of the ensemble-based and temporal convolutional neural network in achieving good performances and even competing with the state-of-the-art benchmark models." }, { "code": null, "e": 1690, "s": 1615, "text": "MR. Movie Reviews — classifying a review as positive or negative [1]. Link" }, { "code": null, "e": 1771, "s": 1690, "text": "SUBJ. Subjectivity — classifying a sentence as subjective or objective [2]. Link" }, { "code": null, "e": 1906, "s": 1771, "text": "TREC. Text REtrieval Conference — classifying a question into six categories (a person, location, numeric information, etc.) [3]. Link" }, { "code": null, "e": 2014, "s": 1906, "text": "CR. Customer Reviews — classifying a product review (cameras, MP3s, etc.) as positive or negative [4]. Link" }, { "code": null, "e": 2096, "s": 2014, "text": "MPQA. Multi-Perspective Question Answering — opinion polarity detection [5]. Link" }, { "code": null, "e": 2174, "s": 2096, "text": "To make things easy, we have prepared the datasets in the pickle format here." }, { "code": null, "e": 2555, "s": 2174, "text": "Shaojie Bai et al. [6] proposed a generic temporal convolutional network (TCN) as a dilated-causal version of CNN. It works as a strong alternative to recurrent architectures that can handle a long input sequence without suffering from vanishing or exploding gradient problems. If you care to learn more about the model blocks, you can refer to [6] and [7] for the implementation." }, { "code": null, "e": 2672, "s": 2555, "text": "The proposed TCN model is inspired by Christof Henkel [8], one of the grandmasters on Kaggle. The model consists of:" }, { "code": null, "e": 2758, "s": 2672, "text": "Two TCN blocks stacked with the kernel size of 3 and dilation factors of 1, 2, and 4." }, { "code": null, "e": 2890, "s": 2758, "text": "The first TCN block contains 128 filters, and the second block uses 64 filters. The input features will be based on Word Embedding." }, { "code": null, "e": 2944, "s": 2890, "text": "Each block’s result will take the form of a sequence." }, { "code": null, "e": 3018, "s": 2944, "text": "The final sequence is then passed to two different global pooling layers." }, { "code": null, "e": 3123, "s": 3018, "text": "Next, both results are concatenated and passed into a dense layer of 16 neurons, and pass to the output." }, { "code": null, "e": 4337, "s": 3123, "text": "def tcn_model(kernel_size = 3, activation='relu', input_dim = None, \n output_dim=300, max_length = None, emb_matrix = None):\n \n inp = Input( shape=(max_length,))\n x = Embedding(input_dim=input_dim, \n output_dim=output_dim, \n input_length=max_length,\n # Assign the embedding weight with word2vec embedding marix\n weights = [emb_matrix],\n # Set the weight to be not trainable (static)\n trainable = False)(inp)\n \n x = SpatialDropout1D(0.1)(x)\n \n x = TCN(128,dilations = [1, 2, 4], return_sequences=True, activation = activation, name = 'tcn1')(x)\n x = TCN(64,dilations = [1, 2, 4], return_sequences=True, activation = activation, name = 'tcn2')(x)\n \n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n \n conc = concatenate([avg_pool, max_pool])\n conc = Dense(16, activation=\"relu\")(conc)\n conc = Dropout(0.1)(conc)\n outp = Dense(1, activation=\"sigmoid\")(conc) \n\n model = Model(inputs=inp, outputs=outp)\n model.compile( loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n \n return model" }, { "code": null, "e": 4633, "s": 4337, "text": "K. Kowsari et al. [9] introduced a novel deep learning technique for classification called Random Multimodel Deep Learning (RMDL). The model can be used for any classification task. The figure below illustrates an architecture using deep RNN, deep CNN, and deep feedforward neural network (DNN)." }, { "code": null, "e": 4757, "s": 4633, "text": "In this project, we implement an ensemble learning-based model by combining 1D CNN with a single Bidirectional GRU (BiGRU)." }, { "code": null, "e": 4865, "s": 4757, "text": "The 1D CNN has been proven to work well on text classification despite only a little parameter tuning [10]." }, { "code": null, "e": 4980, "s": 4865, "text": "On the other hand, BiGRU works well on temporal data by taking both earlier and later information in the sequence." }, { "code": null, "e": 5059, "s": 4980, "text": "We will see how this combination affects the model accuracy in the experiment." }, { "code": null, "e": 7223, "s": 5059, "text": "def ensemble_CNN_BiGRU(filters = 100, kernel_size = 3, activation='relu', \n input_dim = None, output_dim=300, max_length = None, emb_matrix = None):\n \n # Channel 1D CNN\n input1 = Input(shape=(max_length,))\n embeddding1 = Embedding(input_dim=input_dim, \n output_dim=output_dim, \n input_length=max_length, \n input_shape=(max_length, ),\n # Assign the embedding weight with word2vec embedding marix\n weights = [emb_matrix],\n # Set the weight to be not trainable (static)\n trainable = False)(input1)\n conv1 = Conv1D(filters=filters, kernel_size=kernel_size, activation='relu', \n kernel_constraint= MaxNorm( max_value=3, axis=[0,1]))(embeddding1)\n pool1 = MaxPool1D(pool_size=2, strides=2)(conv1)\n flat1 = Flatten()(pool1)\n drop1 = Dropout(0.5)(flat1)\n dense1 = Dense(10, activation='relu')(drop1)\n drop1 = Dropout(0.5)(dense1)\n out1 = Dense(1, activation='sigmoid')(drop1)\n \n # Channel BiGRU\n input2 = Input(shape=(max_length,))\n embeddding2 = Embedding(input_dim=input_dim, \n output_dim=output_dim, \n input_length=max_length, \n input_shape=(max_length, ),\n # Assign the embedding weight with word2vec embedding marix\n weights = [emb_matrix],\n # Set the weight to be not trainable (static)\n trainable = False,\n mask_zero=True)(input2)\n gru2 = Bidirectional(GRU(64))(embeddding2)\n drop2 = Dropout(0.5)(gru2)\n out2 = Dense(1, activation='sigmoid')(drop2)\n \n # Merge\n merged = concatenate([out1, out2])\n \n # Interpretation\n outputs = Dense(1, activation='sigmoid')(merged)\n model = Model(inputs=[input1, input2], outputs=outputs)\n \n # Compile\n model.compile( loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n \n return model" }, { "code": null, "e": 7303, "s": 7223, "text": "To compare the performance, we will also evaluate other popular models such as:" }, { "code": null, "e": 7334, "s": 7303, "text": "SNN. A shallow neural network." }, { "code": null, "e": 7402, "s": 7334, "text": "edRVFL. Ensemble deep random vector functional link neural network." }, { "code": null, "e": 7514, "s": 7402, "text": "1D CNN. Our baseline model representing a neural network with a one-dimensional convolution and pooling layers." }, { "code": null, "e": 7676, "s": 7514, "text": "(Stacked) BiGRU/BiLSTM. Bidirectional Gated Recurrent Unit / Long Short-Term Memory. Its stacked version means we add another bidirectional block to the network." }, { "code": null, "e": 7811, "s": 7676, "text": "To sum up, we will build deep learning models using two different feature extractions on five text classification datasets as follows:" }, { "code": null, "e": 7932, "s": 7811, "text": "WE-rand. The model uses an embedding layer where the word vectors are randomly initialized and corrected during training" }, { "code": null, "e": 8168, "s": 7932, "text": "WE-static. The model uses pre-trained word embedding called Word2Vec with 300-dimensional vectors. The vectors are kept static during training. The vectors for unknown words are randomly initialized using a generic normal distribution." }, { "code": null, "e": 8253, "s": 8168, "text": "WE-dynamic. Same as above, but the vectors are modified during training, not static." }, { "code": null, "e": 8475, "s": 8253, "text": "WE-avg. The model uses the average of vectors from the pre-trained word embedding to get the input context. Hence, the size of input features will be the same as the size of the vector dimension used in the Word2Vec, 300." }, { "code": null, "e": 8670, "s": 8475, "text": "Bag-of-Words (BoW). It represents text as the number of word occurrences within a document before feeding It to the model. We will use four word-scoring options: binary, count, freq, and TF-IDF." }, { "code": null, "e": 8708, "s": 8670, "text": "The benchmarks used in this work are:" }, { "code": null, "e": 8747, "s": 8708, "text": "CNN-multichannel (Yoon Kim, 2014) [10]" }, { "code": null, "e": 8787, "s": 8747, "text": "SuBiLSTM (Siddhartha Brahma, 2018) [11]" }, { "code": null, "e": 8832, "s": 8787, "text": "SuBiLSTM-Tied (Siddhartha Brahma, 2018) [11]" }, { "code": null, "e": 8866, "s": 8832, "text": "USE_T+CNN (Cer et al., 2018) [12]" }, { "code": null, "e": 9038, "s": 8866, "text": "We will use accuracy and rank as comparison metrics. The rank will be calculated based on the accuracy of each dataset. In the case there are ties, we average their ranks." }, { "code": null, "e": 9313, "s": 9038, "text": "Table 8 shows the final comparison for each model performance. We also include the SOTA benchmark models (at the bottom) for further observation. Note that we only include the best results for the models that use the bag-of-words and average word embedding (SNN and edRVFL)," }, { "code": null, "e": 9446, "s": 9313, "text": "From Table 8, we can calculate the average accuracy margin of the models to the baseline (1D CNN-rand) on the 5 datasets as follows:" }, { "code": null, "e": 9788, "s": 9446, "text": "In Figure 5, the green bar represents the benchmark model. The purple bar depicts the top six proposed models that beat the baseline. Finally, the red bar is the proposed model with the lowest accuracy margin. The minus (-) sign indicates the model has much lower accuracy than higher ones in all datasets with the baseline as the reference." }, { "code": null, "e": 9882, "s": 9788, "text": "From there, we can calculate the average rank values and visualize the result as shown below:" }, { "code": null, "e": 10355, "s": 9882, "text": "The models with BoW in this experiment cannot do much despite having so many hyperparameter tuning. The large numbers of text data will make the vocabulary of BoW extensive. Hence, the input features will be in sparse form, presenting a bit of information over many zeros. This text representation makes the model harder to train to achieve a better result. Unless we specify the vocabulary size not big enough or work with a small corpus, BoW cannot be a reliable option." }, { "code": null, "e": 10759, "s": 10355, "text": "On the other hand, the models perform better when using word embedding. By only taking the average of Word2Vec to obtain N-dimensional feature inputs, the model can have a very steep increase in accuracy up to 10%. For example, both edRVFL and SNN suddenly jump from 75.2 and 76.2 to 83.6 and 85.8 in the TREC dataset. These results prove the importance of word embedding as a default feature extractor." }, { "code": null, "e": 11068, "s": 10759, "text": "Figure 7 illustrates the effect of different word embedding modes on the model performance. As expected, the static word embedding using pre-trained Word2Vec always performs better. The static mode can help any models predict classes more accurately up to a 3% average accuracy increase than the random mode." }, { "code": null, "e": 11444, "s": 11068, "text": "The dynamic vector representation model will fine-tune the parameters initialized by Word2Vec vectors to learn the meaningful context for each task. Ideally, it will result in better performance than the static one. However, that is not always the case. Although the model can still improve, the change is not significant. In some cases, a model can even have lower accuracy." }, { "code": null, "e": 11830, "s": 11444, "text": "In Figure 7, the dynamic mode slightly lowers the overall model performance on TREC and MPQA datasets. In Table 8, although BiGRU-dynamic offers better performance than its static version in the SUBJ dataset, it decreases performance on the other datasets. This is because the vectors adjust to a specific dataset that can overfit and change the original context derived from Word2Vec." }, { "code": null, "e": 12218, "s": 11830, "text": "If we use word embedding, TCN is more effective than RNN-based models like LSTM or GRU. In four of five datasets, TCN outclasses all the RNN architectures with an excellent accuracy margin. On the other dataset, the TCN accuracy is still high and close to the highest ones. TCN-static and -dynamic sit as the top models, followed by BiLSTM-static, BiGRU-static, and Stacked BiGRU-static." }, { "code": null, "e": 12465, "s": 12218, "text": "Simply put, TCN is the best model not only compared to the RNN family but also to the other models in capturing information to make a stable prediction. The only type of model that can challenge TCN in this experiment is the ensemble-based model." }, { "code": null, "e": 13006, "s": 12465, "text": "As expected, the ensemble models generally outperform the single-based models in almost all the classification tasks. The ensemble model’s static version provides better performance in 3 out of 5 datasets. The key to ensemble learning is that the candidate models need to be proven to work well on the given task. In this case, the 1D CNN and BiRNN are great models to combine for text classification. The result encourages us to experiment combining a potent model, such as TCN, with other existing good deep learning models in the future." }, { "code": null, "e": 13313, "s": 13006, "text": "Finally, Table 9 summarizes the best models in this series of experiments. We use the average accuracy margin in Figure 5 and the average rank values in Figure 6 to compare the top six performing models for classifying text. We can see that the static version of TCN and Ensemble models emerge as the best." }, { "code": null, "e": 13589, "s": 13313, "text": "Next, the TCN-dynamic follows as the best model joining the group as the top three. In the end, TCN and ensemble-based models dominate other configurations to perform text classification tasks, making them the best recommend architectures for future application and research." }, { "code": null, "e": 13824, "s": 13589, "text": "This project has demonstrated a comprehensive experiment focusing on building deep learning models using two different feature extractions on five text classification datasets. In conclusion, the followings are the essential insights:" }, { "code": null, "e": 13913, "s": 13824, "text": "Any model built on top of word embedding causes the model to perform exceptionally well." }, { "code": null, "e": 14017, "s": 13913, "text": "Using a pre-trained word embedding such as Word2Vec can increase the model accuracy with a high margin." }, { "code": null, "e": 14131, "s": 14017, "text": "TCN is an excellent alternative to recurrent architecture and has been proven effective in classifying text data." }, { "code": null, "e": 14241, "s": 14131, "text": "The ensemble learning-based model can help make better predictions than a single model trained independently." }, { "code": null, "e": 14365, "s": 14241, "text": "TCN and Ensemble CNN-GRU models are the best performing algorithms we obtained in this series of text classification tasks." }, { "code": null, "e": 14430, "s": 14365, "text": "We recommend some suggestions for future experiments as follows:" }, { "code": null, "e": 14644, "s": 14430, "text": "An ensemble-based model with TCN. Perform text classification tasks using TCN combined with other good models such as 1D CNN and BiGRU in ensemble-based learning to see if it can challenge the benchmarks even more" }, { "code": null, "e": 14835, "s": 14644, "text": "Kernel size and filters. Explore these two hyperparameters by extending the kernel sizes between 1 to 10 with more or fewer filters in CNN or TCN to see how it affects the model performance." }, { "code": null, "e": 15028, "s": 14835, "text": "Deeper network. Any neural network with more hidden layers typically will do better in any task. Explore the deeper version of CNN, RNN, and TCN to see how it affects the existing performance." }, { "code": null, "e": 15194, "s": 15028, "text": "Use GloVe and FastText. Explore other pre-trained word embedding options such as GloVe and FastText with static and dynamic modes and compare the result to Word2Vec." }, { "code": null, "e": 15205, "s": 15194, "text": "Thank you," }, { "code": null, "e": 15237, "s": 15205, "text": "Diardano RaihanLinkedIn Profile" }, { "code": null, "e": 15380, "s": 15237, "text": "Note: Everything you have seen is documented in my GitHub repository. For those who are curious about the full code, please do have a visit 👍." }, { "code": null, "e": 15540, "s": 15380, "text": "[1] B. Pang, L. Lee, “Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales”, In Proceedings of ACL’05, 2005." }, { "code": null, "e": 15763, "s": 15540, "text": "[2] B. Pang, L. Lee, “A sentimental education: Sentiment analysis using subjectivity summarization based on minimum cuts”, In Proceedings of the 42nd Meeting of the Association for Computational Linguistics (ACL’04), 2004." }, { "code": null, "e": 15852, "s": 15763, "text": "[3] X. Li, D. Roth, “Learning question classifiers”, In Proceedings of COLING ’02, 2002." }, { "code": null, "e": 15947, "s": 15852, "text": "[4] M. Hu, B. Liu, “Mining and summarizing customer reviews”, In Proceedings of KDD ’04, 2004." }, { "code": null, "e": 16106, "s": 15947, "text": "[5] J. Wiebe, T. Wilson, and C. Cardie, “Annotating expressions of opinions and emotions in language”, Language Resources and Evaluation, 39(2):165–210, 2005." }, { "code": null, "e": 16261, "s": 16106, "text": "[6] S. bai, J. Kolter, and V. Koltun, “An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling”, arXiv, April, 2018." }, { "code": null, "e": 16353, "s": 16261, "text": "[7] P. Rémy, “Keras TCN”, GitHub https://github.com/philipperemy/keras-tcn, January. 2021." }, { "code": null, "e": 16496, "s": 16353, "text": "[8] C. Henkel, “Temporal Convolutional Network”, Kaggle, https://www.kaggle.com/christofhenkel/temporal-convolutional-network, February, 2021." }, { "code": null, "e": 16649, "s": 16496, "text": "[9] K. Kowsari, M. Heidarysafa, D. E. Brown, K. J. Meimandi, and L. E. Barnes, “Random Multimodel Deep Learning for Classification”, arXiv, April, 2018." }, { "code": null, "e": 16781, "s": 16649, "text": "[10] Y. Kim, “Convolutional Neural Networks for Sentence Classification,” Association for Computational Linguistics, October, 2014." }, { "code": null, "e": 16883, "s": 16781, "text": "[11] S. Brahma, “Improved Sentence Modeling using Suffix Bidirectional LSTM”, arXiv, September, 2018." } ]
How to create a directory in project folder using Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. The mkdir() method of this class creates a directory with the path represented by the current object. Therefore, to create a directory − Instantiate the File class by passing the path of the directory you need to create, as a parameter (String). Instantiate the File class by passing the path of the directory you need to create, as a parameter (String). Invoke the mkdir() method using the above-created file object. Invoke the mkdir() method using the above-created file object. The following Java example reads the path and name of the directory to be created, from the user, and creates it. Live Demo import java.io.File; import java.util.Scanner; public class CreateDirectory { public static void main(String args[]) { System.out.println("Enter the path to create a directory: "); Scanner sc = new Scanner(System.in); String path = sc.next(); System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Creating a File object File file = new File(path); //Creating the directory boolean bool = file.mkdir(); if(bool){ System.out.println("Directory created successfully"); } else { System.out.println("Sorry couldn’t create specified directory"); } } } Enter the path to create a directory: D:\ Enter the name of the desired a directory: sample_directory Directory created successfully If you verify, you can observe see the created directory as − But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory. For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as − D:\test\myDirectories\sample_directory Where the test and myDirectories folders don’t exist, the mkdir() method will not create it.
[ { "code": null, "e": 1253, "s": 1062, "text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories." }, { "code": null, "e": 1355, "s": 1253, "text": "The mkdir() method of this class creates a directory with the path represented by the current object." }, { "code": null, "e": 1390, "s": 1355, "text": "Therefore, to create a directory −" }, { "code": null, "e": 1499, "s": 1390, "text": "Instantiate the File class by passing the path of the directory you need to create, as a parameter (String)." }, { "code": null, "e": 1608, "s": 1499, "text": "Instantiate the File class by passing the path of the directory you need to create, as a parameter (String)." }, { "code": null, "e": 1671, "s": 1608, "text": "Invoke the mkdir() method using the above-created file object." }, { "code": null, "e": 1734, "s": 1671, "text": "Invoke the mkdir() method using the above-created file object." }, { "code": null, "e": 1848, "s": 1734, "text": "The following Java example reads the path and name of the directory to be created, from the user, and creates it." }, { "code": null, "e": 1859, "s": 1848, "text": " Live Demo" }, { "code": null, "e": 2539, "s": 1859, "text": "import java.io.File;\nimport java.util.Scanner;\npublic class CreateDirectory {\n public static void main(String args[]) {\n System.out.println(\"Enter the path to create a directory: \");\n Scanner sc = new Scanner(System.in);\n String path = sc.next();\n System.out.println(\"Enter the name of the desired a directory: \");\n path = path+sc.next();\n //Creating a File object\n File file = new File(path);\n //Creating the directory\n boolean bool = file.mkdir();\n if(bool){\n System.out.println(\"Directory created successfully\");\n } else {\n System.out.println(\"Sorry couldn’t create specified directory\");\n }\n }\n}" }, { "code": null, "e": 2672, "s": 2539, "text": "Enter the path to create a directory:\nD:\\\nEnter the name of the desired a directory:\nsample_directory\nDirectory created successfully" }, { "code": null, "e": 2734, "s": 2672, "text": "If you verify, you can observe see the created directory as −" }, { "code": null, "e": 2844, "s": 2734, "text": "But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory." }, { "code": null, "e": 2966, "s": 2844, "text": "For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −" }, { "code": null, "e": 3005, "s": 2966, "text": "D:\\test\\myDirectories\\sample_directory" }, { "code": null, "e": 3098, "s": 3005, "text": "Where the test and myDirectories folders don’t exist, the mkdir() method will not create it." } ]
Calculating the LCM of multiple numbers in JavaScript
We are required to write a JavaScript function that takes in an array of numbers of any length and returns their LCM. We will approach this problem in parts − Part 1 − We will create a helper function to calculate the Greatest Common Divisor (GCD) of two numbers Part 2 − Then using Part 1 helper function we will create another helper function to calculate the Least Common Multiple (LCM) of two numbers. Part 3 − Finally, using Part 2 helper function we will create a function that loops over the array and calculates the array LCM. The code for this will be − const calculateLCM = (...arr) => { const gcd2 = (a, b) => { // Greatest common divisor of 2 integers if(!b) return b===0 ? a : NaN; return gcd2(b, a%b); }; const lcm2 = (a, b) => { // Least common multiple of 2 integers return a * b / gcd2(a, b); } // Least common multiple of a list of integers let n = 1; for(let i = 0; i < arr.length; ++i){ n = lcm2(arr[i], n); } return n; }; console.log(calculateLCM(12, 18, 7, 15, 20, 24, 28)); And the output in the console will be − 2520
[ { "code": null, "e": 1180, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of numbers of any length and returns their LCM." }, { "code": null, "e": 1221, "s": 1180, "text": "We will approach this problem in parts −" }, { "code": null, "e": 1325, "s": 1221, "text": "Part 1 − We will create a helper function to calculate the Greatest Common Divisor (GCD) of two numbers" }, { "code": null, "e": 1468, "s": 1325, "text": "Part 2 − Then using Part 1 helper function we will create another helper function to calculate the Least Common Multiple (LCM) of two numbers." }, { "code": null, "e": 1597, "s": 1468, "text": "Part 3 − Finally, using Part 2 helper function we will create a function that loops over the array and calculates the array LCM." }, { "code": null, "e": 1625, "s": 1597, "text": "The code for this will be −" }, { "code": null, "e": 2125, "s": 1625, "text": "const calculateLCM = (...arr) => {\n const gcd2 = (a, b) => {\n // Greatest common divisor of 2 integers\n if(!b) return b===0 ? a : NaN;\n return gcd2(b, a%b);\n };\n const lcm2 = (a, b) => {\n // Least common multiple of 2 integers\n return a * b / gcd2(a, b);\n }\n // Least common multiple of a list of integers\n let n = 1;\n for(let i = 0; i < arr.length; ++i){\n n = lcm2(arr[i], n);\n }\n return n;\n};\nconsole.log(calculateLCM(12, 18, 7, 15, 20, 24, 28));" }, { "code": null, "e": 2165, "s": 2125, "text": "And the output in the console will be −" }, { "code": null, "e": 2170, "s": 2165, "text": "2520" } ]
Passing Multiple ids to single parameter in MySQL?
To pass multiple ids to single parameter, use FIND_IN_SET(). Let us first create a table − mysql> create table DemoTable1817 ( EmployeeName varchar(20), CountryName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1817 values('Chris','AUS'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1817 values('David','UK'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1817 values('Bob','US'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1817; This will produce the following output − +--------------+-------------+ | EmployeeName | CountryName | +--------------+-------------+ | Chris | AUS| | David | UK | | Bob | US | +--------------+-------------+ 3 rows in set (0.00 sec) Here is the query to pass multiple ids to single parameter in MySQL. mysql> select * from DemoTable1817 where find_in_set(CountryName,'US,UK'); This will produce the following output − +--------------+-------------+ | EmployeeName | CountryName | +--------------+-------------+ | David | UK | | Bob | US | +--------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "To pass multiple ids to single parameter, use FIND_IN_SET(). Let us first create a table −" }, { "code": null, "e": 1300, "s": 1153, "text": "mysql> create table DemoTable1817\n (\n EmployeeName varchar(20),\n CountryName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1356, "s": 1300, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1628, "s": 1356, "text": "mysql> insert into DemoTable1817 values('Chris','AUS');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1817 values('David','UK');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1817 values('Bob','US');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1688, "s": 1628, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1724, "s": 1688, "text": "mysql> select * from DemoTable1817;" }, { "code": null, "e": 1765, "s": 1724, "text": "This will produce the following output −" }, { "code": null, "e": 2007, "s": 1765, "text": "+--------------+-------------+\n| EmployeeName | CountryName |\n+--------------+-------------+\n| Chris | AUS|\n| David | UK |\n| Bob | US |\n+--------------+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2076, "s": 2007, "text": "Here is the query to pass multiple ids to single parameter in MySQL." }, { "code": null, "e": 2156, "s": 2076, "text": "mysql> select * from DemoTable1817\n where find_in_set(CountryName,'US,UK');" }, { "code": null, "e": 2197, "s": 2156, "text": "This will produce the following output −" }, { "code": null, "e": 2408, "s": 2197, "text": "+--------------+-------------+\n| EmployeeName | CountryName |\n+--------------+-------------+\n| David | UK |\n| Bob | US |\n+--------------+-------------+\n2 rows in set (0.00 sec)" } ]
OpenCV - Drawing a Line
You can draw a line on an image using the method line() of the imgproc class. Following is the syntax of this method. line(img, pt1, pt2, color, thickness) This method accepts the following parameters − mat − A Mat object representing the image on which the line is to be drawn. mat − A Mat object representing the image on which the line is to be drawn. pt1 and pt2 − Two Point objects representing the points between which the line is to be drawn. pt1 and pt2 − Two Point objects representing the points between which the line is to be drawn. scalar − A Scalar object representing the color of the circle. (BGR) scalar − A Scalar object representing the color of the circle. (BGR) thickness − An integer representing the thickness of the line; by default, the value of thickness is 1. thickness − An integer representing the thickness of the line; by default, the value of thickness is 1. The following program demonstrates how to draw a line on an image and display it using JavaFX window. import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; 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.MatOfByte; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class DrawingLine extends Application { Mat matrix = null; @Override public void start(Stage stage) throws Exception { // Capturing the snapshot from the camera DrawingLine obj = new DrawingLine(); WritableImage writableImage = obj.LoadImage(); // Setting the image view ImageView imageView = new ImageView(writableImage); // setting the fit height and width of the image view imageView.setFitHeight(600); imageView.setFitWidth(600); // Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // Creating a Group object Group root = new Group(imageView); // Creating a scene object Scene scene = new Scene(root, 600, 400); // Setting title to the Stage stage.setTitle("Drawing a line on the image"); // Adding scene to the stage stage.setScene(scene); // Displaying the contents of the stage stage.show(); } public WritableImage LoadImage() throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap8/input.jpg"; Mat matrix = Imgcodecs.imread(file); // Drawing a line Imgproc.line ( matrix, //Matrix obj of the image new Point(10, 200), //p1 new Point(300, 200), //p2 new Scalar(0, 0, 255), //Scalar object for color 5 //Thickness of the line ); // Encoding the image MatOfByte matOfByte = new MatOfByte(); Imgcodecs.imencode(".jpg", matrix, matOfByte); // Storing the encoded Mat in a byte array byte[] byteArray = matOfByte.toArray(); // Displaying the image InputStream in = new ByteArrayInputStream(byteArray); BufferedImage bufImage = ImageIO.read(in); this.matrix = matrix; // Creating the Writable Image WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null); return writableImage; } public static void main(String args[]) { launch(args); } } On executing the above program, you will get the following output − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3122, "s": 3004, "text": "You can draw a line on an image using the method line() of the imgproc class. Following is the syntax of this method." }, { "code": null, "e": 3161, "s": 3122, "text": "line(img, pt1, pt2, color, thickness)\n" }, { "code": null, "e": 3208, "s": 3161, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3284, "s": 3208, "text": "mat − A Mat object representing the image on which the line is to be drawn." }, { "code": null, "e": 3360, "s": 3284, "text": "mat − A Mat object representing the image on which the line is to be drawn." }, { "code": null, "e": 3455, "s": 3360, "text": "pt1 and pt2 − Two Point objects representing the points between which the line is to be drawn." }, { "code": null, "e": 3550, "s": 3455, "text": "pt1 and pt2 − Two Point objects representing the points between which the line is to be drawn." }, { "code": null, "e": 3619, "s": 3550, "text": "scalar − A Scalar object representing the color of the circle. (BGR)" }, { "code": null, "e": 3688, "s": 3619, "text": "scalar − A Scalar object representing the color of the circle. (BGR)" }, { "code": null, "e": 3792, "s": 3688, "text": "thickness − An integer representing the thickness of the line; by default, the value of thickness is 1." }, { "code": null, "e": 3896, "s": 3792, "text": "thickness − An integer representing the thickness of the line; by default, the value of thickness is 1." }, { "code": null, "e": 3998, "s": 3896, "text": "The following program demonstrates how to draw a line on an image and display it using JavaFX window." }, { "code": null, "e": 6833, "s": 3998, "text": "import java.awt.image.BufferedImage;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport javax.imageio.ImageIO;\n\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;\n\nimport org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfByte;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class DrawingLine extends Application {\n Mat matrix = null;\n\n @Override\n public void start(Stage stage) throws Exception {\n \n // Capturing the snapshot from the camera\n DrawingLine obj = new DrawingLine();\n WritableImage writableImage = obj.LoadImage();\n\n // Setting the image view\n ImageView imageView = new ImageView(writableImage);\n\n // setting the fit height and width of the image view\n imageView.setFitHeight(600);\n imageView.setFitWidth(600);\n\n // Setting the preserve ratio of the image view\n imageView.setPreserveRatio(true);\n\n // Creating a Group object \n Group root = new Group(imageView);\n\n // Creating a scene object\n Scene scene = new Scene(root, 600, 400);\n\n // Setting title to the Stage\n stage.setTitle(\"Drawing a line on the image\");\n\n // Adding scene to the stage\n stage.setScene(scene);\n\n // Displaying the contents of the stage\n stage.show();\n }\n public WritableImage LoadImage() throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap8/input.jpg\";\n Mat matrix = Imgcodecs.imread(file);\n\n // Drawing a line\n Imgproc.line (\n matrix, //Matrix obj of the image\n new Point(10, 200), //p1\n new Point(300, 200), //p2\n new Scalar(0, 0, 255), //Scalar object for color\n 5 //Thickness of the line\n );\n // Encoding the image\n MatOfByte matOfByte = new MatOfByte();\n Imgcodecs.imencode(\".jpg\", matrix, matOfByte);\n\n // Storing the encoded Mat in a byte array\n byte[] byteArray = matOfByte.toArray();\n\n // Displaying the image\n InputStream in = new ByteArrayInputStream(byteArray);\n BufferedImage bufImage = ImageIO.read(in);\n\n this.matrix = matrix;\n\n // Creating the Writable Image\n WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);\n return writableImage;\n }\n public static void main(String args[]) {\n launch(args);\n }\n}" }, { "code": null, "e": 6901, "s": 6833, "text": "On executing the above program, you will get the following output −" }, { "code": null, "e": 6934, "s": 6901, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 6951, "s": 6934, "text": " Abhilash Nelson" }, { "code": null, "e": 6984, "s": 6951, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7001, "s": 6984, "text": " Abhilash Nelson" }, { "code": null, "e": 7034, "s": 7001, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7048, "s": 7034, "text": " Spotle Learn" }, { "code": null, "e": 7080, "s": 7048, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7097, "s": 7080, "text": " Srikanth Guskra" }, { "code": null, "e": 7130, "s": 7097, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7145, "s": 7130, "text": " Haithem Gasmi" }, { "code": null, "e": 7180, "s": 7145, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7198, "s": 7180, "text": " Gianluca Mottola" }, { "code": null, "e": 7205, "s": 7198, "text": " Print" }, { "code": null, "e": 7216, "s": 7205, "text": " Add Notes" } ]
How to change JFrame background color in Java
At first, create a JFrame − JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(550, 300)); Now, change the background color of the JFrame − frame.getContentPane().setBackground(Color.BLUE); The following is an example to change JFrame background color − import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(550, 300)); frame.getContentPane().setBackground(Color.BLUE); frame.pack(); frame.setVisible(true); } }
[ { "code": null, "e": 1090, "s": 1062, "text": "At first, create a JFrame −" }, { "code": null, "e": 1222, "s": 1090, "text": "JFrame frame = new JFrame();\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\nframe.setPreferredSize(new Dimension(550, 300));" }, { "code": null, "e": 1271, "s": 1222, "text": "Now, change the background color of the JFrame −" }, { "code": null, "e": 1321, "s": 1271, "text": "frame.getContentPane().setBackground(Color.BLUE);" }, { "code": null, "e": 1385, "s": 1321, "text": "The following is an example to change JFrame background color −" }, { "code": null, "e": 1794, "s": 1385, "text": "import java.awt.Color;\nimport java.awt.Dimension;\nimport javax.swing.JFrame;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setPreferredSize(new Dimension(550, 300));\n frame.getContentPane().setBackground(Color.BLUE);\n frame.pack();\n frame.setVisible(true);\n }\n}" } ]
Isolation Forest and Pyspark part 2 | by Maria Karanasou | Towards Data Science
So, after a few runs with the PySpark ml implementation of Isolation Forest presented here, I stumbled upon a couple of things and I thought I’d write about them so that you don’t waste the time I wasted troubleshooting. In the previous article, I used VectorAssembler to gather the feature vectors. It so happened that the test data I had, created only DenseVectors, but when I tried the example on a different dataset, I realized that: VectorAssembler can create both Dense and Sparse vectors in the same dataframe (which is smart and other spark ml argorithms can leverage it and work with it) Isolation Forest (or at least the implementation found here ) does not support the above, so the input must be DenseVectors only. To demonstrate the issue: The current workaround is to transform all vectors to dense, using a udf unfortunately. Set the approxQuantileRelativeError or the threshold parameter for large datasets If you are planning on training on a big dataset, e.g. more than 10M rows, even if you set parameters like maxSamples and maxFeatures to decrease the dimensions, you need to set the approxQuantileRelativeError parameter to something reasonable, e.g. 0.2. The reason is that the approxQuantile function is a very expensive function to use, especially if we expect the approxQuantileRelativeError to be 0. (which is the default value). Doing this, drastically cut the training time and the OOM and executor communication issues, and, up to now, I haven’t seen any decline in prediction accuracy. From the comments of the implementation: * The proportion of outliers in the data set (0< contamination < 1).* It will be used in the prediction. In order to enhance performance,* Our method to get anomaly score threshold adopts DataFrameStsFunctions.approxQuantile,* which is designed for performance with some extent accuracy loss.* Set the param approxQuantileRelativeError (0 < e < 1) to calculate* an approximate quantile threshold of anomaly scores for large dataset. Alternatively, set the threshold beforehand in fit and avoid the approxQuantile calculation like this: model = iforest.fit(df, {'threshold': 0.5})print(model.getThreshold())> 0.49272560194039505 Hope this helps and saves you some time :) Let me know if you have any suggestions, corrections or ideas. towardsdatascience.com Understanding your model’s predictions:
[ { "code": null, "e": 393, "s": 172, "text": "So, after a few runs with the PySpark ml implementation of Isolation Forest presented here, I stumbled upon a couple of things and I thought I’d write about them so that you don’t waste the time I wasted troubleshooting." }, { "code": null, "e": 610, "s": 393, "text": "In the previous article, I used VectorAssembler to gather the feature vectors. It so happened that the test data I had, created only DenseVectors, but when I tried the example on a different dataset, I realized that:" }, { "code": null, "e": 769, "s": 610, "text": "VectorAssembler can create both Dense and Sparse vectors in the same dataframe (which is smart and other spark ml argorithms can leverage it and work with it)" }, { "code": null, "e": 899, "s": 769, "text": "Isolation Forest (or at least the implementation found here ) does not support the above, so the input must be DenseVectors only." }, { "code": null, "e": 925, "s": 899, "text": "To demonstrate the issue:" }, { "code": null, "e": 1013, "s": 925, "text": "The current workaround is to transform all vectors to dense, using a udf unfortunately." }, { "code": null, "e": 1095, "s": 1013, "text": "Set the approxQuantileRelativeError or the threshold parameter for large datasets" }, { "code": null, "e": 1689, "s": 1095, "text": "If you are planning on training on a big dataset, e.g. more than 10M rows, even if you set parameters like maxSamples and maxFeatures to decrease the dimensions, you need to set the approxQuantileRelativeError parameter to something reasonable, e.g. 0.2. The reason is that the approxQuantile function is a very expensive function to use, especially if we expect the approxQuantileRelativeError to be 0. (which is the default value). Doing this, drastically cut the training time and the OOM and executor communication issues, and, up to now, I haven’t seen any decline in prediction accuracy." }, { "code": null, "e": 1730, "s": 1689, "text": "From the comments of the implementation:" }, { "code": null, "e": 2163, "s": 1730, "text": "* The proportion of outliers in the data set (0< contamination < 1).* It will be used in the prediction. In order to enhance performance,* Our method to get anomaly score threshold adopts DataFrameStsFunctions.approxQuantile,* which is designed for performance with some extent accuracy loss.* Set the param approxQuantileRelativeError (0 < e < 1) to calculate* an approximate quantile threshold of anomaly scores for large dataset." }, { "code": null, "e": 2266, "s": 2163, "text": "Alternatively, set the threshold beforehand in fit and avoid the approxQuantile calculation like this:" }, { "code": null, "e": 2358, "s": 2266, "text": "model = iforest.fit(df, {'threshold': 0.5})print(model.getThreshold())> 0.49272560194039505" }, { "code": null, "e": 2464, "s": 2358, "text": "Hope this helps and saves you some time :) Let me know if you have any suggestions, corrections or ideas." }, { "code": null, "e": 2487, "s": 2464, "text": "towardsdatascience.com" } ]
Program to calculate the value of nCr Efficiently
22 Mar, 2021 Given two numbers n, r ( n>=r ). The task is to find the value of C(n, r) for big value of n. Examples: Input: n = 30, r = 15 Output: 155117520 C(30, 15) is 155117520 by 30!/((30-15)!*15!) Input: n = 50, r = 25 Output: 126410606437752 Approach: A simple code can be created with the following knowledge that : C(n, r) = [n * (n-1) * .... * (n-r+1)] / [r * (r-1) * .... * 1] However, for big values of n, r the products may overflow, hence during each iteration we divide the current variables holding value of products by their gcd. Below is the required implementation: C++ Java Python3 C# PHP Javascript // C++ implementation to find nCr#include <bits/stdc++.h>using namespace std; // Function to find the nCrvoid printNcR(int n, int r){ // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; // gcd of p, k long long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else p = 1; // if our approach is correct p = ans and k =1 cout << p << endl;} // Driver codeint main(){ int n = 50, r = 25; printNcR(n, r); return 0;} // Java implementation to find nCr class GFG { // Function to find the nCr static void printNcR(int n, int r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; // gcd of p, k long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { p = 1; } // if our approach is correct p = ans and k =1 System.out.println(p); } static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } // Driver code public static void main(String[] args) { int n = 50, r = 25; printNcR(n, r); }} # Python3 implementation to find nCr from math import * # Function to find the nCr def printNcR(n, r): # p holds the value of n*(n-1)*(n-2)..., # k holds the value of r*(r-1)... p = 1 k = 1 # C(n, r) == C(n, n-r), # choosing the smaller value if (n - r < r): r = n - r if (r != 0): while (r): p *= n k *= r # gcd of p, k m = gcd(p, k) # dividing by gcd, to simplify product # division by their gcd saves from # the overflow p //= m k //= m n -= 1 r -= 1 # k should be simplified to 1 # as C(n, r) is a natural number # (denominator should be 1 ) else: p = 1 # if our approach is correct p = ans and k =1 print(p) # Driver codeif __name__ == "__main__": n = 50 r = 25 printNcR(n, r) # this code is contributed by# ChitraNayal // C# implementation to find nCr using System; public class GFG { // Function to find the nCr static void printNcR(int n, int r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; // gcd of p, k long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { p = 1; } // if our approach is correct p = ans and k =1 Console.WriteLine(p); } static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } // Driver code static public void Main() { int n = 50, r = 25; printNcR(n, r); } // This code is contributed by ajit.} <?php// PHP implementation to find nCr // Function to find the nCrfunction printNcR($n, $r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... $p = 1; $k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if ($n - $r < $r) { $r = $n - $r; } if ($r != 0) { while ($r > 0) { $p *= $n; $k *= $r; // gcd of p, k $m = __gcd($p, $k); // dividing by gcd, to simplify product // division by their gcd saves from the overflow $p /= $m; $k /= $m; $n--; $r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { $p = 1; } // if our approach is correct p = ans and k =1 echo ($p); } function __gcd($n1, $n2) { $gcd = 1; for ($i = 1; $i <= $n1 && $i <= $n2; ++$i) { // Checks if i is factor of both integers if ($n1 % $i == 0 && $n2 % $i == 0) { $gcd = $i; } } return $gcd; } // Driver code $n = 50; $r = 25; printNcR($n, $r); //This code is contributed by Sachin. ?> <script> // Javascript implementation to find nCr function __gcd(n1, n2){ var gcd = 1; for (var i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd;} // Function to find the nCrfunction printNcR(n, r){ // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... var p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; // gcd of p, k var m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else p = 1; // if our approach is correct p = ans and k =1 document.write(p);} // Driver codevar n = 50, r = 25;printNcR(n, r); </script> 126410606437752 Time Complexity: O( R Log N) Auxiliary Space: O(1) ukasp 29AjayKumar jit_t Sach_Code ujjwalgoel1103 rutvik_56 GCD-LCM Permutation and Combination Technical Scripter 2018 Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Find the K-th Permutation Sequence of first N natural numbers Count Derangements (Permutation such that no element appears in its original position) Print all possible strings of length k that can be formed from a set of n characters Permutations of a given string using STL Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Mar, 2021" }, { "code": null, "e": 148, "s": 54, "text": "Given two numbers n, r ( n>=r ). The task is to find the value of C(n, r) for big value of n." }, { "code": null, "e": 159, "s": 148, "text": "Examples: " }, { "code": null, "e": 293, "s": 159, "text": "Input: n = 30, r = 15\nOutput: 155117520\nC(30, 15) is 155117520 by 30!/((30-15)!*15!)\n\n\nInput: n = 50, r = 25\nOutput: 126410606437752" }, { "code": null, "e": 369, "s": 293, "text": "Approach: A simple code can be created with the following knowledge that : " }, { "code": null, "e": 433, "s": 369, "text": "C(n, r) = [n * (n-1) * .... * (n-r+1)] / [r * (r-1) * .... * 1]" }, { "code": null, "e": 593, "s": 433, "text": "However, for big values of n, r the products may overflow, hence during each iteration we divide the current variables holding value of products by their gcd. " }, { "code": null, "e": 632, "s": 593, "text": "Below is the required implementation: " }, { "code": null, "e": 636, "s": 632, "text": "C++" }, { "code": null, "e": 641, "s": 636, "text": "Java" }, { "code": null, "e": 649, "s": 641, "text": "Python3" }, { "code": null, "e": 652, "s": 649, "text": "C#" }, { "code": null, "e": 656, "s": 652, "text": "PHP" }, { "code": null, "e": 667, "s": 656, "text": "Javascript" }, { "code": "// C++ implementation to find nCr#include <bits/stdc++.h>using namespace std; // Function to find the nCrvoid printNcR(int n, int r){ // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; // gcd of p, k long long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else p = 1; // if our approach is correct p = ans and k =1 cout << p << endl;} // Driver codeint main(){ int n = 50, r = 25; printNcR(n, r); return 0;}", "e": 1661, "s": 667, "text": null }, { "code": "// Java implementation to find nCr class GFG { // Function to find the nCr static void printNcR(int n, int r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; // gcd of p, k long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { p = 1; } // if our approach is correct p = ans and k =1 System.out.println(p); } static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } // Driver code public static void main(String[] args) { int n = 50, r = 25; printNcR(n, r); }}", "e": 3106, "s": 1661, "text": null }, { "code": "# Python3 implementation to find nCr from math import * # Function to find the nCr def printNcR(n, r): # p holds the value of n*(n-1)*(n-2)..., # k holds the value of r*(r-1)... p = 1 k = 1 # C(n, r) == C(n, n-r), # choosing the smaller value if (n - r < r): r = n - r if (r != 0): while (r): p *= n k *= r # gcd of p, k m = gcd(p, k) # dividing by gcd, to simplify product # division by their gcd saves from # the overflow p //= m k //= m n -= 1 r -= 1 # k should be simplified to 1 # as C(n, r) is a natural number # (denominator should be 1 ) else: p = 1 # if our approach is correct p = ans and k =1 print(p) # Driver codeif __name__ == \"__main__\": n = 50 r = 25 printNcR(n, r) # this code is contributed by# ChitraNayal", "e": 4048, "s": 3106, "text": null }, { "code": "// C# implementation to find nCr using System; public class GFG { // Function to find the nCr static void printNcR(int n, int r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... long p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; // gcd of p, k long m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { p = 1; } // if our approach is correct p = ans and k =1 Console.WriteLine(p); } static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } // Driver code static public void Main() { int n = 50, r = 25; printNcR(n, r); } // This code is contributed by ajit.}", "e": 5537, "s": 4048, "text": null }, { "code": "<?php// PHP implementation to find nCr // Function to find the nCrfunction printNcR($n, $r) { // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... $p = 1; $k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if ($n - $r < $r) { $r = $n - $r; } if ($r != 0) { while ($r > 0) { $p *= $n; $k *= $r; // gcd of p, k $m = __gcd($p, $k); // dividing by gcd, to simplify product // division by their gcd saves from the overflow $p /= $m; $k /= $m; $n--; $r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else { $p = 1; } // if our approach is correct p = ans and k =1 echo ($p); } function __gcd($n1, $n2) { $gcd = 1; for ($i = 1; $i <= $n1 && $i <= $n2; ++$i) { // Checks if i is factor of both integers if ($n1 % $i == 0 && $n2 % $i == 0) { $gcd = $i; } } return $gcd; } // Driver code $n = 50; $r = 25; printNcR($n, $r); //This code is contributed by Sachin. ?>", "e": 6934, "s": 5537, "text": null }, { "code": "<script> // Javascript implementation to find nCr function __gcd(n1, n2){ var gcd = 1; for (var i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd;} // Function to find the nCrfunction printNcR(n, r){ // p holds the value of n*(n-1)*(n-2)..., // k holds the value of r*(r-1)... var p = 1, k = 1; // C(n, r) == C(n, n-r), // choosing the smaller value if (n - r < r) r = n - r; if (r != 0) { while (r) { p *= n; k *= r; // gcd of p, k var m = __gcd(p, k); // dividing by gcd, to simplify // product division by their gcd // saves from the overflow p /= m; k /= m; n--; r--; } // k should be simplified to 1 // as C(n, r) is a natural number // (denominator should be 1 ) . } else p = 1; // if our approach is correct p = ans and k =1 document.write(p);} // Driver codevar n = 50, r = 25;printNcR(n, r); </script>", "e": 8086, "s": 6934, "text": null }, { "code": null, "e": 8102, "s": 8086, "text": "126410606437752" }, { "code": null, "e": 8153, "s": 8102, "text": "Time Complexity: O( R Log N) Auxiliary Space: O(1)" }, { "code": null, "e": 8159, "s": 8153, "text": "ukasp" }, { "code": null, "e": 8171, "s": 8159, "text": "29AjayKumar" }, { "code": null, "e": 8177, "s": 8171, "text": "jit_t" }, { "code": null, "e": 8187, "s": 8177, "text": "Sach_Code" }, { "code": null, "e": 8202, "s": 8187, "text": "ujjwalgoel1103" }, { "code": null, "e": 8212, "s": 8202, "text": "rutvik_56" }, { "code": null, "e": 8220, "s": 8212, "text": "GCD-LCM" }, { "code": null, "e": 8248, "s": 8220, "text": "Permutation and Combination" }, { "code": null, "e": 8272, "s": 8248, "text": "Technical Scripter 2018" }, { "code": null, "e": 8286, "s": 8272, "text": "Combinatorial" }, { "code": null, "e": 8299, "s": 8286, "text": "Mathematical" }, { "code": null, "e": 8312, "s": 8299, "text": "Mathematical" }, { "code": null, "e": 8326, "s": 8312, "text": "Combinatorial" }, { "code": null, "e": 8424, "s": 8326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8461, "s": 8424, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 8523, "s": 8461, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 8610, "s": 8523, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 8695, "s": 8610, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 8736, "s": 8695, "text": "Permutations of a given string using STL" }, { "code": null, "e": 8779, "s": 8736, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8794, "s": 8779, "text": "C++ Data Types" }, { "code": null, "e": 8818, "s": 8794, "text": "Merge two sorted arrays" }, { "code": null, "e": 8839, "s": 8818, "text": "Operators in C / C++" } ]
Quantifiers in Java
06 Dec, 2021 Prerequisite: Regular Expressions in Java Quantifiers in Java allow users to specify the number of occurrences to match against. Below are some commonly used quantifiers in Java. X* Zero or more occurrences of X X? Zero or One occurrences of X X+ One or More occurrences of X X{n} Exactly n occurrences of X X{n, } At-least n occurrences of X X{n, m} Count of occurrences of X is from n to m The above quantifiers can be made Greedy, Reluctant, and Possessive. By default, quantifiers are Greedy. Greedy quantifiers try to match the longest text that matches a given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the whole text doesn’t match, remove the last character and try again, repeating the process until a match is found. Java // Java program to demonstrate Greedy Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // By default quantifier "+" is Greedy Pattern p = Pattern.compile("g+"); // Making an instance of Matcher class Matcher m = p.matcher("ggg"); while (m.find()) System.out.println("Pattern found from " + m.start() + " to " + (m.end()-1)); }} Pattern found from 0 to 2 Explanation: The pattern g+ means one or more occurrences of g. Text is ggg. The greedy matcher would match the longest text even if parts of the matching text also match. In this example, g and gg also match, but the greedy matcher produces ggg. This quantifier uses the approach that is the opposite of greedy quantifiers. It starts with the first character and processes one character at a time. Java // Java program to demonstrate Reluctant Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // Here "+" is a Reluctant quantifier because // a "?' is appended after it. Pattern p = Pattern.compile("g+?"); // Making an instance of Matcher class Matcher m = p.matcher("ggg"); while (m.find()) System.out.println("Pattern found from " + m.start() + " to " + (m.end()-1)); }} Pattern found from 0 to 0 Pattern found from 1 to 1 Pattern found from 2 to 2 Explanation: Since the quantifier is reluctant, it matches the shortest part of the test with the pattern. It processes one character at a time. This quantifier matches as many characters as possible, like a greedy quantifier. But if the entire string doesn’t match, then it doesn’t try removing characters from the end. Java // Java program to demonstrate Possessive Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // Here "+" is a Possessive quantifier because // a "+' is appended after it. Pattern p = Pattern.compile("g++"); // Making an instance of Matcher class Matcher m = p.matcher("ggg"); while (m.find()) System.out.println("Pattern found from " + m.start() + " to " + (m.end()-1)); }} Pattern found from 0 to 2 Explanation: We get the same output as Greedy because the whole text matches the pattern. Java // Java program to demonstrate difference// between Possessive and Greedy Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Create a pattern with Greedy quantifier Pattern pg = Pattern.compile("g+g"); // Create same pattern with possessive quantifier Pattern pp = Pattern.compile("g++g"); System.out.println("Using Greedy Quantifier"); Matcher mg = pg.matcher("ggg"); while (mg.find()) System.out.println("Pattern found from " + mg.start() + " to " + (mg.end()-1)); System.out.println("\nUsing Possessive Quantifier"); Matcher mp = pp.matcher("ggg"); while (mp.find()) System.out.println("Pattern found from " + mp.start() + " to " + (mp.end()-1)); }} Using Greedy Quantifier Pattern found from 0 to 2 Using Possessive Quantifier In the above example, since the first quantifier is greedy, g+ matches the whole string. If we match g+ with whole string, g+g doesn’t match, the Greedy quantifier removes the last character, matches gg with g+, and finds a match. In the Possessive quantifier, we start like Greedy. g+ matches the whole string, but matching g+ with the whole string doesn’t match g+g with ggg. Unlike Greedy, since quantifier is possessive, we stop at this point. This article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nishkarshgandhi java-regular-expression Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2021" }, { "code": null, "e": 94, "s": 52, "text": "Prerequisite: Regular Expressions in Java" }, { "code": null, "e": 231, "s": 94, "text": "Quantifiers in Java allow users to specify the number of occurrences to match against. Below are some commonly used quantifiers in Java." }, { "code": null, "e": 476, "s": 231, "text": "X* Zero or more occurrences of X\nX? Zero or One occurrences of X\nX+ One or More occurrences of X\nX{n} Exactly n occurrences of X \nX{n, } At-least n occurrences of X\nX{n, m} Count of occurrences of X is from n to m" }, { "code": null, "e": 545, "s": 476, "text": "The above quantifiers can be made Greedy, Reluctant, and Possessive." }, { "code": null, "e": 866, "s": 545, "text": "By default, quantifiers are Greedy. Greedy quantifiers try to match the longest text that matches a given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the whole text doesn’t match, remove the last character and try again, repeating the process until a match is found. " }, { "code": null, "e": 871, "s": 866, "text": "Java" }, { "code": "// Java program to demonstrate Greedy Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // By default quantifier \"+\" is Greedy Pattern p = Pattern.compile(\"g+\"); // Making an instance of Matcher class Matcher m = p.matcher(\"ggg\"); while (m.find()) System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end()-1)); }}", "e": 1416, "s": 871, "text": null }, { "code": null, "e": 1442, "s": 1416, "text": "Pattern found from 0 to 2" }, { "code": null, "e": 1689, "s": 1442, "text": "Explanation: The pattern g+ means one or more occurrences of g. Text is ggg. The greedy matcher would match the longest text even if parts of the matching text also match. In this example, g and gg also match, but the greedy matcher produces ggg." }, { "code": null, "e": 1842, "s": 1689, "text": "This quantifier uses the approach that is the opposite of greedy quantifiers. It starts with the first character and processes one character at a time. " }, { "code": null, "e": 1847, "s": 1842, "text": "Java" }, { "code": "// Java program to demonstrate Reluctant Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // Here \"+\" is a Reluctant quantifier because // a \"?' is appended after it. Pattern p = Pattern.compile(\"g+?\"); // Making an instance of Matcher class Matcher m = p.matcher(\"ggg\"); while (m.find()) System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end()-1)); }}", "e": 2441, "s": 1847, "text": null }, { "code": null, "e": 2519, "s": 2441, "text": "Pattern found from 0 to 0\nPattern found from 1 to 1\nPattern found from 2 to 2" }, { "code": null, "e": 2664, "s": 2519, "text": "Explanation: Since the quantifier is reluctant, it matches the shortest part of the test with the pattern. It processes one character at a time." }, { "code": null, "e": 2840, "s": 2664, "text": "This quantifier matches as many characters as possible, like a greedy quantifier. But if the entire string doesn’t match, then it doesn’t try removing characters from the end." }, { "code": null, "e": 2845, "s": 2840, "text": "Java" }, { "code": "// Java program to demonstrate Possessive Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Making an instance of Pattern class // Here \"+\" is a Possessive quantifier because // a \"+' is appended after it. Pattern p = Pattern.compile(\"g++\"); // Making an instance of Matcher class Matcher m = p.matcher(\"ggg\"); while (m.find()) System.out.println(\"Pattern found from \" + m.start() + \" to \" + (m.end()-1)); }}", "e": 3439, "s": 2845, "text": null }, { "code": null, "e": 3465, "s": 3439, "text": "Pattern found from 0 to 2" }, { "code": null, "e": 3555, "s": 3465, "text": "Explanation: We get the same output as Greedy because the whole text matches the pattern." }, { "code": null, "e": 3560, "s": 3555, "text": "Java" }, { "code": "// Java program to demonstrate difference// between Possessive and Greedy Quantifiers import java.util.regex.Matcher;import java.util.regex.Pattern; class Test{ public static void main(String[] args) { // Create a pattern with Greedy quantifier Pattern pg = Pattern.compile(\"g+g\"); // Create same pattern with possessive quantifier Pattern pp = Pattern.compile(\"g++g\"); System.out.println(\"Using Greedy Quantifier\"); Matcher mg = pg.matcher(\"ggg\"); while (mg.find()) System.out.println(\"Pattern found from \" + mg.start() + \" to \" + (mg.end()-1)); System.out.println(\"\\nUsing Possessive Quantifier\"); Matcher mp = pp.matcher(\"ggg\"); while (mp.find()) System.out.println(\"Pattern found from \" + mp.start() + \" to \" + (mp.end()-1)); }}", "e": 4467, "s": 3560, "text": null }, { "code": null, "e": 4546, "s": 4467, "text": "Using Greedy Quantifier\nPattern found from 0 to 2\n\nUsing Possessive Quantifier" }, { "code": null, "e": 4994, "s": 4546, "text": "In the above example, since the first quantifier is greedy, g+ matches the whole string. If we match g+ with whole string, g+g doesn’t match, the Greedy quantifier removes the last character, matches gg with g+, and finds a match. In the Possessive quantifier, we start like Greedy. g+ matches the whole string, but matching g+ with the whole string doesn’t match g+g with ggg. Unlike Greedy, since quantifier is possessive, we stop at this point." }, { "code": null, "e": 5386, "s": 4994, "text": "This article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 5402, "s": 5386, "text": "nishkarshgandhi" }, { "code": null, "e": 5426, "s": 5402, "text": "java-regular-expression" }, { "code": null, "e": 5431, "s": 5426, "text": "Java" }, { "code": null, "e": 5450, "s": 5431, "text": "Technical Scripter" }, { "code": null, "e": 5455, "s": 5450, "text": "Java" } ]
SciPy - Interpolate
In this chapter, we will discuss how interpolation helps in SciPy. Interpolation is the process of finding a value between two points on a line or a curve. To help us remember what it means, we should think of the first part of the word, 'inter,' as meaning 'enter,' which reminds us to look 'inside' the data we originally had. This tool, interpolation, is not only useful in statistics, but is also useful in science, business, or when there is a need to predict values that fall within two existing data points. Let us create some data and see how this interpolation can be done using the scipy.interpolate package. import numpy as np from scipy import interpolate import matplotlib.pyplot as plt x = np.linspace(0, 4, 12) y = np.cos(x**2/3+4) print x,y The above program will generate the following output. ( array([0., 0.36363636, 0.72727273, 1.09090909, 1.45454545, 1.81818182, 2.18181818, 2.54545455, 2.90909091, 3.27272727, 3.63636364, 4.]), array([-0.65364362, -0.61966189, -0.51077021, -0.31047698, -0.00715476, 0.37976236, 0.76715099, 0.99239518, 0.85886263, 0.27994201, -0.52586509, -0.99582185]) ) Now, we have two arrays. Assuming those two arrays as the two dimensions of the points in space, let us plot using the following program and see how they look like. plt.plot(x, y,’o’) plt.show() The above program will generate the following output. The interp1d class in the scipy.interpolate is a convenient method to create a function based on fixed data points, which can be evaluated anywhere within the domain defined by the given data using linear interpolation. By using the above data, let us create a interpolate function and draw a new interpolated graph. f1 = interp1d(x, y,kind = 'linear') f2 = interp1d(x, y, kind = 'cubic') Using the interp1d function, we created two functions f1 and f2. These functions, for a given input x returns y. The third variable kind represents the type of the interpolation technique. 'Linear', 'Nearest', 'Zero', 'Slinear', 'Quadratic', 'Cubic' are a few techniques of interpolation. Now, let us create a new input of more length to see the clear difference of interpolation. We will use the same function of the old data on the new data. xnew = np.linspace(0, 4,30) plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--') plt.legend(['data', 'linear', 'cubic','nearest'], loc = 'best') plt.show() The above program will generate the following output. To draw smooth curves through data points, drafters once used thin flexible strips of wood, hard rubber, metal or plastic called mechanical splines. To use a mechanical spline, pins were placed at a judicious selection of points along a curve in a design, and then the spline was bent, so that it touched each of these pins. Clearly, with this construction, the spline interpolates the curve at these pins. It can be used to reproduce the curve in other drawings. The points where the pins are located is called knots. We can change the shape of the curve defined by the spline by adjusting the location of the knots. One-dimensional smoothing spline fits a given set of data points. The UnivariateSpline class in scipy.interpolate is a convenient method to create a function, based on fixed data points class – scipy.interpolate.UnivariateSpline(x, y, w = None, bbox = [None, None], k = 3, s = None, ext = 0, check_finite = False). Parameters − Following are the parameters of a Univariate Spline. This fits a spline y = spl(x) of degree k to the provided x, y data. This fits a spline y = spl(x) of degree k to the provided x, y data. ‘w’ − Specifies the weights for spline fitting. Must be positive. If none (default), weights are all equal. ‘w’ − Specifies the weights for spline fitting. Must be positive. If none (default), weights are all equal. ‘s’ − Specifies the number of knots by specifying a smoothing condition. ‘s’ − Specifies the number of knots by specifying a smoothing condition. ‘k’ − Degree of the smoothing spline. Must be <= 5. Default is k = 3, a cubic spline. ‘k’ − Degree of the smoothing spline. Must be <= 5. Default is k = 3, a cubic spline. Ext − Controls the extrapolation mode for elements not in the interval defined by the knot sequence. Ext − Controls the extrapolation mode for elements not in the interval defined by the knot sequence. if ext = 0 or ‘extrapolate’, returns the extrapolated value. if ext = 0 or ‘extrapolate’, returns the extrapolated value. if ext = 1 or ‘zero’, returns 0 if ext = 1 or ‘zero’, returns 0 if ext = 2 or ‘raise’, raises a ValueError if ext = 2 or ‘raise’, raises a ValueError if ext = 3 of ‘const’, returns the boundary value. if ext = 3 of ‘const’, returns the boundary value. check_finite – Whether to check that the input arrays contain only finite numbers. check_finite – Whether to check that the input arrays contain only finite numbers. Let us consider the following example. import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline x = np.linspace(-3, 3, 50) y = np.exp(-x**2) + 0.1 * np.random.randn(50) plt.plot(x, y, 'ro', ms = 5) plt.show() Use the default value for the smoothing parameter. spl = UnivariateSpline(x, y) xs = np.linspace(-3, 3, 1000) plt.plot(xs, spl(xs), 'g', lw = 3) plt.show() Manually change the amount of smoothing. spl.set_smoothing_factor(0.5) plt.plot(xs, spl(xs), 'b', lw = 3)
[ { "code": null, "e": 2088, "s": 2021, "text": "In this chapter, we will discuss how interpolation helps in SciPy." }, { "code": null, "e": 2536, "s": 2088, "text": "Interpolation is the process of finding a value between two points on a line or a curve. To help us remember what it means, we should think of the first part of the word, 'inter,' as meaning 'enter,' which reminds us to look 'inside' the data we originally had. This tool, interpolation, is not only useful in statistics, but is also useful in science, business, or when there is a need to predict values that fall within two existing data points." }, { "code": null, "e": 2640, "s": 2536, "text": "Let us create some data and see how this interpolation can be done using the scipy.interpolate package." }, { "code": null, "e": 2778, "s": 2640, "text": "import numpy as np\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\nx = np.linspace(0, 4, 12)\ny = np.cos(x**2/3+4)\nprint x,y" }, { "code": null, "e": 2832, "s": 2778, "text": "The above program will generate the following output." }, { "code": null, "e": 3206, "s": 2832, "text": "(\n array([0., 0.36363636, 0.72727273, 1.09090909, 1.45454545, 1.81818182, \n 2.18181818, 2.54545455, 2.90909091, 3.27272727, 3.63636364, 4.]),\n \n array([-0.65364362, -0.61966189, -0.51077021, -0.31047698, -0.00715476,\n 0.37976236, 0.76715099, 0.99239518, 0.85886263, 0.27994201,\n -0.52586509, -0.99582185])\n)\n" }, { "code": null, "e": 3371, "s": 3206, "text": "Now, we have two arrays. Assuming those two arrays as the two dimensions of the points in space, let us plot using the following program and see how they look like." }, { "code": null, "e": 3401, "s": 3371, "text": "plt.plot(x, y,’o’)\nplt.show()" }, { "code": null, "e": 3455, "s": 3401, "text": "The above program will generate the following output." }, { "code": null, "e": 3675, "s": 3455, "text": "The interp1d class in the scipy.interpolate is a convenient method to create a function based on fixed data points, which can be evaluated anywhere within the domain defined by the given data using linear interpolation." }, { "code": null, "e": 3772, "s": 3675, "text": "By using the above data, let us create a interpolate function and draw a new interpolated graph." }, { "code": null, "e": 3846, "s": 3772, "text": "f1 = interp1d(x, y,kind = 'linear')\n\nf2 = interp1d(x, y, kind = 'cubic')\n" }, { "code": null, "e": 4135, "s": 3846, "text": "Using the interp1d function, we created two functions f1 and f2. These functions, for a given input x returns y. The third variable kind represents the type of the interpolation technique. 'Linear', 'Nearest', 'Zero', 'Slinear', 'Quadratic', 'Cubic' are a few techniques of interpolation." }, { "code": null, "e": 4290, "s": 4135, "text": "Now, let us create a new input of more length to see the clear difference of interpolation. We will use the same function of the old data on the new data." }, { "code": null, "e": 4458, "s": 4290, "text": "xnew = np.linspace(0, 4,30)\n\nplt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')\n\nplt.legend(['data', 'linear', 'cubic','nearest'], loc = 'best')\n\nplt.show()" }, { "code": null, "e": 4512, "s": 4458, "text": "The above program will generate the following output." }, { "code": null, "e": 4837, "s": 4512, "text": "To draw smooth curves through data points, drafters once used thin flexible strips of wood, hard rubber, metal or plastic called mechanical splines. To use a mechanical spline, pins were placed at a judicious selection of points along a curve in a design, and then the spline was bent, so that it touched each of these pins." }, { "code": null, "e": 5130, "s": 4837, "text": "Clearly, with this construction, the spline interpolates the curve at these pins. It can be used to reproduce the curve in other drawings. The points where the pins are located is called knots. We can change the shape of the curve defined by the spline by adjusting the location of the knots." }, { "code": null, "e": 5445, "s": 5130, "text": "One-dimensional smoothing spline fits a given set of data points. The UnivariateSpline class in scipy.interpolate is a convenient method to create a function, based on fixed data points class – scipy.interpolate.UnivariateSpline(x, y, w = None, bbox = [None, None], k = 3, s = None, ext = 0, check_finite = False)." }, { "code": null, "e": 5511, "s": 5445, "text": "Parameters − Following are the parameters of a Univariate Spline." }, { "code": null, "e": 5580, "s": 5511, "text": "This fits a spline y = spl(x) of degree k to the provided x, y data." }, { "code": null, "e": 5649, "s": 5580, "text": "This fits a spline y = spl(x) of degree k to the provided x, y data." }, { "code": null, "e": 5757, "s": 5649, "text": "‘w’ − Specifies the weights for spline fitting. Must be positive. If none (default), weights are all equal." }, { "code": null, "e": 5865, "s": 5757, "text": "‘w’ − Specifies the weights for spline fitting. Must be positive. If none (default), weights are all equal." }, { "code": null, "e": 5938, "s": 5865, "text": "‘s’ − Specifies the number of knots by specifying a smoothing condition." }, { "code": null, "e": 6011, "s": 5938, "text": "‘s’ − Specifies the number of knots by specifying a smoothing condition." }, { "code": null, "e": 6097, "s": 6011, "text": "‘k’ − Degree of the smoothing spline. Must be <= 5. Default is k = 3, a cubic spline." }, { "code": null, "e": 6183, "s": 6097, "text": "‘k’ − Degree of the smoothing spline. Must be <= 5. Default is k = 3, a cubic spline." }, { "code": null, "e": 6284, "s": 6183, "text": "Ext − Controls the extrapolation mode for elements not in the interval defined by the knot sequence." }, { "code": null, "e": 6385, "s": 6284, "text": "Ext − Controls the extrapolation mode for elements not in the interval defined by the knot sequence." }, { "code": null, "e": 6446, "s": 6385, "text": "if ext = 0 or ‘extrapolate’, returns the extrapolated value." }, { "code": null, "e": 6507, "s": 6446, "text": "if ext = 0 or ‘extrapolate’, returns the extrapolated value." }, { "code": null, "e": 6539, "s": 6507, "text": "if ext = 1 or ‘zero’, returns 0" }, { "code": null, "e": 6571, "s": 6539, "text": "if ext = 1 or ‘zero’, returns 0" }, { "code": null, "e": 6614, "s": 6571, "text": "if ext = 2 or ‘raise’, raises a ValueError" }, { "code": null, "e": 6657, "s": 6614, "text": "if ext = 2 or ‘raise’, raises a ValueError" }, { "code": null, "e": 6708, "s": 6657, "text": "if ext = 3 of ‘const’, returns the boundary value." }, { "code": null, "e": 6759, "s": 6708, "text": "if ext = 3 of ‘const’, returns the boundary value." }, { "code": null, "e": 6842, "s": 6759, "text": "check_finite – Whether to check that the input arrays contain only finite numbers." }, { "code": null, "e": 6925, "s": 6842, "text": "check_finite – Whether to check that the input arrays contain only finite numbers." }, { "code": null, "e": 6964, "s": 6925, "text": "Let us consider the following example." }, { "code": null, "e": 7156, "s": 6964, "text": "import matplotlib.pyplot as plt\nfrom scipy.interpolate import UnivariateSpline\nx = np.linspace(-3, 3, 50)\ny = np.exp(-x**2) + 0.1 * np.random.randn(50)\nplt.plot(x, y, 'ro', ms = 5)\nplt.show()" }, { "code": null, "e": 7207, "s": 7156, "text": "Use the default value for the smoothing parameter." }, { "code": null, "e": 7313, "s": 7207, "text": "spl = UnivariateSpline(x, y)\nxs = np.linspace(-3, 3, 1000)\nplt.plot(xs, spl(xs), 'g', lw = 3)\nplt.show()\n" }, { "code": null, "e": 7354, "s": 7313, "text": "Manually change the amount of smoothing." } ]
Java.lang.Boolean Class in Java
23 Aug, 2018 Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolean variable. Creating a Boolean object Boolean class provides two constructors for creating Boolean object. The below statement creates a Boolean object which contain the value argument.Boolean b = new Boolean(boolean value); Boolean b = new Boolean(boolean value); The below statement creates a Boolean object which contain the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise Boolean object with value false is created.Boolean b = new Boolean(String s); Boolean b = new Boolean(String s); Fields: static Boolean FALSE : The Boolean object corresponding to the primitive value false. static Boolean TRUE : The Boolean object corresponding to the primitive value true. static Class : The Class object representing the primitive type boolean. Methods: static boolean parseBoolean(String s) : This method parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise return false.Syntax : public static boolean parseBoolean(String s) Parameters : s - the String containing the boolean representation to be parsed Returns : the boolean represented by the string argument // Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean("True"); boolean b2 = Boolean.parseBoolean("TruE"); boolean b3 = Boolean.parseBoolean("False"); boolean b4 = Boolean.parseBoolean("FALSE"); boolean b5 = Boolean.parseBoolean("GeeksForGeeks"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true true false false false boolean booleanValue() : This method returns the value of this Boolean object as a boolean primitive.Syntax : public boolean booleanValue() Parameters : NA Returns : the primitive boolean value of this object. // Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }}Output:true false false static Boolean valueOf(boolean b) : This method returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, it returns Boolean.TRUE or if it is false, then this method returns Boolean.FALSE. The other variant of this method is discussed next.Syntax : public static boolean valueOf(boolean b) Parameters : b - a boolean value. Returns : a Boolean object representing b. // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }}Output:true false static Boolean valueOf(String s) : This method returns a Boolean with a value represented by the specified string ‘s’. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.Syntax : public static boolean valueOf(String s) Parameters : s - a string Returns : a Boolean value represented by the string // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf("true"); Boolean b2 = Boolean.valueOf("TRue"); Boolean b3 = Boolean.valueOf("False"); Boolean b4 = Boolean.valueOf("GeeksForGeeks"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true true false false false static String toString(boolean b) : This method returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be returned, otherwise the string “false” will be returned.The other variant of this method is discussed next.Syntax : public static String toString(boolean b) Parameters : b - the boolean to be converted Returns : the string representation of the specified boolean // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }}Output:true false String toString() : This method returns a String object representing this Boolean’s value. If this object represents the value true, a string equal to “true” is returned. Otherwise, the string “false” is returned.Syntax : public String toString() Parameters : NA Returns : a string representation of this object Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }}Output:true false false false int hashCode() : This method returns a hash code for this Boolean object. Note that hashcode for true is 1231 and for false is 1237. To find reason for choosing this integers as hashcode, refer here.Syntax : public int hashCode() Parameters : NA Returns : the integer 1231 if this object represents true; returns the integer 1237 if this object represents false Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }}Output:1231 1237 1231 1237 boolean equals(Object obj) : This method returns true iff the argument is not null and is a Boolean object that represents the same boolean value as this object.Syntax : public boolean equals(Object obj) Parameters : obj - the object to compare with. Returns : true if the Boolean objects represent the same value; false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TrUe"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }}Output:false true true false int compareTo(Boolean b) : This method “compares” this Boolean instance with passed argument ‘b’.Syntax : public int compareTo(Boolean b) Parameters : b - the Boolean instance to be compared Returns : zero if this object represents the same boolean value as the argument; a positive value if this object represents true and the argument represents false; a negative value if this object represents false and the argument represents true. Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }}Output:1 0 -1 1 0 int compare(boolean x, boolean y) : This method is used to “compares” primitives boolean variables.Syntax : public static int compare(boolean x, boolean y) Parameters : x - the first boolean to compare y - the second boolean to compare Returns : zero if x is same boolean value as y; a positive value x is true and y is false; a negative value if x is false and y is true; Throws : NullPointerException - if the argument is null // Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }}Output:1 0 -1 0 static boolean parseBoolean(String s) : This method parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise return false.Syntax : public static boolean parseBoolean(String s) Parameters : s - the String containing the boolean representation to be parsed Returns : the boolean represented by the string argument // Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean("True"); boolean b2 = Boolean.parseBoolean("TruE"); boolean b3 = Boolean.parseBoolean("False"); boolean b4 = Boolean.parseBoolean("FALSE"); boolean b5 = Boolean.parseBoolean("GeeksForGeeks"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true true false false false Syntax : public static boolean parseBoolean(String s) Parameters : s - the String containing the boolean representation to be parsed Returns : the boolean represented by the string argument // Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean("True"); boolean b2 = Boolean.parseBoolean("TruE"); boolean b3 = Boolean.parseBoolean("False"); boolean b4 = Boolean.parseBoolean("FALSE"); boolean b5 = Boolean.parseBoolean("GeeksForGeeks"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }} Output: true true false false false boolean booleanValue() : This method returns the value of this Boolean object as a boolean primitive.Syntax : public boolean booleanValue() Parameters : NA Returns : the primitive boolean value of this object. // Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }}Output:true false false Syntax : public boolean booleanValue() Parameters : NA Returns : the primitive boolean value of this object. // Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }} Output: true false false static Boolean valueOf(boolean b) : This method returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, it returns Boolean.TRUE or if it is false, then this method returns Boolean.FALSE. The other variant of this method is discussed next.Syntax : public static boolean valueOf(boolean b) Parameters : b - a boolean value. Returns : a Boolean object representing b. // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }}Output:true false Syntax : public static boolean valueOf(boolean b) Parameters : b - a boolean value. Returns : a Boolean object representing b. // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }} Output: true false static Boolean valueOf(String s) : This method returns a Boolean with a value represented by the specified string ‘s’. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.Syntax : public static boolean valueOf(String s) Parameters : s - a string Returns : a Boolean value represented by the string // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf("true"); Boolean b2 = Boolean.valueOf("TRue"); Boolean b3 = Boolean.valueOf("False"); Boolean b4 = Boolean.valueOf("GeeksForGeeks"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true true false false false Syntax : public static boolean valueOf(String s) Parameters : s - a string Returns : a Boolean value represented by the string // Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf("true"); Boolean b2 = Boolean.valueOf("TRue"); Boolean b3 = Boolean.valueOf("False"); Boolean b4 = Boolean.valueOf("GeeksForGeeks"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }} Output: true true false false false static String toString(boolean b) : This method returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be returned, otherwise the string “false” will be returned.The other variant of this method is discussed next.Syntax : public static String toString(boolean b) Parameters : b - the boolean to be converted Returns : the string representation of the specified boolean // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }}Output:true false Syntax : public static String toString(boolean b) Parameters : b - the boolean to be converted Returns : the string representation of the specified boolean // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }} Output: true false String toString() : This method returns a String object representing this Boolean’s value. If this object represents the value true, a string equal to “true” is returned. Otherwise, the string “false” is returned.Syntax : public String toString() Parameters : NA Returns : a string representation of this object Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }}Output:true false false false Syntax : public String toString() Parameters : NA Returns : a string representation of this object Overrides : toString in class Object // Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("GeeksForGeeks"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }} Output: true false false false int hashCode() : This method returns a hash code for this Boolean object. Note that hashcode for true is 1231 and for false is 1237. To find reason for choosing this integers as hashcode, refer here.Syntax : public int hashCode() Parameters : NA Returns : the integer 1231 if this object represents true; returns the integer 1237 if this object represents false Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }}Output:1231 1237 1231 1237 Syntax : public int hashCode() Parameters : NA Returns : the integer 1231 if this object represents true; returns the integer 1237 if this object represents false Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }} Output: 1231 1237 1231 1237 boolean equals(Object obj) : This method returns true iff the argument is not null and is a Boolean object that represents the same boolean value as this object.Syntax : public boolean equals(Object obj) Parameters : obj - the object to compare with. Returns : true if the Boolean objects represent the same value; false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TrUe"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }}Output:false true true false Syntax : public boolean equals(Object obj) Parameters : obj - the object to compare with. Returns : true if the Boolean objects represent the same value; false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TrUe"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }} Output: false true true false int compareTo(Boolean b) : This method “compares” this Boolean instance with passed argument ‘b’.Syntax : public int compareTo(Boolean b) Parameters : b - the Boolean instance to be compared Returns : zero if this object represents the same boolean value as the argument; a positive value if this object represents true and the argument represents false; a negative value if this object represents false and the argument represents true. Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }}Output:1 0 -1 1 0 Syntax : public int compareTo(Boolean b) Parameters : b - the Boolean instance to be compared Returns : zero if this object represents the same boolean value as the argument; a positive value if this object represents true and the argument represents false; a negative value if this object represents false and the argument represents true. Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean("True"); Boolean b2 = new Boolean("False"); Boolean b3 = new Boolean("TRue"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }} Output: 1 0 -1 1 0 int compare(boolean x, boolean y) : This method is used to “compares” primitives boolean variables.Syntax : public static int compare(boolean x, boolean y) Parameters : x - the first boolean to compare y - the second boolean to compare Returns : zero if x is same boolean value as y; a positive value x is true and y is false; a negative value if x is false and y is true; Throws : NullPointerException - if the argument is null // Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }}Output:1 0 -1 0 Syntax : public static int compare(boolean x, boolean y) Parameters : x - the first boolean to compare y - the second boolean to compare Returns : zero if x is same boolean value as y; a positive value x is true and y is false; a negative value if x is false and y is true; Throws : NullPointerException - if the argument is null // Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }} Output: 1 0 -1 0 This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-lang package java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2018" }, { "code": null, "e": 262, "s": 52, "text": "Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean." }, { "code": null, "e": 414, "s": 262, "text": "In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolean variable." }, { "code": null, "e": 440, "s": 414, "text": "Creating a Boolean object" }, { "code": null, "e": 509, "s": 440, "text": "Boolean class provides two constructors for creating Boolean object." }, { "code": null, "e": 628, "s": 509, "text": "The below statement creates a Boolean object which contain the value argument.Boolean b = new Boolean(boolean value);\n" }, { "code": null, "e": 669, "s": 628, "text": "Boolean b = new Boolean(boolean value);\n" }, { "code": null, "e": 918, "s": 669, "text": "The below statement creates a Boolean object which contain the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise Boolean object with value false is created.Boolean b = new Boolean(String s);\n" }, { "code": null, "e": 954, "s": 918, "text": "Boolean b = new Boolean(String s);\n" }, { "code": null, "e": 962, "s": 954, "text": "Fields:" }, { "code": null, "e": 1048, "s": 962, "text": "static Boolean FALSE : The Boolean object corresponding to the primitive value false." }, { "code": null, "e": 1132, "s": 1048, "text": "static Boolean TRUE : The Boolean object corresponding to the primitive value true." }, { "code": null, "e": 1205, "s": 1132, "text": "static Class : The Class object representing the primitive type boolean." }, { "code": null, "e": 1214, "s": 1205, "text": "Methods:" }, { "code": null, "e": 11138, "s": 1214, "text": "static boolean parseBoolean(String s) : This method parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise return false.Syntax : \npublic static boolean parseBoolean(String s)\nParameters : \ns - the String containing the boolean representation to be parsed\nReturns :\nthe boolean represented by the string argument\n// Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean(\"True\"); boolean b2 = Boolean.parseBoolean(\"TruE\"); boolean b3 = Boolean.parseBoolean(\"False\"); boolean b4 = Boolean.parseBoolean(\"FALSE\"); boolean b5 = Boolean.parseBoolean(\"GeeksForGeeks\"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true\ntrue\nfalse\nfalse\nfalse\nboolean booleanValue() : This method returns the value of this Boolean object as a boolean primitive.Syntax : \npublic boolean booleanValue()\nParameters : \nNA\nReturns :\nthe primitive boolean value of this object.\n// Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }}Output:true\nfalse\nfalse\nstatic Boolean valueOf(boolean b) : This method returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, it returns Boolean.TRUE or if it is false, then this method returns Boolean.FALSE. The other variant of this method is discussed next.Syntax : \npublic static boolean valueOf(boolean b)\nParameters : \nb - a boolean value.\nReturns :\na Boolean object representing b.\n// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }}Output:true\nfalse\nstatic Boolean valueOf(String s) : This method returns a Boolean with a value represented by the specified string ‘s’. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.Syntax : \npublic static boolean valueOf(String s)\nParameters : \ns - a string\nReturns :\na Boolean value represented by the string\n// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf(\"true\"); Boolean b2 = Boolean.valueOf(\"TRue\"); Boolean b3 = Boolean.valueOf(\"False\"); Boolean b4 = Boolean.valueOf(\"GeeksForGeeks\"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true\ntrue\nfalse\nfalse\nfalse\nstatic String toString(boolean b) : This method returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be returned, otherwise the string “false” will be returned.The other variant of this method is discussed next.Syntax : \npublic static String toString(boolean b)\nParameters : \nb - the boolean to be converted\nReturns :\nthe string representation of the specified boolean\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }}Output:true\nfalse\nString toString() : This method returns a String object representing this Boolean’s value. If this object represents the value true, a string equal to “true” is returned. Otherwise, the string “false” is returned.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this object\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }}Output:true\nfalse\nfalse\nfalse\nint hashCode() : This method returns a hash code for this Boolean object. Note that hashcode for true is 1231 and for false is 1237. To find reason for choosing this integers as hashcode, refer here.Syntax : \npublic int hashCode()\nParameters : \nNA\nReturns :\nthe integer 1231 if this object represents true;\nreturns the integer 1237 if this object represents false\nOverrides :\nhashCode in class Object\n// Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }}Output:1231\n1237\n1231\n1237\nboolean equals(Object obj) : This method returns true iff the argument is not null and is a Boolean object that represents the same boolean value as this object.Syntax : \npublic boolean equals(Object obj)\nParameters : \nobj - the object to compare with.\nReturns :\ntrue if the Boolean objects represent the same value; \nfalse otherwise\nOverrides :\nequals in class Object\n// Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TrUe\"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }}Output:false\ntrue\ntrue\nfalse\nint compareTo(Boolean b) : This method “compares” this Boolean instance with passed argument ‘b’.Syntax : \npublic int compareTo(Boolean b)\nParameters : \nb - the Boolean instance to be compared\nReturns :\nzero if this object represents the same boolean value as the argument; \na positive value if this object represents true and the argument represents false;\na negative value if this object represents false and the argument represents true.\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }}Output:1\n0\n-1\n1\n0\nint compare(boolean x, boolean y) : This method is used to “compares” primitives boolean variables.Syntax : \npublic static int compare(boolean x, boolean y)\nParameters : \nx - the first boolean to compare\ny - the second boolean to compare\nReturns :\nzero if x is same boolean value as y; \na positive value x is true and y is false;\na negative value if x is false and y is true;\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }}Output:1\n0\n-1\n0\n" }, { "code": null, "e": 12210, "s": 11138, "text": "static boolean parseBoolean(String s) : This method parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise return false.Syntax : \npublic static boolean parseBoolean(String s)\nParameters : \ns - the String containing the boolean representation to be parsed\nReturns :\nthe boolean represented by the string argument\n// Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean(\"True\"); boolean b2 = Boolean.parseBoolean(\"TruE\"); boolean b3 = Boolean.parseBoolean(\"False\"); boolean b4 = Boolean.parseBoolean(\"FALSE\"); boolean b5 = Boolean.parseBoolean(\"GeeksForGeeks\"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true\ntrue\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 12403, "s": 12210, "text": "Syntax : \npublic static boolean parseBoolean(String s)\nParameters : \ns - the String containing the boolean representation to be parsed\nReturns :\nthe boolean represented by the string argument\n" }, { "code": "// Java program to demonstrate parseBoolean() methodpublic class Test{ public static void main(String[] args) { // parsing different Strings boolean b1 = Boolean.parseBoolean(\"True\"); boolean b2 = Boolean.parseBoolean(\"TruE\"); boolean b3 = Boolean.parseBoolean(\"False\"); boolean b4 = Boolean.parseBoolean(\"FALSE\"); boolean b5 = Boolean.parseBoolean(\"GeeksForGeeks\"); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}", "e": 12999, "s": 12403, "text": null }, { "code": null, "e": 13007, "s": 12999, "text": "Output:" }, { "code": null, "e": 13036, "s": 13007, "text": "true\ntrue\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 13856, "s": 13036, "text": "boolean booleanValue() : This method returns the value of this Boolean object as a boolean primitive.Syntax : \npublic boolean booleanValue()\nParameters : \nNA\nReturns :\nthe primitive boolean value of this object.\n// Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }}Output:true\nfalse\nfalse\n" }, { "code": null, "e": 13968, "s": 13856, "text": "Syntax : \npublic boolean booleanValue()\nParameters : \nNA\nReturns :\nthe primitive boolean value of this object.\n" }, { "code": "// Java program to demonstrate booleanValue() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); // getting primitive boolean value boolean b4 = b1.booleanValue(); boolean b5 = b2.booleanValue(); boolean b6 = b3.booleanValue(); System.out.println(b4); System.out.println(b5); System.out.println(b6); }}", "e": 14552, "s": 13968, "text": null }, { "code": null, "e": 14560, "s": 14552, "text": "Output:" }, { "code": null, "e": 14578, "s": 14560, "text": "true\nfalse\nfalse\n" }, { "code": null, "e": 15455, "s": 14578, "text": "static Boolean valueOf(boolean b) : This method returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, it returns Boolean.TRUE or if it is false, then this method returns Boolean.FALSE. The other variant of this method is discussed next.Syntax : \npublic static boolean valueOf(boolean b)\nParameters : \nb - a boolean value.\nReturns :\na Boolean object representing b.\n// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }}Output:true\nfalse\n" }, { "code": null, "e": 15585, "s": 15455, "text": "Syntax : \npublic static boolean valueOf(boolean b)\nParameters : \nb - a boolean value.\nReturns :\na Boolean object representing b.\n" }, { "code": "// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting Boolean objects from boolean variables Boolean b3 = Boolean.valueOf(b1); Boolean b4 = Boolean.valueOf(b2); System.out.println(b3); System.out.println(b4); }}", "e": 16024, "s": 15585, "text": null }, { "code": null, "e": 16032, "s": 16024, "text": "Output:" }, { "code": null, "e": 16044, "s": 16032, "text": "true\nfalse\n" }, { "code": null, "e": 17044, "s": 16044, "text": "static Boolean valueOf(String s) : This method returns a Boolean with a value represented by the specified string ‘s’. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.Syntax : \npublic static boolean valueOf(String s)\nParameters : \ns - a string\nReturns :\na Boolean value represented by the string\n// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf(\"true\"); Boolean b2 = Boolean.valueOf(\"TRue\"); Boolean b3 = Boolean.valueOf(\"False\"); Boolean b4 = Boolean.valueOf(\"GeeksForGeeks\"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}Output:true\ntrue\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 17174, "s": 17044, "text": "Syntax : \npublic static boolean valueOf(String s)\nParameters : \ns - a string\nReturns :\na Boolean value represented by the string\n" }, { "code": "// Java program to demonstrate valueOf() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable using different Strings Boolean b1 = Boolean.valueOf(\"true\"); Boolean b2 = Boolean.valueOf(\"TRue\"); Boolean b3 = Boolean.valueOf(\"False\"); Boolean b4 = Boolean.valueOf(\"GeeksForGeeks\"); Boolean b5 = Boolean.valueOf(null); System.out.println(b1); System.out.println(b2); System.out.println(b3); System.out.println(b4); System.out.println(b5); }}", "e": 17761, "s": 17174, "text": null }, { "code": null, "e": 17769, "s": 17761, "text": "Output:" }, { "code": null, "e": 17798, "s": 17769, "text": "true\ntrue\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 18692, "s": 17798, "text": "static String toString(boolean b) : This method returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be returned, otherwise the string “false” will be returned.The other variant of this method is discussed next.Syntax : \npublic static String toString(boolean b)\nParameters : \nb - the boolean to be converted\nReturns :\nthe string representation of the specified boolean\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }}Output:true\nfalse\n" }, { "code": null, "e": 18851, "s": 18692, "text": "Syntax : \npublic static String toString(boolean b)\nParameters : \nb - the boolean to be converted\nReturns :\nthe string representation of the specified boolean\n" }, { "code": "// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; // getting String value of the primitives boolean String str1 = Boolean.toString(b1); String str2 = Boolean.toString(b2); System.out.println(str1); System.out.println(str2); }}", "e": 19289, "s": 18851, "text": null }, { "code": null, "e": 19297, "s": 19289, "text": "Output:" }, { "code": null, "e": 19309, "s": 19297, "text": "true\nfalse\n" }, { "code": null, "e": 20379, "s": 19309, "text": "String toString() : This method returns a String object representing this Boolean’s value. If this object represents the value true, a string equal to “true” is returned. Otherwise, the string “false” is returned.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this object\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }}Output:true\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 20518, "s": 20379, "text": "Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this object\nOverrides :\ntoString in class Object\n" }, { "code": "// Java program to demonstrate toString() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"GeeksForGeeks\"); Boolean b4 = new Boolean(null); // getting String value of Boolean objects String str1 = b1.toString(); String str2 = b2.toString(); String str3 = b3.toString(); String str4 = b4.toString(); System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }}", "e": 21207, "s": 20518, "text": null }, { "code": null, "e": 21215, "s": 21207, "text": "Output:" }, { "code": null, "e": 21239, "s": 21215, "text": "true\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 22169, "s": 21239, "text": "int hashCode() : This method returns a hash code for this Boolean object. Note that hashcode for true is 1231 and for false is 1237. To find reason for choosing this integers as hashcode, refer here.Syntax : \npublic int hashCode()\nParameters : \nNA\nReturns :\nthe integer 1231 if this object represents true;\nreturns the integer 1237 if this object represents false\nOverrides :\nhashCode in class Object\n// Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }}Output:1231\n1237\n1231\n1237\n" }, { "code": null, "e": 22372, "s": 22169, "text": "Syntax : \npublic int hashCode()\nParameters : \nNA\nReturns :\nthe integer 1231 if this object represents true;\nreturns the integer 1237 if this object represents false\nOverrides :\nhashCode in class Object\n" }, { "code": "// Java program to demonstrate hashCode() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); System.out.println(b1.hashCode()); System.out.println(b2.hashCode()); System.out.println(b3.hashCode()); System.out.println(b4.hashCode()); }}", "e": 22874, "s": 22372, "text": null }, { "code": null, "e": 22882, "s": 22874, "text": "Output:" }, { "code": null, "e": 22903, "s": 22882, "text": "1231\n1237\n1231\n1237\n" }, { "code": null, "e": 23858, "s": 22903, "text": "boolean equals(Object obj) : This method returns true iff the argument is not null and is a Boolean object that represents the same boolean value as this object.Syntax : \npublic boolean equals(Object obj)\nParameters : \nobj - the object to compare with.\nReturns :\ntrue if the Boolean objects represent the same value; \nfalse otherwise\nOverrides :\nequals in class Object\n// Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TrUe\"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }}Output:false\ntrue\ntrue\nfalse\n" }, { "code": null, "e": 24067, "s": 23858, "text": "Syntax : \npublic boolean equals(Object obj)\nParameters : \nobj - the object to compare with.\nReturns :\ntrue if the Boolean objects represent the same value; \nfalse otherwise\nOverrides :\nequals in class Object\n" }, { "code": "// Java program to demonstrate equals() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TrUe\"); Boolean b4 = new Boolean(null); // checking equality of Boolean objects System.out.println(b1.equals(b2)); System.out.println(b2.equals(b4)); System.out.println(b1.equals(b3)); System.out.println(b1.equals(b4)); }}", "e": 24624, "s": 24067, "text": null }, { "code": null, "e": 24632, "s": 24624, "text": "Output:" }, { "code": null, "e": 24655, "s": 24632, "text": "false\ntrue\ntrue\nfalse\n" }, { "code": null, "e": 25883, "s": 24655, "text": "int compareTo(Boolean b) : This method “compares” this Boolean instance with passed argument ‘b’.Syntax : \npublic int compareTo(Boolean b)\nParameters : \nb - the Boolean instance to be compared\nReturns :\nzero if this object represents the same boolean value as the argument; \na positive value if this object represents true and the argument represents false;\na negative value if this object represents false and the argument represents true.\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }}Output:1\n0\n-1\n1\n0\n" }, { "code": null, "e": 26284, "s": 25883, "text": "Syntax : \npublic int compareTo(Boolean b)\nParameters : \nb - the Boolean instance to be compared\nReturns :\nzero if this object represents the same boolean value as the argument; \na positive value if this object represents true and the argument represents false;\na negative value if this object represents false and the argument represents true.\nThrows :\nNullPointerException - if the argument is null\n" }, { "code": "// Java program to demonstrate compareTo() methodpublic class Test{ public static void main(String[] args) { // creating different Boolean objects Boolean b1 = new Boolean(\"True\"); Boolean b2 = new Boolean(\"False\"); Boolean b3 = new Boolean(\"TRue\"); Boolean b4 = new Boolean(null); //comparing b1,b2,b3,b4 System.out.println(b1.compareTo(b2)); System.out.println(b1.compareTo(b3)); System.out.println(b2.compareTo(b1)); System.out.println(b1.compareTo(b4)); System.out.println(b2.compareTo(b4)); // The following statement throws NullPointerExcetion // System.out.println(b1.compareTo(null)); }}", "e": 26997, "s": 26284, "text": null }, { "code": null, "e": 27005, "s": 26997, "text": "Output:" }, { "code": null, "e": 27017, "s": 27005, "text": "1\n0\n-1\n1\n0\n" }, { "code": null, "e": 28104, "s": 27017, "text": "int compare(boolean x, boolean y) : This method is used to “compares” primitives boolean variables.Syntax : \npublic static int compare(boolean x, boolean y)\nParameters : \nx - the first boolean to compare\ny - the second boolean to compare\nReturns :\nzero if x is same boolean value as y; \na positive value x is true and y is false;\na negative value if x is false and y is true;\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }}Output:1\n0\n-1\n0\n" }, { "code": null, "e": 28438, "s": 28104, "text": "Syntax : \npublic static int compare(boolean x, boolean y)\nParameters : \nx - the first boolean to compare\ny - the second boolean to compare\nReturns :\nzero if x is same boolean value as y; \na positive value x is true and y is false;\na negative value if x is false and y is true;\nThrows :\nNullPointerException - if the argument is null\n" }, { "code": "// Java program to demonstrate compare() methodpublic class Test{ public static void main(String[] args) { // creating boolean variable boolean b1 = true; boolean b2 = false; boolean b3 = true; boolean b4 = false; //comparing b1,b2,b3,b4 System.out.println(Boolean.compare(b1, b2)); System.out.println(Boolean.compare(b1, b3)); System.out.println(Boolean.compare(b2, b1)); System.out.println(Boolean.compare(b2, b4)); // The following statement throws NullPointerExcetion // System.out.println(Boolean.compare(b1, null)); }}", "e": 29077, "s": 28438, "text": null }, { "code": null, "e": 29085, "s": 29077, "text": "Output:" }, { "code": null, "e": 29095, "s": 29085, "text": "1\n0\n-1\n0\n" }, { "code": null, "e": 29397, "s": 29095, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29522, "s": 29397, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29540, "s": 29522, "text": "Java-lang package" }, { "code": null, "e": 29559, "s": 29540, "text": "java-wrapper-class" }, { "code": null, "e": 29564, "s": 29559, "text": "Java" }, { "code": null, "e": 29569, "s": 29564, "text": "Java" } ]
Oracle Database Connection in Python
25 May, 2021 Sometimes as part of programming, we required to work with the databases because we want to store a huge amount of information so we use databases, such as Oracle, MySQL, etc. So In this article, we will discuss the connectivity of Oracle database using Python. This can be done through the module name cx_Oracle. Oracle Database For communicating with any database through our Python program we require some connector which is nothing but the cx_Oracle module. For installing cx-Oracle : If you are using Python >= 3.6 use the below command in Linux: – pip install cx-Oracle If you are using Python >= 3.6 use the below command in Windows: – py -m pip install cx-Oracle By this command, you can install cx-Oracle package but it is required to install Oracle database first on your PC. Import database specific module Ex. import cx_Oracle connect(): Now Establish a connection between the Python program and Oracle database by using connect() function. con = cx_Oracle.connect('username/password@localhost') cursor(): To execute a SQL query and to provide results some special object is required that is nothing but cursor() object. cursor = cx_Oracle.cursor() execute/executemany method : cursor.execute(sqlquery) – – – -> to execute a single query. cursor.executemany(sqlqueries) – – – -> to execute a single query with multiple bind variables/place holders. commit(): For DML(Data Manipulation Language) queries that comprise operations like update, insert, delete. We need to commit() then only the result reflects in the database. fetchone(), fetchmany(int), fetchall():fetchone() : This method is used to fetch one single row from the top of the result set.fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it.fetchall() : This method is used to fetch all rows from the result set. fetchone() : This method is used to fetch one single row from the top of the result set.fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it.fetchall() : This method is used to fetch all rows from the result set. fetchone() : This method is used to fetch one single row from the top of the result set. fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it. fetchall() : This method is used to fetch all rows from the result set. close(): After all done it is mandatory to close all operations. cursor.close() con.close() Python3 # importing moduleimport cx_Oracle # Create a table in Oracle databasetry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') print(con.version) # Now execute the sqlquery cursor = con.cursor() # Creating a table employee cursor.execute("create table employee(empid integer primary key, name varchar2(30), salary number(10, 2))") print("Table Created successfully") except cx_Oracle.DatabaseError as e: print("There is a problem with Oracle", e) # by writing finally if any error occurs# then also we can close the all database operationfinally: if cursor: cursor.close() if con: con.close() Output: Table Created successfully DDL statements don’t require to be committed. They are automatically committed. In the above program, I have used execute() method to execute an SQL statement. Python3 # importing moduleimport cx_Oracle # Inserting a record into a table in Oracle databasetry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') cursor = con.cursor() #con.autocommit = True # Inserting a record into table employee cursor.execute('insert into employee values(10001,\'Rahul\',50000.50)') # commit() to make changes reflect in the database con.commit() print('Record inserted successfully') except cx_Oracle.DatabaseError as e: print("There is a problem with Oracle", e) # by writing finally if any error occurs# then also we can close the all database operationfinally: if cursor: cursor.close() if con: con.close() Output: Record inserted successfully Once we execute any DML statement it is required to commit the transaction. You can commit a transaction in 2 ways: – con.commit(). This is used to commit a transaction manually.con.autocommit = True. This is used to commit a transaction automatically. con.commit(). This is used to commit a transaction manually. con.autocommit = True. This is used to commit a transaction automatically. Python3 import cx_Oracle # Load data from a csv file into Oracle table using executemanytry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is an error in Oracle database:', er) else: try: cur = con.cursor() data = [[10007, 'Vikram', 48000.0], [10008, 'Sunil', 65000.1], [10009, 'Sameer', 75000.0]] cur = con.cursor() # Inserting multiple records into employee table # (:1,:2,:3) are place holders. They pick data from a list supplied as argument cur.executemany('insert into employee values(:1,:2,:3)', data) except cx_Oracle.DatabaseError as er: print('There is an error in Oracle database:', er) except Exception as er: print(er) else: # To commit the transaction manually con.commit() print('Multiple records are inserted successfully') finally: if cur: cur.close() if con: con.close() Output: Multiple records are inserted successfully There might be times when it is required to execute a SQL statement multiple times based on the different values supplied to it each time. This can be achieved using executemany() method. We supply a list containing a list of values that will replace placeholders in a SQL query to be executed. From the above case :1 is substituted by value 10007 :2 is substituted by value ‘Vikram’ :3 is substituted by value 48000.0 And so on(next list of values in a given list) Similarly, you can supply a list of dictionaries. But instead of placeholder, we will use the bind variable( discussed later). Python3 import cx_Oracle try: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is an error in the Oracle database:', er) else: try: cur = con.cursor() # fetchall() is used to fetch all records from result set cur.execute('select * from employee') rows = cur.fetchall() print(rows) # fetchmany(int) is used to fetch limited number of records from result set based on integer argument passed in it cur.execute('select * from employee') rows = cur.fetchmany(3) print(rows) # fetchone() is used fetch one record from top of the result set cur.execute('select * from employee') rows = cur.fetchone() print(rows) except cx_Oracle.DatabaseError as er: print('There is an error in the Oracle database:', er) except Exception as er: print('Error:'+str(er)) finally: if cur: cur.close() finally: if con: con.close() Output: [(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003, 'Soumik', 30000.25), (10004, 'Sayan', 45000.0), (10005, 'Sobhan', 60000.1), (10006, 'Gururaj', 70000.0), (10007, 'Vikram', 48000.0), (10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)] [(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003, 'Soumik', 30000.25)] (10001, 'Rahul', 50000.5) In the above program, we have used 3 methods fetchall() : The fetchall() is used to fetch all records from the result set.fetchmany(int) : The fetchmany(int) is used to fetch the limited number of records from the result set based on the integer argument passed in it.fetchone() : The fetchone() is used to fetch one record from the top of the result set. fetchall() : The fetchall() is used to fetch all records from the result set. fetchmany(int) : The fetchmany(int) is used to fetch the limited number of records from the result set based on the integer argument passed in it. fetchone() : The fetchone() is used to fetch one record from the top of the result set. Python3 import cx_Oracle try: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is error in the Oracle database:', er) else: try: cur = con.cursor() cur.execute('select * from employee where salary > :sal', {'sal': 50000}) rows = cur.fetchall() print(rows) except cx_Oracle.DatabaseError as er: print('There is error in the Oracle database:', er) except Exception as er: print('Error:', er) finally: if cur: cur.close() finally: if con: con.close() Output: [(10001, 'Rahul', 50000.5), (10005, 'Sobhan', 60000.1), (10006, 'Gururaj', 70000.0), (10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)] In this case, I have passed a dictionary in execute() method. This dictionary contains the name of the bind variable as a key, and it’s corresponding value. When the SQL query is executed, value from the key is substituted in place of bind variable. sangram1992 python-input-output Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2021" }, { "code": null, "e": 369, "s": 54, "text": "Sometimes as part of programming, we required to work with the databases because we want to store a huge amount of information so we use databases, such as Oracle, MySQL, etc. So In this article, we will discuss the connectivity of Oracle database using Python. This can be done through the module name cx_Oracle. " }, { "code": null, "e": 517, "s": 369, "text": "Oracle Database For communicating with any database through our Python program we require some connector which is nothing but the cx_Oracle module." }, { "code": null, "e": 545, "s": 517, "text": "For installing cx-Oracle : " }, { "code": null, "e": 610, "s": 545, "text": "If you are using Python >= 3.6 use the below command in Linux: –" }, { "code": null, "e": 632, "s": 610, "text": "pip install cx-Oracle" }, { "code": null, "e": 699, "s": 632, "text": "If you are using Python >= 3.6 use the below command in Windows: –" }, { "code": null, "e": 727, "s": 699, "text": "py -m pip install cx-Oracle" }, { "code": null, "e": 843, "s": 727, "text": "By this command, you can install cx-Oracle package but it is required to install Oracle database first on your PC. " }, { "code": null, "e": 896, "s": 843, "text": "Import database specific module Ex. import cx_Oracle" }, { "code": null, "e": 1012, "s": 896, "text": "connect(): Now Establish a connection between the Python program and Oracle database by using connect() function. " }, { "code": null, "e": 1067, "s": 1012, "text": "con = cx_Oracle.connect('username/password@localhost')" }, { "code": null, "e": 1193, "s": 1067, "text": "cursor(): To execute a SQL query and to provide results some special object is required that is nothing but cursor() object. " }, { "code": null, "e": 1221, "s": 1193, "text": "cursor = cx_Oracle.cursor()" }, { "code": null, "e": 1251, "s": 1221, "text": "execute/executemany method : " }, { "code": null, "e": 1422, "s": 1251, "text": "cursor.execute(sqlquery) – – – -> to execute a single query. cursor.executemany(sqlqueries) – – – -> to execute a single query with multiple bind variables/place holders." }, { "code": null, "e": 1597, "s": 1422, "text": "commit(): For DML(Data Manipulation Language) queries that comprise operations like update, insert, delete. We need to commit() then only the result reflects in the database." }, { "code": null, "e": 1901, "s": 1597, "text": "fetchone(), fetchmany(int), fetchall():fetchone() : This method is used to fetch one single row from the top of the result set.fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it.fetchall() : This method is used to fetch all rows from the result set." }, { "code": null, "e": 2166, "s": 1901, "text": "fetchone() : This method is used to fetch one single row from the top of the result set.fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it.fetchall() : This method is used to fetch all rows from the result set." }, { "code": null, "e": 2255, "s": 2166, "text": "fetchone() : This method is used to fetch one single row from the top of the result set." }, { "code": null, "e": 2361, "s": 2255, "text": "fetchmany(int): This method is used to fetch a limited number of rows based on the argument passed in it." }, { "code": null, "e": 2433, "s": 2361, "text": "fetchall() : This method is used to fetch all rows from the result set." }, { "code": null, "e": 2499, "s": 2433, "text": "close(): After all done it is mandatory to close all operations. " }, { "code": null, "e": 2526, "s": 2499, "text": "cursor.close()\ncon.close()" }, { "code": null, "e": 2534, "s": 2526, "text": "Python3" }, { "code": "# importing moduleimport cx_Oracle # Create a table in Oracle databasetry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') print(con.version) # Now execute the sqlquery cursor = con.cursor() # Creating a table employee cursor.execute(\"create table employee(empid integer primary key, name varchar2(30), salary number(10, 2))\") print(\"Table Created successfully\") except cx_Oracle.DatabaseError as e: print(\"There is a problem with Oracle\", e) # by writing finally if any error occurs# then also we can close the all database operationfinally: if cursor: cursor.close() if con: con.close()", "e": 3180, "s": 2534, "text": null }, { "code": null, "e": 3189, "s": 3180, "text": "Output: " }, { "code": null, "e": 3216, "s": 3189, "text": "Table Created successfully" }, { "code": null, "e": 3376, "s": 3216, "text": "DDL statements don’t require to be committed. They are automatically committed. In the above program, I have used execute() method to execute an SQL statement." }, { "code": null, "e": 3384, "s": 3376, "text": "Python3" }, { "code": "# importing moduleimport cx_Oracle # Inserting a record into a table in Oracle databasetry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') cursor = con.cursor() #con.autocommit = True # Inserting a record into table employee cursor.execute('insert into employee values(10001,\\'Rahul\\',50000.50)') # commit() to make changes reflect in the database con.commit() print('Record inserted successfully') except cx_Oracle.DatabaseError as e: print(\"There is a problem with Oracle\", e) # by writing finally if any error occurs# then also we can close the all database operationfinally: if cursor: cursor.close() if con: con.close()", "e": 4072, "s": 3384, "text": null }, { "code": null, "e": 4081, "s": 4072, "text": "Output: " }, { "code": null, "e": 4110, "s": 4081, "text": "Record inserted successfully" }, { "code": null, "e": 4228, "s": 4110, "text": "Once we execute any DML statement it is required to commit the transaction. You can commit a transaction in 2 ways: –" }, { "code": null, "e": 4363, "s": 4228, "text": "con.commit(). This is used to commit a transaction manually.con.autocommit = True. This is used to commit a transaction automatically." }, { "code": null, "e": 4424, "s": 4363, "text": "con.commit(). This is used to commit a transaction manually." }, { "code": null, "e": 4499, "s": 4424, "text": "con.autocommit = True. This is used to commit a transaction automatically." }, { "code": null, "e": 4507, "s": 4499, "text": "Python3" }, { "code": "import cx_Oracle # Load data from a csv file into Oracle table using executemanytry: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is an error in Oracle database:', er) else: try: cur = con.cursor() data = [[10007, 'Vikram', 48000.0], [10008, 'Sunil', 65000.1], [10009, 'Sameer', 75000.0]] cur = con.cursor() # Inserting multiple records into employee table # (:1,:2,:3) are place holders. They pick data from a list supplied as argument cur.executemany('insert into employee values(:1,:2,:3)', data) except cx_Oracle.DatabaseError as er: print('There is an error in Oracle database:', er) except Exception as er: print(er) else: # To commit the transaction manually con.commit() print('Multiple records are inserted successfully') finally: if cur: cur.close() if con: con.close()", "e": 5469, "s": 4507, "text": null }, { "code": null, "e": 5479, "s": 5469, "text": "Output: " }, { "code": null, "e": 5522, "s": 5479, "text": "Multiple records are inserted successfully" }, { "code": null, "e": 5818, "s": 5522, "text": "There might be times when it is required to execute a SQL statement multiple times based on the different values supplied to it each time. This can be achieved using executemany() method. We supply a list containing a list of values that will replace placeholders in a SQL query to be executed. " }, { "code": null, "e": 5838, "s": 5818, "text": "From the above case" }, { "code": null, "e": 5871, "s": 5838, "text": ":1 is substituted by value 10007" }, { "code": null, "e": 5907, "s": 5871, "text": ":2 is substituted by value ‘Vikram’" }, { "code": null, "e": 5942, "s": 5907, "text": ":3 is substituted by value 48000.0" }, { "code": null, "e": 5989, "s": 5942, "text": "And so on(next list of values in a given list)" }, { "code": null, "e": 6116, "s": 5989, "text": "Similarly, you can supply a list of dictionaries. But instead of placeholder, we will use the bind variable( discussed later)." }, { "code": null, "e": 6124, "s": 6116, "text": "Python3" }, { "code": "import cx_Oracle try: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is an error in the Oracle database:', er) else: try: cur = con.cursor() # fetchall() is used to fetch all records from result set cur.execute('select * from employee') rows = cur.fetchall() print(rows) # fetchmany(int) is used to fetch limited number of records from result set based on integer argument passed in it cur.execute('select * from employee') rows = cur.fetchmany(3) print(rows) # fetchone() is used fetch one record from top of the result set cur.execute('select * from employee') rows = cur.fetchone() print(rows) except cx_Oracle.DatabaseError as er: print('There is an error in the Oracle database:', er) except Exception as er: print('Error:'+str(er)) finally: if cur: cur.close() finally: if con: con.close()", "e": 7138, "s": 6124, "text": null }, { "code": null, "e": 7146, "s": 7138, "text": "Output:" }, { "code": null, "e": 7509, "s": 7146, "text": "[(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003, 'Soumik', 30000.25), (10004, 'Sayan', 45000.0), (10005, 'Sobhan', 60000.1), (10006, 'Gururaj', 70000.0), (10007, 'Vikram', 48000.0), (10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)]\n[(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003, 'Soumik', 30000.25)]\n(10001, 'Rahul', 50000.5)" }, { "code": null, "e": 7555, "s": 7509, "text": "In the above program, we have used 3 methods " }, { "code": null, "e": 7866, "s": 7555, "text": "fetchall() : The fetchall() is used to fetch all records from the result set.fetchmany(int) : The fetchmany(int) is used to fetch the limited number of records from the result set based on the integer argument passed in it.fetchone() : The fetchone() is used to fetch one record from the top of the result set." }, { "code": null, "e": 7944, "s": 7866, "text": "fetchall() : The fetchall() is used to fetch all records from the result set." }, { "code": null, "e": 8091, "s": 7944, "text": "fetchmany(int) : The fetchmany(int) is used to fetch the limited number of records from the result set based on the integer argument passed in it." }, { "code": null, "e": 8179, "s": 8091, "text": "fetchone() : The fetchone() is used to fetch one record from the top of the result set." }, { "code": null, "e": 8187, "s": 8179, "text": "Python3" }, { "code": "import cx_Oracle try: con = cx_Oracle.connect('tiger/scott@localhost:1521/xe') except cx_Oracle.DatabaseError as er: print('There is error in the Oracle database:', er) else: try: cur = con.cursor() cur.execute('select * from employee where salary > :sal', {'sal': 50000}) rows = cur.fetchall() print(rows) except cx_Oracle.DatabaseError as er: print('There is error in the Oracle database:', er) except Exception as er: print('Error:', er) finally: if cur: cur.close() finally: if con: con.close()", "e": 8778, "s": 8187, "text": null }, { "code": null, "e": 8786, "s": 8778, "text": "Output:" }, { "code": null, "e": 8927, "s": 8786, "text": "[(10001, 'Rahul', 50000.5), (10005, 'Sobhan', 60000.1), (10006, 'Gururaj', 70000.0),\n (10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)]" }, { "code": null, "e": 9177, "s": 8927, "text": "In this case, I have passed a dictionary in execute() method. This dictionary contains the name of the bind variable as a key, and it’s corresponding value. When the SQL query is executed, value from the key is substituted in place of bind variable." }, { "code": null, "e": 9189, "s": 9177, "text": "sangram1992" }, { "code": null, "e": 9209, "s": 9189, "text": "python-input-output" }, { "code": null, "e": 9216, "s": 9209, "text": "Python" }, { "code": null, "e": 9314, "s": 9216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9356, "s": 9314, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 9378, "s": 9356, "text": "Enumerate() in Python" }, { "code": null, "e": 9404, "s": 9378, "text": "Python String | replace()" }, { "code": null, "e": 9436, "s": 9404, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 9465, "s": 9436, "text": "*args and **kwargs in Python" }, { "code": null, "e": 9492, "s": 9465, "text": "Python Classes and Objects" }, { "code": null, "e": 9513, "s": 9492, "text": "Python OOPs Concepts" }, { "code": null, "e": 9549, "s": 9513, "text": "Convert integer to string in Python" }, { "code": null, "e": 9572, "s": 9549, "text": "Introduction To PYTHON" } ]
Scala Map
07 Feb, 2019 Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly. Maps can be created in different ways based upon our requirement and nature of the Map. We have different syntax depending upon whether the Map is mutable or immutable. Syntax : // Immutable variable = Map(key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....) // Mutable variable = scala.collection.mutable.Map(key_1 -> value_1, key_2 -> value_2, key_3 -> value_3, ....) There are three basic operations we can carry out on a Map: keys: In Scala Map, This method returns an iterable containing each key in the map.values: Value method returns an iterable containing each value in the Scala map.isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Accessing Values Using KeysValues can be accessed using Map variable name and key.Example:// Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // Accessing score of Ajay val ajay = mapIm("Ajay") println(ajay) }} Output:30If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map. Therefore, it is recommended to use contains() function while accessing any value using key.This function checks for the key in the Map. If the key is present then it returns true, false otherwise.// Scala map program of // Accessing Values Using // Keys by contains() function // Creating objectobject GFG{ // Main methode def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // the key check in the Map val ajay = if(mapIm.contains("Ajay")) mapIm("Ajay") else 0 val john = if(mapIm.contains("John")) mapIm("John") else 0 println("Ajay:" + ajay) println("John:" + john) }} Output:Ajay:30 John:0 Updating the valuesIf we try to update value of an immutable Map, Scala outputs an error. On the other hand, any changes made in value of any key in case of mutable Maps is accepted.Example:Updating immutable Map:// Scala map program of // Updating the values// in immutable map // Creating an objectobject GFG{ // Main method def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println(mapIm) //Updating mapIm("Ajay") = 10 println(mapIm) }}Output:error: value update is not a member of scala.collection.immutable.Map[String, Int] Updating mutable Map:// Scala map program of // Updating the values// in mutable map // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Updating: " + mapMut) // Updating mapMut("Ajay") = 10 println("After Updating: " + mapMut) }}Output:Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20)Adding new key-value pairWe can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.Example:// Scala map program of // Adding new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Adding: "+mapMut) // Adding a new key "Dinesh" and // updating an existing key "Ajay" mapMut += ("Ajay" -> 10, "Dinesh" -> 60) println("After Adding: "+mapMut) }}Output:Before Adding: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Adding: Map(Ajay -> 10, Dinesh -> 60, Charlie -> 50, Bhavesh -> 20)Deleting a key-value pair:Deleting a key-value pair is similar to adding a new entry. The difference is instead of += we use -= operator followed by keys that are to be deleted.Example:// Scala map program of // Deleting new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Deleting: "+mapMut) // Deleting key-value pairs with // keys "Ajay" and "Charlie" mapMut -= ("Ajay", "Charlie") println("After Deleting: " + mapMut) }}Output:Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Deleting: Map(Bhavesh -> 20)Iteration in a MapKey-value pair corresponds to a tuple with two elements. Therefore, while performing iteration loop variable needs to be a pair.To understand syntax and working of loops in Scala refer : Loops|ScalaExample:// Scala map program of // Iteration in a Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // (k, v) is a tuple with two elements for((k, v) <- mapMut) { //where k is key and v is value print("Key:"+k+", ") println("Value:"+v) } }}Output:Key:Ajay, Value:30 Key:Charlie, Value:50 Key:Bhavesh, Value:20 Empty MapIn Scala Map, We can also create an empty Map and later add elements to it.Example:// Scala map program of // Empty Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creation of Map having key-value // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println("Empty Map: " + mapMut) // Adding new entry mapMut += ("Charlie" -> 50) println("New Entry: " + mapMut) }}Output:Empty Map: Map() New Entry: Map(Charlie -> 50)My Personal Notes arrow_drop_upSave keys: In Scala Map, This method returns an iterable containing each key in the map. values: Value method returns an iterable containing each value in the Scala map. isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Values can be accessed using Map variable name and key.Example: // Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // Accessing score of Ajay val ajay = mapIm("Ajay") println(ajay) }} Output: 30 If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map. Therefore, it is recommended to use contains() function while accessing any value using key.This function checks for the key in the Map. If the key is present then it returns true, false otherwise. // Scala map program of // Accessing Values Using // Keys by contains() function // Creating objectobject GFG{ // Main methode def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // the key check in the Map val ajay = if(mapIm.contains("Ajay")) mapIm("Ajay") else 0 val john = if(mapIm.contains("John")) mapIm("John") else 0 println("Ajay:" + ajay) println("John:" + john) }} Output: Ajay:30 John:0 If we try to update value of an immutable Map, Scala outputs an error. On the other hand, any changes made in value of any key in case of mutable Maps is accepted.Example:Updating immutable Map: // Scala map program of // Updating the values// in immutable map // Creating an objectobject GFG{ // Main method def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println(mapIm) //Updating mapIm("Ajay") = 10 println(mapIm) }} Output: error: value update is not a member of scala.collection.immutable.Map[String, Int] Updating mutable Map: // Scala map program of // Updating the values// in mutable map // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Updating: " + mapMut) // Updating mapMut("Ajay") = 10 println("After Updating: " + mapMut) }} Output: Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20) We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.Example: // Scala map program of // Adding new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Adding: "+mapMut) // Adding a new key "Dinesh" and // updating an existing key "Ajay" mapMut += ("Ajay" -> 10, "Dinesh" -> 60) println("After Adding: "+mapMut) }} Output: Before Adding: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Adding: Map(Ajay -> 10, Dinesh -> 60, Charlie -> 50, Bhavesh -> 20) Deleting a key-value pair is similar to adding a new entry. The difference is instead of += we use -= operator followed by keys that are to be deleted.Example: // Scala map program of // Deleting new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) println("Before Deleting: "+mapMut) // Deleting key-value pairs with // keys "Ajay" and "Charlie" mapMut -= ("Ajay", "Charlie") println("After Deleting: " + mapMut) }} Output: Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Deleting: Map(Bhavesh -> 20) Key-value pair corresponds to a tuple with two elements. Therefore, while performing iteration loop variable needs to be a pair.To understand syntax and working of loops in Scala refer : Loops|ScalaExample: // Scala map program of // Iteration in a Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // (k, v) is a tuple with two elements for((k, v) <- mapMut) { //where k is key and v is value print("Key:"+k+", ") println("Value:"+v) } }} Output: Key:Ajay, Value:30 Key:Charlie, Value:50 Key:Bhavesh, Value:20 In Scala Map, We can also create an empty Map and later add elements to it.Example: // Scala map program of // Empty Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creation of Map having key-value // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println("Empty Map: " + mapMut) // Adding new entry mapMut += ("Charlie" -> 50) println("New Entry: " + mapMut) }} Output: Empty Map: Map() New Entry: Map(Charlie -> 50) Scala Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. For Loop in Scala Scala | map() method Scala | flatMap Method String concatenation in Scala Scala | reduce() Function Type Casting in Scala Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example Enumeration in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2019" }, { "code": null, "e": 478, "s": 28, "text": "Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly." }, { "code": null, "e": 647, "s": 478, "text": "Maps can be created in different ways based upon our requirement and nature of the Map. We have different syntax depending upon whether the Map is mutable or immutable." }, { "code": null, "e": 656, "s": 647, "text": "Syntax :" }, { "code": null, "e": 858, "s": 656, "text": "// Immutable\nvariable = Map(key_1 -> value_1, key_2 -> value_2,\n key_3 -> value_3, ....)\n\n// Mutable\nvariable = scala.collection.mutable.Map(key_1 -> value_1, \nkey_2 -> value_2, key_3 -> value_3, ....)" }, { "code": null, "e": 920, "s": 860, "text": "There are three basic operations we can carry out on a Map:" }, { "code": null, "e": 7083, "s": 920, "text": "keys: In Scala Map, This method returns an iterable containing each key in the map.values: Value method returns an iterable containing each value in the Scala map.isEmpty: This Scala map method returns true if the map is empty otherwise this returns false. Accessing Values Using KeysValues can be accessed using Map variable name and key.Example:// Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // Accessing score of Ajay val ajay = mapIm(\"Ajay\") println(ajay) }} Output:30If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map. Therefore, it is recommended to use contains() function while accessing any value using key.This function checks for the key in the Map. If the key is present then it returns true, false otherwise.// Scala map program of // Accessing Values Using // Keys by contains() function // Creating objectobject GFG{ // Main methode def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // the key check in the Map val ajay = if(mapIm.contains(\"Ajay\")) mapIm(\"Ajay\") else 0 val john = if(mapIm.contains(\"John\")) mapIm(\"John\") else 0 println(\"Ajay:\" + ajay) println(\"John:\" + john) }} Output:Ajay:30 \nJohn:0 Updating the valuesIf we try to update value of an immutable Map, Scala outputs an error. On the other hand, any changes made in value of any key in case of mutable Maps is accepted.Example:Updating immutable Map:// Scala map program of // Updating the values// in immutable map // Creating an objectobject GFG{ // Main method def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(mapIm) //Updating mapIm(\"Ajay\") = 10 println(mapIm) }}Output:error: value update is not a member of scala.collection.immutable.Map[String, Int] Updating mutable Map:// Scala map program of // Updating the values// in mutable map // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Updating: \" + mapMut) // Updating mapMut(\"Ajay\") = 10 println(\"After Updating: \" + mapMut) }}Output:Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20)Adding new key-value pairWe can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.Example:// Scala map program of // Adding new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Adding: \"+mapMut) // Adding a new key \"Dinesh\" and // updating an existing key \"Ajay\" mapMut += (\"Ajay\" -> 10, \"Dinesh\" -> 60) println(\"After Adding: \"+mapMut) }}Output:Before Adding: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Adding: Map(Ajay -> 10, Dinesh -> 60, Charlie -> 50, Bhavesh -> 20)Deleting a key-value pair:Deleting a key-value pair is similar to adding a new entry. The difference is instead of += we use -= operator followed by keys that are to be deleted.Example:// Scala map program of // Deleting new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Deleting: \"+mapMut) // Deleting key-value pairs with // keys \"Ajay\" and \"Charlie\" mapMut -= (\"Ajay\", \"Charlie\") println(\"After Deleting: \" + mapMut) }}Output:Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Deleting: Map(Bhavesh -> 20)Iteration in a MapKey-value pair corresponds to a tuple with two elements. Therefore, while performing iteration loop variable needs to be a pair.To understand syntax and working of loops in Scala refer : Loops|ScalaExample:// Scala map program of // Iteration in a Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // (k, v) is a tuple with two elements for((k, v) <- mapMut) { //where k is key and v is value print(\"Key:\"+k+\", \") println(\"Value:\"+v) } }}Output:Key:Ajay, Value:30\nKey:Charlie, Value:50\nKey:Bhavesh, Value:20 Empty MapIn Scala Map, We can also create an empty Map and later add elements to it.Example:// Scala map program of // Empty Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creation of Map having key-value // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println(\"Empty Map: \" + mapMut) // Adding new entry mapMut += (\"Charlie\" -> 50) println(\"New Entry: \" + mapMut) }}Output:Empty Map: Map()\nNew Entry: Map(Charlie -> 50)My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7167, "s": 7083, "text": "keys: In Scala Map, This method returns an iterable containing each key in the map." }, { "code": null, "e": 7248, "s": 7167, "text": "values: Value method returns an iterable containing each value in the Scala map." }, { "code": null, "e": 7342, "s": 7248, "text": "isEmpty: This Scala map method returns true if the map is empty otherwise this returns false." }, { "code": null, "e": 7408, "s": 7344, "text": "Values can be accessed using Map variable name and key.Example:" }, { "code": "// Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // Accessing score of Ajay val ajay = mapIm(\"Ajay\") println(ajay) }} ", "e": 7767, "s": 7408, "text": null }, { "code": null, "e": 7775, "s": 7767, "text": "Output:" }, { "code": null, "e": 7778, "s": 7775, "text": "30" }, { "code": null, "e": 8098, "s": 7778, "text": "If we try to access value associated with the key “John”, we will get an error because no such key is present in the Map. Therefore, it is recommended to use contains() function while accessing any value using key.This function checks for the key in the Map. If the key is present then it returns true, false otherwise." }, { "code": "// Scala map program of // Accessing Values Using // Keys by contains() function // Creating objectobject GFG{ // Main methode def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // the key check in the Map val ajay = if(mapIm.contains(\"Ajay\")) mapIm(\"Ajay\") else 0 val john = if(mapIm.contains(\"John\")) mapIm(\"John\") else 0 println(\"Ajay:\" + ajay) println(\"John:\" + john) }} ", "e": 8709, "s": 8098, "text": null }, { "code": null, "e": 8717, "s": 8709, "text": "Output:" }, { "code": null, "e": 8733, "s": 8717, "text": "Ajay:30 \nJohn:0" }, { "code": null, "e": 8930, "s": 8735, "text": "If we try to update value of an immutable Map, Scala outputs an error. On the other hand, any changes made in value of any key in case of mutable Maps is accepted.Example:Updating immutable Map:" }, { "code": "// Scala map program of // Updating the values// in immutable map // Creating an objectobject GFG{ // Main method def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(mapIm) //Updating mapIm(\"Ajay\") = 10 println(mapIm) }}", "e": 9329, "s": 8930, "text": null }, { "code": null, "e": 9337, "s": 9329, "text": "Output:" }, { "code": null, "e": 9420, "s": 9337, "text": "error: value update is not a member of scala.collection.immutable.Map[String, Int]" }, { "code": null, "e": 9443, "s": 9420, "text": " Updating mutable Map:" }, { "code": "// Scala map program of // Updating the values// in mutable map // Creating Objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Updating: \" + mapMut) // Updating mapMut(\"Ajay\") = 10 println(\"After Updating: \" + mapMut) }}", "e": 9943, "s": 9443, "text": null }, { "code": null, "e": 9951, "s": 9943, "text": "Output:" }, { "code": null, "e": 10075, "s": 9951, "text": "Before Updating: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Updating: Map(Ajay -> 10, Charlie -> 50, Bhavesh -> 20)" }, { "code": null, "e": 10198, "s": 10075, "text": "We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.Example:" }, { "code": "// Scala map program of // Adding new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Adding: \"+mapMut) // Adding a new key \"Dinesh\" and // updating an existing key \"Ajay\" mapMut += (\"Ajay\" -> 10, \"Dinesh\" -> 60) println(\"After Adding: \"+mapMut) }}", "e": 10765, "s": 10198, "text": null }, { "code": null, "e": 10773, "s": 10765, "text": "Output:" }, { "code": null, "e": 10907, "s": 10773, "text": "Before Adding: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Adding: Map(Ajay -> 10, Dinesh -> 60, Charlie -> 50, Bhavesh -> 20)" }, { "code": null, "e": 11067, "s": 10907, "text": "Deleting a key-value pair is similar to adding a new entry. The difference is instead of += we use -= operator followed by keys that are to be deleted.Example:" }, { "code": "// Scala map program of // Deleting new key-value pair // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) println(\"Before Deleting: \"+mapMut) // Deleting key-value pairs with // keys \"Ajay\" and \"Charlie\" mapMut -= (\"Ajay\", \"Charlie\") println(\"After Deleting: \" + mapMut) }}", "e": 11623, "s": 11067, "text": null }, { "code": null, "e": 11631, "s": 11623, "text": "Output:" }, { "code": null, "e": 11728, "s": 11631, "text": "Before Deleting: Map(Ajay -> 30, Charlie -> 50, Bhavesh -> 20)After Deleting: Map(Bhavesh -> 20)" }, { "code": null, "e": 11935, "s": 11728, "text": "Key-value pair corresponds to a tuple with two elements. Therefore, while performing iteration loop variable needs to be a pair.To understand syntax and working of loops in Scala refer : Loops|ScalaExample:" }, { "code": "// Scala map program of // Iteration in a Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { val mapMut = scala.collection.mutable.Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // (k, v) is a tuple with two elements for((k, v) <- mapMut) { //where k is key and v is value print(\"Key:\"+k+\", \") println(\"Value:\"+v) } }}", "e": 12482, "s": 11935, "text": null }, { "code": null, "e": 12490, "s": 12482, "text": "Output:" }, { "code": null, "e": 12553, "s": 12490, "text": "Key:Ajay, Value:30\nKey:Charlie, Value:50\nKey:Bhavesh, Value:20" }, { "code": null, "e": 12639, "s": 12555, "text": "In Scala Map, We can also create an empty Map and later add elements to it.Example:" }, { "code": "// Scala map program of // Empty Map // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creation of Map having key-value // pairs of type (String, Int) val mapMut = scala.collection.mutable.Map[String, Int]() println(\"Empty Map: \" + mapMut) // Adding new entry mapMut += (\"Charlie\" -> 50) println(\"New Entry: \" + mapMut) }}", "e": 13069, "s": 12639, "text": null }, { "code": null, "e": 13077, "s": 13069, "text": "Output:" }, { "code": null, "e": 13124, "s": 13077, "text": "Empty Map: Map()\nNew Entry: Map(Charlie -> 50)" }, { "code": null, "e": 13130, "s": 13124, "text": "Scala" }, { "code": null, "e": 13136, "s": 13130, "text": "Scala" }, { "code": null, "e": 13234, "s": 13136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13252, "s": 13234, "text": "For Loop in Scala" }, { "code": null, "e": 13273, "s": 13252, "text": "Scala | map() method" }, { "code": null, "e": 13296, "s": 13273, "text": "Scala | flatMap Method" }, { "code": null, "e": 13326, "s": 13296, "text": "String concatenation in Scala" }, { "code": null, "e": 13352, "s": 13326, "text": "Scala | reduce() Function" }, { "code": null, "e": 13374, "s": 13352, "text": "Type Casting in Scala" }, { "code": null, "e": 13414, "s": 13374, "text": "Scala List filter() method with example" }, { "code": null, "e": 13467, "s": 13414, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 13512, "s": 13467, "text": "Scala String substring() method with example" } ]
Powers of 2 to required sum
26 May, 2022 Given an integer N, task is to find the numbers which when raised to the power of 2 and added finally, gives the integer N. Example : Input : 71307 Output : 0, 1, 3, 7, 9, 10, 12, 16 Explanation : 71307 = 2^0 + 2^1 + 2^3 + 2^7 + 2^9 + 2^10 + 2^12 + 2^16 Input : 1213 Output : 0, 2, 3, 4, 5, 7, 10 Explanation : 1213 = 2^0 + 2^2 + 2^3 + 2^4 + 2^5 + 2^7 + 2^10 Approach : Every number can be described in powers of 2. Example : 29 = 2^0 + 2^2 + 2^3 + 2^4.2^0 ( exponent of 2 is ‘0’) 0 2^2 ( exponent of 2 is ‘2’) 1 2^3 ( exponent of 2 is ‘3’) 3 2^4 ( exponent of 2 is ‘4’) 4Convert each number into its binary equivalent by pushing remainder of given number, when divided by 2 till it is greater than 0, to vector. Now, Iterate through its binary equivalent and whenever there is set bit, just print the i-th value(iteration number). Application : Hamming Code : Hamming Code is an error correcting code which can detect and correct one bit error. This pattern is also used in Hamming code error detection where parity bits store the XOR of numbers on the basis of LSB(Least Significant bit), where numbers are assigned in blocks and you need to find the blocks where the sum of power of 2 resulting to given number exists. Below is the image to show the blocks with given numbers. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Below is the implementation of above approach : C++ Java Python3 C# PHP Javascript // CPP program to find the// blocks for given number.#include <bits/stdc++.h>using namespace std; void block(long int x){ vector<long int> v; // Converting the decimal number // into its binary equivalent. cout << "Blocks for " << x << " : "; while (x > 0) { v.push_back(x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v[i] == 1) { cout << i; if (i != v.size() - 1) cout << ", "; } } cout << endl;} // Driver Functionint main(){ block(71307); block(1213); block(29); block(100); return 0;} // Java program to find the// blocks for given number.import java.util.*; class GFG { static void block(long x){ ArrayList<Integer> v = new ArrayList<Integer>(); // Convert decimal number to // its binary equivalent System.out.print("Blocks for "+x+" : "); while (x > 0) { v.add((int)x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v.get(i) == 1) { System.out.print(i); if (i != v.size() - 1) System.out.print( ", "); } }System.out.println();} // Driver Codepublic static void main(String args[]){ block(71307); block(1213); block(29); block(100);}} // This code is contributed by Arnab Kundu. # Python3 program to find the# blocks for given number.def block(x): v = [] # Converting the decimal number # into its binary equivalent. print ("Blocks for %d : " %x, end="") while (x > 0): v.append(int(x % 2)) x = int(x / 2) # Displaying the output when # the bit is '1' in binary # equivalent of number. for i in range(0, len(v)): if (v[i] == 1): print (i, end = "") if (i != len(v) - 1): print (", ", end = "") print ("\n") block(71307)block(1213)block(29)block(100) # This code is contributed by Manish# Shaw (manishshaw1) // C# program to find the// blocks for given number.using System;using System.Collections.Generic; class GFG { static void block(long x) { List<int> v = new List<int>(); // Convert decimal number to // its binary equivalent Console.Write("Blocks for " + x + " : "); while (x > 0) { v.Add((int)x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.Count; i++) { if (v[i] == 1) { Console.Write(i); if (i != v.Count - 1) Console.Write(", "); } } Console.WriteLine(); } // Driver Code here public static void Main() { block(71307); block(1213); block(29); block(100); }} // This code is contributed by Ajit. <?php// PHP program to find the// blocks for given number. function block($x){ $v = array(); // Convert decimal number to // its binary equivalent echo 'Blocks for ' .$x.' : '; while ($x > 0) { array_push($v,intval($x % 2)); $x = intval($x / 2); } // Displaying the output when // the bit is '1' in binary // equivalent of number. for ($i = 0; $i < sizeof($v); $i++) { if ($v[$i] == 1) { print $i; if ($i != sizeof($v) - 1) echo ', '; } } echo "\n";} // Driver Codeblock(71307);block(1213);block(29);block(100); // This code is contributed// by Manish Shaw (manishshaw1)?> <script> // Javascript program to find the// blocks for given number.function block(x){ let v = []; // Convert decimal number to // its binary equivalent document.write("Blocks for " + x + " : "); while (x > 0) { v.push(x % 2); x = parseInt(x / 2, 10); } // Displaying the output when // the bit is '1' in binary // equivalent of number. for(let i = 0; i < v.length; i++) { if (v[i] == 1) { document.write(i); if (i != v.length - 1) document.write(", "); } } document.write("</br>");} // Driver codeblock(71307);block(1213);block(29);block(100); // This code is contributed by mukesh07 </script> Blocks for 71307 : 0, 1, 3, 7, 9, 10, 12, 16 Blocks for 1213 : 0, 2, 3, 4, 5, 7, 10 Blocks for 29 : 0, 2, 3, 4 Blocks for 100 : 2, 5, 6 Time Complexity: O(log2n) Auxiliary Space: O(log2n) Powers of 2 to required sum | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPowers of 2 to required sum | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XMrV93KSgKk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> andrew1234 jit_t manishshaw1 saumyaagnihotri mukesh07 ranjanrohit840 Bit Algorithms cpp-vector Bit Magic Mathematical Technical Scripter Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Bit Fields in C Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2022" }, { "code": null, "e": 178, "s": 54, "text": "Given an integer N, task is to find the numbers which when raised to the power of 2 and added finally, gives the integer N." }, { "code": null, "e": 189, "s": 178, "text": "Example : " }, { "code": null, "e": 432, "s": 189, "text": "Input : 71307\nOutput : 0, 1, 3, 7, 9, 10, 12, 16\nExplanation :\n71307 = 2^0 + 2^1 + 2^3 + 2^7 +\n 2^9 + 2^10 + 2^12 + 2^16\n\nInput : 1213\nOutput : 0, 2, 3, 4, 5, 7, 10\nExplanation : \n1213 = 2^0 + 2^2 + 2^3 + 2^4 + \n 2^5 + 2^7 + 2^10" }, { "code": null, "e": 906, "s": 432, "text": "Approach : Every number can be described in powers of 2. Example : 29 = 2^0 + 2^2 + 2^3 + 2^4.2^0 ( exponent of 2 is ‘0’) 0 2^2 ( exponent of 2 is ‘2’) 1 2^3 ( exponent of 2 is ‘3’) 3 2^4 ( exponent of 2 is ‘4’) 4Convert each number into its binary equivalent by pushing remainder of given number, when divided by 2 till it is greater than 0, to vector. Now, Iterate through its binary equivalent and whenever there is set bit, just print the i-th value(iteration number). " }, { "code": null, "e": 1296, "s": 906, "text": "Application : Hamming Code : Hamming Code is an error correcting code which can detect and correct one bit error. This pattern is also used in Hamming code error detection where parity bits store the XOR of numbers on the basis of LSB(Least Significant bit), where numbers are assigned in blocks and you need to find the blocks where the sum of power of 2 resulting to given number exists." }, { "code": null, "e": 1356, "s": 1296, "text": "Below is the image to show the blocks with given numbers. " }, { "code": null, "e": 1365, "s": 1356, "text": "Chapters" }, { "code": null, "e": 1392, "s": 1365, "text": "descriptions off, selected" }, { "code": null, "e": 1442, "s": 1392, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1465, "s": 1442, "text": "captions off, selected" }, { "code": null, "e": 1473, "s": 1465, "text": "English" }, { "code": null, "e": 1491, "s": 1473, "text": "default, selected" }, { "code": null, "e": 1515, "s": 1491, "text": "This is a modal window." }, { "code": null, "e": 1584, "s": 1515, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1606, "s": 1584, "text": "End of dialog window." }, { "code": null, "e": 1655, "s": 1606, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 1659, "s": 1655, "text": "C++" }, { "code": null, "e": 1664, "s": 1659, "text": "Java" }, { "code": null, "e": 1672, "s": 1664, "text": "Python3" }, { "code": null, "e": 1675, "s": 1672, "text": "C#" }, { "code": null, "e": 1679, "s": 1675, "text": "PHP" }, { "code": null, "e": 1690, "s": 1679, "text": "Javascript" }, { "code": "// CPP program to find the// blocks for given number.#include <bits/stdc++.h>using namespace std; void block(long int x){ vector<long int> v; // Converting the decimal number // into its binary equivalent. cout << \"Blocks for \" << x << \" : \"; while (x > 0) { v.push_back(x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v[i] == 1) { cout << i; if (i != v.size() - 1) cout << \", \"; } } cout << endl;} // Driver Functionint main(){ block(71307); block(1213); block(29); block(100); return 0;}", "e": 2412, "s": 1690, "text": null }, { "code": "// Java program to find the// blocks for given number.import java.util.*; class GFG { static void block(long x){ ArrayList<Integer> v = new ArrayList<Integer>(); // Convert decimal number to // its binary equivalent System.out.print(\"Blocks for \"+x+\" : \"); while (x > 0) { v.add((int)x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.size(); i++) { if (v.get(i) == 1) { System.out.print(i); if (i != v.size() - 1) System.out.print( \", \"); } }System.out.println();} // Driver Codepublic static void main(String args[]){ block(71307); block(1213); block(29); block(100);}} // This code is contributed by Arnab Kundu.", "e": 3224, "s": 2412, "text": null }, { "code": "# Python3 program to find the# blocks for given number.def block(x): v = [] # Converting the decimal number # into its binary equivalent. print (\"Blocks for %d : \" %x, end=\"\") while (x > 0): v.append(int(x % 2)) x = int(x / 2) # Displaying the output when # the bit is '1' in binary # equivalent of number. for i in range(0, len(v)): if (v[i] == 1): print (i, end = \"\") if (i != len(v) - 1): print (\", \", end = \"\") print (\"\\n\") block(71307)block(1213)block(29)block(100) # This code is contributed by Manish# Shaw (manishshaw1)", "e": 3851, "s": 3224, "text": null }, { "code": "// C# program to find the// blocks for given number.using System;using System.Collections.Generic; class GFG { static void block(long x) { List<int> v = new List<int>(); // Convert decimal number to // its binary equivalent Console.Write(\"Blocks for \" + x + \" : \"); while (x > 0) { v.Add((int)x % 2); x = x / 2; } // Displaying the output when // the bit is '1' in binary // equivalent of number. for (int i = 0; i < v.Count; i++) { if (v[i] == 1) { Console.Write(i); if (i != v.Count - 1) Console.Write(\", \"); } } Console.WriteLine(); } // Driver Code here public static void Main() { block(71307); block(1213); block(29); block(100); }} // This code is contributed by Ajit.", "e": 4825, "s": 3851, "text": null }, { "code": "<?php// PHP program to find the// blocks for given number. function block($x){ $v = array(); // Convert decimal number to // its binary equivalent echo 'Blocks for ' .$x.' : '; while ($x > 0) { array_push($v,intval($x % 2)); $x = intval($x / 2); } // Displaying the output when // the bit is '1' in binary // equivalent of number. for ($i = 0; $i < sizeof($v); $i++) { if ($v[$i] == 1) { print $i; if ($i != sizeof($v) - 1) echo ', '; } } echo \"\\n\";} // Driver Codeblock(71307);block(1213);block(29);block(100); // This code is contributed// by Manish Shaw (manishshaw1)?>", "e": 5533, "s": 4825, "text": null }, { "code": "<script> // Javascript program to find the// blocks for given number.function block(x){ let v = []; // Convert decimal number to // its binary equivalent document.write(\"Blocks for \" + x + \" : \"); while (x > 0) { v.push(x % 2); x = parseInt(x / 2, 10); } // Displaying the output when // the bit is '1' in binary // equivalent of number. for(let i = 0; i < v.length; i++) { if (v[i] == 1) { document.write(i); if (i != v.length - 1) document.write(\", \"); } } document.write(\"</br>\");} // Driver codeblock(71307);block(1213);block(29);block(100); // This code is contributed by mukesh07 </script>", "e": 6271, "s": 5533, "text": null }, { "code": null, "e": 6407, "s": 6271, "text": "Blocks for 71307 : 0, 1, 3, 7, 9, 10, 12, 16\nBlocks for 1213 : 0, 2, 3, 4, 5, 7, 10\nBlocks for 29 : 0, 2, 3, 4\nBlocks for 100 : 2, 5, 6" }, { "code": null, "e": 6435, "s": 6409, "text": "Time Complexity: O(log2n)" }, { "code": null, "e": 6461, "s": 6435, "text": "Auxiliary Space: O(log2n)" }, { "code": null, "e": 7333, "s": 6461, "text": "Powers of 2 to required sum | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPowers of 2 to required sum | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=XMrV93KSgKk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7344, "s": 7333, "text": "andrew1234" }, { "code": null, "e": 7350, "s": 7344, "text": "jit_t" }, { "code": null, "e": 7362, "s": 7350, "text": "manishshaw1" }, { "code": null, "e": 7378, "s": 7362, "text": "saumyaagnihotri" }, { "code": null, "e": 7387, "s": 7378, "text": "mukesh07" }, { "code": null, "e": 7402, "s": 7387, "text": "ranjanrohit840" }, { "code": null, "e": 7417, "s": 7402, "text": "Bit Algorithms" }, { "code": null, "e": 7428, "s": 7417, "text": "cpp-vector" }, { "code": null, "e": 7438, "s": 7428, "text": "Bit Magic" }, { "code": null, "e": 7451, "s": 7438, "text": "Mathematical" }, { "code": null, "e": 7470, "s": 7451, "text": "Technical Scripter" }, { "code": null, "e": 7483, "s": 7470, "text": "Mathematical" }, { "code": null, "e": 7493, "s": 7483, "text": "Bit Magic" }, { "code": null, "e": 7591, "s": 7493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7621, "s": 7591, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 7659, "s": 7621, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 7699, "s": 7659, "text": "Binary representation of a given number" }, { "code": null, "e": 7742, "s": 7699, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 7758, "s": 7742, "text": "Bit Fields in C" }, { "code": null, "e": 7788, "s": 7758, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7831, "s": 7788, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7891, "s": 7831, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7906, "s": 7891, "text": "C++ Data Types" } ]
Python | Split a sentence into list of words
01 Sep, 2021 Given a Sentence, write a Python program to convert the given sentence into list of words. Examples: Input : ['Hello World'] Output : ['Hello', 'world'] Input : ['Geeks For geeks'] Output : ['Geeks', 'for', 'geeks'] The simplest approach provided by Python to convert the given list of Sentence into words with separate indices is to use split() method. This method split a string into a list where each word is a list item. We have alternative ways to use this function in order to achieve the required output. Method #1 : Splitting the first index element Python3 # Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return (lst[0].split()) # Driver codelst = ["Geeks For geeks"]print( convert(lst)) ['Geeks', 'For', 'geeks'] Method #2 : Using for loop We can also use a for loop to split the first element. This method is also beneficial if we have more than one element. Python3 # Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return ([i for item in lst for i in item.split()]) # Driver codelst = ['Geeksforgeeks is a portal for geeks']print( convert(lst)) ['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks'] Method #3 : Using join() We can split the given list and than join using join() function. We can also use this when you have a list of string or single string inside a list. Python3 # Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return ' '.join(lst).split() # Driver codelst = ['Hello Geeks for geeks']print( convert(lst)) ['Hello', 'Geeks', 'for', 'geeks'] varshagumber28 akshaysingh98088 Python list-programs python-list Python Python Programs python-list 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Sep, 2021" }, { "code": null, "e": 146, "s": 54, "text": "Given a Sentence, write a Python program to convert the given sentence into list of words. " }, { "code": null, "e": 157, "s": 146, "text": "Examples: " }, { "code": null, "e": 273, "s": 157, "text": "Input : ['Hello World']\nOutput : ['Hello', 'world']\n\nInput : ['Geeks For geeks']\nOutput : ['Geeks', 'for', 'geeks']" }, { "code": null, "e": 569, "s": 273, "text": "The simplest approach provided by Python to convert the given list of Sentence into words with separate indices is to use split() method. This method split a string into a list where each word is a list item. We have alternative ways to use this function in order to achieve the required output." }, { "code": null, "e": 616, "s": 569, "text": "Method #1 : Splitting the first index element " }, { "code": null, "e": 624, "s": 616, "text": "Python3" }, { "code": "# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return (lst[0].split()) # Driver codelst = [\"Geeks For geeks\"]print( convert(lst))", "e": 806, "s": 624, "text": null }, { "code": null, "e": 832, "s": 806, "text": "['Geeks', 'For', 'geeks']" }, { "code": null, "e": 983, "s": 834, "text": "Method #2 : Using for loop We can also use a for loop to split the first element. This method is also beneficial if we have more than one element. " }, { "code": null, "e": 991, "s": 983, "text": "Python3" }, { "code": "# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return ([i for item in lst for i in item.split()]) # Driver codelst = ['Geeksforgeeks is a portal for geeks']print( convert(lst))", "e": 1224, "s": 991, "text": null }, { "code": null, "e": 1279, "s": 1224, "text": "['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks']" }, { "code": null, "e": 1457, "s": 1281, "text": "Method #3 : Using join() We can split the given list and than join using join() function. We can also use this when you have a list of string or single string inside a list. " }, { "code": null, "e": 1465, "s": 1457, "text": "Python3" }, { "code": "# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst): return ' '.join(lst).split() # Driver codelst = ['Hello Geeks for geeks']print( convert(lst))", "e": 1663, "s": 1465, "text": null }, { "code": null, "e": 1698, "s": 1663, "text": "['Hello', 'Geeks', 'for', 'geeks']" }, { "code": null, "e": 1715, "s": 1700, "text": "varshagumber28" }, { "code": null, "e": 1732, "s": 1715, "text": "akshaysingh98088" }, { "code": null, "e": 1753, "s": 1732, "text": "Python list-programs" }, { "code": null, "e": 1765, "s": 1753, "text": "python-list" }, { "code": null, "e": 1772, "s": 1765, "text": "Python" }, { "code": null, "e": 1788, "s": 1772, "text": "Python Programs" }, { "code": null, "e": 1800, "s": 1788, "text": "python-list" }, { "code": null, "e": 1898, "s": 1800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1940, "s": 1898, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1962, "s": 1940, "text": "Enumerate() in Python" }, { "code": null, "e": 1988, "s": 1962, "text": "Python String | replace()" }, { "code": null, "e": 2020, "s": 1988, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2049, "s": 2020, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2071, "s": 2049, "text": "Defaultdict in Python" }, { "code": null, "e": 2110, "s": 2071, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2148, "s": 2110, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2185, "s": 2148, "text": "Python Program for Fibonacci numbers" } ]
Python – Append Similar Values as Key
08 May, 2020 Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be problem in counting data. Like counting votes or counting coins. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loopThis is brute way in which this task can be performed. In this, we run a loop to add values to dictionary value list, if not present we dynamically create key and perform append. # Python3 code to demonstrate working of # Append Similar Values as Key# Using loop # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet'] # printing original listprint("The original list is : " + str(test_list)) # Append Similar Values as Key# Using loopres = dict()for ele in test_list: try: res[ele].append(ele) except KeyError: res[ele] = [ele] # printing result print("The similar values dictionary is : " + str(res)) The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]} Method #2 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we pre initialize the dictionary using defaultdict(). # Python3 code to demonstrate working of # Append Similar Values as Key# Using defaultdict() + loopfrom collections import defaultdict # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet'] # printing original listprint("The original list is : " + str(test_list)) # Append Similar Values as Key# Using defaultdict() + loopres = defaultdict(list)for sub in test_list: res[sub].append(sub) # printing result print("The similar values dictionary is : " + str(dict(res))) The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]} 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": "\n08 May, 2020" }, { "code": null, "e": 303, "s": 28, "text": "Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be problem in counting data. Like counting votes or counting coins. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 504, "s": 303, "text": "Method #1 : Using loopThis is brute way in which this task can be performed. In this, we run a loop to add values to dictionary value list, if not present we dynamically create key and perform append." }, { "code": "# Python3 code to demonstrate working of # Append Similar Values as Key# Using loop # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet'] # printing original listprint(\"The original list is : \" + str(test_list)) # Append Similar Values as Key# Using loopres = dict()for ele in test_list: try: res[ele].append(ele) except KeyError: res[ele] = [ele] # printing result print(\"The similar values dictionary is : \" + str(res)) ", "e": 1022, "s": 504, "text": null }, { "code": null, "e": 1291, "s": 1022, "text": "The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}" }, { "code": null, "e": 1464, "s": 1293, "text": "Method #2 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we pre initialize the dictionary using defaultdict()." }, { "code": "# Python3 code to demonstrate working of # Append Similar Values as Key# Using defaultdict() + loopfrom collections import defaultdict # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash', 'Manjeet', 'Akash', 'Akshat', 'Manjeet'] # printing original listprint(\"The original list is : \" + str(test_list)) # Append Similar Values as Key# Using defaultdict() + loopres = defaultdict(list)for sub in test_list: res[sub].append(sub) # printing result print(\"The similar values dictionary is : \" + str(dict(res))) ", "e": 2007, "s": 1464, "text": null }, { "code": null, "e": 2276, "s": 2007, "text": "The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}" }, { "code": null, "e": 2297, "s": 2276, "text": "Python list-programs" }, { "code": null, "e": 2304, "s": 2297, "text": "Python" }, { "code": null, "e": 2320, "s": 2304, "text": "Python Programs" }, { "code": null, "e": 2418, "s": 2320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2460, "s": 2418, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2482, "s": 2460, "text": "Enumerate() in Python" }, { "code": null, "e": 2508, "s": 2482, "text": "Python String | replace()" }, { "code": null, "e": 2540, "s": 2508, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2569, "s": 2540, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2612, "s": 2569, "text": "Python program to convert a list to string" }, { "code": null, "e": 2634, "s": 2612, "text": "Defaultdict in Python" }, { "code": null, "e": 2673, "s": 2634, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2711, "s": 2673, "text": "Python | Convert a list to dictionary" } ]
Java Swing | Simple Calculator
16 Apr, 2021 Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (Abstract Window Toolkit).In this article we will use Java Swing components to create a simple calculator with only +, -, /, * operations.methods used : add(Component c) : adds component to container.addActionListenerListener(ActionListener d) : add actionListener for specified componentsetBackground(Color c) : sets the background color of the specified containersetSize(int a, int b) : sets the size of container to specified dimensions.setText(String s) : sets the text of the label to s.getText() : returns the text of the label. add(Component c) : adds component to container. addActionListenerListener(ActionListener d) : add actionListener for specified component setBackground(Color c) : sets the background color of the specified container setSize(int a, int b) : sets the size of container to specified dimensions. setText(String s) : sets the text of the label to s. getText() : returns the text of the label. Java program to create a simple calculator with basic +, -, /, * using java swing elements. Java // Java program to create a simple calculator// with basic +, -, /, * using java swing elements import java.awt.event.*;import javax.swing.*;import java.awt.*;class calculator extends JFrame implements ActionListener { // create a frame static JFrame f; // create a textfield static JTextField l; // store operator and operands String s0, s1, s2; // default constructor calculator() { s0 = s1 = s2 = ""; } // main function public static void main(String args[]) { // create a frame f = new JFrame("calculator"); try { // set look and feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e.getMessage()); } // create a object of class calculator c = new calculator(); // create a textfield l = new JTextField(16); // set the textfield to non editable l.setEditable(false); // create number buttons and some operators JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1; // create number buttons b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); // equals button beq1 = new JButton("="); // create operator buttons ba = new JButton("+"); bs = new JButton("-"); bd = new JButton("/"); bm = new JButton("*"); beq = new JButton("C"); // create . button be = new JButton("."); // create a panel JPanel p = new JPanel(); // add action listeners bm.addActionListener(c); bd.addActionListener(c); bs.addActionListener(c); ba.addActionListener(c); b9.addActionListener(c); b8.addActionListener(c); b7.addActionListener(c); b6.addActionListener(c); b5.addActionListener(c); b4.addActionListener(c); b3.addActionListener(c); b2.addActionListener(c); b1.addActionListener(c); b0.addActionListener(c); be.addActionListener(c); beq.addActionListener(c); beq1.addActionListener(c); // add elements to panel p.add(l); p.add(ba); p.add(b1); p.add(b2); p.add(b3); p.add(bs); p.add(b4); p.add(b5); p.add(b6); p.add(bm); p.add(b7); p.add(b8); p.add(b9); p.add(bd); p.add(be); p.add(b0); p.add(beq); p.add(beq1); // set Background of panel p.setBackground(Color.blue); // add panel to frame f.add(p); f.setSize(200, 220); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); // if the value is a number if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') { // if operand is present then add to second no if (!s1.equals("")) s2 = s2 + s; else s0 = s0 + s; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == 'C') { // clear the one letter s0 = s1 = s2 = ""; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == '=') { double te; // store the value in 1st if (s1.equals("+")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals("-")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals("/")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // set the value of text l.setText(s0 + s1 + s2 + "=" + te); // convert it to string s0 = Double.toString(te); s1 = s2 = ""; } else { // if there was no operand if (s1.equals("") || s2.equals("")) s1 = s; // else evaluate else { double te; // store the value in 1st if (s1.equals("+")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals("-")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals("/")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // convert it to string s0 = Double.toString(te); // place the operator s1 = s; // make the operand blank s2 = ""; } // set the value of text l.setText(s0 + s1 + s2); } }} Output : Note : this program might not run in an online compiler please use an offline IDE. sweetyty java-swing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Apr, 2021" }, { "code": null, "e": 507, "s": 54, "text": "Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (Abstract Window Toolkit).In this article we will use Java Swing components to create a simple calculator with only +, -, /, * operations.methods used : " }, { "code": null, "e": 889, "s": 507, "text": "add(Component c) : adds component to container.addActionListenerListener(ActionListener d) : add actionListener for specified componentsetBackground(Color c) : sets the background color of the specified containersetSize(int a, int b) : sets the size of container to specified dimensions.setText(String s) : sets the text of the label to s.getText() : returns the text of the label." }, { "code": null, "e": 937, "s": 889, "text": "add(Component c) : adds component to container." }, { "code": null, "e": 1026, "s": 937, "text": "addActionListenerListener(ActionListener d) : add actionListener for specified component" }, { "code": null, "e": 1104, "s": 1026, "text": "setBackground(Color c) : sets the background color of the specified container" }, { "code": null, "e": 1180, "s": 1104, "text": "setSize(int a, int b) : sets the size of container to specified dimensions." }, { "code": null, "e": 1233, "s": 1180, "text": "setText(String s) : sets the text of the label to s." }, { "code": null, "e": 1276, "s": 1233, "text": "getText() : returns the text of the label." }, { "code": null, "e": 1370, "s": 1276, "text": "Java program to create a simple calculator with basic +, -, /, * using java swing elements. " }, { "code": null, "e": 1375, "s": 1370, "text": "Java" }, { "code": "// Java program to create a simple calculator// with basic +, -, /, * using java swing elements import java.awt.event.*;import javax.swing.*;import java.awt.*;class calculator extends JFrame implements ActionListener { // create a frame static JFrame f; // create a textfield static JTextField l; // store operator and operands String s0, s1, s2; // default constructor calculator() { s0 = s1 = s2 = \"\"; } // main function public static void main(String args[]) { // create a frame f = new JFrame(\"calculator\"); try { // set look and feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e.getMessage()); } // create a object of class calculator c = new calculator(); // create a textfield l = new JTextField(16); // set the textfield to non editable l.setEditable(false); // create number buttons and some operators JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1; // create number buttons b0 = new JButton(\"0\"); b1 = new JButton(\"1\"); b2 = new JButton(\"2\"); b3 = new JButton(\"3\"); b4 = new JButton(\"4\"); b5 = new JButton(\"5\"); b6 = new JButton(\"6\"); b7 = new JButton(\"7\"); b8 = new JButton(\"8\"); b9 = new JButton(\"9\"); // equals button beq1 = new JButton(\"=\"); // create operator buttons ba = new JButton(\"+\"); bs = new JButton(\"-\"); bd = new JButton(\"/\"); bm = new JButton(\"*\"); beq = new JButton(\"C\"); // create . button be = new JButton(\".\"); // create a panel JPanel p = new JPanel(); // add action listeners bm.addActionListener(c); bd.addActionListener(c); bs.addActionListener(c); ba.addActionListener(c); b9.addActionListener(c); b8.addActionListener(c); b7.addActionListener(c); b6.addActionListener(c); b5.addActionListener(c); b4.addActionListener(c); b3.addActionListener(c); b2.addActionListener(c); b1.addActionListener(c); b0.addActionListener(c); be.addActionListener(c); beq.addActionListener(c); beq1.addActionListener(c); // add elements to panel p.add(l); p.add(ba); p.add(b1); p.add(b2); p.add(b3); p.add(bs); p.add(b4); p.add(b5); p.add(b6); p.add(bm); p.add(b7); p.add(b8); p.add(b9); p.add(bd); p.add(be); p.add(b0); p.add(beq); p.add(beq1); // set Background of panel p.setBackground(Color.blue); // add panel to frame f.add(p); f.setSize(200, 220); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); // if the value is a number if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') { // if operand is present then add to second no if (!s1.equals(\"\")) s2 = s2 + s; else s0 = s0 + s; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == 'C') { // clear the one letter s0 = s1 = s2 = \"\"; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == '=') { double te; // store the value in 1st if (s1.equals(\"+\")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals(\"-\")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals(\"/\")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // set the value of text l.setText(s0 + s1 + s2 + \"=\" + te); // convert it to string s0 = Double.toString(te); s1 = s2 = \"\"; } else { // if there was no operand if (s1.equals(\"\") || s2.equals(\"\")) s1 = s; // else evaluate else { double te; // store the value in 1st if (s1.equals(\"+\")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals(\"-\")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals(\"/\")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // convert it to string s0 = Double.toString(te); // place the operator s1 = s; // make the operand blank s2 = \"\"; } // set the value of text l.setText(s0 + s1 + s2); } }}", "e": 6626, "s": 1375, "text": null }, { "code": null, "e": 6637, "s": 6626, "text": "Output : " }, { "code": null, "e": 6723, "s": 6639, "text": "Note : this program might not run in an online compiler please use an offline IDE. " }, { "code": null, "e": 6732, "s": 6723, "text": "sweetyty" }, { "code": null, "e": 6743, "s": 6732, "text": "java-swing" }, { "code": null, "e": 6748, "s": 6743, "text": "Java" }, { "code": null, "e": 6753, "s": 6748, "text": "Java" } ]
Menu driven program for all operations on singly linked list in C
03 Jul, 2022 A Linked List is a linear data structure that consists of two parts: one is the data part and the other is the address part. In this article, all the common operations of a singly linked list is discussed in one menu-driven program. Operations to be performed: createList(): To create the list with ‘n’ number of nodes initially as defined by the user. traverse(): To see the contents of the linked list, it is necessary to traverse the given linked list. The given traverse() function traverses and prints the content of the linked list. insertAtFront(): This function simply inserts an element at the front/beginning of the linked list. insertAtEnd(): This function inserts an element at the end of the linked list. insertAtPosition(): This function inserts an element at a specified position in the linked list. deleteFirst(): This function simply deletes an element from the front/beginning of the linked list. deleteEnd(): This function simply deletes an element from the end of the linked list. deletePosition(): This function deletes an element from a specified position in the linked list. maximum(): This function finds the maximum element in a linked list. mean(): This function finds the mean of the elements in a linked list. sort(): This function sort the given linked list in ascending order. reverseLL(): This function reverses the given linked list. Below is the implementation of the above operations: C // C program for the all operations in// the Singly Linked List#include <stdio.h>#include <stdlib.h>// Linked List Nodestruct node { int info; struct node* link;};struct node* start = NULL; // Function to create list with n nodes initially void createList(){ if (start == NULL) { int n; printf("\nEnter the number of nodes: "); scanf("%d", &n); if (n != 0) { int data; struct node* newnode; struct node* temp; newnode = malloc(sizeof(struct node)); start = newnode; temp = start; printf("\nEnter number to" " be inserted : "); scanf("%d", &data); start->info = data; for (int i = 2; i <= n; i++) { newnode = malloc(sizeof(struct node)); temp->link = newnode; printf("\nEnter number to" " be inserted : "); scanf("%d", &data); newnode->info = data; temp = temp->link; } } printf("\nThe list is created\n"); } else printf("\nThe list is already created\n");} // Function to traverse the linked listvoid traverse(){ struct node* temp; // List is empty if (start == NULL) printf("\nList is empty\n"); // Else print the LL else { temp = start; while (temp != NULL) { printf("Data = %d\n", temp->info); temp = temp->link; } }} // Function to insert at the front// of the linked listvoid insertAtFront(){ int data; struct node* temp; temp = malloc(sizeof(struct node)); printf("\nEnter number to" " be inserted : "); scanf("%d", &data); temp->info = data; // Pointer of temp will be // assigned to start temp->link = start; start = temp;} // Function to insert at the end of// the linked listvoid insertAtEnd(){ int data; struct node *temp, *head; temp = malloc(sizeof(struct node)); // Enter the number printf("\nEnter number to" " be inserted : "); scanf("%d", &data); // Changes links temp->link = 0; temp->info = data; head = start; while (head->link != NULL) { head = head->link; } head->link = temp;} // Function to insert at any specified// position in the linked listvoid insertAtPosition(){ struct node *temp, *newnode; int pos, data, i = 1; newnode = malloc(sizeof(struct node)); // Enter the position and data printf("\nEnter position and data :"); scanf("%d %d", &pos, &data); // Change Links temp = start; newnode->info = data; newnode->link = 0; while (i < pos - 1) { temp = temp->link; i++; } newnode->link = temp->link; temp->link = newnode;} // Function to delete from the front// of the linked listvoid deleteFirst(){ struct node* temp; if (start == NULL) printf("\nList is empty\n"); else { temp = start; start = start->link; free(temp); }} // Function to delete from the end// of the linked listvoid deleteEnd(){ struct node *temp, *prevnode; if (start == NULL) printf("\nList is Empty\n"); else { temp = start; while (temp->link != 0) { prevnode = temp; temp = temp->link; } free(temp); prevnode->link = 0; }} // Function to delete from any specified// position from the linked listvoid deletePosition(){ struct node *temp, *position; int i = 1, pos; // If LL is empty if (start == NULL) printf("\nList is empty\n"); // Otherwise else { printf("\nEnter index : "); // Position to be deleted scanf("%d", &pos); position = malloc(sizeof(struct node)); temp = start; // Traverse till position while (i < pos - 1) { temp = temp->link; i++; } // Change Links position = temp->link; temp->link = position->link; // Free memory free(position); }} // Function to find the maximum element// in the linked listvoid maximum(){ int a[10]; int i; struct node* temp; // If LL is empty if (start == NULL) printf("\nList is empty\n"); // Otherwise else { temp = start; int max = temp->info; // Traverse LL and update the // maximum element while (temp != NULL) { // Update the maximum // element if (max < temp->info) max = temp->info; temp = temp->link; } printf("\nMaximum number " "is : %d ", max); }} // Function to find the mean of the// elements in the linked listvoid mean(){ int a[10]; int i; struct node* temp; // If LL is empty if (start == NULL) printf("\nList is empty\n"); // Otherwise else { temp = start; // Stores the sum and count of // element in the LL int sum = 0, count = 0; float m; // Traverse the LL while (temp != NULL) { // Update the sum sum = sum + temp->info; temp = temp->link; count++; } // Find the mean m = sum / count; // Print the mean value printf("\nMean is %f ", m); }} // Function to sort the linked list// in ascending ordervoid sort(){ struct node* current = start; struct node* index = NULL; int temp; // If LL is empty if (start == NULL) { return; } // Else else { // Traverse the LL while (current != NULL) { index = current->link; // Traverse the LL nestedly // and find the minimum // element while (index != NULL) { // Swap with it the value // at current if (current->info > index->info) { temp = current->info; current->info = index->info; index->info = temp; } index = index->link; } // Update the current current = current->link; } }} // Function to reverse the linked listvoid reverseLL(){ struct node *t1, *t2, *temp; t1 = t2 = NULL; // If LL is empty if (start == NULL) printf("List is empty\n"); // Else else { // Traverse the LL while (start != NULL) { // reversing of points t2 = start->link; start->link = t1; t1 = start; start = t2; } start = t1; // New head Node temp = start; printf("Reversed linked " "list is : "); // Print the LL while (temp != NULL) { printf("%d ", temp->info); temp = temp->link; } }} // Driver Codeint main(){ int choice; while (1) { printf("\n\t1 To see list\n"); printf("\t2 For insertion at" " starting\n"); printf("\t3 For insertion at" " end\n"); printf("\t4 For insertion at " "any position\n"); printf("\t5 For deletion of " "first element\n"); printf("\t6 For deletion of " "last element\n"); printf("\t7 For deletion of " "element at any position\n"); printf("\t8 To find maximum among" " the elements\n"); printf("\t9 To find mean of " "the elements\n"); printf("\t10 To sort element\n"); printf("\t11 To reverse the " "linked list\n"); printf("\t12 To exit\n"); printf("\nEnter Choice :\n"); scanf("%d", &choice); switch (choice) { case 1: traverse(); break; case 2: insertAtFront(); break; case 3: insertAtEnd(); break; case 4: insertAtPosition(); break; case 5: deleteFirst(); break; case 6: deleteEnd(); break; case 7: deletePosition(); break; case 8: maximum(); break; case 9: mean(); break; case 10: sort(); break; case 11: reverseLL(); break; case 12: exit(1); break; default: printf("Incorrect Choice\n"); } } return 0;} Output: Menu: Insertion at the starting: Insertion at the end: Insertion at specific position: Print the Linked List: Maximum among Linked List: Sorting the Linked List: Reverse the Linked List: Delete the first and last element with choice 5 and 6: jayghughri1 akhilhakkim Delete a Linked List Linked Lists Linked-List-Sorting Menu driven programs Technical Scripter 2020 Data Structures Linked List Technical Scripter Data Structures Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jul, 2022" }, { "code": null, "e": 285, "s": 52, "text": "A Linked List is a linear data structure that consists of two parts: one is the data part and the other is the address part. In this article, all the common operations of a singly linked list is discussed in one menu-driven program." }, { "code": null, "e": 313, "s": 285, "text": "Operations to be performed:" }, { "code": null, "e": 405, "s": 313, "text": "createList(): To create the list with ‘n’ number of nodes initially as defined by the user." }, { "code": null, "e": 591, "s": 405, "text": "traverse(): To see the contents of the linked list, it is necessary to traverse the given linked list. The given traverse() function traverses and prints the content of the linked list." }, { "code": null, "e": 691, "s": 591, "text": "insertAtFront(): This function simply inserts an element at the front/beginning of the linked list." }, { "code": null, "e": 770, "s": 691, "text": "insertAtEnd(): This function inserts an element at the end of the linked list." }, { "code": null, "e": 867, "s": 770, "text": "insertAtPosition(): This function inserts an element at a specified position in the linked list." }, { "code": null, "e": 967, "s": 867, "text": "deleteFirst(): This function simply deletes an element from the front/beginning of the linked list." }, { "code": null, "e": 1053, "s": 967, "text": "deleteEnd(): This function simply deletes an element from the end of the linked list." }, { "code": null, "e": 1150, "s": 1053, "text": "deletePosition(): This function deletes an element from a specified position in the linked list." }, { "code": null, "e": 1219, "s": 1150, "text": "maximum(): This function finds the maximum element in a linked list." }, { "code": null, "e": 1290, "s": 1219, "text": "mean(): This function finds the mean of the elements in a linked list." }, { "code": null, "e": 1359, "s": 1290, "text": "sort(): This function sort the given linked list in ascending order." }, { "code": null, "e": 1418, "s": 1359, "text": "reverseLL(): This function reverses the given linked list." }, { "code": null, "e": 1471, "s": 1418, "text": "Below is the implementation of the above operations:" }, { "code": null, "e": 1473, "s": 1471, "text": "C" }, { "code": "// C program for the all operations in// the Singly Linked List#include <stdio.h>#include <stdlib.h>// Linked List Nodestruct node { int info; struct node* link;};struct node* start = NULL; // Function to create list with n nodes initially void createList(){ if (start == NULL) { int n; printf(\"\\nEnter the number of nodes: \"); scanf(\"%d\", &n); if (n != 0) { int data; struct node* newnode; struct node* temp; newnode = malloc(sizeof(struct node)); start = newnode; temp = start; printf(\"\\nEnter number to\" \" be inserted : \"); scanf(\"%d\", &data); start->info = data; for (int i = 2; i <= n; i++) { newnode = malloc(sizeof(struct node)); temp->link = newnode; printf(\"\\nEnter number to\" \" be inserted : \"); scanf(\"%d\", &data); newnode->info = data; temp = temp->link; } } printf(\"\\nThe list is created\\n\"); } else printf(\"\\nThe list is already created\\n\");} // Function to traverse the linked listvoid traverse(){ struct node* temp; // List is empty if (start == NULL) printf(\"\\nList is empty\\n\"); // Else print the LL else { temp = start; while (temp != NULL) { printf(\"Data = %d\\n\", temp->info); temp = temp->link; } }} // Function to insert at the front// of the linked listvoid insertAtFront(){ int data; struct node* temp; temp = malloc(sizeof(struct node)); printf(\"\\nEnter number to\" \" be inserted : \"); scanf(\"%d\", &data); temp->info = data; // Pointer of temp will be // assigned to start temp->link = start; start = temp;} // Function to insert at the end of// the linked listvoid insertAtEnd(){ int data; struct node *temp, *head; temp = malloc(sizeof(struct node)); // Enter the number printf(\"\\nEnter number to\" \" be inserted : \"); scanf(\"%d\", &data); // Changes links temp->link = 0; temp->info = data; head = start; while (head->link != NULL) { head = head->link; } head->link = temp;} // Function to insert at any specified// position in the linked listvoid insertAtPosition(){ struct node *temp, *newnode; int pos, data, i = 1; newnode = malloc(sizeof(struct node)); // Enter the position and data printf(\"\\nEnter position and data :\"); scanf(\"%d %d\", &pos, &data); // Change Links temp = start; newnode->info = data; newnode->link = 0; while (i < pos - 1) { temp = temp->link; i++; } newnode->link = temp->link; temp->link = newnode;} // Function to delete from the front// of the linked listvoid deleteFirst(){ struct node* temp; if (start == NULL) printf(\"\\nList is empty\\n\"); else { temp = start; start = start->link; free(temp); }} // Function to delete from the end// of the linked listvoid deleteEnd(){ struct node *temp, *prevnode; if (start == NULL) printf(\"\\nList is Empty\\n\"); else { temp = start; while (temp->link != 0) { prevnode = temp; temp = temp->link; } free(temp); prevnode->link = 0; }} // Function to delete from any specified// position from the linked listvoid deletePosition(){ struct node *temp, *position; int i = 1, pos; // If LL is empty if (start == NULL) printf(\"\\nList is empty\\n\"); // Otherwise else { printf(\"\\nEnter index : \"); // Position to be deleted scanf(\"%d\", &pos); position = malloc(sizeof(struct node)); temp = start; // Traverse till position while (i < pos - 1) { temp = temp->link; i++; } // Change Links position = temp->link; temp->link = position->link; // Free memory free(position); }} // Function to find the maximum element// in the linked listvoid maximum(){ int a[10]; int i; struct node* temp; // If LL is empty if (start == NULL) printf(\"\\nList is empty\\n\"); // Otherwise else { temp = start; int max = temp->info; // Traverse LL and update the // maximum element while (temp != NULL) { // Update the maximum // element if (max < temp->info) max = temp->info; temp = temp->link; } printf(\"\\nMaximum number \" \"is : %d \", max); }} // Function to find the mean of the// elements in the linked listvoid mean(){ int a[10]; int i; struct node* temp; // If LL is empty if (start == NULL) printf(\"\\nList is empty\\n\"); // Otherwise else { temp = start; // Stores the sum and count of // element in the LL int sum = 0, count = 0; float m; // Traverse the LL while (temp != NULL) { // Update the sum sum = sum + temp->info; temp = temp->link; count++; } // Find the mean m = sum / count; // Print the mean value printf(\"\\nMean is %f \", m); }} // Function to sort the linked list// in ascending ordervoid sort(){ struct node* current = start; struct node* index = NULL; int temp; // If LL is empty if (start == NULL) { return; } // Else else { // Traverse the LL while (current != NULL) { index = current->link; // Traverse the LL nestedly // and find the minimum // element while (index != NULL) { // Swap with it the value // at current if (current->info > index->info) { temp = current->info; current->info = index->info; index->info = temp; } index = index->link; } // Update the current current = current->link; } }} // Function to reverse the linked listvoid reverseLL(){ struct node *t1, *t2, *temp; t1 = t2 = NULL; // If LL is empty if (start == NULL) printf(\"List is empty\\n\"); // Else else { // Traverse the LL while (start != NULL) { // reversing of points t2 = start->link; start->link = t1; t1 = start; start = t2; } start = t1; // New head Node temp = start; printf(\"Reversed linked \" \"list is : \"); // Print the LL while (temp != NULL) { printf(\"%d \", temp->info); temp = temp->link; } }} // Driver Codeint main(){ int choice; while (1) { printf(\"\\n\\t1 To see list\\n\"); printf(\"\\t2 For insertion at\" \" starting\\n\"); printf(\"\\t3 For insertion at\" \" end\\n\"); printf(\"\\t4 For insertion at \" \"any position\\n\"); printf(\"\\t5 For deletion of \" \"first element\\n\"); printf(\"\\t6 For deletion of \" \"last element\\n\"); printf(\"\\t7 For deletion of \" \"element at any position\\n\"); printf(\"\\t8 To find maximum among\" \" the elements\\n\"); printf(\"\\t9 To find mean of \" \"the elements\\n\"); printf(\"\\t10 To sort element\\n\"); printf(\"\\t11 To reverse the \" \"linked list\\n\"); printf(\"\\t12 To exit\\n\"); printf(\"\\nEnter Choice :\\n\"); scanf(\"%d\", &choice); switch (choice) { case 1: traverse(); break; case 2: insertAtFront(); break; case 3: insertAtEnd(); break; case 4: insertAtPosition(); break; case 5: deleteFirst(); break; case 6: deleteEnd(); break; case 7: deletePosition(); break; case 8: maximum(); break; case 9: mean(); break; case 10: sort(); break; case 11: reverseLL(); break; case 12: exit(1); break; default: printf(\"Incorrect Choice\\n\"); } } return 0;}", "e": 10094, "s": 1473, "text": null }, { "code": null, "e": 10105, "s": 10097, "text": "Output:" }, { "code": null, "e": 10113, "s": 10105, "text": "Menu: " }, { "code": null, "e": 10142, "s": 10113, "text": "Insertion at the starting: " }, { "code": null, "e": 10166, "s": 10142, "text": "Insertion at the end: " }, { "code": null, "e": 10200, "s": 10166, "text": "Insertion at specific position: " }, { "code": null, "e": 10225, "s": 10200, "text": "Print the Linked List: " }, { "code": null, "e": 10254, "s": 10225, "text": "Maximum among Linked List: " }, { "code": null, "e": 10281, "s": 10254, "text": "Sorting the Linked List: " }, { "code": null, "e": 10310, "s": 10283, "text": "Reverse the Linked List: " }, { "code": null, "e": 10367, "s": 10310, "text": "Delete the first and last element with choice 5 and 6: " }, { "code": null, "e": 10383, "s": 10371, "text": "jayghughri1" }, { "code": null, "e": 10395, "s": 10383, "text": "akhilhakkim" }, { "code": null, "e": 10416, "s": 10395, "text": "Delete a Linked List" }, { "code": null, "e": 10429, "s": 10416, "text": "Linked Lists" }, { "code": null, "e": 10449, "s": 10429, "text": "Linked-List-Sorting" }, { "code": null, "e": 10470, "s": 10449, "text": "Menu driven programs" }, { "code": null, "e": 10494, "s": 10470, "text": "Technical Scripter 2020" }, { "code": null, "e": 10510, "s": 10494, "text": "Data Structures" }, { "code": null, "e": 10522, "s": 10510, "text": "Linked List" }, { "code": null, "e": 10541, "s": 10522, "text": "Technical Scripter" }, { "code": null, "e": 10557, "s": 10541, "text": "Data Structures" }, { "code": null, "e": 10569, "s": 10557, "text": "Linked List" } ]
What is a Designated Port?
04 Oct, 2021 The switch with the best path to the root switch is set to forwarding. That switch is referred to as the designated switch, and its port is referred to as the designated port. A designated port is a port that can have the lowest path cost on a Local Area Network(LAN) segment. Each segment has a port called a single port that is used to reach the root switch or root bridge. A bridge device is equipped with two (or more) ports. The one connected on side where the STP root is located is referred to as the ‘root port.’ A ‘designated port’ is a port that does not face the root but forwards traffic from another segment at the lowest possible cost. Working: The root bridge is Switch 1. The root port (RP) is the port that connects to the root bridge, therefore there are no root ports on the root bridge. Every port on a root bridge forwards, and they are all designated ports (DP). When the switches power up, they exchange BPDUs and select a root bridge as the first thing they do. In this scenario, Switch 1 is chosen. Following that, each switch must determine shortest way to root bridge. I haven’t added expenses for each link in this diagram, however, based on the information above, Switch 3 considers its direct connection to Switch1 to be least expensive, therefore port on that link becomes the RP. Switch 2 considers its direct connection to Switch 1 to be the least expensive, therefore port on that link becomes RP. After the switches have agreed on root bridge and respective RPs, they must now locate their assigned ports. The selected ports are in charge of forwarding traffic onto a network segment. Consider following:The RPs lead to the root bridge.DPs are paths that lead away from the root bridge.Because the root bridge does not have any blocking ports, all of its ports are DPs. The RPs lead to the root bridge. DPs are paths that lead away from the root bridge. Because the root bridge does not have any blocking ports, all of its ports are DPs. So the only other section not included in the figure is Switch 2 -> Switch 3. One of the ports connecting that segment must forward traffic to that segment; otherwise, that segment will never receive traffic. But they can’t both forward since it would create a loop, i.e. a packet sent from Switch 1 would travel to Switch 3 -> Switch 2 and back to Switch 1 and so on. So Switch 2 and Switch 3 compare prices on that segment in the BPDUs delivered between them, and one of them, in this example Switch 3, has a lower cost. It forwards its port, transforming it into a DP. Switch 2 must now put its port into blocking mode to break the loop. Some major key points: The switch with the lowest cost to the root is selected as the link’s designated switch. A switch can have multiple designated ports. All ports on a Root Bridge (Root Switch) are designated ports. If one end of a LAN segment is a Designated Port, the other end is referred to as a Non-Designated Port (marked as NDP) if it is not a Root Port. A root port can never be a designated port. A bridge can only have one Root Port (Switch). A bridge may have numerous Designated Ports (Switch). Picked Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Bluetooth Cryptography and its Types Intrusion Detection System (IDS) Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Oct, 2021" }, { "code": null, "e": 404, "s": 28, "text": "The switch with the best path to the root switch is set to forwarding. That switch is referred to as the designated switch, and its port is referred to as the designated port. A designated port is a port that can have the lowest path cost on a Local Area Network(LAN) segment. Each segment has a port called a single port that is used to reach the root switch or root bridge." }, { "code": null, "e": 678, "s": 404, "text": "A bridge device is equipped with two (or more) ports. The one connected on side where the STP root is located is referred to as the ‘root port.’ A ‘designated port’ is a port that does not face the root but forwards traffic from another segment at the lowest possible cost." }, { "code": null, "e": 687, "s": 678, "text": "Working:" }, { "code": null, "e": 716, "s": 687, "text": "The root bridge is Switch 1." }, { "code": null, "e": 913, "s": 716, "text": "The root port (RP) is the port that connects to the root bridge, therefore there are no root ports on the root bridge. Every port on a root bridge forwards, and they are all designated ports (DP)." }, { "code": null, "e": 1052, "s": 913, "text": "When the switches power up, they exchange BPDUs and select a root bridge as the first thing they do. In this scenario, Switch 1 is chosen." }, { "code": null, "e": 1221, "s": 1052, "text": "Following that, each switch must determine shortest way to root bridge. I haven’t added expenses for each link in this diagram, however, based on the information above," }, { "code": null, "e": 1340, "s": 1221, "text": "Switch 3 considers its direct connection to Switch1 to be least expensive, therefore port on that link becomes the RP." }, { "code": null, "e": 1460, "s": 1340, "text": "Switch 2 considers its direct connection to Switch 1 to be the least expensive, therefore port on that link becomes RP." }, { "code": null, "e": 1833, "s": 1460, "text": "After the switches have agreed on root bridge and respective RPs, they must now locate their assigned ports. The selected ports are in charge of forwarding traffic onto a network segment. Consider following:The RPs lead to the root bridge.DPs are paths that lead away from the root bridge.Because the root bridge does not have any blocking ports, all of its ports are DPs." }, { "code": null, "e": 1866, "s": 1833, "text": "The RPs lead to the root bridge." }, { "code": null, "e": 1917, "s": 1866, "text": "DPs are paths that lead away from the root bridge." }, { "code": null, "e": 2001, "s": 1917, "text": "Because the root bridge does not have any blocking ports, all of its ports are DPs." }, { "code": null, "e": 2370, "s": 2001, "text": "So the only other section not included in the figure is Switch 2 -> Switch 3. One of the ports connecting that segment must forward traffic to that segment; otherwise, that segment will never receive traffic. But they can’t both forward since it would create a loop, i.e. a packet sent from Switch 1 would travel to Switch 3 -> Switch 2 and back to Switch 1 and so on." }, { "code": null, "e": 2642, "s": 2370, "text": "So Switch 2 and Switch 3 compare prices on that segment in the BPDUs delivered between them, and one of them, in this example Switch 3, has a lower cost. It forwards its port, transforming it into a DP. Switch 2 must now put its port into blocking mode to break the loop." }, { "code": null, "e": 2665, "s": 2642, "text": "Some major key points:" }, { "code": null, "e": 2754, "s": 2665, "text": "The switch with the lowest cost to the root is selected as the link’s designated switch." }, { "code": null, "e": 2799, "s": 2754, "text": "A switch can have multiple designated ports." }, { "code": null, "e": 2862, "s": 2799, "text": "All ports on a Root Bridge (Root Switch) are designated ports." }, { "code": null, "e": 3008, "s": 2862, "text": "If one end of a LAN segment is a Designated Port, the other end is referred to as a Non-Designated Port (marked as NDP) if it is not a Root Port." }, { "code": null, "e": 3052, "s": 3008, "text": "A root port can never be a designated port." }, { "code": null, "e": 3153, "s": 3052, "text": "A bridge can only have one Root Port (Switch). A bridge may have numerous Designated Ports (Switch)." }, { "code": null, "e": 3160, "s": 3153, "text": "Picked" }, { "code": null, "e": 3178, "s": 3160, "text": "Computer Networks" }, { "code": null, "e": 3196, "s": 3178, "text": "Computer Networks" }, { "code": null, "e": 3294, "s": 3196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3324, "s": 3294, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3350, "s": 3324, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 3380, "s": 3350, "text": "Wireless Application Protocol" }, { "code": null, "e": 3420, "s": 3380, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 3466, "s": 3420, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 3501, "s": 3466, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 3511, "s": 3501, "text": "Bluetooth" }, { "code": null, "e": 3538, "s": 3511, "text": "Cryptography and its Types" }, { "code": null, "e": 3571, "s": 3538, "text": "Intrusion Detection System (IDS)" } ]
JavaScript | exec() Method
12 Apr, 2021 The exec() Method in JavaScript is used to test for match in a string. If there is a match this method returns the first match else it returns NULL.Syntax: RegExpObject.exec(str) Where str is the string to be searched. This is required field. Example-1: This example searches for the string “computer” in the original string. html <!DOCTYPE html><html> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>exec() Method</h2> <p> String: GeeksforGeeks is the computer science portal for geeks. </p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str = "GeeksforGeeks is the "+ "computer science portal for geeks."; var regex = new RegExp("computer", ); // match "computer" in string. var rex = regex.exec(str); document.getElementById("app").innerHTML = " Found " + rex.length + " match: " + rex; } </script></body> </html> Output: Before clicking the button: After clicking the button: Example-2: This example searches for the string “rep” in the original string. html <!DOCTYPE html><html> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> exec() Method </h2> <p> String: GeeksforGeeks is the computer science portal for geeks. </p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str = "GeeksforGeeks is the"+ " computer science "+ "portal for geeks."; var regex = new RegExp("rep"); // Match "rep" in string. var rex = regex.exec(str); alert(rex); } </script></body> </html> Output: Before clicking the button: After clicking the button: Supported Browsers: The browsers supported by JavaScript exec() Method are listed below: Google Chrome Apple Safari Mozilla Firefox Opera Internet Explorer simranarora5sos javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2021" }, { "code": null, "e": 210, "s": 52, "text": "The exec() Method in JavaScript is used to test for match in a string. If there is a match this method returns the first match else it returns NULL.Syntax: " }, { "code": null, "e": 233, "s": 210, "text": "RegExpObject.exec(str)" }, { "code": null, "e": 382, "s": 233, "text": "Where str is the string to be searched. This is required field. Example-1: This example searches for the string “computer” in the original string. " }, { "code": null, "e": 387, "s": 382, "text": "html" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>exec() Method</h2> <p> String: GeeksforGeeks is the computer science portal for geeks. </p> <button onclick=\"geek()\"> Click it! </button> <p id=\"app\"></p> <script> function geek() { var str = \"GeeksforGeeks is the \"+ \"computer science portal for geeks.\"; var regex = new RegExp(\"computer\", ); // match \"computer\" in string. var rex = regex.exec(str); document.getElementById(\"app\").innerHTML = \" Found \" + rex.length + \" match: \" + rex; } </script></body> </html>", "e": 1149, "s": 387, "text": null }, { "code": null, "e": 1187, "s": 1149, "text": "Output: Before clicking the button: " }, { "code": null, "e": 1216, "s": 1187, "text": "After clicking the button: " }, { "code": null, "e": 1296, "s": 1216, "text": "Example-2: This example searches for the string “rep” in the original string. " }, { "code": null, "e": 1301, "s": 1296, "text": "html" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2> exec() Method </h2> <p> String: GeeksforGeeks is the computer science portal for geeks. </p> <button onclick=\"geek()\"> Click it! </button> <p id=\"app\"></p> <script> function geek() { var str = \"GeeksforGeeks is the\"+ \" computer science \"+ \"portal for geeks.\"; var regex = new RegExp(\"rep\"); // Match \"rep\" in string. var rex = regex.exec(str); alert(rex); } </script></body> </html>", "e": 1972, "s": 1301, "text": null }, { "code": null, "e": 2010, "s": 1972, "text": "Output: Before clicking the button: " }, { "code": null, "e": 2039, "s": 2010, "text": "After clicking the button: " }, { "code": null, "e": 2130, "s": 2039, "text": "Supported Browsers: The browsers supported by JavaScript exec() Method are listed below: " }, { "code": null, "e": 2144, "s": 2130, "text": "Google Chrome" }, { "code": null, "e": 2157, "s": 2144, "text": "Apple Safari" }, { "code": null, "e": 2173, "s": 2157, "text": "Mozilla Firefox" }, { "code": null, "e": 2179, "s": 2173, "text": "Opera" }, { "code": null, "e": 2197, "s": 2179, "text": "Internet Explorer" }, { "code": null, "e": 2215, "s": 2199, "text": "simranarora5sos" }, { "code": null, "e": 2236, "s": 2215, "text": "javascript-functions" }, { "code": null, "e": 2247, "s": 2236, "text": "JavaScript" }, { "code": null, "e": 2264, "s": 2247, "text": "Web Technologies" } ]
Reduce the array to a single element with the given operation
02 Jul, 2022 Given an integer N and an array arr containing integers from 1 to N in a sorted fashion. The task is to reduce the array to a single element by performing the following operation: All the elements in the odd positions will be removed after a single operation. This operation will be performed until only a single element is left int the array and it prints that element at the end. Examples: Input: N = 3 Output: 2 Initially the array will be arr[] = {1, 2, 3} After the 1st operation, ‘1’ and ‘3’ will be removed and the array becomes arr[] = {2} So 2 is the only element left at the end. Input: N = 6 Output: 4 arr[] = {1, 2, 3, 4, 5, 6} After the first iteration, the array becomes {2, 4, 6} After the second iteration, the array becomes {4} So 4 is the last element. Approach: For this kind of problem: Write multiple test cases and the respective output. Analyze the output for the given input and the relation between them. Once we find the relation we will try to express it in the form of a mathematical expression if possible. Write the code/algorithm for the above expression. So let’s create a table for the given input N and its respective output. Analyzed Relation: The output is at 2i. Using the above table, we can create the output table for the range of inputs. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach #include<bits/stdc++.h>using namespace std; // Function to return the final elementlong getFinalElement(long n){ long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum;} // Driver codeint main(){ int N = 12; cout << getFinalElement(N) ; return 0;}// This code is contributed by Ryuga // Java implementation of the approachclass OddPosition { // Function to return the final element public static long getFinalElement(long n) { long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code public static void main(String[] args) { int N = 12; System.out.println(getFinalElement(N)); }} # Python 3 implementation of the approach # Function to return the final elementdef getFinalElement(n): finalNum = 2 while finalNum * 2 <= n: finalNum *= 2 return finalNum # Driver codeif __name__ =="__main__": N = 12 print( getFinalElement(N)) # This code is contributed# by ChitraNayal // C# implementation of the approachusing System; public class GFG{ // Function to return the final element public static long getFinalElement(long n) { long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code static public void Main (){ int N = 12; Console.WriteLine(getFinalElement(N)); }} <?php//PHP implementation of the approach // Function to return the final elementfunction getFinalElement($n){ $finalNum=0; for ($finalNum = 2; ($finalNum * 2) <= $n; $finalNum *= 2) ; return $finalNum;} // Driver code $N = 12; echo getFinalElement($N) ; // This code is contributed by akt_mit?> <script>// Javascript implementation of the approach // Function to return the final element function getFinalElement(n) { let finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code let N = 12; document.write(getFinalElement(N)); // This code is contributed by avanitrachhadiya2155</script> 8 Time Complexity: O(logN), since every time the finalNum value is becoming twice its current value.Auxiliary Space: O(1), since no extra space has been taken. Sach_Code ankthon ukasp jit_t avanitrachhadiya2155 pankajsharmagfg subham348 Algorithms Competitive Programming Mathematical Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Competitive Programming - A Complete Guide Practice for cracking any coding interview Modulo 10^9+7 (1000000007) Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jul, 2022" }, { "code": null, "e": 436, "s": 54, "text": "Given an integer N and an array arr containing integers from 1 to N in a sorted fashion. The task is to reduce the array to a single element by performing the following operation: All the elements in the odd positions will be removed after a single operation. This operation will be performed until only a single element is left int the array and it prints that element at the end." }, { "code": null, "e": 448, "s": 436, "text": "Examples: " }, { "code": null, "e": 646, "s": 448, "text": "Input: N = 3 Output: 2 Initially the array will be arr[] = {1, 2, 3} After the 1st operation, ‘1’ and ‘3’ will be removed and the array becomes arr[] = {2} So 2 is the only element left at the end." }, { "code": null, "e": 829, "s": 646, "text": "Input: N = 6 Output: 4 arr[] = {1, 2, 3, 4, 5, 6} After the first iteration, the array becomes {2, 4, 6} After the second iteration, the array becomes {4} So 4 is the last element. " }, { "code": null, "e": 867, "s": 829, "text": "Approach: For this kind of problem: " }, { "code": null, "e": 920, "s": 867, "text": "Write multiple test cases and the respective output." }, { "code": null, "e": 990, "s": 920, "text": "Analyze the output for the given input and the relation between them." }, { "code": null, "e": 1096, "s": 990, "text": "Once we find the relation we will try to express it in the form of a mathematical expression if possible." }, { "code": null, "e": 1147, "s": 1096, "text": "Write the code/algorithm for the above expression." }, { "code": null, "e": 1221, "s": 1147, "text": "So let’s create a table for the given input N and its respective output. " }, { "code": null, "e": 1341, "s": 1221, "text": "Analyzed Relation: The output is at 2i. Using the above table, we can create the output table for the range of inputs. " }, { "code": null, "e": 1394, "s": 1341, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1398, "s": 1394, "text": "C++" }, { "code": null, "e": 1403, "s": 1398, "text": "Java" }, { "code": null, "e": 1411, "s": 1403, "text": "Python3" }, { "code": null, "e": 1414, "s": 1411, "text": "C#" }, { "code": null, "e": 1418, "s": 1414, "text": "PHP" }, { "code": null, "e": 1429, "s": 1418, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include<bits/stdc++.h>using namespace std; // Function to return the final elementlong getFinalElement(long n){ long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum;} // Driver codeint main(){ int N = 12; cout << getFinalElement(N) ; return 0;}// This code is contributed by Ryuga", "e": 1818, "s": 1429, "text": null }, { "code": "// Java implementation of the approachclass OddPosition { // Function to return the final element public static long getFinalElement(long n) { long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code public static void main(String[] args) { int N = 12; System.out.println(getFinalElement(N)); }}", "e": 2233, "s": 1818, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the final elementdef getFinalElement(n): finalNum = 2 while finalNum * 2 <= n: finalNum *= 2 return finalNum # Driver codeif __name__ ==\"__main__\": N = 12 print( getFinalElement(N)) # This code is contributed# by ChitraNayal", "e": 2545, "s": 2233, "text": null }, { "code": "// C# implementation of the approachusing System; public class GFG{ // Function to return the final element public static long getFinalElement(long n) { long finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code static public void Main (){ int N = 12; Console.WriteLine(getFinalElement(N)); }}", "e": 2957, "s": 2545, "text": null }, { "code": "<?php//PHP implementation of the approach // Function to return the final elementfunction getFinalElement($n){ $finalNum=0; for ($finalNum = 2; ($finalNum * 2) <= $n; $finalNum *= 2) ; return $finalNum;} // Driver code $N = 12; echo getFinalElement($N) ; // This code is contributed by akt_mit?>", "e": 3289, "s": 2957, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the final element function getFinalElement(n) { let finalNum; for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2) ; return finalNum; } // Driver code let N = 12; document.write(getFinalElement(N)); // This code is contributed by avanitrachhadiya2155</script> ", "e": 3696, "s": 3289, "text": null }, { "code": null, "e": 3698, "s": 3696, "text": "8" }, { "code": null, "e": 3858, "s": 3700, "text": "Time Complexity: O(logN), since every time the finalNum value is becoming twice its current value.Auxiliary Space: O(1), since no extra space has been taken." }, { "code": null, "e": 3868, "s": 3858, "text": "Sach_Code" }, { "code": null, "e": 3876, "s": 3868, "text": "ankthon" }, { "code": null, "e": 3882, "s": 3876, "text": "ukasp" }, { "code": null, "e": 3888, "s": 3882, "text": "jit_t" }, { "code": null, "e": 3909, "s": 3888, "text": "avanitrachhadiya2155" }, { "code": null, "e": 3925, "s": 3909, "text": "pankajsharmagfg" }, { "code": null, "e": 3935, "s": 3925, "text": "subham348" }, { "code": null, "e": 3946, "s": 3935, "text": "Algorithms" }, { "code": null, "e": 3970, "s": 3946, "text": "Competitive Programming" }, { "code": null, "e": 3983, "s": 3970, "text": "Mathematical" }, { "code": null, "e": 3996, "s": 3983, "text": "Mathematical" }, { "code": null, "e": 4007, "s": 3996, "text": "Algorithms" }, { "code": null, "e": 4105, "s": 4007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4143, "s": 4105, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 4211, "s": 4143, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 4238, "s": 4211, "text": "How to Start Learning DSA?" }, { "code": null, "e": 4281, "s": 4238, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 4348, "s": 4281, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 4391, "s": 4348, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 4434, "s": 4391, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 4461, "s": 4434, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 4502, "s": 4461, "text": "Arrow operator -> in C/C++ with Examples" } ]
Python | Filter Tuple Dictionary Keys
30 Jan, 2020 Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functionalities to achieve this. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionIn this method, we just iterate through the each dictionary item and get it’s filtered key’s elements into a list. # Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using list comprehension # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'} # printing original dictprint("The original dict is : " + str(test_dict)) # Initializing K K = 5 # Filter Tuple Dictionary Keys# Using list comprehensionres = [ele for key in test_dict for ele in key if ele > K] # printing resultprint("The filtered dictionary tuple key elements are : " + str(res)) The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'} The filtered dictionary tuple key elements are : [6, 9, 10, 8] Method #2 : Using chain.from_iterable()This task can be performed in more compact form, using one word instead of one-line by using from_iterable(), which internally accesses the tuple elements and stores in list and then perform the filter operation. # Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using chain.from_iterable()from itertools import chain # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'} # printing original dictprint("The original dict is : " + str(test_dict)) # Initializing K K = 5 # Filter Tuple Dictionary Keys# Using chain.from_iterable()temp = list(chain.from_iterable(test_dict))res = [ele for ele in temp if ele > K] # printing resultprint("The filtered dictionary tuple key elements are : " + str(res)) The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'} The filtered dictionary tuple key elements are : [6, 9, 10, 8] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() 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": "\n30 Jan, 2020" }, { "code": null, "e": 419, "s": 28, "text": "Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functionalities to achieve this. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 570, "s": 419, "text": "Method #1 : Using list comprehensionIn this method, we just iterate through the each dictionary item and get it’s filtered key’s elements into a list." }, { "code": "# Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using list comprehension # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'} # printing original dictprint(\"The original dict is : \" + str(test_dict)) # Initializing K K = 5 # Filter Tuple Dictionary Keys# Using list comprehensionres = [ele for key in test_dict for ele in key if ele > K] # printing resultprint(\"The filtered dictionary tuple key elements are : \" + str(res))", "e": 1055, "s": 570, "text": null }, { "code": null, "e": 1192, "s": 1055, "text": "The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}\nThe filtered dictionary tuple key elements are : [6, 9, 10, 8]\n" }, { "code": null, "e": 1446, "s": 1194, "text": "Method #2 : Using chain.from_iterable()This task can be performed in more compact form, using one word instead of one-line by using from_iterable(), which internally accesses the tuple elements and stores in list and then perform the filter operation." }, { "code": "# Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using chain.from_iterable()from itertools import chain # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'} # printing original dictprint(\"The original dict is : \" + str(test_dict)) # Initializing K K = 5 # Filter Tuple Dictionary Keys# Using chain.from_iterable()temp = list(chain.from_iterable(test_dict))res = [ele for ele in temp if ele > K] # printing resultprint(\"The filtered dictionary tuple key elements are : \" + str(res))", "e": 1988, "s": 1446, "text": null }, { "code": null, "e": 2125, "s": 1988, "text": "The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}\nThe filtered dictionary tuple key elements are : [6, 9, 10, 8]\n" }, { "code": null, "e": 2146, "s": 2125, "text": "Python list-programs" }, { "code": null, "e": 2153, "s": 2146, "text": "Python" }, { "code": null, "e": 2169, "s": 2153, "text": "Python Programs" }, { "code": null, "e": 2267, "s": 2169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2285, "s": 2267, "text": "Python Dictionary" }, { "code": null, "e": 2327, "s": 2285, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2349, "s": 2327, "text": "Enumerate() in Python" }, { "code": null, "e": 2384, "s": 2349, "text": "Read a file line by line in Python" }, { "code": null, "e": 2410, "s": 2384, "text": "Python String | replace()" }, { "code": null, "e": 2453, "s": 2410, "text": "Python program to convert a list to string" }, { "code": null, "e": 2475, "s": 2453, "text": "Defaultdict in Python" }, { "code": null, "e": 2514, "s": 2475, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2552, "s": 2514, "text": "Python | Convert a list to dictionary" } ]
Find out when a download has completed using Python & Selenium
We can find when a download has completed with Selenium webdriver in Python. We shall use the ChromeOptions class for this purpose. First, we shall create an object of the ChromeOptions class. Then apply the add_experimental_option method on the object created. We shall pass browser preferences and download.default_directory:<location of downloaded file> as parameters to that method. Finally, this information shall be passed to the driver object. Once the download is completed, we can verify it with the help of the os.path.isfile method. The path of the downloaded file is passed as a parameter to that method. The method os.path.exists shall also be used to verify if the downloaded file path exists. op = webdriver.ChromeOptions() p = {'download.default_directory':'C:\\Users\\Downloads\\Test'} op.add_experimental_option('prefs', p) from selenium import webdriver from selenium.webdriver.chrome.options import Options import time import os.path #object of ChromeOptions class op = webdriver.ChromeOptions() #browser preferences p = {'download.default_directory': 'C:\\Users\\Downloads\\Test'} #add options to browser op.add_experimental_option('prefs', p) #set chromedriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe", options=op) #maximize browser driver.maximize_window() #launch URL driver.get("https://www.seleniumhq.org/download/"); #click download link l = driver.find_element_by_link_text("32 bit Windows IE") l.click() #check if file downloaded file path exists while not os.path.exists('C:\\Users\\Downloads\\Test'): time.sleep(2) #check file if os.path.isfile('C:\\Users\\Downloads\\Test\\IEDriverServer_Win32.zip): print("File download is completed") else: print("File download is not completed") #close browser driver.quit()
[ { "code": null, "e": 1380, "s": 1187, "text": "We can find when a download has completed with Selenium webdriver in Python. We shall use the ChromeOptions class for this purpose. First, we shall create an object of the ChromeOptions class." }, { "code": null, "e": 1638, "s": 1380, "text": "Then apply the add_experimental_option method on the object created. We shall pass browser preferences and download.default_directory:<location of\ndownloaded file> as parameters to that method. Finally, this information shall be passed to the driver object." }, { "code": null, "e": 1895, "s": 1638, "text": "Once the download is completed, we can verify it with the help of the os.path.isfile method. The path of the downloaded file is passed as a parameter to that method. The method os.path.exists shall also be used to verify if the downloaded file path exists." }, { "code": null, "e": 2029, "s": 1895, "text": "op = webdriver.ChromeOptions()\np = {'download.default_directory':'C:\\\\Users\\\\Downloads\\\\Test'}\nop.add_experimental_option('prefs', p)" }, { "code": null, "e": 2969, "s": 2029, "text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\nimport os.path\n#object of ChromeOptions class\nop = webdriver.ChromeOptions()\n#browser preferences\np = {'download.default_directory': 'C:\\\\Users\\\\Downloads\\\\Test'}\n#add options to browser\nop.add_experimental_option('prefs', p)\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\",\noptions=op)\n#maximize browser\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.seleniumhq.org/download/\");\n#click download link\nl = driver.find_element_by_link_text(\"32 bit Windows IE\")\nl.click()\n#check if file downloaded file path exists\nwhile not os.path.exists('C:\\\\Users\\\\Downloads\\\\Test'):\ntime.sleep(2)\n#check file\nif os.path.isfile('C:\\\\Users\\\\Downloads\\\\Test\\\\IEDriverServer_Win32.zip):\n print(\"File download is completed\")\nelse:\n print(\"File download is not completed\")\n#close browser\ndriver.quit()" } ]
Python | Split given string into equal halves
03 Jul, 2019 Sometimes, we need to simply divide the string into two equal halves. This type of application can occur in various domain ranging from simple programming to web development. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + String slicingThis is the naive method to perform this particular task. In this we just use brute divisions and slicing to separate first and last part of string. # Python3 code to demonstrate working of# Splitting string into equal halves# Using list comprehension + string slicing # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # Using list comprehension + string slicing# Splitting string into equal halvesres_first = test_str[0:len(test_str)//2]res_second = test_str[len(test_str)//2 if len(test_str)%2 == 0 else ((len(test_str)//2)+1):] # printing result print("The first part of string : " + res_first)print("The second part of string : " + res_second) The original string is : GeeksforGeeks The first part of string : Geeksf The second part of string : rGeeks Method #2 : Using string slicingTo overcome the shortcomings of above method and find a more elegant solution, we use string slicing to perform this particular task. # Python3 code to demonstrate working of# Splitting string into equal halves# Using string slicing # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # Using string slicing# Splitting string into equal halvesres_first, res_second = test_str[:len(test_str)//2], test_str[len(test_str)//2:] # printing result print("The first part of string : " + res_first)print("The second part of string : " + res_second) The original string is : GeeksforGeeks The first part of string : Geeksf The second part of string : orGeeks 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": 28, "s": 0, "text": "\n03 Jul, 2019" }, { "code": null, "e": 262, "s": 28, "text": "Sometimes, we need to simply divide the string into two equal halves. This type of application can occur in various domain ranging from simple programming to web development. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 464, "s": 262, "text": "Method #1 : Using list comprehension + String slicingThis is the naive method to perform this particular task. In this we just use brute divisions and slicing to separate first and last part of string." }, { "code": "# Python3 code to demonstrate working of# Splitting string into equal halves# Using list comprehension + string slicing # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # Using list comprehension + string slicing# Splitting string into equal halvesres_first = test_str[0:len(test_str)//2]res_second = test_str[len(test_str)//2 if len(test_str)%2 == 0 else ((len(test_str)//2)+1):] # printing result print(\"The first part of string : \" + res_first)print(\"The second part of string : \" + res_second)", "e": 1071, "s": 464, "text": null }, { "code": null, "e": 1180, "s": 1071, "text": "The original string is : GeeksforGeeks\nThe first part of string : Geeksf\nThe second part of string : rGeeks\n" }, { "code": null, "e": 1348, "s": 1182, "text": "Method #2 : Using string slicingTo overcome the shortcomings of above method and find a more elegant solution, we use string slicing to perform this particular task." }, { "code": "# Python3 code to demonstrate working of# Splitting string into equal halves# Using string slicing # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # Using string slicing# Splitting string into equal halvesres_first, res_second = test_str[:len(test_str)//2], test_str[len(test_str)//2:] # printing result print(\"The first part of string : \" + res_first)print(\"The second part of string : \" + res_second)", "e": 1853, "s": 1348, "text": null }, { "code": null, "e": 1963, "s": 1853, "text": "The original string is : GeeksforGeeks\nThe first part of string : Geeksf\nThe second part of string : orGeeks\n" }, { "code": null, "e": 1986, "s": 1963, "text": "Python string-programs" }, { "code": null, "e": 1993, "s": 1986, "text": "Python" }, { "code": null, "e": 2009, "s": 1993, "text": "Python Programs" } ]
ReactJS Reactstrap Table Component - GeeksforGeeks
22 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Table component allows the user to display rows of data. We can use the following approach in ReactJS to use the ReactJS Reactstrap Table Component. Table Props: tag: It is used to denote the tag for this component. size: It is used to denote the size of the table. bordered: It is used to indicate whether the table has bordered style or not. borderless: It is used to indicate whether the table has a borderless style or not. striped: It is used to indicate whether the table has a striped style or not. dark: It is used to indicate whether the table has a dark style or not. hover: It is used to denote that the row of the table has a mouseover effect. responsive: It is used to indicate whether the table is responsive or not. innerRef: It is used to denote the custom ref handler for the <table> element. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here, we have shown a table without multiple columns and with bordered style. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Table } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 500, padding: 30 }}> <h4>ReactJS Reactstrap Table Component</h4> <Table bordered={true}> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>Dummmy</td> </tr> <tr> <td>Raj</td> </tr> <tr> <td>Lucky</td> </tr> </tbody> </Table> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here, we have shown a table with multiple columns and without bordered style. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Table } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Table Component</h4> <Table> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Dummmy</td> <td>25</td> </tr> <tr> <td>Raj</td> <td>33</td> </tr> <tr> <td>Lucky</td> <td>23</td> </tr> </tbody> </Table> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/tables/ Reactstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to navigate on path by button click in react router ? How to create a table in ReactJS ? How to check the version of ReactJS ? Explain the purpose of render() in ReactJS How to set background images in ReactJS ? Express.js express.Router() Function Installation of Node.js on Linux How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24397, "s": 24369, "text": "\n22 Jul, 2021" }, { "code": null, "e": 24712, "s": 24397, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Table component allows the user to display rows of data. We can use the following approach in ReactJS to use the ReactJS Reactstrap Table Component." }, { "code": null, "e": 24725, "s": 24712, "text": "Table Props:" }, { "code": null, "e": 24779, "s": 24725, "text": "tag: It is used to denote the tag for this component." }, { "code": null, "e": 24829, "s": 24779, "text": "size: It is used to denote the size of the table." }, { "code": null, "e": 24907, "s": 24829, "text": "bordered: It is used to indicate whether the table has bordered style or not." }, { "code": null, "e": 24991, "s": 24907, "text": "borderless: It is used to indicate whether the table has a borderless style or not." }, { "code": null, "e": 25069, "s": 24991, "text": "striped: It is used to indicate whether the table has a striped style or not." }, { "code": null, "e": 25141, "s": 25069, "text": "dark: It is used to indicate whether the table has a dark style or not." }, { "code": null, "e": 25219, "s": 25141, "text": "hover: It is used to denote that the row of the table has a mouseover effect." }, { "code": null, "e": 25294, "s": 25219, "text": "responsive: It is used to indicate whether the table is responsive or not." }, { "code": null, "e": 25373, "s": 25294, "text": "innerRef: It is used to denote the custom ref handler for the <table> element." }, { "code": null, "e": 25423, "s": 25373, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25518, "s": 25423, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 25582, "s": 25518, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25614, "s": 25582, "text": "npx create-react-app foldername" }, { "code": null, "e": 25727, "s": 25614, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 25827, "s": 25727, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25841, "s": 25827, "text": "cd foldername" }, { "code": null, "e": 25978, "s": 25841, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap" }, { "code": null, "e": 26083, "s": 25978, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 26116, "s": 26083, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 26168, "s": 26116, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26186, "s": 26168, "text": "Project Structure" }, { "code": null, "e": 26329, "s": 26186, "text": "Example 1: Now write down the following code in the App.js file. Here, we have shown a table without multiple columns and with bordered style." }, { "code": null, "e": 26336, "s": 26329, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Table } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 500, padding: 30 }}> <h4>ReactJS Reactstrap Table Component</h4> <Table bordered={true}> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr> <td>Dummmy</td> </tr> <tr> <td>Raj</td> </tr> <tr> <td>Lucky</td> </tr> </tbody> </Table> </div> );} export default App;", "e": 27149, "s": 26336, "text": null }, { "code": null, "e": 27262, "s": 27149, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27272, "s": 27262, "text": "npm start" }, { "code": null, "e": 27371, "s": 27272, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27514, "s": 27371, "text": "Example 2: Now write down the following code in the App.js file. Here, we have shown a table with multiple columns and without bordered style." }, { "code": null, "e": 27521, "s": 27514, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Table } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Table Component</h4> <Table> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Dummmy</td> <td>25</td> </tr> <tr> <td>Raj</td> <td>33</td> </tr> <tr> <td>Lucky</td> <td>23</td> </tr> </tbody> </Table> </div> );} export default App;", "e": 28459, "s": 27521, "text": null }, { "code": null, "e": 28572, "s": 28459, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28582, "s": 28572, "text": "npm start" }, { "code": null, "e": 28681, "s": 28582, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28740, "s": 28681, "text": "Reference: https://reactstrap.github.io/components/tables/" }, { "code": null, "e": 28751, "s": 28740, "text": "Reactstrap" }, { "code": null, "e": 28759, "s": 28751, "text": "ReactJS" }, { "code": null, "e": 28776, "s": 28759, "text": "Web Technologies" }, { "code": null, "e": 28874, "s": 28776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28883, "s": 28874, "text": "Comments" }, { "code": null, "e": 28896, "s": 28883, "text": "Old Comments" }, { "code": null, "e": 28954, "s": 28896, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28989, "s": 28954, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29027, "s": 28989, "text": "How to check the version of ReactJS ?" }, { "code": null, "e": 29070, "s": 29027, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 29112, "s": 29070, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29149, "s": 29112, "text": "Express.js express.Router() Function" }, { "code": null, "e": 29182, "s": 29149, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29243, "s": 29182, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29315, "s": 29243, "text": "Differences between Functional Components and Class Components in React" } ]
Overcoming Data Preprocessing Bottlenecks with TensorFlow Data Service, NVIDIA DALI, and Other Methods | by Chaim Rand | Towards Data Science
In a previous post, I spoke about the importance of profiling the runtime performance of your DNN training sessions as a means to making the most of your training resources, accelerating your training, and saving money. I described a typical training pipeline, (see the diagram below), reviewed some of the potential performance bottlenecks, and surveyed some of the tools available for identifying such bottlenecks. In this post I would like to expand on one of the more common performance bottlenecks, the CPU bottleneck, and some of the ways to overcome it. More specifically, we will discuss bottlenecks that occur in the data preprocessing pipeline, and ways to overcome them. In the context of this post, we will assume that we are using TensorFlow, specifically TensorFlow 2.4, to train an image processing model on a GPU device, but the content is, mostly, just as relevant to other training frameworks, other types of models, and other training accelerators. A CPU bottleneck occurs when the GPU resource is under utilized as a result of one, or more of the CPUs, having reached maximum utilization. In this situation, the GPU will be partially idle while it waits for the CPU to pass in training data. This is an undesired state. Being that the GPU is, typically, the most expensive resource in the system, your goal should always be to maximize its utilization. Without getting into too many technical details, a CPU bottleneck generally occurs when the ratio between the “amount” of data pre-processing, which is performed on the CPU, and the “amount” of compute performed by the model on the GPU, is greater that the ratio between the overall CPU compute capacity and the overall GPU compute capacity. For example, if both your CPU cores and GPU are maximally utilized, and then you upgrade to a more powerful GPU, or downgrade to a system with fewer CPU cores, your training runtime performance will become CPU bound. Naturally, your first instinct will be to simply switch over to a machine with a more appropriate CPU to GPU compute ratio. But, sadly, most of us don’t have that freedom. And while cloud services, such as Amazon SageMaker, offer a variety of training instance types, with different CPU-compute to GPU-compute ratios, you may find that none of them quite fit your specific needs. Assuming that you are stuck with the system that you have, what steps can you take to address your performance bottleneck and speed up the training? In the next sections we will propose four steps for addressing the preprocessing data bottleneck. Identify any operations that can be moved to the data preparation phaseOptimize the data pre-processing pipelinePerform some of the pre-processing steps on the GPUUse the TensorFlow data service to offload some of the CPU compute to other machines Identify any operations that can be moved to the data preparation phase Optimize the data pre-processing pipeline Perform some of the pre-processing steps on the GPU Use the TensorFlow data service to offload some of the CPU compute to other machines In order to facilitate our discussion, we will build a toy example based on Resnet50. In the code block below, I have built a model using TensorFlow’s built in Resnet50 application. I have added a relatively heavy data pre-processing pipeline which includes dilation, blur filtering, and a number of TensorFlow pre-processing layers. (See the documentation for the advantages of using such layers.) import tensorflow as tfimport tensorflow_addons as tfafrom tensorflow.keras.applications.resnet50 import ResNet50from tensorflow.keras.layers.experimental import preprocessingdef get_dataset(batch_size): # parse TFRecord def parse_image_function(example_proto): image_feature_description = {'image': tf.io.FixedLenFeature([], tf.string), 'label': tf.io.FixedLenFeature([], tf.int64)} features = tf.io.parse_single_example( example_proto, image_feature_description) image = tf.io.decode_raw(features['image'], tf.uint8) image.set_shape([3 * 32 * 32]) image = tf.reshape(image, [32, 32, 3]) label = tf.cast(features['label'], tf.int32) return image, label # dilation filter def dilate(image, label): dilateFilter = tf.zeros([3, 3, 3], tf.uint8) image = tf.expand_dims(image, 0) image = tf.nn.dilation2d( image, dilateFilter, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], padding='SAME', data_format='NHWC') image = tf.squeeze(image) return image, label # blur filter def blur(image, label): image = tfa.image.gaussian_filter2d(image=image, filter_shape=(11, 11), sigma=0.8) return image, label # rescale filter def rescale(image, label): image = preprocessing.Rescaling(1.0 / 255)(image) return image, label # augmentation filters def augment(image, label): data_augmentation = tf.keras.Sequential( [preprocessing.RandomFlip("horizontal"), preprocessing.RandomRotation(0.1), preprocessing.RandomZoom(0.1)]) image = data_augmentation(image) return image, label autotune = tf.data.experimental.AUTOTUNE options = tf.data.Options() options.experimental_deterministic = False records = tf.data.Dataset.list_files('data/*', shuffle=True).with_options(options) # load from TFRecord files ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune).repeat() ds = ds.map(parse_image_function, num_parallel_calls=autotune) ds = ds.map(dilate, num_parallel_calls=autotune) ds = ds.map(blur, num_parallel_calls=autotune) ds = ds.batch(batch_size) ds = ds.map(rescale,num_parallel_calls=autotune) ds = ds.map(augment, num_parallel_calls=autotune) ds = ds.prefetch(autotune) return dsif __name__ == "__main__": model = ResNet50(weights=None, input_shape=(32, 32, 3), classes=10) model.compile(loss=tf.losses.SparseCategoricalCrossentropy(), optimizer=tf.optimizers.Adam()) dataset = get_dataset(batch_size = 1024) model.fit(dataset, steps_per_epoch=100, epochs=10)) The raw data input is stored in TFRecord files, which I created from the CIFAR-10 dataset, (using this script). I have created this example so as to artificially create a performance bottleneck. I would not, under any circumstances, recommend using it for actual training. All tests were run on an Amazon ec2 p2.xlarge instance type using an Amazon Deep Learning AMI. There are a number of different tools and techniques for evaluating the runtime performance of a training session, and identifying and studying an input pipeline bottleneck. Let’s review just a few of them: The first thing to check is the system resource utilization. There are a number of different ways to do this. The Linux top command shows the CPU utilization. To see how the utilization breaks down per CPU core, type ‘1’ while top is running. To measure the GPU utilization, you can use nvidia-smi. When training in Amazon EC2, you can use Amazon CloudWatch to monitor system metrics. While the GPU metrics are not included by default, you can add these by using the gpumon utility. Below is a sample graph of the CPU and GPU utilization captured across several different experiments. In the use case we introduced above, the average reported GPU utilization caps out under 50% with long periods of idle time. At the same time, the CPU is highly utilized, with some of the cores reaching maximum utilization. To dive into the next level of detail of how the training is performing, you can use a performance profiler. TensorFlow Profiler: The built in TensorFlow profiler includes a wealth of performance analytics, and in particular tools for analyzing the performance of the input pipeline. You can view using TensorBoard by installing the TensorBoard profile plugin. One way to enable the profiler, is to program the training loop with the TensorBoad callback. # program the callback to capture steps 20-24cb = tf.keras.callbacks.TensorBoard( log_dir='/tmp/profile', profile_batch='20,24', histogram_freq=0, write_images=False)model.fit(dataset, steps_per_epoch=100, epochs=10, callbacks=[cb]) Below is the profiling overview page for our use case example on which the data input bottleneck is glaringly apparent. The trace-viewer tool allows you to drill down into the details of the pipeline execution, and study the flow of data in between the CPU and GPU. In our example, you can clearly see long periods of GPU idle time, due to the data input bottleneck. Amazon SageMaker Debugger: If you are training in the Amazon SageMaker environment, you can take advantage of the profiling features that are built into Amazon SageMaker Debugger. Here is an example of how a severe bottleneck in the input pipeline will appear in Amazon SageMaker Studio. Linux Profilers: General purpose Linux performance profilers are also often helpful in analyzing training bottlenecks. For example, using the Linux perf utility we are able to see that our CPU spends a large chunk of its time on an internal linear algebra function: Being that the objective of our analysis is to accelerate the training runtime, it is only natural that we would use this metric as a measure of our performance. In our example, we will use the average runtime of a single (100 step) epoch as our primary performance metric, and measure how different changes to the model affect this value. The average runtime of a single epoch of the model above, is 122 seconds. A useful technique (described here) for measuring what the runtime would be, if it were not for the data input bottleneck, is by caching the first processed input batch and using the same cached batch for all subsequent steps. This essentially shuts off the preprocessing pipeline, and enables us to calculate the ideal epoch runtime. To implement the technique, we simply tack on the following line of code at the end of our dataset creation: ds = ds.take(1).cache().repeat() By applying this technique to our example, we are able to reduce the runtime to 58 seconds. In other words, were it not for the data input bottleneck, we would be able to speed up training by more than a factor of 2. In the next sections we will walk through a number of proposed steps for solving a bottleneck in the input pipeline. We will demonstrate some of the steps on our toy example, keeping in mind the target runtime we have just calculated, 58 seconds per epoch. The first thing to do in order to address the data preprocessing bottleneck, is to identify any operations that can be preponed into the, raw, data record creation phase. The more operations we can move into the data creation phase, the more we can free up CPU cycles during training. Any operations that are run in the beginning of the pipeline, in a deterministic fashion (have no random component), that do not depend on a hyper-parameter, and do not excessively increase the size of the data, are good candidates for preponement. In our toy example, the dilation operation, (assuming it does not depend on a hyper parameter), fits this criteria. So the first thing we will do is knock off the dilation operation, and assume that the TFRecords contain the image data after it has already undergone appropriate dilation. In our specific implementation, the blur filter might have also been a good candidate for preponement, but since, in most cases, blurring is applied randomly, we will leave it in. By removing just the dilation operation, our runtime decreases to 115 seconds per epoch. This is less than our starting value of 122 seconds per epoch, but we still have a long way to go to get to our target of 58 seconds per epoch. One thing to take note of, is that certain operations might change the size of your data records, and thus, might impact the overall size of your dataset, as well as the amount of network traffic during training (if the training set is stored remotely). If you choose to prepone operations that increase the size of the data, excessively, you might run the risk of replacing one bottleneck with another, i.e. a network IO or data-loading bottleneck. Once we have moved as many operations as possible to the data creation phase, the second step is to identify ways in which to optimize the performance of the remaining pipeline. Often times, some small tweaks to the input pipeline setup, could reduce the performance overhead. Here are just a few things you could try: If you have multiple dataset map functions that are relatively small, consider grouping them into a single map function.Conversely, if you have a dataset map function that is very large, consider breaking it up into two or more smaller functions in order to better utilize the built in parallel call support.Look for operations that could be applied post batching rather than per record. (In our example, the blur function could, theoretically, be applied on training batches, but since it is typically applied in a random fashion, we will leave it per record.)Use low precision types wherever possible. Postpone casting to higher precision to the end of the pipeline.If your pipeline includes tf.numpy_function or tf.py_function, consider using TensorFlow primitives instead. If you have multiple dataset map functions that are relatively small, consider grouping them into a single map function. Conversely, if you have a dataset map function that is very large, consider breaking it up into two or more smaller functions in order to better utilize the built in parallel call support. Look for operations that could be applied post batching rather than per record. (In our example, the blur function could, theoretically, be applied on training batches, but since it is typically applied in a random fashion, we will leave it per record.) Use low precision types wherever possible. Postpone casting to higher precision to the end of the pipeline. If your pipeline includes tf.numpy_function or tf.py_function, consider using TensorFlow primitives instead. Make sure that your TensorFlow binaries were configured (and compiled) to take full advantage of your CPU, and CPU extensions. For example, if you are using a modern x86 ISA CPU, (such as Intel or AMD), make sure to use TensorFlow binaries that are optimized to use the CPU’s advanced vector extensions (e.g. AVX2). Intel, in general, offers a wide variety of binaries that are specifically optimized to run on Intel CPUs, including intelpython, and TensorFlow-mkl. Note that one of the advantages of using a cloud based solution for training, is that the cloud learning environment is, (presumably,) configured to take full advantage of the cloud system resources. When you have a CPU bottleneck in a multi-CPU core system, you might find that, while one or more of the CPU cores are at full utilization, other are not. This is actually quite common. One thing that you could try, is to improve the load balancing between the CPUs so that the overall CPU utilization increases. You could try this by using the tf.config.set_logical_device_configuration API to separate the CPU compute into multiple logical devices, and the tf.device API to specify where each operation should be run. You can also try to improve the load balancing by playing around with different options for the num_parallel_calls argument of the tf.data.Dataset.mapfunction, (instead of relying on TensorFlow’s autotune feature). In any case, keep in mind that this is likely to be a tedious, pain-staking, effort, and that even the slightest change to your model, will, likely require recalculating the load balancing. As in our example, you might find that even after you have exhausted all options for preponing operations to the data creation phase, and optimizing the CPU code, you continue to face a data preprocessing bottleneck. The next option to consider is to modify the load balancing between the CPU and the GPU, by moving some of the preprocessing operations onto the GPU. The downside to this approach is that we are almost certain to increase the runtime of a GPU step. Also, since we are increasing the size of the computation graph that is running on the GPU, we may need to free up some GPU memory by running with a smaller batch size. As a result, it is highly unlikely that we will be able to achieve the target throughput we calculated above. But if it reduces the overall train time, then it is totally worth it. Let’s explore a few ways to offload preprocessing operations onto the GPU. In most cases, the best way to offload from the CPU, is by moving operations that are performed at the end of the preprocessing pipeline unto the GPU. By targeting these “tail” operations, rather than operations in the middle of the pipeline, we avoid the overhead of data transfers between the GPU and the CPU. If the “tail” operations are performed on the model input, we can place them at the head of the model. If they are performed on label data, we can modify our loss function to perform these operations before applying the actual loss. In our example, we have removed the augmentations from our input pipeline, and instead applied them to the beginning of our GPU computation graph: data_augmentation = tf.keras.Sequential( [preprocessing.RandomFlip("horizontal"), preprocessing.RandomRotation(0.1), preprocessing.RandomZoom(0.1)])inputs = tf.keras.Input(shape=(32, 32, 3))# Augment imagesx = data_augmentation(inputs)# Add the rest of the modeloutputs = tf.keras.applications.ResNet50(weights=None, input_shape=(32, 32, 3), classes=10)(x)model = tf.keras.Model(inputs, outputs) By applying this change, we are able to reduce the runtime down to 108 seconds per epoch. By wrapping operations with a tf.device(‘/device:GPU:0’) statement, we can force certain operations to run on the GPU. The downside to this method, is that it requires transferring data to and from the GPU device. In our example, we chose to apply this technique to the blur function, by modifying it as follows: def blur(image, label): import tensorflow_addons as tfa with tf.device('/device:GPU:0'): image = tfa.image.gaussian_filter2d(image=image, filter_shape=(11, 11), sigma=0.8) return image, label When running the blur function on the GPU in this manner, while leaving the augmentations on the CPU, we attain an epoch runtime of 97 seconds. When combining both techniques, the epoch runtime is 98 seconds. Using the TensorFlow profiler trace-viewer, we are able to see how the tf.device technique increases the data traffic between the CPU and the GPU: By comparing the highlighted streams in this experiment, to the same streams in the trace-viewer capture above, we see that there are significantly more memory copies to and from the GPU. We also see that the GPU is far more active. Another way to verify that the blur function is indeed running on the CPU, is to set tf.debugging.set_log_device_placement(True). You can run the example, once with the blur function on the CPU, and once with the blur function on the GPU, and see how it impacts the output of the log device placement routine. NVIDAI DALI is a framework for building highly optimized preprocessing pipelines. In particular, using NVIDIA DALI, you can program parts of your pipeline, or your entire pipeline, to run on the GPU. A DALI pipeline is built from DALI operations. DALI comes with a list of supported operations, as well as APIs for creating custom operations. Using the TensorFlow DALI plugin, DALI pipelines can be wrapped with the, tf.data.Dataset API compliant, DALIDataset, as shown here. In addition, DALI supports loading from TFRecord files as shown here. Unfortunately, as of the time of this writing, the documented support for DALI is limited to version 1 compatible TensorFlow. (Those of you who have read my previous blogs, should already know how I feel about using legacy code.) In addition, NVIDIA DALI was designed for NVIDIA GPUs. It will not run on other machine learning accelerators. Another consideration is distributed training. While DALI does support multi-gpu training, depending on how you implement distributed training, (e.g. with Horovod or a TensorFlow distribution strategy, with model.fit() or a custom training loop), integrating a DALI pipeline will vary between being slightly more difficult, and much more difficult. If you feel strongly about using the latest TensorFlow features, or if you want your code to be compliant with other accelerators, (AWS Tranium, Habana Gaudi, TPU, etc.), or if converting your pipeline to DALI operations would require a lot of work, or if you rely on the high level TensorFlow distributed training APIs, NVIDIA DALI might not be the right solution for you. Using DALI requires use of the TensorFlow DALI plugin python package. See the documentation for installation steps. In the code block below, I show how to convert the pipeline from our use case to NVIDIA DALI. I have left out some of the random augmentations, as there were no built-in, corresponding, DALI operations. from nvidia.dali.pipeline import Pipelineimport nvidia.dali.ops as opsimport nvidia.dali.types as typesimport nvidia.dali.tfrecord as tfrecimport nvidia.dali.plugin.tf as dali_tfimport tensorflow.compat.v1 as tftf.disable_eager_execution()class TFRecordPipeline(Pipeline): def __init__(self, batch_size, num_threads, device = 'cpu', device_id = 0): super(TFRecordPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.TFRecordReader( path = ['data/train0.tfrecords'], index_path = ['index/train0'], features = { "image": tfrec.FixedLenFeature((), tfrec.string, ""), "label": tfrec.FixedLenFeature([], tfrec.int64, -1)}) self.decode = ops.Cast(device=device,dtype=types.UINT8) self.reshape = ops.Reshape(device=device, shape=[32, 32, 3]) self.cast = ops.Cast(device=device, dtype=types.DALIDataType.INT32) self.blur = ops.GaussianBlur(device=device, window_size=11,sigma=0.8) self.iter = 0 def define_graph(self): inputs = self.input() images = self.decode(inputs["image"].gpu()) images = self.reshape(images) images = self.blur(images)/255. labels = self.cast(inputs["label"].gpu()) return (images, labels) def iter_setup(self): passif __name__ == "__main__": batch_size = 1024 shapes = ((batch_size, 32, 32, 3), (batch_size)) pipe = TFRecordPipeline(batch_size=batch_size, num_threads=4, device='gpu', device_id=0) with tf.device('/gpu:0'): # Create dataset ds = dali_tf.DALIDataset( pipeline=pipe, batch_size=batch_size, output_shapes=shapes, output_dtypes=(tf.float32, tf.int32), device_id=0) model = tf.keras.applications.resnet.ResNet50( weights=None, input_shape=(32, 32, 3), classes=10) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.Adam()) model.fit(ds, steps_per_epoch=100, epochs=10) I ran the script in TensorFlow 2.3 (as it would seem that, as of the time of this writing, DALI has not been updated to support TensorFlow 2.4). The resultant runtime of a 100 step epoch was 77 seconds. While this trial did not include the augmentations, it is clear that DALI offers potential for significant runtime improvement. As I mentioned above, offloading operations to the GPU might require freeing up some memory be reducing the size of the training batch. It turns out that this was not required in our toy example. (This probably means that we could have started out with a larger batch size.) This finding will not necessarily carry over to other models, especially if you are making sure to maximize your GPU memory and batch size. The final option we explore, is to offload some of the preprocessing activity to other machines. Rather than moving preprocessing computation onto the GPU, we will move it to CPU cores on auxiliary machines. We will explore this approach using the, relatively new, TensorFlow data service feature. Introduced in TensorFlow version 2.3, tf.data.experimental.service provides APIs for defining dedicated worker machines for performing data preprocessing. A dispatch server is responsible for distributing preprocessing tasks to one, or more, worker servers, each of which load the raw data directly from storage, and send the processed data to the GPU device. By applying tf.data.experimental.service.distribute to your dataset, you can program the dataset to run all preprocessing operations up to the point of application, on the dedicated workers. The number and types of worker services to use, and where in the pipeline to apply the service, should be determined by considerations, such as the severity of your bottleneck, the availability and cost of auxiliary machines, the manner in which the preprocessing operations impact the size of the data, and how this impacts the network traffic. For example, if you choose a remote worker machine with a low network bandwidth, and program a preprocessing operation that blows up the size of the data to run on the worker, you might not see any performance improvement. Let’s demonstrate the use of this API on our toy example. For this demonstration, I have chosen a single, auxiliary Amazon EC2 c5.4xlarge instance with 16 CPU cores, and with the same Amazon Deep Learning AMI. The communication between p2.xlarge and the c5.4xlarge will use the grpc network protocol, so you need to make sure that both instances are in a security group which allows inbound traffic of the relevant protocol, one from the other. On the worker device we run the following script, where “10.0.1.171” is the ip adress of the auxiliary device: import tensorflow as tfd_config = tf.data.experimental.service.DispatcherConfig(port=5000)dispatcher = tf.data.experimental.service.DispatchServer(d_config)w_config = tf.data.experimental.service.WorkerConfig(port=5001, dispatcher_address=dispatcher.target.split("://")[1], worker_address='10.0.1.171:5001')worker = tf.data.experimental.service.WorkerServer(w_config)dispatcher.join() Note that we are running the dispatch server and worker server on the same machine. We also make sure that the TFRecord files are copied over to this machine, as the workers will load the raw data from those files. On the GPU machine we have modified the train script as follows: autotune = tf.data.experimental.AUTOTUNEoptions = tf.data.Options()options.experimental_deterministic = Falserecords = tf.data.Dataset.list_files('data/*', shuffle=True).with_options(options)ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune).repeat()ds = ds.map(parse_image_function, num_parallel_calls=autotune)ds = ds.map(blur, num_parallel_calls=autotune)# use the TensorFlow Data Serviceds = ds.apply(tf.data.experimental.service.distribute( processing_mode="parallel_epochs", service='grpc://10.0.1.171:5000'))ds = ds.batch(batch_size)ds = ds.map(rescale,num_parallel_calls=autotune)ds = ds.map(augment, num_parallel_calls=autotune)ds = ds.prefetch(autotune) Note, that we have programmed just the record parsing, and heavy blur function to run on the worker. The batching and augmentations remain on the primary device. The results of running this setup could not be better! The runtime per epoch is 58 seconds, meeting the target we set for ourselves above. By using an auxiliary CPU device, and the TensorFlow data service to offload preprocessing computation, we have completely solved the CPU bottleneck! And indeed, we find that the average GPU utilization in this case is up around 97%. In the table below we summarize our findings on our toy, resnet50 model: In this post we have surveyed a number of ways to address a performance bottleneck in the data input pipeline. In particular, we have shown how the TensorFlow Data Service can be used to completely solve this bottleneck. This survey is not intended to be all comprehensive. There are likely to be additional tools and techniques available. While we have demonstrated how to apply these techniques to a toy Resnet50 model, their impact is certain to vary across models and datasets. Please don’t hesitate to share your own tools, techniques, and experiences.
[ { "code": null, "e": 853, "s": 171, "text": "In a previous post, I spoke about the importance of profiling the runtime performance of your DNN training sessions as a means to making the most of your training resources, accelerating your training, and saving money. I described a typical training pipeline, (see the diagram below), reviewed some of the potential performance bottlenecks, and surveyed some of the tools available for identifying such bottlenecks. In this post I would like to expand on one of the more common performance bottlenecks, the CPU bottleneck, and some of the ways to overcome it. More specifically, we will discuss bottlenecks that occur in the data preprocessing pipeline, and ways to overcome them." }, { "code": null, "e": 1139, "s": 853, "text": "In the context of this post, we will assume that we are using TensorFlow, specifically TensorFlow 2.4, to train an image processing model on a GPU device, but the content is, mostly, just as relevant to other training frameworks, other types of models, and other training accelerators." }, { "code": null, "e": 2103, "s": 1139, "text": "A CPU bottleneck occurs when the GPU resource is under utilized as a result of one, or more of the CPUs, having reached maximum utilization. In this situation, the GPU will be partially idle while it waits for the CPU to pass in training data. This is an undesired state. Being that the GPU is, typically, the most expensive resource in the system, your goal should always be to maximize its utilization. Without getting into too many technical details, a CPU bottleneck generally occurs when the ratio between the “amount” of data pre-processing, which is performed on the CPU, and the “amount” of compute performed by the model on the GPU, is greater that the ratio between the overall CPU compute capacity and the overall GPU compute capacity. For example, if both your CPU cores and GPU are maximally utilized, and then you upgrade to a more powerful GPU, or downgrade to a system with fewer CPU cores, your training runtime performance will become CPU bound." }, { "code": null, "e": 2483, "s": 2103, "text": "Naturally, your first instinct will be to simply switch over to a machine with a more appropriate CPU to GPU compute ratio. But, sadly, most of us don’t have that freedom. And while cloud services, such as Amazon SageMaker, offer a variety of training instance types, with different CPU-compute to GPU-compute ratios, you may find that none of them quite fit your specific needs." }, { "code": null, "e": 2632, "s": 2483, "text": "Assuming that you are stuck with the system that you have, what steps can you take to address your performance bottleneck and speed up the training?" }, { "code": null, "e": 2730, "s": 2632, "text": "In the next sections we will propose four steps for addressing the preprocessing data bottleneck." }, { "code": null, "e": 2978, "s": 2730, "text": "Identify any operations that can be moved to the data preparation phaseOptimize the data pre-processing pipelinePerform some of the pre-processing steps on the GPUUse the TensorFlow data service to offload some of the CPU compute to other machines" }, { "code": null, "e": 3050, "s": 2978, "text": "Identify any operations that can be moved to the data preparation phase" }, { "code": null, "e": 3092, "s": 3050, "text": "Optimize the data pre-processing pipeline" }, { "code": null, "e": 3144, "s": 3092, "text": "Perform some of the pre-processing steps on the GPU" }, { "code": null, "e": 3229, "s": 3144, "text": "Use the TensorFlow data service to offload some of the CPU compute to other machines" }, { "code": null, "e": 3315, "s": 3229, "text": "In order to facilitate our discussion, we will build a toy example based on Resnet50." }, { "code": null, "e": 3628, "s": 3315, "text": "In the code block below, I have built a model using TensorFlow’s built in Resnet50 application. I have added a relatively heavy data pre-processing pipeline which includes dilation, blur filtering, and a number of TensorFlow pre-processing layers. (See the documentation for the advantages of using such layers.)" }, { "code": null, "e": 6488, "s": 3628, "text": "import tensorflow as tfimport tensorflow_addons as tfafrom tensorflow.keras.applications.resnet50 import ResNet50from tensorflow.keras.layers.experimental import preprocessingdef get_dataset(batch_size): # parse TFRecord def parse_image_function(example_proto): image_feature_description = {'image': tf.io.FixedLenFeature([], tf.string), 'label': tf.io.FixedLenFeature([], tf.int64)} features = tf.io.parse_single_example( example_proto, image_feature_description) image = tf.io.decode_raw(features['image'], tf.uint8) image.set_shape([3 * 32 * 32]) image = tf.reshape(image, [32, 32, 3]) label = tf.cast(features['label'], tf.int32) return image, label # dilation filter def dilate(image, label): dilateFilter = tf.zeros([3, 3, 3], tf.uint8) image = tf.expand_dims(image, 0) image = tf.nn.dilation2d( image, dilateFilter, strides=[1, 1, 1, 1], dilations=[1, 1, 1, 1], padding='SAME', data_format='NHWC') image = tf.squeeze(image) return image, label # blur filter def blur(image, label): image = tfa.image.gaussian_filter2d(image=image, filter_shape=(11, 11), sigma=0.8) return image, label # rescale filter def rescale(image, label): image = preprocessing.Rescaling(1.0 / 255)(image) return image, label # augmentation filters def augment(image, label): data_augmentation = tf.keras.Sequential( [preprocessing.RandomFlip(\"horizontal\"), preprocessing.RandomRotation(0.1), preprocessing.RandomZoom(0.1)]) image = data_augmentation(image) return image, label autotune = tf.data.experimental.AUTOTUNE options = tf.data.Options() options.experimental_deterministic = False records = tf.data.Dataset.list_files('data/*', shuffle=True).with_options(options) # load from TFRecord files ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune).repeat() ds = ds.map(parse_image_function, num_parallel_calls=autotune) ds = ds.map(dilate, num_parallel_calls=autotune) ds = ds.map(blur, num_parallel_calls=autotune) ds = ds.batch(batch_size) ds = ds.map(rescale,num_parallel_calls=autotune) ds = ds.map(augment, num_parallel_calls=autotune) ds = ds.prefetch(autotune) return dsif __name__ == \"__main__\": model = ResNet50(weights=None, input_shape=(32, 32, 3), classes=10) model.compile(loss=tf.losses.SparseCategoricalCrossentropy(), optimizer=tf.optimizers.Adam()) dataset = get_dataset(batch_size = 1024) model.fit(dataset, steps_per_epoch=100, epochs=10))" }, { "code": null, "e": 6600, "s": 6488, "text": "The raw data input is stored in TFRecord files, which I created from the CIFAR-10 dataset, (using this script)." }, { "code": null, "e": 6761, "s": 6600, "text": "I have created this example so as to artificially create a performance bottleneck. I would not, under any circumstances, recommend using it for actual training." }, { "code": null, "e": 6856, "s": 6761, "text": "All tests were run on an Amazon ec2 p2.xlarge instance type using an Amazon Deep Learning AMI." }, { "code": null, "e": 7063, "s": 6856, "text": "There are a number of different tools and techniques for evaluating the runtime performance of a training session, and identifying and studying an input pipeline bottleneck. Let’s review just a few of them:" }, { "code": null, "e": 7648, "s": 7063, "text": "The first thing to check is the system resource utilization. There are a number of different ways to do this. The Linux top command shows the CPU utilization. To see how the utilization breaks down per CPU core, type ‘1’ while top is running. To measure the GPU utilization, you can use nvidia-smi. When training in Amazon EC2, you can use Amazon CloudWatch to monitor system metrics. While the GPU metrics are not included by default, you can add these by using the gpumon utility. Below is a sample graph of the CPU and GPU utilization captured across several different experiments." }, { "code": null, "e": 7872, "s": 7648, "text": "In the use case we introduced above, the average reported GPU utilization caps out under 50% with long periods of idle time. At the same time, the CPU is highly utilized, with some of the cores reaching maximum utilization." }, { "code": null, "e": 7981, "s": 7872, "text": "To dive into the next level of detail of how the training is performing, you can use a performance profiler." }, { "code": null, "e": 8327, "s": 7981, "text": "TensorFlow Profiler: The built in TensorFlow profiler includes a wealth of performance analytics, and in particular tools for analyzing the performance of the input pipeline. You can view using TensorBoard by installing the TensorBoard profile plugin. One way to enable the profiler, is to program the training loop with the TensorBoad callback." }, { "code": null, "e": 8574, "s": 8327, "text": "# program the callback to capture steps 20-24cb = tf.keras.callbacks.TensorBoard( log_dir='/tmp/profile', profile_batch='20,24', histogram_freq=0, write_images=False)model.fit(dataset, steps_per_epoch=100, epochs=10, callbacks=[cb])" }, { "code": null, "e": 8694, "s": 8574, "text": "Below is the profiling overview page for our use case example on which the data input bottleneck is glaringly apparent." }, { "code": null, "e": 8941, "s": 8694, "text": "The trace-viewer tool allows you to drill down into the details of the pipeline execution, and study the flow of data in between the CPU and GPU. In our example, you can clearly see long periods of GPU idle time, due to the data input bottleneck." }, { "code": null, "e": 9229, "s": 8941, "text": "Amazon SageMaker Debugger: If you are training in the Amazon SageMaker environment, you can take advantage of the profiling features that are built into Amazon SageMaker Debugger. Here is an example of how a severe bottleneck in the input pipeline will appear in Amazon SageMaker Studio." }, { "code": null, "e": 9495, "s": 9229, "text": "Linux Profilers: General purpose Linux performance profilers are also often helpful in analyzing training bottlenecks. For example, using the Linux perf utility we are able to see that our CPU spends a large chunk of its time on an internal linear algebra function:" }, { "code": null, "e": 9657, "s": 9495, "text": "Being that the objective of our analysis is to accelerate the training runtime, it is only natural that we would use this metric as a measure of our performance." }, { "code": null, "e": 9909, "s": 9657, "text": "In our example, we will use the average runtime of a single (100 step) epoch as our primary performance metric, and measure how different changes to the model affect this value. The average runtime of a single epoch of the model above, is 122 seconds." }, { "code": null, "e": 10244, "s": 9909, "text": "A useful technique (described here) for measuring what the runtime would be, if it were not for the data input bottleneck, is by caching the first processed input batch and using the same cached batch for all subsequent steps. This essentially shuts off the preprocessing pipeline, and enables us to calculate the ideal epoch runtime." }, { "code": null, "e": 10353, "s": 10244, "text": "To implement the technique, we simply tack on the following line of code at the end of our dataset creation:" }, { "code": null, "e": 10386, "s": 10353, "text": "ds = ds.take(1).cache().repeat()" }, { "code": null, "e": 10603, "s": 10386, "text": "By applying this technique to our example, we are able to reduce the runtime to 58 seconds. In other words, were it not for the data input bottleneck, we would be able to speed up training by more than a factor of 2." }, { "code": null, "e": 10860, "s": 10603, "text": "In the next sections we will walk through a number of proposed steps for solving a bottleneck in the input pipeline. We will demonstrate some of the steps on our toy example, keeping in mind the target runtime we have just calculated, 58 seconds per epoch." }, { "code": null, "e": 11683, "s": 10860, "text": "The first thing to do in order to address the data preprocessing bottleneck, is to identify any operations that can be preponed into the, raw, data record creation phase. The more operations we can move into the data creation phase, the more we can free up CPU cycles during training. Any operations that are run in the beginning of the pipeline, in a deterministic fashion (have no random component), that do not depend on a hyper-parameter, and do not excessively increase the size of the data, are good candidates for preponement. In our toy example, the dilation operation, (assuming it does not depend on a hyper parameter), fits this criteria. So the first thing we will do is knock off the dilation operation, and assume that the TFRecords contain the image data after it has already undergone appropriate dilation." }, { "code": null, "e": 11863, "s": 11683, "text": "In our specific implementation, the blur filter might have also been a good candidate for preponement, but since, in most cases, blurring is applied randomly, we will leave it in." }, { "code": null, "e": 12096, "s": 11863, "text": "By removing just the dilation operation, our runtime decreases to 115 seconds per epoch. This is less than our starting value of 122 seconds per epoch, but we still have a long way to go to get to our target of 58 seconds per epoch." }, { "code": null, "e": 12546, "s": 12096, "text": "One thing to take note of, is that certain operations might change the size of your data records, and thus, might impact the overall size of your dataset, as well as the amount of network traffic during training (if the training set is stored remotely). If you choose to prepone operations that increase the size of the data, excessively, you might run the risk of replacing one bottleneck with another, i.e. a network IO or data-loading bottleneck." }, { "code": null, "e": 12724, "s": 12546, "text": "Once we have moved as many operations as possible to the data creation phase, the second step is to identify ways in which to optimize the performance of the remaining pipeline." }, { "code": null, "e": 12865, "s": 12724, "text": "Often times, some small tweaks to the input pipeline setup, could reduce the performance overhead. Here are just a few things you could try:" }, { "code": null, "e": 13642, "s": 12865, "text": "If you have multiple dataset map functions that are relatively small, consider grouping them into a single map function.Conversely, if you have a dataset map function that is very large, consider breaking it up into two or more smaller functions in order to better utilize the built in parallel call support.Look for operations that could be applied post batching rather than per record. (In our example, the blur function could, theoretically, be applied on training batches, but since it is typically applied in a random fashion, we will leave it per record.)Use low precision types wherever possible. Postpone casting to higher precision to the end of the pipeline.If your pipeline includes tf.numpy_function or tf.py_function, consider using TensorFlow primitives instead." }, { "code": null, "e": 13763, "s": 13642, "text": "If you have multiple dataset map functions that are relatively small, consider grouping them into a single map function." }, { "code": null, "e": 13952, "s": 13763, "text": "Conversely, if you have a dataset map function that is very large, consider breaking it up into two or more smaller functions in order to better utilize the built in parallel call support." }, { "code": null, "e": 14206, "s": 13952, "text": "Look for operations that could be applied post batching rather than per record. (In our example, the blur function could, theoretically, be applied on training batches, but since it is typically applied in a random fashion, we will leave it per record.)" }, { "code": null, "e": 14314, "s": 14206, "text": "Use low precision types wherever possible. Postpone casting to higher precision to the end of the pipeline." }, { "code": null, "e": 14423, "s": 14314, "text": "If your pipeline includes tf.numpy_function or tf.py_function, consider using TensorFlow primitives instead." }, { "code": null, "e": 14889, "s": 14423, "text": "Make sure that your TensorFlow binaries were configured (and compiled) to take full advantage of your CPU, and CPU extensions. For example, if you are using a modern x86 ISA CPU, (such as Intel or AMD), make sure to use TensorFlow binaries that are optimized to use the CPU’s advanced vector extensions (e.g. AVX2). Intel, in general, offers a wide variety of binaries that are specifically optimized to run on Intel CPUs, including intelpython, and TensorFlow-mkl." }, { "code": null, "e": 15089, "s": 14889, "text": "Note that one of the advantages of using a cloud based solution for training, is that the cloud learning environment is, (presumably,) configured to take full advantage of the cloud system resources." }, { "code": null, "e": 16014, "s": 15089, "text": "When you have a CPU bottleneck in a multi-CPU core system, you might find that, while one or more of the CPU cores are at full utilization, other are not. This is actually quite common. One thing that you could try, is to improve the load balancing between the CPUs so that the overall CPU utilization increases. You could try this by using the tf.config.set_logical_device_configuration API to separate the CPU compute into multiple logical devices, and the tf.device API to specify where each operation should be run. You can also try to improve the load balancing by playing around with different options for the num_parallel_calls argument of the tf.data.Dataset.mapfunction, (instead of relying on TensorFlow’s autotune feature). In any case, keep in mind that this is likely to be a tedious, pain-staking, effort, and that even the slightest change to your model, will, likely require recalculating the load balancing." }, { "code": null, "e": 16905, "s": 16014, "text": "As in our example, you might find that even after you have exhausted all options for preponing operations to the data creation phase, and optimizing the CPU code, you continue to face a data preprocessing bottleneck. The next option to consider is to modify the load balancing between the CPU and the GPU, by moving some of the preprocessing operations onto the GPU. The downside to this approach is that we are almost certain to increase the runtime of a GPU step. Also, since we are increasing the size of the computation graph that is running on the GPU, we may need to free up some GPU memory by running with a smaller batch size. As a result, it is highly unlikely that we will be able to achieve the target throughput we calculated above. But if it reduces the overall train time, then it is totally worth it. Let’s explore a few ways to offload preprocessing operations onto the GPU." }, { "code": null, "e": 17450, "s": 16905, "text": "In most cases, the best way to offload from the CPU, is by moving operations that are performed at the end of the preprocessing pipeline unto the GPU. By targeting these “tail” operations, rather than operations in the middle of the pipeline, we avoid the overhead of data transfers between the GPU and the CPU. If the “tail” operations are performed on the model input, we can place them at the head of the model. If they are performed on label data, we can modify our loss function to perform these operations before applying the actual loss." }, { "code": null, "e": 17597, "s": 17450, "text": "In our example, we have removed the augmentations from our input pipeline, and instead applied them to the beginning of our GPU computation graph:" }, { "code": null, "e": 18037, "s": 17597, "text": "data_augmentation = tf.keras.Sequential( [preprocessing.RandomFlip(\"horizontal\"), preprocessing.RandomRotation(0.1), preprocessing.RandomZoom(0.1)])inputs = tf.keras.Input(shape=(32, 32, 3))# Augment imagesx = data_augmentation(inputs)# Add the rest of the modeloutputs = tf.keras.applications.ResNet50(weights=None, input_shape=(32, 32, 3), classes=10)(x)model = tf.keras.Model(inputs, outputs)" }, { "code": null, "e": 18127, "s": 18037, "text": "By applying this change, we are able to reduce the runtime down to 108 seconds per epoch." }, { "code": null, "e": 18341, "s": 18127, "text": "By wrapping operations with a tf.device(‘/device:GPU:0’) statement, we can force certain operations to run on the GPU. The downside to this method, is that it requires transferring data to and from the GPU device." }, { "code": null, "e": 18440, "s": 18341, "text": "In our example, we chose to apply this technique to the blur function, by modifying it as follows:" }, { "code": null, "e": 18678, "s": 18440, "text": "def blur(image, label): import tensorflow_addons as tfa with tf.device('/device:GPU:0'): image = tfa.image.gaussian_filter2d(image=image, filter_shape=(11, 11), sigma=0.8) return image, label" }, { "code": null, "e": 18887, "s": 18678, "text": "When running the blur function on the GPU in this manner, while leaving the augmentations on the CPU, we attain an epoch runtime of 97 seconds. When combining both techniques, the epoch runtime is 98 seconds." }, { "code": null, "e": 19034, "s": 18887, "text": "Using the TensorFlow profiler trace-viewer, we are able to see how the tf.device technique increases the data traffic between the CPU and the GPU:" }, { "code": null, "e": 19267, "s": 19034, "text": "By comparing the highlighted streams in this experiment, to the same streams in the trace-viewer capture above, we see that there are significantly more memory copies to and from the GPU. We also see that the GPU is far more active." }, { "code": null, "e": 19577, "s": 19267, "text": "Another way to verify that the blur function is indeed running on the CPU, is to set tf.debugging.set_log_device_placement(True). You can run the example, once with the blur function on the CPU, and once with the blur function on the GPU, and see how it impacts the output of the log device placement routine." }, { "code": null, "e": 21187, "s": 19577, "text": "NVIDAI DALI is a framework for building highly optimized preprocessing pipelines. In particular, using NVIDIA DALI, you can program parts of your pipeline, or your entire pipeline, to run on the GPU. A DALI pipeline is built from DALI operations. DALI comes with a list of supported operations, as well as APIs for creating custom operations. Using the TensorFlow DALI plugin, DALI pipelines can be wrapped with the, tf.data.Dataset API compliant, DALIDataset, as shown here. In addition, DALI supports loading from TFRecord files as shown here. Unfortunately, as of the time of this writing, the documented support for DALI is limited to version 1 compatible TensorFlow. (Those of you who have read my previous blogs, should already know how I feel about using legacy code.) In addition, NVIDIA DALI was designed for NVIDIA GPUs. It will not run on other machine learning accelerators. Another consideration is distributed training. While DALI does support multi-gpu training, depending on how you implement distributed training, (e.g. with Horovod or a TensorFlow distribution strategy, with model.fit() or a custom training loop), integrating a DALI pipeline will vary between being slightly more difficult, and much more difficult. If you feel strongly about using the latest TensorFlow features, or if you want your code to be compliant with other accelerators, (AWS Tranium, Habana Gaudi, TPU, etc.), or if converting your pipeline to DALI operations would require a lot of work, or if you rely on the high level TensorFlow distributed training APIs, NVIDIA DALI might not be the right solution for you." }, { "code": null, "e": 21506, "s": 21187, "text": "Using DALI requires use of the TensorFlow DALI plugin python package. See the documentation for installation steps. In the code block below, I show how to convert the pipeline from our use case to NVIDIA DALI. I have left out some of the random augmentations, as there were no built-in, corresponding, DALI operations." }, { "code": null, "e": 23919, "s": 21506, "text": "from nvidia.dali.pipeline import Pipelineimport nvidia.dali.ops as opsimport nvidia.dali.types as typesimport nvidia.dali.tfrecord as tfrecimport nvidia.dali.plugin.tf as dali_tfimport tensorflow.compat.v1 as tftf.disable_eager_execution()class TFRecordPipeline(Pipeline): def __init__(self, batch_size, num_threads, device = 'cpu', device_id = 0): super(TFRecordPipeline, self).__init__(batch_size, num_threads, device_id) self.input = ops.TFRecordReader( path = ['data/train0.tfrecords'], index_path = ['index/train0'], features = { \"image\": tfrec.FixedLenFeature((), tfrec.string, \"\"), \"label\": tfrec.FixedLenFeature([], tfrec.int64, -1)}) self.decode = ops.Cast(device=device,dtype=types.UINT8) self.reshape = ops.Reshape(device=device, shape=[32, 32, 3]) self.cast = ops.Cast(device=device, dtype=types.DALIDataType.INT32) self.blur = ops.GaussianBlur(device=device, window_size=11,sigma=0.8) self.iter = 0 def define_graph(self): inputs = self.input() images = self.decode(inputs[\"image\"].gpu()) images = self.reshape(images) images = self.blur(images)/255. labels = self.cast(inputs[\"label\"].gpu()) return (images, labels) def iter_setup(self): passif __name__ == \"__main__\": batch_size = 1024 shapes = ((batch_size, 32, 32, 3), (batch_size)) pipe = TFRecordPipeline(batch_size=batch_size, num_threads=4, device='gpu', device_id=0) with tf.device('/gpu:0'): # Create dataset ds = dali_tf.DALIDataset( pipeline=pipe, batch_size=batch_size, output_shapes=shapes, output_dtypes=(tf.float32, tf.int32), device_id=0) model = tf.keras.applications.resnet.ResNet50( weights=None, input_shape=(32, 32, 3), classes=10) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.Adam()) model.fit(ds, steps_per_epoch=100, epochs=10)" }, { "code": null, "e": 24250, "s": 23919, "text": "I ran the script in TensorFlow 2.3 (as it would seem that, as of the time of this writing, DALI has not been updated to support TensorFlow 2.4). The resultant runtime of a 100 step epoch was 77 seconds. While this trial did not include the augmentations, it is clear that DALI offers potential for significant runtime improvement." }, { "code": null, "e": 24665, "s": 24250, "text": "As I mentioned above, offloading operations to the GPU might require freeing up some memory be reducing the size of the training batch. It turns out that this was not required in our toy example. (This probably means that we could have started out with a larger batch size.) This finding will not necessarily carry over to other models, especially if you are making sure to maximize your GPU memory and batch size." }, { "code": null, "e": 26083, "s": 24665, "text": "The final option we explore, is to offload some of the preprocessing activity to other machines. Rather than moving preprocessing computation onto the GPU, we will move it to CPU cores on auxiliary machines. We will explore this approach using the, relatively new, TensorFlow data service feature. Introduced in TensorFlow version 2.3, tf.data.experimental.service provides APIs for defining dedicated worker machines for performing data preprocessing. A dispatch server is responsible for distributing preprocessing tasks to one, or more, worker servers, each of which load the raw data directly from storage, and send the processed data to the GPU device. By applying tf.data.experimental.service.distribute to your dataset, you can program the dataset to run all preprocessing operations up to the point of application, on the dedicated workers. The number and types of worker services to use, and where in the pipeline to apply the service, should be determined by considerations, such as the severity of your bottleneck, the availability and cost of auxiliary machines, the manner in which the preprocessing operations impact the size of the data, and how this impacts the network traffic. For example, if you choose a remote worker machine with a low network bandwidth, and program a preprocessing operation that blows up the size of the data to run on the worker, you might not see any performance improvement." }, { "code": null, "e": 26528, "s": 26083, "text": "Let’s demonstrate the use of this API on our toy example. For this demonstration, I have chosen a single, auxiliary Amazon EC2 c5.4xlarge instance with 16 CPU cores, and with the same Amazon Deep Learning AMI. The communication between p2.xlarge and the c5.4xlarge will use the grpc network protocol, so you need to make sure that both instances are in a security group which allows inbound traffic of the relevant protocol, one from the other." }, { "code": null, "e": 26639, "s": 26528, "text": "On the worker device we run the following script, where “10.0.1.171” is the ip adress of the auxiliary device:" }, { "code": null, "e": 27030, "s": 26639, "text": "import tensorflow as tfd_config = tf.data.experimental.service.DispatcherConfig(port=5000)dispatcher = tf.data.experimental.service.DispatchServer(d_config)w_config = tf.data.experimental.service.WorkerConfig(port=5001, dispatcher_address=dispatcher.target.split(\"://\")[1], worker_address='10.0.1.171:5001')worker = tf.data.experimental.service.WorkerServer(w_config)dispatcher.join()" }, { "code": null, "e": 27310, "s": 27030, "text": "Note that we are running the dispatch server and worker server on the same machine. We also make sure that the TFRecord files are copied over to this machine, as the workers will load the raw data from those files. On the GPU machine we have modified the train script as follows:" }, { "code": null, "e": 28000, "s": 27310, "text": "autotune = tf.data.experimental.AUTOTUNEoptions = tf.data.Options()options.experimental_deterministic = Falserecords = tf.data.Dataset.list_files('data/*', shuffle=True).with_options(options)ds = tf.data.TFRecordDataset(records, num_parallel_reads=autotune).repeat()ds = ds.map(parse_image_function, num_parallel_calls=autotune)ds = ds.map(blur, num_parallel_calls=autotune)# use the TensorFlow Data Serviceds = ds.apply(tf.data.experimental.service.distribute( processing_mode=\"parallel_epochs\", service='grpc://10.0.1.171:5000'))ds = ds.batch(batch_size)ds = ds.map(rescale,num_parallel_calls=autotune)ds = ds.map(augment, num_parallel_calls=autotune)ds = ds.prefetch(autotune)" }, { "code": null, "e": 28162, "s": 28000, "text": "Note, that we have programmed just the record parsing, and heavy blur function to run on the worker. The batching and augmentations remain on the primary device." }, { "code": null, "e": 28535, "s": 28162, "text": "The results of running this setup could not be better! The runtime per epoch is 58 seconds, meeting the target we set for ourselves above. By using an auxiliary CPU device, and the TensorFlow data service to offload preprocessing computation, we have completely solved the CPU bottleneck! And indeed, we find that the average GPU utilization in this case is up around 97%." }, { "code": null, "e": 28608, "s": 28535, "text": "In the table below we summarize our findings on our toy, resnet50 model:" } ]
JavaScript Tutorial
JavaScript is the world's most popular programming language. JavaScript is the programming language of the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. With our "Try it Yourself" editor, you can edit the source code and view the result. Try it Yourself » We recommend reading this tutorial, in the sequence listed in the menu. If you have a large screen, the menu will always be present on the left. If you have a small screen, open the menu by clicking the top menu sign ☰. Examples are better than 1000 words. Examples are often easier to understand than text explanations. This tutorial supplements all explanations with clarifying "Try it Yourself" examples. If you try all the examples, you will learn a lot about JavaScript, in a very short time! JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages This tutorial covers every version of JavaScript: The Original JavaScript ES1 ES2 ES3 (1997-1999) The First Main Revision ES5 (2009) The Second Revision ES6 (2015) The Yearly Additions (2016, 2017, 2018) In this tutorial, the learning speed is your choice. Everything is up to you. If you are struggling, take a break, or re-read the material. Always make sure you understand all the "Try-it-Yourself" examples. The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code ! Create a variable called carName and assign the value Volvo to it. var = ""; Start the Exercise How do I get JavaScript? Where can I download JavaScript? Is JavaScript Free? You don't have to get or download JavaScript. JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone. JavaScript is free to use for everyone. W3Schools maintains a complete JavaScript reference, including all HTML and browser objects. The reference contains examples for all properties, methods and events, and is continuously updated according to the latest web standards. Test your JavaScript skills at W3Schools! Start JavaScript Quiz! Get certified by completing the JavaScript course 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": 61, "s": 0, "text": "JavaScript is the world's most popular programming language." }, { "code": null, "e": 112, "s": 61, "text": "JavaScript is the programming language of the Web." }, { "code": null, "e": 141, "s": 112, "text": "JavaScript is easy to learn." }, { "code": null, "e": 205, "s": 141, "text": "This tutorial will teach you JavaScript from basic to advanced." }, { "code": null, "e": 291, "s": 205, "text": "With our \"Try it Yourself\" editor, you can edit the source code and view \nthe result." }, { "code": null, "e": 311, "s": 291, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 383, "s": 311, "text": "We recommend reading this tutorial, in the sequence listed in the menu." }, { "code": null, "e": 456, "s": 383, "text": "If you have a large screen, the menu will always be present on the left." }, { "code": null, "e": 531, "s": 456, "text": "If you have a small screen, open the menu by clicking the top menu sign ☰." }, { "code": null, "e": 633, "s": 531, "text": "Examples are better than 1000 words. Examples are often easier to understand \nthan text explanations." }, { "code": null, "e": 720, "s": 633, "text": "This tutorial supplements all explanations with clarifying \"Try it Yourself\" examples." }, { "code": null, "e": 810, "s": 720, "text": "If you try all the examples, you will learn a lot about JavaScript, in a very short time!" }, { "code": null, "e": 880, "s": 810, "text": "JavaScript is one of the 3 languages all web developers \nmust \nlearn:" }, { "code": null, "e": 926, "s": 880, "text": " 1. HTML to define the content of web pages" }, { "code": null, "e": 971, "s": 926, "text": " 2. CSS to specify the layout of web pages" }, { "code": null, "e": 1026, "s": 971, "text": " 3. JavaScript to program the behavior of web pages " }, { "code": null, "e": 1076, "s": 1026, "text": "This tutorial covers every version of JavaScript:" }, { "code": null, "e": 1124, "s": 1076, "text": "The Original JavaScript ES1 ES2 ES3 (1997-1999)" }, { "code": null, "e": 1159, "s": 1124, "text": "The First Main Revision ES5 (2009)" }, { "code": null, "e": 1190, "s": 1159, "text": "The Second Revision ES6 (2015)" }, { "code": null, "e": 1230, "s": 1190, "text": "The Yearly Additions (2016, 2017, 2018)" }, { "code": null, "e": 1283, "s": 1230, "text": "In this tutorial, the learning speed is your choice." }, { "code": null, "e": 1308, "s": 1283, "text": "Everything is up to you." }, { "code": null, "e": 1370, "s": 1308, "text": "If you are struggling, take a break, or re-read the material." }, { "code": null, "e": 1439, "s": 1370, "text": "Always make sure you understand all the \"Try-it-Yourself\" \nexamples." }, { "code": null, "e": 1538, "s": 1439, "text": "The only way to become a clever programmer is to:\nPractice. Practice. Practice. Code. Code. Code !" }, { "code": null, "e": 1605, "s": 1538, "text": "Create a variable called carName and assign the value Volvo to it." }, { "code": null, "e": 1617, "s": 1605, "text": "var = \"\";\n" }, { "code": null, "e": 1636, "s": 1617, "text": "Start the Exercise" }, { "code": null, "e": 1661, "s": 1636, "text": "How do I get JavaScript?" }, { "code": null, "e": 1694, "s": 1661, "text": "Where can I download JavaScript?" }, { "code": null, "e": 1714, "s": 1694, "text": "Is JavaScript Free?" }, { "code": null, "e": 1760, "s": 1714, "text": "You don't have to get or download JavaScript." }, { "code": null, "e": 1865, "s": 1760, "text": "JavaScript is already running in your browser on your computer,\non your tablet, and on your smart-phone." }, { "code": null, "e": 1905, "s": 1865, "text": "JavaScript is free to use for everyone." }, { "code": null, "e": 1998, "s": 1905, "text": "W3Schools maintains a complete JavaScript reference, including all HTML and browser objects." }, { "code": null, "e": 2138, "s": 1998, "text": "The reference contains examples for all properties, methods and events, and \nis continuously updated according to the latest web standards." }, { "code": null, "e": 2180, "s": 2138, "text": "Test your JavaScript skills at W3Schools!" }, { "code": null, "e": 2203, "s": 2180, "text": "Start JavaScript Quiz!" }, { "code": null, "e": 2253, "s": 2203, "text": "Get certified by completing the JavaScript course" }, { "code": null, "e": 2286, "s": 2253, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2328, "s": 2286, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2435, "s": 2328, "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": 2454, "s": 2435, "text": "help@w3schools.com" } ]
RichFaces - Output Components
In the previous chapter, we have learned about different input fields or tags that help the user provide the inputs through the browser. In this chapter, we will learn about different output components provided by RichFaces. In some of our previous examples, we have already come across the panel tag. <rich:panel> creates a rectangular area inside the webpage, which may contain any information. You can include other panels, images, and any other rich components inside one panel. In the following example, we will create a custom panel according to choice and we will provide a header to our panel using the “header” attribute. Please create a xhtml file and name it as “richPanelExamlple.xhtml”. Place the following code inside it. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <h:head> <title>Panel Example</title> </h:head> <h:body> <rich:panel header = "RichFace Tutorials " style = "font-size: 500px; align-items:center; background-color: activecaption"> RichFace Tutorials Presented by TutorialsPoint.com. </rich:panel> </h:body> </html> The above piece of code will yield the following output in the browser. The simpleTogglePanel provides an opportunity to the developers to change the contains of the panel in a dynamic way. However, in RichFaces 4, this tag has been suppressed. JBoss has introduced advanced tags such as <rich:togglePanel>, <rich:tab>, and <rich:tabPanel>. It is recommended to use the updated version of RichFaces tags for more features and functionalities. If you are still using RichFaces 3, then you can use the following tag. <ui:composition xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <rich:simpleTogglePanel switchType = "client" label = "SimpleToggle"> The simple example of SimpleToggle tag </rich:simpleTogglePanel> </ui:composition> This tag helps the developers create different tabs inside a panel. We have used this tag in our skin chapter, where we have created two separate tags inside another panel. Following code will describe how we use <rich:tabPanel>. <?xml version = '1.0' encoding = 'UTF-8' ?> <ui:composition xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <f:view> <h:head> <title>Rich Faces Tab Example</title> </h:head> <h:body> <h:form> <rich:panel style = "width:60%"> <rich:tabPanel switchType = "AJAX"> <rich:tab header = "Name"> Tutorials Point----This is Tab Number 1 </rich:tab> <rich:tab header = "Features"> Best Place to learn -------This is Tab Number 2 </rich:tab> </rich:tabPanel> </rich:panel> </h:form> </h:body> </f:view> </ui:composition> In this example, we have created two tabs with different headers called “Name” and “Features”. These two tags will be created inside the <rich:panel>. The above code will yield the following output. Like simpleToggleBar, it allows the developers to implement vertical toggling depending on some JS event. This tag is also suppressed in RichFaces 4. However, you can use it as shown below if you are using RichFaces 3.0. . <ui:composition xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <rich:panelBar height = "400" width = "500"> <rich:panelBarItem label = "Toggle1”> First vertical toggle </rich:panelBarItem> <rich:panelBarItem label = ”Toggle2”> Second Vertical Toggle </rich:panelBarItem> </rich:panelBar > </ ui:composition > In RichFaces 4, the same functionality has been implemented using <rich:PanelMenu> tag. We are already familiar with this tag. In the example of <rich:tabPanel>, we have created different tabs with this tag. In the following example, we have created two tags. <?xml version = '1.0' encoding = 'UTF-8' ?> <ui:composition xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <f:view> <h:head> <title>Rich Faces Tab Example</title> </h:head> <h:body> <h:form> <rich:panel style = "width:60%"> <rich:tabPanel switchType = "AJAX"> <rich:tab header = "Name"> Tutorials Point----This is Tab Number 1 </rich:tab> <rich:tab header = "Features"> Best Place to learn -------This is Tab Number 2 </rich:tab> </rich:tabPanel> </rich:panel> </h:form> </h:body> </f:view> </ui:composition> The above piece of code will generate the following output in the browser. Panel Menu helps the developers create a vertical dropdown toggle inside a panel area. The following example will help us understand this tag better. Create the “richPanelMenu.xhtml” file and place the following piece of code inside it. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <h:head> <title>Panel Menu example</title> </h:head> <h:body> <h:form id = "form"> <h:panelGrid columns = "2" columnClasses = "cols,cols" width = "400"> <rich:panelMenu style = "width:200px"> <rich:panelMenuGroup label = "Group 1"> <rich:panelMenuItem label = "Database" action = "#{managedBean.subjectList}"> <f:param name = "current" value = "DB"/> </rich:panelMenuItem> <rich:panelMenuItem label = "Oracle" action = "#{managedBean.subjectList}"> <f:param name = "current" value = "Oracle"/> </rich:panelMenuItem> <rich:panelMenuItem label = "JAVA" action = "#{managedBean.subjectList}"> <f:param name = "current" value = "JAVA"/> </rich:panelMenuItem> </rich:panelMenuGroup> </rich:panelMenu> </h:panelGrid> </h:form> </h:body> </html> As seen in the above example, panelMenu comes with some other associated tags which helps in a different manner. <panelGrid> helps create a grid inside the panel. <panelMenuGroup> helps group the different components that we are going to populate .<panelMenuItem> is the actual item that will be rendered to the browser. Using the “action” attribute, you can call different action methods depending on the item selected. The “label” attribute is used to populate the value in the front-end and the rendered value will be processed to the back-end once the specified action class is called. The above piece of code will yield the following output in the browser. This tag is used to render different outputs that can be switched or toggled using the Toggle control method. This toggle control method can be implemented or customized. In the following example, we will implement this method. Create an xhtml file and name it as “richTogglePanel.xhtml”. Place the following code inside it. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <h:head> <title>Rich Toggle Panel Example</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"/> </h:head> <h:body> <h:form id = "form"> <rich:togglePanel id = "panel1" activeItem = "item1" itemChangeListener = "#{panelMenuBean.updateCurrent}"> <rich:togglePanelItem name = "item1"> <p>Content of the toggle 1</p> </rich0:togglePanelItem> <rich:togglePanelItem name = "item2"> <p>Content of the toggle 2</p> </rich:togglePanelItem> </rich:togglePanel> <a4j:outputPanel id = "tabs" layout = "block"> <a4j:outputPanel layout = "block" styleClass = "tabDiv"> <rich:toggleControl event = "click" targetPanel = "panel1" targetItem = "item1" /> <a4j:commandButton value = "Toggle1"/> </a4j:outputPanel> <a4j:outputPanel layout = "block" styleClass = "tabDiv"> <rich:toggleControl event = "click" targetPanel = "panel1" targetItem = "item2" /> <a4j:commandButton value = "Toggle2"/> </a4j:outputPanel> </a4j:outputPanel> </h:form> </h:body> </html> We also need to create a bean class to control the transition of the website. Create “MenuBean.java” class like the following. import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import org.richfaces.event.ItemChangeEvent; @ManagedBean @ViewScoped public class MenuBean { private String current; private boolean singleMode; public boolean isSingleMode() { return singleMode; } public void setSingleMode(boolean singleMode) { this.singleMode = singleMode; } public String getCurrent() { return this.current; } public void setCurrent(String current) { this.current = current; } public void updateCurrent(ItemChangeEvent event) { setCurrent(event.getNewItemName()); } } The above code will yield the following output in the browser. In the above example, the content of the webpage will be changed depending on the button clicked by the user. “updateCurrent()” is the method which handles the JS event content and sets the website content on the go. toolBar is used to create a horizontal bar in the panel. It is used to create top level menu in the webpage. In the following example, we will learn how to use this tag in the webpage. Create a “xhtml” file and name it as “toolbar.xhml”. Place the following code in it. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <h:head> <title>ToolBar Example</title> </h:head> <h:body> <rich:panel> <rich:toolbar height = "26" itemSeparator = "grid"> <rich:toolbarGroup location = "left"> <h:commandButton styleClass = "barsearchbutton" onclick = "return false;" value = "TAB" /> </rich:toolbarGroup> <rich:toolbarGroup location = "left"> <h:commandButton styleClass = "barsearchbutton" onclick = "return false;" value = "TAB2" /> </rich:toolbarGroup> <rich:toolbarGroup location = "left"> <h:commandButton styleClass = "barsearchbutton" onclick = "return false;" value = "TAB3" /> </rich:toolbarGroup> </rich:toolbar> </rich:panel> </h:body> </html> The above code will yield the following output in the browser. In the above example, <toolbarGroup> tag is used to group different same types of tool. Any number of groups can be created. Location provides the position of the webpage, where the button will be placed. As the name suggests, it is used to separate different components on the webpage. This tag has been suppressed in RichFaces 4, however, if you are still using RichFaces 3, then you can use the following tag. <rich:separator lineType = "beveled" height = "8" width = "75%" align = "center"/> <p>Here is more examples of different line types:</p> <rich:separator height = "2" lineType = "dotted"/><br/> <rich:separator height = "2" lineType = "dashed"/><br/> <rich:separator height = "4" lineType = "double"/><br/> <rich:separator height = "2" lineType = "solid"/><br/> In the above example, LineType is the attribute that helps us determine the type of separator we want to use. All of these separator names are pretty much self-descriptive in nature. Spacer is a self-described tag that helps the developer provide a space between two components. This tag is also suppressed in RichFaces4 along with other tags, however, you can use the following code if you are using RichFaces 3. <rich:spacer width = "1" height = "5" title = "Here is a spacer..."/> Modal Panel is used to show a pop-up on the go. In RichFaces 4, the modal panel tag has been changed to popupPanel. In the following example, we will see how it works. Create a xhtml file and name it as “PopingUp.xhtml”. Place the following code into it. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns:a4j = "http://richfaces.org/a4j" xmlns:rich = "http://richfaces.org/rich"> <h:head> <title>ModalPanel and popupPanel</title> </h:head> <h:body> <h:form> <h:commandButton value = "Click ME"> <rich:componentControl target = "popup" operation = "show" /> </h:commandButton> <rich:popupPanel id = "popup" modal = "true" autosized = "false" resizeable = "false"> Hey !!! How are you? </rich:popupPanel> </h:form> </h:body> </html> The above example will generate the following output when the “ClickMe” button is clicked. Print Add Notes Bookmark this page
[ { "code": null, "e": 2144, "s": 1919, "text": "In the previous chapter, we have learned about different input fields or tags that help the user provide the inputs through the browser. In this chapter, we will learn about different output components provided by RichFaces." }, { "code": null, "e": 2402, "s": 2144, "text": "In some of our previous examples, we have already come across the panel tag. <rich:panel> creates a rectangular area inside the webpage, which may contain any information. You can include other panels, images, and any other rich components inside one panel." }, { "code": null, "e": 2655, "s": 2402, "text": "In the following example, we will create a custom panel according to choice and we will provide a header to our panel using the “header” attribute. Please create a xhtml file and name it as “richPanelExamlple.xhtml”. Place the following code inside it." }, { "code": null, "e": 3350, "s": 2655, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html> \n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <h:head> \n <title>Panel Example</title> \n </h:head> \n \n <h:body> \n <rich:panel header = \"RichFace Tutorials \" style = \"font-size: 500px; \n align-items:center; background-color: activecaption\"> \n \n RichFace Tutorials Presented by TutorialsPoint.com. \n </rich:panel> \n </h:body>\n</html> " }, { "code": null, "e": 3422, "s": 3350, "text": "The above piece of code will yield the following output in the browser." }, { "code": null, "e": 3865, "s": 3422, "text": "The simpleTogglePanel provides an opportunity to the developers to change the contains of the panel in a dynamic way. However, in RichFaces 4, this tag has been suppressed. JBoss has introduced advanced tags such as <rich:togglePanel>, <rich:tab>, and <rich:tabPanel>. It is recommended to use the updated version of RichFaces tags for more features and functionalities. If you are still using RichFaces 3, then you can use the following tag." }, { "code": null, "e": 4326, "s": 3865, "text": "<ui:composition xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <rich:simpleTogglePanel switchType = \"client\" label = \"SimpleToggle\"> \n The simple example of SimpleToggle tag \n </rich:simpleTogglePanel> \n</ui:composition> " }, { "code": null, "e": 4556, "s": 4326, "text": "This tag helps the developers create different tabs inside a panel. We have used this tag in our skin chapter, where we have created two separate tags inside another panel. Following code will describe how we use <rich:tabPanel>." }, { "code": null, "e": 5630, "s": 4556, "text": "<?xml version = '1.0' encoding = 'UTF-8' ?> \n<ui:composition xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <f:view> \n <h:head> \n <title>Rich Faces Tab Example</title> \n </h:head> \n \n <h:body> \n <h:form> \n <rich:panel style = \"width:60%\"> \n \n <rich:tabPanel switchType = \"AJAX\"> \n <rich:tab header = \"Name\"> \n Tutorials Point----This is Tab Number 1 \n </rich:tab> \n \n <rich:tab header = \"Features\"> \n Best Place to learn -------This is Tab Number 2 \n </rich:tab> \n </rich:tabPanel> \n </rich:panel> \n \n </h:form> \n </h:body> \n \n </f:view> \n</ui:composition>" }, { "code": null, "e": 5829, "s": 5630, "text": "In this example, we have created two tabs with different headers called “Name” and “Features”. These two tags will be created inside the <rich:panel>. The above code will yield the following output." }, { "code": null, "e": 6052, "s": 5829, "text": "Like simpleToggleBar, it allows the developers to implement vertical toggling depending on some JS event. This tag is also suppressed in RichFaces 4. However, you can use it as shown below if you are using RichFaces 3.0. ." }, { "code": null, "e": 6657, "s": 6052, "text": "<ui:composition xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <rich:panelBar height = \"400\" width = \"500\"> \n <rich:panelBarItem label = \"Toggle1”> \n First vertical toggle \n </rich:panelBarItem> \n \n <rich:panelBarItem label = ”Toggle2”> \n Second Vertical Toggle \n </rich:panelBarItem> \n </rich:panelBar >\n \n</ ui:composition >" }, { "code": null, "e": 6745, "s": 6657, "text": "In RichFaces 4, the same functionality has been implemented using <rich:PanelMenu> tag." }, { "code": null, "e": 6917, "s": 6745, "text": "We are already familiar with this tag. In the example of <rich:tabPanel>, we have created different tabs with this tag. In the following example, we have created two tags." }, { "code": null, "e": 7988, "s": 6917, "text": "<?xml version = '1.0' encoding = 'UTF-8' ?> \n<ui:composition xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <f:view> \n <h:head> \n <title>Rich Faces Tab Example</title> \n </h:head> \n \n <h:body> \n <h:form> \n \n <rich:panel style = \"width:60%\"> \n <rich:tabPanel switchType = \"AJAX\"> \n <rich:tab header = \"Name\"> \n Tutorials Point----This is Tab Number 1 \n </rich:tab> \n \n <rich:tab header = \"Features\"> \n Best Place to learn -------This is Tab Number 2 \n </rich:tab> \n </rich:tabPanel> \n </rich:panel> \n \n </h:form> \n </h:body> \n \n </f:view> \n</ui:composition> " }, { "code": null, "e": 8063, "s": 7988, "text": "The above piece of code will generate the following output in the browser." }, { "code": null, "e": 8300, "s": 8063, "text": "Panel Menu helps the developers create a vertical dropdown toggle inside a panel area. The following example will help us understand this tag better. Create the “richPanelMenu.xhtml” file and place the following piece of code inside it." }, { "code": null, "e": 9763, "s": 8300, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html> \n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <h:head> \n <title>Panel Menu example</title> \n </h:head> \n \n <h:body> \n <h:form id = \"form\"> \n <h:panelGrid columns = \"2\" columnClasses = \"cols,cols\" width = \"400\"> \n <rich:panelMenu style = \"width:200px\"> \n \n <rich:panelMenuGroup label = \"Group 1\"> \n <rich:panelMenuItem label = \"Database\" action = \"#{managedBean.subjectList}\"> \n <f:param name = \"current\" value = \"DB\"/> \n </rich:panelMenuItem> \n \n <rich:panelMenuItem label = \"Oracle\" action = \"#{managedBean.subjectList}\"> \n <f:param name = \"current\" value = \"Oracle\"/> \n </rich:panelMenuItem> \n \n <rich:panelMenuItem label = \"JAVA\" action = \"#{managedBean.subjectList}\"> \n <f:param name = \"current\" value = \"JAVA\"/> \n </rich:panelMenuItem> \n </rich:panelMenuGroup>\n \n </rich:panelMenu> \n </h:panelGrid> \n </h:form> \n </h:body>\n \n</html>" }, { "code": null, "e": 10353, "s": 9763, "text": "As seen in the above example, panelMenu comes with some other associated tags which helps in a different manner. <panelGrid> helps create a grid inside the panel. <panelMenuGroup> helps group the different components that we are going to populate .<panelMenuItem> is the actual item that will be rendered to the browser. Using the “action” attribute, you can call different action methods depending on the item selected. The “label” attribute is used to populate the value in the front-end and the rendered value will be processed to the back-end once the specified action class is called." }, { "code": null, "e": 10425, "s": 10353, "text": "The above piece of code will yield the following output in the browser." }, { "code": null, "e": 10653, "s": 10425, "text": "This tag is used to render different outputs that can be switched or toggled using the Toggle control method. This toggle control method can be implemented or customized. In the following example, we will implement this method." }, { "code": null, "e": 10750, "s": 10653, "text": "Create an xhtml file and name it as “richTogglePanel.xhtml”. Place the following code inside it." }, { "code": null, "e": 12442, "s": 10750, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html> \n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <h:head> \n <title>Rich Toggle Panel Example</title> \n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\"/> \n </h:head> \n \n <h:body> \n <h:form id = \"form\"> \n <rich:togglePanel id = \"panel1\" activeItem = \"item1\" \n itemChangeListener = \"#{panelMenuBean.updateCurrent}\"> \n \n <rich:togglePanelItem name = \"item1\"> \n <p>Content of the toggle 1</p> \n </rich0:togglePanelItem> \n \n <rich:togglePanelItem name = \"item2\"> \n <p>Content of the toggle 2</p> \n </rich:togglePanelItem> \n </rich:togglePanel> \n \n <a4j:outputPanel id = \"tabs\" layout = \"block\"> \n <a4j:outputPanel layout = \"block\" styleClass = \"tabDiv\"> \n <rich:toggleControl event = \"click\" targetPanel = \"panel1\" targetItem = \"item1\" /> \n <a4j:commandButton value = \"Toggle1\"/> \n </a4j:outputPanel> \n \n <a4j:outputPanel layout = \"block\" styleClass = \"tabDiv\"> \n <rich:toggleControl event = \"click\" targetPanel = \"panel1\" targetItem = \"item2\" /> \n <a4j:commandButton value = \"Toggle2\"/> \n </a4j:outputPanel> \n </a4j:outputPanel>\n \n </h:form> \n </h:body>\n \n</html> " }, { "code": null, "e": 12569, "s": 12442, "text": "We also need to create a bean class to control the transition of the website. Create “MenuBean.java” class like the following." }, { "code": null, "e": 13229, "s": 12569, "text": "import javax.faces.bean.ManagedBean; \nimport javax.faces.bean.ViewScoped; \nimport org.richfaces.event.ItemChangeEvent; \n \n@ManagedBean \n@ViewScoped \n\npublic class MenuBean { \n private String current; \n private boolean singleMode; \n \n public boolean isSingleMode() { \n return singleMode; \n } \n public void setSingleMode(boolean singleMode) { \n this.singleMode = singleMode; \n } \n public String getCurrent() { \n return this.current; \n } \n public void setCurrent(String current) { \n this.current = current; \n } \n public void updateCurrent(ItemChangeEvent event) { \n setCurrent(event.getNewItemName()); \n }\n} " }, { "code": null, "e": 13292, "s": 13229, "text": "The above code will yield the following output in the browser." }, { "code": null, "e": 13509, "s": 13292, "text": "In the above example, the content of the webpage will be changed depending on the button clicked by the user. “updateCurrent()” is the method which handles the JS event content and sets the website content on the go." }, { "code": null, "e": 13779, "s": 13509, "text": "toolBar is used to create a horizontal bar in the panel. It is used to create top level menu in the webpage. In the following example, we will learn how to use this tag in the webpage. Create a “xhtml” file and name it as “toolbar.xhml”. Place the following code in it." }, { "code": null, "e": 15028, "s": 13779, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html> \n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <h:head> \n <title>ToolBar Example</title> \n </h:head> \n \n <h:body> \n <rich:panel> \n <rich:toolbar height = \"26\" itemSeparator = \"grid\"> \n <rich:toolbarGroup location = \"left\"> \n <h:commandButton styleClass = \"barsearchbutton\" \n onclick = \"return false;\" value = \"TAB\" /> \n </rich:toolbarGroup> \n \n <rich:toolbarGroup location = \"left\"> \n <h:commandButton styleClass = \"barsearchbutton\" \n onclick = \"return false;\" value = \"TAB2\" /> \n </rich:toolbarGroup> \n \n <rich:toolbarGroup location = \"left\"> \n <h:commandButton styleClass = \"barsearchbutton\" \n onclick = \"return false;\" value = \"TAB3\" /> \n </rich:toolbarGroup> \n </rich:toolbar>\n \n </rich:panel> \n </h:body>\n \n</html> " }, { "code": null, "e": 15091, "s": 15028, "text": "The above code will yield the following output in the browser." }, { "code": null, "e": 15296, "s": 15091, "text": "In the above example, <toolbarGroup> tag is used to group different same types of tool. Any number of groups can be created. Location provides the position of the webpage, where the button will be placed." }, { "code": null, "e": 15504, "s": 15296, "text": "As the name suggests, it is used to separate different components on the webpage. This tag has been suppressed in RichFaces 4, however, if you are still using RichFaces 3, then you can use the following tag." }, { "code": null, "e": 15873, "s": 15504, "text": "<rich:separator lineType = \"beveled\" height = \"8\" width = \"75%\" align = \"center\"/>\n<p>Here is more examples of different line types:</p> \n\n<rich:separator height = \"2\" lineType = \"dotted\"/><br/> \n<rich:separator height = \"2\" lineType = \"dashed\"/><br/> \n<rich:separator height = \"4\" lineType = \"double\"/><br/>\n<rich:separator height = \"2\" lineType = \"solid\"/><br/> " }, { "code": null, "e": 16056, "s": 15873, "text": "In the above example, LineType is the attribute that helps us determine the type of separator we want to use. All of these separator names are pretty much self-descriptive in nature." }, { "code": null, "e": 16287, "s": 16056, "text": "Spacer is a self-described tag that helps the developer provide a space between two components. This tag is also suppressed in RichFaces4 along with other tags, however, you can use the following code if you are using RichFaces 3." }, { "code": null, "e": 16358, "s": 16287, "text": "<rich:spacer width = \"1\" height = \"5\" title = \"Here is a spacer...\"/>\n" }, { "code": null, "e": 16613, "s": 16358, "text": "Modal Panel is used to show a pop-up on the go. In RichFaces 4, the modal panel tag has been changed to popupPanel. In the following example, we will see how it works. Create a xhtml file and name it as “PopingUp.xhtml”. Place the following code into it." }, { "code": null, "e": 17478, "s": 16613, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html> \n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\" \n xmlns:a4j = \"http://richfaces.org/a4j\" \n xmlns:rich = \"http://richfaces.org/rich\"> \n \n <h:head> \n <title>ModalPanel and popupPanel</title> \n </h:head> \n \n <h:body> \n <h:form> \n <h:commandButton value = \"Click ME\"> \n <rich:componentControl target = \"popup\" operation = \"show\" /> \n </h:commandButton> \n \n <rich:popupPanel id = \"popup\" modal = \"true\" autosized = \"false\" \n resizeable = \"false\"> \n \n Hey !!!\n How are you? \n </rich:popupPanel> \n </h:form> \n </h:body>\n \n</html> " }, { "code": null, "e": 17569, "s": 17478, "text": "The above example will generate the following output when the “ClickMe” button is clicked." }, { "code": null, "e": 17576, "s": 17569, "text": " Print" }, { "code": null, "e": 17587, "s": 17576, "text": " Add Notes" } ]
How to extract data frame columns stored in a list in R?
Suppose we have two frames each having 5 columns that are stored in a list in R and the data that belongs to same columns has some kind of inherent relationship or we want to check whether there exists a relationship between them then we might want to extract those columns. Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3). Consider the below data frames and list of these data frames − Live Demo df1<-data.frame(x1=rnorm(20),x2=rnorm(20)) df2<-data.frame(y1=rnorm(20),y2=rnorm(20)) List<-list(df1,df2) List [[1]] x1 x2 1 -0.2616691 0.4838822161 2 -0.4962192 -0.2029131423 3 -0.6289051 0.6067368122 4 -1.8650979 -0.2673970799 5 -0.1144585 1.2794435497 6 -0.7950920 0.3237400683 7 -0.7473936 0.5272240477 8 -1.1275262 0.8650962534 9 -0.2354747 1.0057184299 10 1.3755067 0.0961681148 11 -0.1747653 1.2535584458 12 -1.5245065 1.0977974301 13 -1.9052953 -0.6178104611 14 0.6634748 0.3078744775 15 -0.3464213 -0.9288219551 16 -1.7638077 -1.3873331806 17 -0.6839449 -0.0006287789 18 -0.1494119 0.1155562131 19 -0.3583126 0.2606700288 20 -0.6148202 -0.5952164804 [[2]] y1 y2 1 -0.211831075 0.80770142 2 0.275355837 -0.37532157 3 0.026130608 0.07003241 4 -0.214784788 0.36447807 5 -0.706518246 -2.35280957 6 -0.786380214 -0.83800239 7 0.599793658 1.00900869 8 -0.952037717 0.31360048 9 -0.820999108 1.37718684 10 -1.912105297 -0.48305776 11 0.436298130 0.56800539 12 1.126854489 0.26761877 13 -2.148552234 -1.54496557 14 1.832004140 -0.93939487 15 -0.587988585 0.74063570 16 0.945827064 -0.30905531 17 -1.571678758 -0.44346002 18 -0.704557448 -0.78744069 19 -0.009306419 0.71375917 20 0.734797879 -1.88248741 Extracting column 2 from each data frame stored in List − lapply(List,"[",2) [[1]] x2 1 0.4838822161 2 -0.2029131423 3 0.6067368122 4 -0.2673970799 5 1.2794435497 6 0.3237400683 7 0.5272240477 8 0.8650962534 9 1.0057184299 10 0.0961681148 11 1.2535584458 12 1.0977974301 13 -0.6178104611 14 0.3078744775 15 -0.9288219551 16 -1.3873331806 17 -0.0006287789 18 0.1155562131 19 0.2606700288 20 -0.5952164804 [[2]] y2 1 0.80770142 2 -0.37532157 3 0.07003241 4 0.36447807 5 -2.35280957 6 -0.83800239 7 1.00900869 8 0.31360048 9 1.37718684 10 -0.48305776 11 0.56800539 12 0.26761877 13 -1.54496557 14 -0.93939487 15 0.74063570 16 -0.30905531 17 -0.44346002 18 -0.78744069 19 0.71375917 20 -1.88248741
[ { "code": null, "e": 1557, "s": 1062, "text": "Suppose we have two frames each having 5 columns that are stored in a list in R and the data that belongs to same columns has some kind of inherent relationship or we want to check whether there exists a relationship between them then we might want to extract those columns. Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,\"[\",3)." }, { "code": null, "e": 1620, "s": 1557, "text": "Consider the below data frames and list of these data frames −" }, { "code": null, "e": 1631, "s": 1620, "text": " Live Demo" }, { "code": null, "e": 1742, "s": 1631, "text": "df1<-data.frame(x1=rnorm(20),x2=rnorm(20))\ndf2<-data.frame(y1=rnorm(20),y2=rnorm(20))\nList<-list(df1,df2)\nList" }, { "code": null, "e": 2959, "s": 1742, "text": "[[1]]\n x1 x2\n1 -0.2616691 0.4838822161\n2 -0.4962192 -0.2029131423\n3 -0.6289051 0.6067368122\n4 -1.8650979 -0.2673970799\n5 -0.1144585 1.2794435497\n6 -0.7950920 0.3237400683\n7 -0.7473936 0.5272240477\n8 -1.1275262 0.8650962534\n9 -0.2354747 1.0057184299\n10 1.3755067 0.0961681148\n11 -0.1747653 1.2535584458\n12 -1.5245065 1.0977974301\n13 -1.9052953 -0.6178104611\n14 0.6634748 0.3078744775\n15 -0.3464213 -0.9288219551\n16 -1.7638077 -1.3873331806\n17 -0.6839449 -0.0006287789\n18 -0.1494119 0.1155562131\n19 -0.3583126 0.2606700288\n20 -0.6148202 -0.5952164804\n[[2]]\n y1 y2\n1 -0.211831075 0.80770142\n2 0.275355837 -0.37532157\n3 0.026130608 0.07003241\n4 -0.214784788 0.36447807\n5 -0.706518246 -2.35280957\n6 -0.786380214 -0.83800239\n7 0.599793658 1.00900869\n8 -0.952037717 0.31360048\n9 -0.820999108 1.37718684\n10 -1.912105297 -0.48305776\n11 0.436298130 0.56800539\n12 1.126854489 0.26761877\n13 -2.148552234 -1.54496557\n14 1.832004140 -0.93939487\n15 -0.587988585 0.74063570\n16 0.945827064 -0.30905531\n17 -1.571678758 -0.44346002\n18 -0.704557448 -0.78744069\n19 -0.009306419 0.71375917\n20 0.734797879 -1.88248741" }, { "code": null, "e": 3017, "s": 2959, "text": "Extracting column 2 from each data frame stored in List −" }, { "code": null, "e": 3036, "s": 3017, "text": "lapply(List,\"[\",2)" }, { "code": null, "e": 3706, "s": 3036, "text": "[[1]]\n x2\n1 0.4838822161\n2 -0.2029131423\n3 0.6067368122\n4 -0.2673970799\n5 1.2794435497\n6 0.3237400683\n7 0.5272240477\n8 0.8650962534\n9 1.0057184299\n10 0.0961681148\n11 1.2535584458\n12 1.0977974301\n13 -0.6178104611\n14 0.3078744775\n15 -0.9288219551\n16 -1.3873331806\n17 -0.0006287789\n18 0.1155562131\n19 0.2606700288\n20 -0.5952164804\n[[2]]\n y2\n1 0.80770142\n2 -0.37532157\n3 0.07003241\n4 0.36447807\n5 -2.35280957\n6 -0.83800239\n7 1.00900869\n8 0.31360048\n9 1.37718684\n10 -0.48305776\n11 0.56800539\n12 0.26761877\n13 -1.54496557\n14 -0.93939487\n15 0.74063570\n16 -0.30905531\n17 -0.44346002\n18 -0.78744069\n19 0.71375917\n20 -1.88248741" } ]
A square matrix as sum of symmetric and skew-symmetric matrices - GeeksforGeeks
27 May, 2021 Let A be a square matrix with all real number entries. Find two symmetric matrix P and skew symmetric matrix Q such that P + Q = A.Symmetric Matrix:- A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the original matrix. Skew Symmetric Matrix:- A square matrix is said to be skew symmetric matrix if the negative transpose of matrix is same as the original matrix.Examples : Input : {{ 2, -2, -4}, mat= {-1, 3, 4}, { 1, -2, -3}}; Output : Symmetric matrix- 2 -1.5 -1.5 -1.5 3 1 -1.5 1 -3 Skew Symmetric Matrix- 0 -0.5 -2.5 0.5 0 3 2.5 -3 0 Explanation : The first matrix is symmetric as transpose of it is same as the given matrix. The second matrix is Skew Symmetric as negative transpose is same as this matrix. Also sum of the two matrices is same as mat[][]. Input: {{5, 6, 8}, mat = {3, 4, 9}, {7, 2, 3}}; Output : Symmetric matrix- 5 4.5 7.5 4.5 4 5.5 7.5 5.5 3 Skew Symmetric Matrix- 0 1.5 0.5 -1.5 0 3.5 -0.5 -3.5 0 Let A be a square matrix, then A = (1/2)*(A + A’) + (1/2)*(A – A’) Where A’ is the transpose matrix of A. In the above formula (1/2)*(A + A’) represents symmetric matrix and (1/2)*(A – A’) represents skew symmetric matrix. If we take a closer look, we can notice that the two matrices are symmetric and skew symmetric (We are basically distributing half of two cell values to both). C++ Java Python3 C# PHP Javascript // C++ program for distribute a square matrix into// symmetric and skew symmetric matrix.#include <bits/stdc++.h>#define N 3using namespace std; /* Below functions can be used to verify result// Returns true if matrix is skew symmetric,// else false.bool isSymmetric(float mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Returns true if matrix is skew symmetric,// else false.bool isSkewSymmetric(float mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != -mat[j][i]) return false; return true;} */ void printMatrix(float mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << mat[i][j] << " "; cout << endl; }} void printDistribution(float mat[N][N]){ // tr is the transpose of matrix mat. float tr[N][N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. float symm[N][N], skewsymm[N][N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } cout << "Symmetric matrix-" << endl; printMatrix(symm); cout << "Skew Symmetric matrix-" << endl; printMatrix(skewsymm);} // Driver function.int main(){ // mat is the N * N square matrix. float mat[N][N] = { { 2, -2, -4 }, { -1, 3, 4 }, { 1, -2, -3 } }; printDistribution(mat); return 0;} // Java program for distribute// a square matrix into// symmetric and skew symmetric// matrix. import java.io.*;import java.util.*; class GFG {static void printMatrix(float mat[][]){ for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + " "); System.out.println(); }} static void printDistribution(float mat[][]){ // tr is the transpose of matrix mat. int N=mat.length; float[][] tr = new float[N][N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. float[][] symm=new float[N][N]; float[][] skewsymm=new float[N][N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } System.out.println("Symmetric matrix-" ); printMatrix(symm); System.out.println("Skew Symmetric matrix-" ); printMatrix(skewsymm);} public static void main (String[] args) { // mat is the N * N square matrix. float mat[][] = { { 2, -2, -4 }, { -1, 3, 4 }, { 1, -2, -3 } }; printDistribution(mat); }} // This code is contributed by Gitanjali. # Python3 program to distribute a# square matrix into symmetric# and skew symmetric matrix.N = 3; def printMatrix(mat): for i in range(N): for j in range(N): print(mat[i][j], end = " "); print(""); def printDistribution(mat): # tr is the transpose # of matrix mat. tr = [[0 for x in range(N)] for y in range(N)]; # Find transpose of matrix. for i in range(N): for j in range(N): tr[i][j] = mat[j][i]; # Declare two square # matrix symm and # skewsymm of size N. symm = [[0 for x in range(N)] for y in range(N)] ; skewsymm = [[0 for x in range(N)] for y in range(N)]; # Loop to find symmetric # and skew symmetric and # store it into symm and # skewsymm matrix. for i in range(N): for j in range(N): symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; print("Symmetric matrix-"); printMatrix(symm); print("Skew Symmetric matrix"); printMatrix(skewsymm); # Driver Code # mat is the N * N# square matrix.mat = [[2, -2, -4], [-1, 3, 4], [1, -2, -3]];printDistribution(mat); # This code is contributed by mits. // C# program for distribute// a square matrix into// symmetric and skew// symmetric matrix.using System; class GFG{ static int N = 3;static void printMatrix(float[,] mat){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(mat[i, j] + " "); System.Console.WriteLine(); }} static void printDistribution(float[,] mat){ // tr is the transpose // of matrix mat. float[,] tr = new float[N, N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i, j] = mat[j, i]; // Declare two square matrix symm and // skewsymm of size N. float[,] symm = new float[N, N]; float[,] skewsymm = new float[N, N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i, j] = (mat[i, j] + tr[i, j]) / 2; skewsymm[i, j] = (mat[i, j] - tr[i, j]) / 2; } } System.Console.WriteLine("Symmetric matrix-" ); printMatrix(symm); System.Console.WriteLine("Skew Symmetric matrix-" ); printMatrix(skewsymm);} // Driver codepublic static void Main(){ // mat is the N * N // square matrix. float[,] mat = new float[,]{{ 2, -2, -4}, {-1, 3, 4}, {1, -2, -3}}; printDistribution(mat);}} // This code is contributed by mits. <?php// PHP program to distribute a // square matrix into symmetric// and skew symmetric matrix.$N = 3; function printMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) echo $mat[$i][$j]. " "; echo "\n"; }} function printDistribution($mat){ global $N; // tr is the transpose // of matrix mat. $tr; // Find transpose of matrix. for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $tr[$i][$j] = $mat[$j][$i]; // Declare two square // matrix symm and // skewsymm of size N. $symm; $skewsymm; // Loop to find symmetric // and skew symmetric and // store it into symm and // skewsymm matrix. for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) { $symm[$i][$j] = ($mat[$i][$j] + $tr[$i][$j]) / 2; $skewsymm[$i][$j] = ($mat[$i][$j] - $tr[$i][$j]) / 2; } } echo "Symmetric matrix-\n"; printMatrix($symm); echo "Skew Symmetric matrix-\n"; printMatrix($skewsymm);} // Driver Code // mat is the N * N// square matrix.$mat = array(array(2, -2, -4), array(-1, 3, 4), array(1, -2, -3));printDistribution($mat); // This code is contributed by mits.?> <script> // javascript program for distribute// a square matrix into// symmetric and skew symmetric// matrix.function printMatrix(mat){ for (var i = 0; i < mat.length; i++) { for (var j = 0; j < mat[i].length; j++) document.write(mat[i][j] + " "); document.write('<br>'); }} function printDistribution(mat){ // tr is the transpose of matrix mat. var N=mat.length; var tr = Array(N).fill(0).map(x => Array(N).fill(0)); // Find transpose of matrix. for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. var symm=Array(N).fill(0).map(x => Array(N).fill(0)); var skewsymm=Array(N).fill(0).map(x => Array(N).fill(0)); // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (var i = 0; i < N; i++) { for (var j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } document.write("Symmetric matrix-<br>" ); printMatrix(symm); document.write("Skew Symmetric matrix-<br>" ); printMatrix(skewsymm);} // mat is the N * N square matrix. var mat = [ [ 2, -2, -4 ], [ -1, 3, 4 ], [ 1, -2, -3 ] ]; printDistribution(mat); // This code is contributed by Princi Singh</script> Output : Symmetric matrix- 2 -1.5 -1.5 -1.5 3 1 -1.5 1 -3 Skew Symmetric matrix- 0 -0.5 -2.5 0.5 0 3 2.5 -3 0 Mithun Kumar princi singh Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24327, "s": 24299, "text": "\n27 May, 2021" }, { "code": null, "e": 24743, "s": 24327, "text": "Let A be a square matrix with all real number entries. Find two symmetric matrix P and skew symmetric matrix Q such that P + Q = A.Symmetric Matrix:- A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the original matrix. Skew Symmetric Matrix:- A square matrix is said to be skew symmetric matrix if the negative transpose of matrix is same as the original matrix.Examples : " }, { "code": null, "e": 25461, "s": 24743, "text": "Input :\n {{ 2, -2, -4},\n mat= {-1, 3, 4},\n { 1, -2, -3}};\nOutput :\nSymmetric matrix-\n 2 -1.5 -1.5\n -1.5 3 1\n -1.5 1 -3\nSkew Symmetric Matrix-\n 0 -0.5 -2.5\n 0.5 0 3\n 2.5 -3 0\nExplanation : The first matrix is symmetric as\ntranspose of it is same as the given matrix. The\nsecond matrix is Skew Symmetric as negative transpose\nis same as this matrix. Also sum of the two matrices\nis same as mat[][].\n\n\nInput:\n {{5, 6, 8},\n mat = {3, 4, 9},\n {7, 2, 3}};\nOutput :\nSymmetric matrix-\n 5 4.5 7.5\n 4.5 4 5.5\n 7.5 5.5 3\nSkew Symmetric Matrix-\n 0 1.5 0.5\n -1.5 0 3.5\n -0.5 -3.5 0" }, { "code": null, "e": 25848, "s": 25463, "text": "Let A be a square matrix, then A = (1/2)*(A + A’) + (1/2)*(A – A’) Where A’ is the transpose matrix of A. In the above formula (1/2)*(A + A’) represents symmetric matrix and (1/2)*(A – A’) represents skew symmetric matrix. If we take a closer look, we can notice that the two matrices are symmetric and skew symmetric (We are basically distributing half of two cell values to both). " }, { "code": null, "e": 25852, "s": 25848, "text": "C++" }, { "code": null, "e": 25857, "s": 25852, "text": "Java" }, { "code": null, "e": 25865, "s": 25857, "text": "Python3" }, { "code": null, "e": 25868, "s": 25865, "text": "C#" }, { "code": null, "e": 25872, "s": 25868, "text": "PHP" }, { "code": null, "e": 25883, "s": 25872, "text": "Javascript" }, { "code": "// C++ program for distribute a square matrix into// symmetric and skew symmetric matrix.#include <bits/stdc++.h>#define N 3using namespace std; /* Below functions can be used to verify result// Returns true if matrix is skew symmetric,// else false.bool isSymmetric(float mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true;} // Returns true if matrix is skew symmetric,// else false.bool isSkewSymmetric(float mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != -mat[j][i]) return false; return true;} */ void printMatrix(float mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << mat[i][j] << \" \"; cout << endl; }} void printDistribution(float mat[N][N]){ // tr is the transpose of matrix mat. float tr[N][N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. float symm[N][N], skewsymm[N][N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } cout << \"Symmetric matrix-\" << endl; printMatrix(symm); cout << \"Skew Symmetric matrix-\" << endl; printMatrix(skewsymm);} // Driver function.int main(){ // mat is the N * N square matrix. float mat[N][N] = { { 2, -2, -4 }, { -1, 3, 4 }, { 1, -2, -3 } }; printDistribution(mat); return 0;}", "e": 27731, "s": 25883, "text": null }, { "code": "// Java program for distribute// a square matrix into// symmetric and skew symmetric// matrix. import java.io.*;import java.util.*; class GFG {static void printMatrix(float mat[][]){ for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); }} static void printDistribution(float mat[][]){ // tr is the transpose of matrix mat. int N=mat.length; float[][] tr = new float[N][N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. float[][] symm=new float[N][N]; float[][] skewsymm=new float[N][N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } System.out.println(\"Symmetric matrix-\" ); printMatrix(symm); System.out.println(\"Skew Symmetric matrix-\" ); printMatrix(skewsymm);} public static void main (String[] args) { // mat is the N * N square matrix. float mat[][] = { { 2, -2, -4 }, { -1, 3, 4 }, { 1, -2, -3 } }; printDistribution(mat); }} // This code is contributed by Gitanjali.", "e": 29219, "s": 27731, "text": null }, { "code": "# Python3 program to distribute a# square matrix into symmetric# and skew symmetric matrix.N = 3; def printMatrix(mat): for i in range(N): for j in range(N): print(mat[i][j], end = \" \"); print(\"\"); def printDistribution(mat): # tr is the transpose # of matrix mat. tr = [[0 for x in range(N)] for y in range(N)]; # Find transpose of matrix. for i in range(N): for j in range(N): tr[i][j] = mat[j][i]; # Declare two square # matrix symm and # skewsymm of size N. symm = [[0 for x in range(N)] for y in range(N)] ; skewsymm = [[0 for x in range(N)] for y in range(N)]; # Loop to find symmetric # and skew symmetric and # store it into symm and # skewsymm matrix. for i in range(N): for j in range(N): symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; print(\"Symmetric matrix-\"); printMatrix(symm); print(\"Skew Symmetric matrix\"); printMatrix(skewsymm); # Driver Code # mat is the N * N# square matrix.mat = [[2, -2, -4], [-1, 3, 4], [1, -2, -3]];printDistribution(mat); # This code is contributed by mits.", "e": 30446, "s": 29219, "text": null }, { "code": "// C# program for distribute// a square matrix into// symmetric and skew// symmetric matrix.using System; class GFG{ static int N = 3;static void printMatrix(float[,] mat){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(mat[i, j] + \" \"); System.Console.WriteLine(); }} static void printDistribution(float[,] mat){ // tr is the transpose // of matrix mat. float[,] tr = new float[N, N]; // Find transpose of matrix. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i, j] = mat[j, i]; // Declare two square matrix symm and // skewsymm of size N. float[,] symm = new float[N, N]; float[,] skewsymm = new float[N, N]; // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { symm[i, j] = (mat[i, j] + tr[i, j]) / 2; skewsymm[i, j] = (mat[i, j] - tr[i, j]) / 2; } } System.Console.WriteLine(\"Symmetric matrix-\" ); printMatrix(symm); System.Console.WriteLine(\"Skew Symmetric matrix-\" ); printMatrix(skewsymm);} // Driver codepublic static void Main(){ // mat is the N * N // square matrix. float[,] mat = new float[,]{{ 2, -2, -4}, {-1, 3, 4}, {1, -2, -3}}; printDistribution(mat);}} // This code is contributed by mits.", "e": 31976, "s": 30446, "text": null }, { "code": "<?php// PHP program to distribute a // square matrix into symmetric// and skew symmetric matrix.$N = 3; function printMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) echo $mat[$i][$j]. \" \"; echo \"\\n\"; }} function printDistribution($mat){ global $N; // tr is the transpose // of matrix mat. $tr; // Find transpose of matrix. for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $tr[$i][$j] = $mat[$j][$i]; // Declare two square // matrix symm and // skewsymm of size N. $symm; $skewsymm; // Loop to find symmetric // and skew symmetric and // store it into symm and // skewsymm matrix. for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) { $symm[$i][$j] = ($mat[$i][$j] + $tr[$i][$j]) / 2; $skewsymm[$i][$j] = ($mat[$i][$j] - $tr[$i][$j]) / 2; } } echo \"Symmetric matrix-\\n\"; printMatrix($symm); echo \"Skew Symmetric matrix-\\n\"; printMatrix($skewsymm);} // Driver Code // mat is the N * N// square matrix.$mat = array(array(2, -2, -4), array(-1, 3, 4), array(1, -2, -3));printDistribution($mat); // This code is contributed by mits.?>", "e": 33312, "s": 31976, "text": null }, { "code": "<script> // javascript program for distribute// a square matrix into// symmetric and skew symmetric// matrix.function printMatrix(mat){ for (var i = 0; i < mat.length; i++) { for (var j = 0; j < mat[i].length; j++) document.write(mat[i][j] + \" \"); document.write('<br>'); }} function printDistribution(mat){ // tr is the transpose of matrix mat. var N=mat.length; var tr = Array(N).fill(0).map(x => Array(N).fill(0)); // Find transpose of matrix. for (var i = 0; i < N; i++) for (var j = 0; j < N; j++) tr[i][j] = mat[j][i]; // Declare two square matrix symm and // skewsymm of size N. var symm=Array(N).fill(0).map(x => Array(N).fill(0)); var skewsymm=Array(N).fill(0).map(x => Array(N).fill(0)); // Loop to find symmetric and skew symmetric // and store it into symm and skewsymm matrix. for (var i = 0; i < N; i++) { for (var j = 0; j < N; j++) { symm[i][j] = (mat[i][j] + tr[i][j]) / 2; skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2; } } document.write(\"Symmetric matrix-<br>\" ); printMatrix(symm); document.write(\"Skew Symmetric matrix-<br>\" ); printMatrix(skewsymm);} // mat is the N * N square matrix. var mat = [ [ 2, -2, -4 ], [ -1, 3, 4 ], [ 1, -2, -3 ] ]; printDistribution(mat); // This code is contributed by Princi Singh</script>", "e": 34767, "s": 33312, "text": null }, { "code": null, "e": 34778, "s": 34767, "text": "Output : " }, { "code": null, "e": 34885, "s": 34778, "text": "Symmetric matrix-\n2 -1.5 -1.5 \n-1.5 3 1 \n-1.5 1 -3 \nSkew Symmetric matrix-\n0 -0.5 -2.5 \n0.5 0 3 \n2.5 -3 0 " }, { "code": null, "e": 34900, "s": 34887, "text": "Mithun Kumar" }, { "code": null, "e": 34913, "s": 34900, "text": "princi singh" }, { "code": null, "e": 34926, "s": 34913, "text": "Mathematical" }, { "code": null, "e": 34933, "s": 34926, "text": "Matrix" }, { "code": null, "e": 34946, "s": 34933, "text": "Mathematical" }, { "code": null, "e": 34953, "s": 34946, "text": "Matrix" }, { "code": null, "e": 35051, "s": 34953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35060, "s": 35051, "text": "Comments" }, { "code": null, "e": 35073, "s": 35060, "text": "Old Comments" }, { "code": null, "e": 35118, "s": 35073, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 35150, "s": 35118, "text": "Check if a number is Palindrome" }, { "code": null, "e": 35194, "s": 35150, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 35228, "s": 35194, "text": "Program to add two binary strings" }, { "code": null, "e": 35261, "s": 35228, "text": "Program to multiply two matrices" }, { "code": null, "e": 35296, "s": 35261, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 35340, "s": 35296, "text": "Program to find largest element in an array" }, { "code": null, "e": 35376, "s": 35340, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 35400, "s": 35376, "text": "Sudoku | Backtracking-7" } ]
Espresso Testing Framework - Setup Instructions
In this chapter, let us understand how to install espresso framework, configure it to write espresso tests and execute it in our android application. Espresso is a user interface-testing framework for testing android application developed in Java / Kotlin language using Android SDK. Therefore, espresso’s only requirement is to develop the application using Android SDK in either Java or Kotlin and it is advised to have the latest Android Studio. The list of items to be configured properly before we start working in espresso framework is as follows − Install latest Java JDK and configure JAVA_HOME environment variable. Install latest Java JDK and configure JAVA_HOME environment variable. Install latest Android Studio (version 3.2. or higher). Install latest Android Studio (version 3.2. or higher). Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable. Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable. Install latest Gradle Build Tool and configure GRADLE_HOME environment variable. Install latest Gradle Build Tool and configure GRADLE_HOME environment variable. Initially, espresso testing framework is provided as part of the Android Support library. Later, the Android team provides a new Android library, AndroidX and moves the latest espresso testing framework development into the library. Latest development (Android 9.0, API level 28 or higher) of espresso testing framework will be done in AndroidX library. Including espresso testing framework in a project is as simple as setting the espresso testing framework as a dependency in the application gradle file, app/build.gradle. The complete configuration is as follow, Using Android support library, android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2' } Using AndroidX library, android { defaultConfig { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } } dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.androidx.test:runner:1.0.2' androidTestImplementation 'com.androidx.espresso:espresso-core:3.0.2' } testInstrumentationRunner in the android/defaultConfig sets AndroidJUnitRunner class to run the instrumentation tests. The first line in the dependencies includes the JUnit testing framework, the second line in the dependencies includes the test runner library to run the test cases and finally the third line in the dependencies includes the espresso testing framework. By default, Android studio sets the espresso testing framework (Android support library) as a dependency while creating the android project and gradle will download the necessary library from the Maven repository. Let us create a simple Hello world android application and check whether the espresso testing framework is configured properly. The steps to create a new Android application are described below − Start Android Studio. Start Android Studio. Select File → New → New Project. Select File → New → New Project. Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next. Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next. To create Android Project, Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next. Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next. To target Android Devices, Select Empty Activity and then click Next. Select Empty Activity and then click Next. To add an activity to Mobile, Enter name for main activity and then click Finish. Enter name for main activity and then click Finish. To configure Activity, Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below, Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below, apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.tutorialspoint.espressosamples.helloworldapp" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2' } The last line specifies the espresso testing framework dependency. By default, Android support library is configured. We can reconfigure the application to use AndroidX library by clicking Refactor → Migrate to AndroidX in the menu. To migrate to Androidx, Now, the app/build.gradle changes as specified below, Now, the app/build.gradle changes as specified below, apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.tutorialspoint.espressosamples.helloworldapp" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0-alpha01' implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } Now, the last line includes espresso testing framework from AndroidX library. During testing, it is recommended to turn off the animation on the Android device, which is used for testing. This will reduce the confusions while checking ideling resources. Let us see how to disable animation on Android devices – (Settings → Developer options), Window animation scale Window animation scale Transition animation scale Transition animation scale Animator duration scale Animator duration scale If Developer options menu is not available in the Settings screen, then click Build Number available inside the About Phone option several times. This enables the Developer Option menu. 17 Lectures 1.5 hours Anuja Jain Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 1976, "text": "In this chapter, let us understand how to install espresso framework, configure it to write espresso tests and execute it in our android application." }, { "code": null, "e": 2425, "s": 2126, "text": "Espresso is a user interface-testing framework for testing android application developed in Java / Kotlin language using Android SDK. Therefore, espresso’s only requirement is to develop the application using Android SDK in either Java or Kotlin and it is advised to have the latest Android Studio." }, { "code": null, "e": 2531, "s": 2425, "text": "The list of items to be configured properly before we start working in espresso framework is as follows −" }, { "code": null, "e": 2601, "s": 2531, "text": "Install latest Java JDK and configure JAVA_HOME environment variable." }, { "code": null, "e": 2671, "s": 2601, "text": "Install latest Java JDK and configure JAVA_HOME environment variable." }, { "code": null, "e": 2727, "s": 2671, "text": "Install latest Android Studio (version 3.2. or higher)." }, { "code": null, "e": 2783, "s": 2727, "text": "Install latest Android Studio (version 3.2. or higher)." }, { "code": null, "e": 2877, "s": 2783, "text": "Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable." }, { "code": null, "e": 2971, "s": 2877, "text": "Install latest Android SDK using SDK Manager and configure ANDROID_HOME environment variable." }, { "code": null, "e": 3052, "s": 2971, "text": "Install latest Gradle Build Tool and configure GRADLE_HOME environment variable." }, { "code": null, "e": 3133, "s": 3052, "text": "Install latest Gradle Build Tool and configure GRADLE_HOME environment variable." }, { "code": null, "e": 3487, "s": 3133, "text": "Initially, espresso testing framework is provided as part of the Android Support library. Later, the Android team provides a new Android library, AndroidX and moves the latest espresso testing framework development into the library. Latest development (Android 9.0, API level 28 or higher) of espresso testing framework will be done in AndroidX library." }, { "code": null, "e": 3699, "s": 3487, "text": "Including espresso testing framework in a project is as simple as setting the espresso testing framework as a dependency in the application gradle file, app/build.gradle. The complete configuration is as follow," }, { "code": null, "e": 3730, "s": 3699, "text": "Using Android support library," }, { "code": null, "e": 4059, "s": 3730, "text": "android {\n defaultConfig {\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n}\ndependencies {\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2'\n}\n" }, { "code": null, "e": 4083, "s": 4059, "text": "Using AndroidX library," }, { "code": null, "e": 4387, "s": 4083, "text": "android {\n defaultConfig {\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n }\n}\ndependencies {\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.androidx.test:runner:1.0.2'\n androidTestImplementation 'com.androidx.espresso:espresso-core:3.0.2'\n}\n" }, { "code": null, "e": 4758, "s": 4387, "text": "testInstrumentationRunner in the android/defaultConfig sets AndroidJUnitRunner class to run the instrumentation tests. The first line in the dependencies includes the JUnit testing framework, the second line in the dependencies includes the test runner library to run the test cases and finally the third line in the dependencies includes the espresso testing framework." }, { "code": null, "e": 5100, "s": 4758, "text": "By default, Android studio sets the espresso testing framework (Android support library) as a dependency while creating the android project and gradle will download the necessary library from the Maven repository. Let us create a simple Hello world android application and check whether the espresso testing framework is configured properly." }, { "code": null, "e": 5168, "s": 5100, "text": "The steps to create a new Android application are described below −" }, { "code": null, "e": 5190, "s": 5168, "text": "Start Android Studio." }, { "code": null, "e": 5212, "s": 5190, "text": "Start Android Studio." }, { "code": null, "e": 5245, "s": 5212, "text": "Select File → New → New Project." }, { "code": null, "e": 5278, "s": 5245, "text": "Select File → New → New Project." }, { "code": null, "e": 5394, "s": 5278, "text": "Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next." }, { "code": null, "e": 5510, "s": 5394, "text": "Enter Application Name (HelloWorldApp) and Company domain (espressosamples.tutorialspoint.com) and then click Next." }, { "code": null, "e": 5537, "s": 5510, "text": "To create Android Project," }, { "code": null, "e": 5621, "s": 5537, "text": "Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next." }, { "code": null, "e": 5705, "s": 5621, "text": "Select minimum API as API 15: Android 4.0.3 (IceCreamSandwich) and then click Next." }, { "code": null, "e": 5732, "s": 5705, "text": "To target Android Devices," }, { "code": null, "e": 5775, "s": 5732, "text": "Select Empty Activity and then click Next." }, { "code": null, "e": 5818, "s": 5775, "text": "Select Empty Activity and then click Next." }, { "code": null, "e": 5848, "s": 5818, "text": "To add an activity to Mobile," }, { "code": null, "e": 5900, "s": 5848, "text": "Enter name for main activity and then click Finish." }, { "code": null, "e": 5952, "s": 5900, "text": "Enter name for main activity and then click Finish." }, { "code": null, "e": 5975, "s": 5952, "text": "To configure Activity," }, { "code": null, "e": 6105, "s": 5975, "text": "Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below," }, { "code": null, "e": 6235, "s": 6105, "text": "Once, a new project is created, open the app/build.gradle file and check its content. The content of the file is specified below," }, { "code": null, "e": 7155, "s": 6235, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.tutorialspoint.espressosamples.helloworldapp\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espressocore:3.0.2'\n}" }, { "code": null, "e": 7388, "s": 7155, "text": "The last line specifies the espresso testing framework dependency. By default, Android support library is configured. We can reconfigure the application to use AndroidX library by clicking Refactor → Migrate to AndroidX in the menu." }, { "code": null, "e": 7412, "s": 7388, "text": "To migrate to Androidx," }, { "code": null, "e": 7466, "s": 7412, "text": "Now, the app/build.gradle changes as specified below," }, { "code": null, "e": 7520, "s": 7466, "text": "Now, the app/build.gradle changes as specified below," }, { "code": null, "e": 8413, "s": 7520, "text": "apply plugin: 'com.android.application'\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.tutorialspoint.espressosamples.helloworldapp\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'\n implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'androidx.test:runner:1.1.1'\n androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'\n}" }, { "code": null, "e": 8491, "s": 8413, "text": "Now, the last line includes espresso testing framework from AndroidX library." }, { "code": null, "e": 8667, "s": 8491, "text": "During testing, it is recommended to turn off the animation on the Android device, which is used for testing. This will reduce the confusions while checking ideling resources." }, { "code": null, "e": 8756, "s": 8667, "text": "Let us see how to disable animation on Android devices – (Settings → Developer options)," }, { "code": null, "e": 8779, "s": 8756, "text": "Window animation scale" }, { "code": null, "e": 8802, "s": 8779, "text": "Window animation scale" }, { "code": null, "e": 8829, "s": 8802, "text": "Transition animation scale" }, { "code": null, "e": 8856, "s": 8829, "text": "Transition animation scale" }, { "code": null, "e": 8880, "s": 8856, "text": "Animator duration scale" }, { "code": null, "e": 8904, "s": 8880, "text": "Animator duration scale" }, { "code": null, "e": 9090, "s": 8904, "text": "If Developer options menu is not available in the Settings screen, then click Build Number available inside the About Phone option several times. This enables the Developer Option menu." }, { "code": null, "e": 9125, "s": 9090, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9137, "s": 9125, "text": " Anuja Jain" }, { "code": null, "e": 9144, "s": 9137, "text": " Print" }, { "code": null, "e": 9155, "s": 9144, "text": " Add Notes" } ]
How to add a margin to a tkinter window?
The margin of a tkinter window can be controlled by specifying the value of fill, expand and padding. Another way to set the margin of a tkinter window is to use grid(**options) Geometry Manager. Grid pack manager allows us to add the margin by specifying the value of row and column property. # Import the required library from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win= Tk() # Set the size of the Tkinter window win.geometry("700x350") # Add a frame to set the size of the window frame= Frame(win, relief= 'sunken', bg= "black") frame.pack(fill= BOTH, expand= True, padx= 10, pady=20) # Add a label widget label= Label(frame, text= "Welcome to Tutorialspoint", font=('Helvetica 15 bold'), bg= "white") label.pack(pady= 30) win.mainloop() Executing the above code will display a Label Text lying inside a frame. The margin of the frame is expandable and resizable.
[ { "code": null, "e": 1356, "s": 1062, "text": "The margin of a tkinter window can be controlled by specifying the value of fill, expand and padding. Another way to set the margin of a tkinter window is to use grid(**options) Geometry Manager. Grid pack manager allows us to add the margin by specifying the value of row and column property." }, { "code": null, "e": 1848, "s": 1356, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the Tkinter window\nwin.geometry(\"700x350\")\n\n# Add a frame to set the size of the window\nframe= Frame(win, relief= 'sunken', bg= \"black\")\nframe.pack(fill= BOTH, expand= True, padx= 10, pady=20)\n\n# Add a label widget\nlabel= Label(frame, text= \"Welcome to Tutorialspoint\",\nfont=('Helvetica 15 bold'), bg= \"white\")\nlabel.pack(pady= 30)\n\nwin.mainloop()" }, { "code": null, "e": 1974, "s": 1848, "text": "Executing the above code will display a Label Text lying inside a frame. The margin of the frame is expandable and resizable." } ]
Ethical Hacking - Enumeration
Enumeration belongs to the first phase of Ethical Hacking, i.e., “Information Gathering”. This is a process where the attacker establishes an active connection with the victim and try to discover as much attack vectors as possible, which can be used to exploit the systems further. Enumeration can be used to gain information on − Network shares SNMP data, if they are not secured properly IP tables Usernames of different systems Passwords policies lists Enumerations depend on the services that the systems offer. They can be − DNS enumeration NTP enumeration SNMP enumeration Linux/Windows enumeration SMB enumeration Let us now discuss some of the tools that are widely used for Enumeration. NTP Suite is used for NTP enumeration. This is important because in a network environment, you can find other primary servers that help the hosts to update their times and you can do it without authenticating the system. Take a look at the following example. ntpdate 192.168.1.100 01 Sept 12:50:49 ntpdate[627]: adjust time server 192.168.1.100 offset 0.005030 sec or ntpdc [-ilnps] [-c command] [hostname/IP_address] root@test]# ntpdc -c sysinfo 192.168.1.100 ***Warning changing to older implementation ***Warning changing the request packet size from 160 to 48 system peer: 192.168.1.101 system peer mode: client leap indicator: 00 stratum: 5 precision: -15 root distance: 0.00107 s root dispersion: 0.02306 s reference ID: [192.168.1.101] reference time: f66s4f45.f633e130, Sept 01 2016 22:06:23.458 system flags: monitor ntp stats calibrate jitter: 0.000000 s stability: 4.256 ppm broadcastdelay: 0.003875 s authdelay: 0.000107 s enum4linux is used to enumerate Linux systems. Take a look at the following screenshot and observe how we have found the usernames present in a target host. smtp-user-enum tries to guess usernames by using SMTP service. Take a look at the following screenshot to understand how it does so. It is recommended to disable all services that you don’t use. It reduces the possibilities of OS enumeration of the services that your systems are running. 36 Lectures 5 hours Sharad Kumar 31 Lectures 3.5 hours Abhilash Nelson 22 Lectures 3 hours Blair Cook 74 Lectures 4.5 hours 199courses 75 Lectures 4.5 hours 199courses 148 Lectures 28.5 hours Joseph Delgadillo Print Add Notes Bookmark this page
[ { "code": null, "e": 2761, "s": 2479, "text": "Enumeration belongs to the first phase of Ethical Hacking, i.e., “Information Gathering”. This is a process where the attacker establishes an active connection with the victim and try to discover as much attack vectors as possible, which can be used to exploit the systems further." }, { "code": null, "e": 2810, "s": 2761, "text": "Enumeration can be used to gain information on −" }, { "code": null, "e": 2825, "s": 2810, "text": "Network shares" }, { "code": null, "e": 2869, "s": 2825, "text": "SNMP data, if they are not secured properly" }, { "code": null, "e": 2879, "s": 2869, "text": "IP tables" }, { "code": null, "e": 2910, "s": 2879, "text": "Usernames of different systems" }, { "code": null, "e": 2935, "s": 2910, "text": "Passwords policies lists" }, { "code": null, "e": 3009, "s": 2935, "text": "Enumerations depend on the services that the systems offer. They can be −" }, { "code": null, "e": 3025, "s": 3009, "text": "DNS enumeration" }, { "code": null, "e": 3041, "s": 3025, "text": "NTP enumeration" }, { "code": null, "e": 3058, "s": 3041, "text": "SNMP enumeration" }, { "code": null, "e": 3084, "s": 3058, "text": "Linux/Windows enumeration" }, { "code": null, "e": 3100, "s": 3084, "text": "SMB enumeration" }, { "code": null, "e": 3175, "s": 3100, "text": "Let us now discuss some of the tools that are widely used for Enumeration." }, { "code": null, "e": 3396, "s": 3175, "text": "NTP Suite is used for NTP enumeration. This is important because in a network environment, you can find other primary servers that help the hosts to update their times and you can do it without authenticating the system." }, { "code": null, "e": 3434, "s": 3396, "text": "Take a look at the following example." }, { "code": null, "e": 4137, "s": 3434, "text": "ntpdate 192.168.1.100 01 Sept 12:50:49 ntpdate[627]: \nadjust time server 192.168.1.100 offset 0.005030 sec \n\nor \nntpdc [-ilnps] [-c command] [hostname/IP_address] \n \nroot@test]# ntpdc -c sysinfo 192.168.1.100 \n***Warning changing to older implementation \n***Warning changing the request packet size from 160 to 48 \nsystem peer: 192.168.1.101 \n\nsystem peer mode: client\nleap indicator: 00 \nstratum: 5 \n\nprecision: -15 \nroot distance: 0.00107 s \nroot dispersion: 0.02306 s \nreference ID: [192.168.1.101] \nreference time: f66s4f45.f633e130, Sept 01 2016 22:06:23.458 \nsystem flags: monitor ntp stats calibrate \njitter: 0.000000 s \nstability: 4.256 ppm \nbroadcastdelay: 0.003875 s \nauthdelay: 0.000107 s\n" }, { "code": null, "e": 4294, "s": 4137, "text": "enum4linux is used to enumerate Linux systems. Take a look at the following screenshot and observe how we have found the usernames present in a target host." }, { "code": null, "e": 4427, "s": 4294, "text": "smtp-user-enum tries to guess usernames by using SMTP service. Take a look at the following screenshot to understand how it does so." }, { "code": null, "e": 4583, "s": 4427, "text": "It is recommended to disable all services that you don’t use. It reduces the possibilities of OS enumeration of the services that your systems are running." }, { "code": null, "e": 4616, "s": 4583, "text": "\n 36 Lectures \n 5 hours \n" }, { "code": null, "e": 4630, "s": 4616, "text": " Sharad Kumar" }, { "code": null, "e": 4665, "s": 4630, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4682, "s": 4665, "text": " Abhilash Nelson" }, { "code": null, "e": 4715, "s": 4682, "text": "\n 22 Lectures \n 3 hours \n" }, { "code": null, "e": 4727, "s": 4715, "text": " Blair Cook" }, { "code": null, "e": 4762, "s": 4727, "text": "\n 74 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4774, "s": 4762, "text": " 199courses" }, { "code": null, "e": 4809, "s": 4774, "text": "\n 75 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4821, "s": 4809, "text": " 199courses" }, { "code": null, "e": 4858, "s": 4821, "text": "\n 148 Lectures \n 28.5 hours \n" }, { "code": null, "e": 4877, "s": 4858, "text": " Joseph Delgadillo" }, { "code": null, "e": 4884, "s": 4877, "text": " Print" }, { "code": null, "e": 4895, "s": 4884, "text": " Add Notes" } ]
How can I remove all empty values when I explode a string using PHP?
The array_filter() or PREG_SPLIT_NO_EMPTY option on preg_split() can be used to remove empty values from a string when it is exploded − Live Demo <?php $_POST['tag'] = ",abc,defg,,,hijk,lmnop,,0,,"; echo "--- version 1: array_filter ----\n"; // note that this also filters "0" out, since (bool)"0" is FALSE in php // array_filter() called with only one parameter tests each element as a boolean value $tags = array_filter( explode(",", $_POST['tag']) ); var_dump($tags); echo "--- version 2: array_filter/strlen ----\n"; // this one keeps the "0" element // array_filter() calls strlen() for each element of the array and tests the result as a boolean value $tags = array_filter( explode(",", $_POST['tag']), 'strlen' ); var_dump($tags); echo "--- version 3: PREG_SPLIT_NO_EMPTY ----\n"; $tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY); var_dump($tags); This will produce the following output − --- version 1: array_filter ---- array(4) { [1]=> string(3) " abc " [2]=> string(4) " defg " [5]=> string(4) "hijk" [6]=> string(5) "lmnop" } --- version 2: array_filter/strlen ---- array(5) { [1]=> string(3) "abc" [2]=> string(4) "defg" [5]=> string(4) "hijk" [6]=> string(5) "lmnop" [8]=> string(1) "0" } --- version 3: PREG_SPLIT_NO_EMPTY ---- array(5) { [0]=> string(3) "abc" [1]=> string(4) "defg" [2]=> string(4) "hijk" [3]=> string(5) "lmnop" [4]=> string(1) "0" }
[ { "code": null, "e": 1198, "s": 1062, "text": "The array_filter() or PREG_SPLIT_NO_EMPTY option on preg_split() can be used to remove empty values from a string when it is exploded −" }, { "code": null, "e": 1209, "s": 1198, "text": " Live Demo" }, { "code": null, "e": 1937, "s": 1209, "text": "<?php\n$_POST['tag'] = \",abc,defg,,,hijk,lmnop,,0,,\";\necho \"--- version 1: array_filter ----\\n\";\n// note that this also filters \"0\" out, since (bool)\"0\" is FALSE in php\n// array_filter() called with only one parameter tests each element as a boolean value\n$tags = array_filter( explode(\",\", $_POST['tag']) );\nvar_dump($tags);\necho \"--- version 2: array_filter/strlen ----\\n\";\n// this one keeps the \"0\" element\n// array_filter() calls strlen() for each element of the array and tests the result as a boolean value\n$tags = array_filter( explode(\",\", $_POST['tag']), 'strlen' );\nvar_dump($tags);\necho \"--- version 3: PREG_SPLIT_NO_EMPTY ----\\n\";\n$tags = preg_split('/,/', $_POST['tag'], -1, PREG_SPLIT_NO_EMPTY);\nvar_dump($tags);\n " }, { "code": null, "e": 1978, "s": 1937, "text": "This will produce the following output −" }, { "code": null, "e": 2454, "s": 1978, "text": "--- version 1: array_filter ---- array(4) { [1]=> string(3) \" abc \" [2]=> string(4) \" defg \" \n[5]=> string(4) \"hijk\" [6]=> string(5) \"lmnop\" } --- version 2: array_filter/strlen ---- array(5) \n{ [1]=> string(3) \"abc\" [2]=> string(4) \"defg\" [5]=> string(4) \"hijk\" [6]=> string(5) \"lmnop\" [8]=> \nstring(1) \"0\" } --- version 3: PREG_SPLIT_NO_EMPTY ---- array(5) { [0]=> string(3) \"abc\" [1]=> \nstring(4) \"defg\" [2]=> string(4) \"hijk\" [3]=> string(5) \"lmnop\" [4]=> string(1) \"0\" }" } ]
How do I check to see if a value is an integer in MySQL?
To check if the given value is a string or not ,we use the cast() function. If the value is not numeric then it returns 0, otherwise it will return the numeric value. In this way, we can check whether the value is an integer or not. mysql> select cast('John123456' AS UNSIGNED); The following is the output. It shows that the value is not numeric, therefore 0 is returned. +--------------------------------+ | cast('John123456' AS UNSIGNED) | +--------------------------------+ | 0 | +--------------------------------+ 1 row in set, 1 warning (0.00 sec) mysql> select cast('123456' AS UNSIGNED); The following is the output. It shows that the value is numeric, therefore the value itself is returned. +----------------------------+ | cast('123456' AS UNSIGNED) | +----------------------------+ | 123456 | +----------------------------+ 1 row in set (0.00 sec) This logic does work well for float as well. The following is the query with float value. mysql> SELECT CAST('78.90' AS UNSIGNED); Here is the output. +---------------------------+ | CAST('78.90' AS UNSIGNED) | +---------------------------+ | 78 | +---------------------------+ 1 row in set, 1 warning (0.00 sec) It works for all conditions for any value, even float. Let us create a new table. mysql> create table CheckingIntegerDemo -> ( -> Value varchar(200) -> ); Query OK, 0 rows affected (0.88 sec) Inserting records into table. mysql> insert into CheckingIntegerDemo values('John123456'); Query OK, 1 row affected (0.10 sec) mysql> insert into CheckingIntegerDemo values('123456'); Query OK, 1 row affected (0.16 sec) mysql> insert into CheckingIntegerDemo values('123.456'); Query OK, 1 row affected (0.16 sec) To display all records. mysql> select *from CheckingIntegerDemo; Here is the output. +------------+ | Value | +------------+ | John123456 | | 123456 | | 123.456 | +------------+ 3 rows in set (0.00 sec In the above output, only 123456 is an integer and the remaining are not. Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value. mysql> select Value from CheckingIntegerDemo where Value REGEXP '^-?[0-9]+$'; The following is the output. +--------+ | Value | +--------+ | 123456 | +--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1295, "s": 1062, "text": "To check if the given value is a string or not ,we use the cast() function. If the value is not numeric then it returns 0, otherwise it will return the numeric value. In this way, we can check whether the value is an integer or not." }, { "code": null, "e": 1341, "s": 1295, "text": "mysql> select cast('John123456' AS UNSIGNED);" }, { "code": null, "e": 1435, "s": 1341, "text": "The following is the output. It shows that the value is not numeric, therefore 0 is returned." }, { "code": null, "e": 1646, "s": 1435, "text": "+--------------------------------+\n| cast('John123456' AS UNSIGNED) |\n+--------------------------------+\n| 0 |\n+--------------------------------+\n1 row in set, 1 warning (0.00 sec)\n" }, { "code": null, "e": 1688, "s": 1646, "text": "mysql> select cast('123456' AS UNSIGNED);" }, { "code": null, "e": 1793, "s": 1688, "text": "The following is the output. It shows that the value is numeric, therefore the value itself is returned." }, { "code": null, "e": 1973, "s": 1793, "text": "+----------------------------+\n| cast('123456' AS UNSIGNED) |\n+----------------------------+\n| 123456 |\n+----------------------------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 2018, "s": 1973, "text": "This logic does work well for float as well." }, { "code": null, "e": 2063, "s": 2018, "text": "The following is the query with float value." }, { "code": null, "e": 2105, "s": 2063, "text": "mysql> SELECT CAST('78.90' AS UNSIGNED);" }, { "code": null, "e": 2125, "s": 2105, "text": "Here is the output." }, { "code": null, "e": 2311, "s": 2125, "text": "+---------------------------+\n| CAST('78.90' AS UNSIGNED) |\n+---------------------------+\n| 78 |\n+---------------------------+\n1 row in set, 1 warning (0.00 sec)\n" }, { "code": null, "e": 2366, "s": 2311, "text": "It works for all conditions for any value, even float." }, { "code": null, "e": 2393, "s": 2366, "text": "Let us create a new table." }, { "code": null, "e": 2513, "s": 2393, "text": "mysql> create table CheckingIntegerDemo\n -> (\n -> Value varchar(200)\n -> );\nQuery OK, 0 rows affected (0.88 sec)\n" }, { "code": null, "e": 2543, "s": 2513, "text": "Inserting records into table." }, { "code": null, "e": 2830, "s": 2543, "text": "mysql> insert into CheckingIntegerDemo values('John123456');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into CheckingIntegerDemo values('123456');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into CheckingIntegerDemo values('123.456');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2854, "s": 2830, "text": "To display all records." }, { "code": null, "e": 2895, "s": 2854, "text": "mysql> select *from CheckingIntegerDemo;" }, { "code": null, "e": 2915, "s": 2895, "text": "Here is the output." }, { "code": null, "e": 3045, "s": 2915, "text": "+------------+\n| Value |\n+------------+\n| John123456 |\n| 123456 |\n| 123.456 |\n+------------+\n3 rows in set (0.00 sec\n" }, { "code": null, "e": 3119, "s": 3045, "text": "In the above output, only 123456 is an integer and the remaining are not." }, { "code": null, "e": 3163, "s": 3119, "text": "Syntax to check if the value is an integer." }, { "code": null, "e": 3246, "s": 3163, "text": "select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$';" }, { "code": null, "e": 3338, "s": 3246, "text": "The query wherein we have used regular expression. This will output only the integer value." }, { "code": null, "e": 3416, "s": 3338, "text": "mysql> select Value from CheckingIntegerDemo where Value REGEXP '^-?[0-9]+$';" }, { "code": null, "e": 3445, "s": 3416, "text": "The following is the output." }, { "code": null, "e": 3525, "s": 3445, "text": "+--------+\n| Value |\n+--------+\n| 123456 |\n+--------+\n1 row in set (0.00 sec)\n" } ]
Having an Imbalanced Dataset? Here Is How You Can Fix It. | by Will Badr | Towards Data Science
Classification is one of the most common machine learning problems. The best way to approach any classification problem is to start by analyzing and exploring the dataset in what we call Exploratory Data Analysis (EDA). The sole purpose of this exercise is to generate as many insights and information about the data as possible. It is also used to find any problems that might exist in the dataset. One of the common issues found in datasets that are used for classification is imbalanced classes issue. What Is Data Imbalance? Data imbalance usually reflects an unequal distribution of classes within a dataset. For example, in a credit card fraud detection dataset, most of the credit card transactions are not fraud and a very few classes are fraud transactions. This leaves us with something like 50:1 ratio between the fraud and non-fraud classes. In this article, I will use the credit card fraud transactions dataset from Kaggle which can be downloaded from here. First, let’s plot the class distribution to see the imbalance. As you can see, the non-fraud transactions far outweigh the fraud transactions. If we train a binary classification model without fixing this problem, the model will be completely biased. It also impacts the correlations between features and I will show you how and why later on. Now, let’s cover a few techniques to solve the class imbalance problem. A notebook with the complete code can be found HERE This is as intuitive as it sounds. Undersampling is the process where you randomly delete some of the observations from the majority class in order to match the numbers with the minority class. An easy way to do that is shown in the code below: After undersampling the dataset, I plot it again and it shows an equal number of classes: The second resampling technique is called, Oversampling. This process is a little more complicated than undersampling. It is the process of generating synthetic data that tries to randomly generate a sample of the attributes from observations in the minority class. There are a number of methods used to oversample a dataset for a typical classification problem. The most common technique is called SMOTE (Synthetic Minority Over-sampling Technique). In simple terms, it looks at the feature space for the minority class data points and considers its k nearest neighbours. To code this in python, I use a library called imbalanced-learn or imblearn. The code below shows how to implement SMOTE. Remember when I said how imbalanced data would affect the feature correlation? Let me show you the correlation before and after treating the imbalanced class. The code below plots the correlation matrix between all the features. # Sample figsize in inchesfig, ax = plt.subplots(figsize=(20,10)) # Imbalanced DataFrame Correlationcorr = credit_df.corr()sns.heatmap(corr, cmap='YlGnBu', annot_kws={'size':30}, ax=ax)ax.set_title("Imbalanced Correlation Matrix", fontsize=14)plt.show() Notice that the feature correlation is much more obvious now. Before fixing the imbalance problem, most of the features did not show any correlation which would definitely have impacted the performance of the model. Since the feature correlation really matters to the overall model’s performance, it is important to fix the imbalance as it will also impact the ML model performance. In Machine Learning, ensemble methods use multiple learning algorithms and techniques to obtain better performance than what could be obtained from any of the constituent learning algorithms alone. (Yes, just like a democratic voting system). When using ensemble classifiers, bagging methods become popular and it works by building multiple estimators on a different randomly selected subset of data. In the scikit-learn library, there is an ensemble classifier namedBaggingClassifier. However, this classifier does not allow to balance each subset of data. Therefore, when training on imbalanced data set, this classifier will favour the majority classes and create a biased model. In order to fix this, we can use BalancedBaggingClassifier from imblearn library. It allows the resampling of each subset of the dataset before training each estimator of the ensemble. Therefore, BalancedBaggingClassifier takes the same parameters as the scikit-learn BaggingClassifierin addition to two other parameters, sampling_strategy and replacement which control the behaviour of the random sampler. Here is some code that shows how to do this: That way, you can train a classifier that will handle the imbalance without having to undersample or oversample manually before training. You should always split your dataset into training and testing sets before balancing the data. That way, you ensure that the test dataset is as unbiased as it can be and reflects a true evaluation for your model. Balancing the data before splitting might introduce bias in the test set where a few data points in the test set are synthetically generated and well-known from the training set. The test set should be as objective as possible. The concern with under-sampling techniques is that you may delete some valuable information and alter the overall dataset distribution that is representative in a specific domain. Hence, under-sampling should not be the first go-to approach for imbalanced datasets. In Conclusion, everyone should know that the overall performance of ML models built on imbalanced datasets, will be constrained by its ability to predict rare and minority points. Identifying and resolving the imbalance of those points is crucial to the quality and performance of the generated models.
[ { "code": null, "e": 677, "s": 172, "text": "Classification is one of the most common machine learning problems. The best way to approach any classification problem is to start by analyzing and exploring the dataset in what we call Exploratory Data Analysis (EDA). The sole purpose of this exercise is to generate as many insights and information about the data as possible. It is also used to find any problems that might exist in the dataset. One of the common issues found in datasets that are used for classification is imbalanced classes issue." }, { "code": null, "e": 701, "s": 677, "text": "What Is Data Imbalance?" }, { "code": null, "e": 1144, "s": 701, "text": "Data imbalance usually reflects an unequal distribution of classes within a dataset. For example, in a credit card fraud detection dataset, most of the credit card transactions are not fraud and a very few classes are fraud transactions. This leaves us with something like 50:1 ratio between the fraud and non-fraud classes. In this article, I will use the credit card fraud transactions dataset from Kaggle which can be downloaded from here." }, { "code": null, "e": 1207, "s": 1144, "text": "First, let’s plot the class distribution to see the imbalance." }, { "code": null, "e": 1487, "s": 1207, "text": "As you can see, the non-fraud transactions far outweigh the fraud transactions. If we train a binary classification model without fixing this problem, the model will be completely biased. It also impacts the correlations between features and I will show you how and why later on." }, { "code": null, "e": 1611, "s": 1487, "text": "Now, let’s cover a few techniques to solve the class imbalance problem. A notebook with the complete code can be found HERE" }, { "code": null, "e": 1856, "s": 1611, "text": "This is as intuitive as it sounds. Undersampling is the process where you randomly delete some of the observations from the majority class in order to match the numbers with the minority class. An easy way to do that is shown in the code below:" }, { "code": null, "e": 1946, "s": 1856, "text": "After undersampling the dataset, I plot it again and it shows an equal number of classes:" }, { "code": null, "e": 2519, "s": 1946, "text": "The second resampling technique is called, Oversampling. This process is a little more complicated than undersampling. It is the process of generating synthetic data that tries to randomly generate a sample of the attributes from observations in the minority class. There are a number of methods used to oversample a dataset for a typical classification problem. The most common technique is called SMOTE (Synthetic Minority Over-sampling Technique). In simple terms, it looks at the feature space for the minority class data points and considers its k nearest neighbours." }, { "code": null, "e": 2641, "s": 2519, "text": "To code this in python, I use a library called imbalanced-learn or imblearn. The code below shows how to implement SMOTE." }, { "code": null, "e": 2800, "s": 2641, "text": "Remember when I said how imbalanced data would affect the feature correlation? Let me show you the correlation before and after treating the imbalanced class." }, { "code": null, "e": 2870, "s": 2800, "text": "The code below plots the correlation matrix between all the features." }, { "code": null, "e": 3132, "s": 2870, "text": "# Sample figsize in inchesfig, ax = plt.subplots(figsize=(20,10)) # Imbalanced DataFrame Correlationcorr = credit_df.corr()sns.heatmap(corr, cmap='YlGnBu', annot_kws={'size':30}, ax=ax)ax.set_title(\"Imbalanced Correlation Matrix\", fontsize=14)plt.show()" }, { "code": null, "e": 3515, "s": 3132, "text": "Notice that the feature correlation is much more obvious now. Before fixing the imbalance problem, most of the features did not show any correlation which would definitely have impacted the performance of the model. Since the feature correlation really matters to the overall model’s performance, it is important to fix the imbalance as it will also impact the ML model performance." }, { "code": null, "e": 4198, "s": 3515, "text": "In Machine Learning, ensemble methods use multiple learning algorithms and techniques to obtain better performance than what could be obtained from any of the constituent learning algorithms alone. (Yes, just like a democratic voting system). When using ensemble classifiers, bagging methods become popular and it works by building multiple estimators on a different randomly selected subset of data. In the scikit-learn library, there is an ensemble classifier namedBaggingClassifier. However, this classifier does not allow to balance each subset of data. Therefore, when training on imbalanced data set, this classifier will favour the majority classes and create a biased model." }, { "code": null, "e": 4650, "s": 4198, "text": "In order to fix this, we can use BalancedBaggingClassifier from imblearn library. It allows the resampling of each subset of the dataset before training each estimator of the ensemble. Therefore, BalancedBaggingClassifier takes the same parameters as the scikit-learn BaggingClassifierin addition to two other parameters, sampling_strategy and replacement which control the behaviour of the random sampler. Here is some code that shows how to do this:" }, { "code": null, "e": 4788, "s": 4650, "text": "That way, you can train a classifier that will handle the imbalance without having to undersample or oversample manually before training." }, { "code": null, "e": 5001, "s": 4788, "text": "You should always split your dataset into training and testing sets before balancing the data. That way, you ensure that the test dataset is as unbiased as it can be and reflects a true evaluation for your model." }, { "code": null, "e": 5229, "s": 5001, "text": "Balancing the data before splitting might introduce bias in the test set where a few data points in the test set are synthetically generated and well-known from the training set. The test set should be as objective as possible." }, { "code": null, "e": 5495, "s": 5229, "text": "The concern with under-sampling techniques is that you may delete some valuable information and alter the overall dataset distribution that is representative in a specific domain. Hence, under-sampling should not be the first go-to approach for imbalanced datasets." } ]
How to save MySQL query output to excel or .txt file?
To save MySQL query output into a text file, we can use the OUTFILE command. Let us first create a table. mysql> create table SaveintoTextFile -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.55 sec) Inserting records into the table. mysql> insert into SaveintoTextFile values(1,'John'); Query OK, 1 row affected (0.44 sec) mysql> insert into SaveintoTextFile values(101,'Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into SaveintoTextFile values(3,'David'); Query OK, 1 row affected (0.14 sec To display all the records. mysql> select *from SaveintoTextFile; Here is the output. +------+-------+ | id | name | +------+-------+ | 1 | John | | 101 | Carol | | 3 | David | +------+-------+ 3 rows in set (0.00 sec) The following is the syntax to display the result in a text file. SELECT col_name1,col_name2,.......N from yourTableName INTO OUTFILE "Path of my.cnf file- secure-file-priv "; Let us implement the above syntax in the following query. Here, our text file is “QueryOutput.txt” mysql> SELECT id,name from SaveintoTextFile -> INTO OUTFILE "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/QueryOutput.txt"; Query OK, 3 rows affected (0.02 sec) To check if the text file is created or not, check the “Uploads” folder. Now, open the text file. The text would be visible in the file as shown in the following screenshot.
[ { "code": null, "e": 1140, "s": 1062, "text": "To save MySQL query output into a text file, we can use the OUTFILE command.\n" }, { "code": null, "e": 1169, "s": 1140, "text": "Let us first create a table." }, { "code": null, "e": 1298, "s": 1169, "text": "mysql> create table SaveintoTextFile\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1332, "s": 1298, "text": "Inserting records into the table." }, { "code": null, "e": 1607, "s": 1332, "text": "mysql> insert into SaveintoTextFile values(1,'John');\nQuery OK, 1 row affected (0.44 sec)\n\nmysql> insert into SaveintoTextFile values(101,'Carol');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into SaveintoTextFile values(3,'David');\nQuery OK, 1 row affected (0.14 sec" }, { "code": null, "e": 1635, "s": 1607, "text": "To display all the records." }, { "code": null, "e": 1673, "s": 1635, "text": "mysql> select *from SaveintoTextFile;" }, { "code": null, "e": 1693, "s": 1673, "text": "Here is the output." }, { "code": null, "e": 1838, "s": 1693, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 101 | Carol |\n| 3 | David |\n+------+-------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 1904, "s": 1838, "text": "The following is the syntax to display the result in a text file." }, { "code": null, "e": 2018, "s": 1904, "text": "SELECT col_name1,col_name2,.......N from yourTableName\n INTO OUTFILE \"Path of my.cnf file- secure-file-priv \";\n" }, { "code": null, "e": 2117, "s": 2018, "text": "Let us implement the above syntax in the following query. Here, our text file is “QueryOutput.txt”" }, { "code": null, "e": 2283, "s": 2117, "text": "mysql> SELECT id,name from SaveintoTextFile\n -> INTO OUTFILE \"C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/QueryOutput.txt\";\nQuery OK, 3 rows affected (0.02 sec)" }, { "code": null, "e": 2356, "s": 2283, "text": "To check if the text file is created or not, check the “Uploads” folder." }, { "code": null, "e": 2457, "s": 2356, "text": "Now, open the text file. The text would be visible in the file as shown in the following screenshot." } ]
Program to find number of friend groups in a set of friends connections in Python
Suppose we have a a friends list, where friends[i] is a list of people i is friends with. The connection of friendships are two-way. And each person is friend with themselves and two people are in a friend group as long as there is some path of mutual friends connecting them. We have to find the total number of friend groups. So, if the input is like friends = [[0, 1, 5],[1, 0],[2],[3, 4],[4, 3],[5, 0]], then the output will be 3, as The three friend groups are as below − To solve this, we will follow these steps − nodes := size of friends visited := a list of size same as nodes and fill with False ans := 0 Define a function dfs() . This will take vertex, visited visited[vertex] := True for each nei in friends[vertex], doif visited[nei] is false, thendfs(nei, visited) if visited[nei] is false, thendfs(nei, visited) dfs(nei, visited) From the main method, do the following − for i in range 0 to nodes, doif visited[i] is false, thendfs(i, visited)ans := ans + 1 if visited[i] is false, thendfs(i, visited)ans := ans + 1 dfs(i, visited) ans := ans + 1 return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, friends): nodes = len(friends) visited = [False for _ in range(nodes)] ans = 0 def dfs(vertex, visited): visited[vertex] = True for nei in friends[vertex]: if not visited[nei]: dfs(nei, visited) for i in range(nodes): if not visited[i]: dfs(i, visited) ans += 1 return ans ob = Solution() friends = [ [0, 1, 5], [1, 0], [2], [3, 4], [4, 3], [5, 0] ] print(ob.solve(friends)) [[0, 1, 5], [1, 0], [2], [3, 4], [4, 3], [5, 0] ] 3
[ { "code": null, "e": 1390, "s": 1062, "text": "Suppose we have a a friends list, where friends[i] is a list of people i is friends with. The connection of friendships are two-way. And each person is friend with themselves and two people are in a friend group as long as there is some path of mutual friends connecting them. We have to find the total number of friend groups." }, { "code": null, "e": 1539, "s": 1390, "text": "So, if the input is like friends = [[0, 1, 5],[1, 0],[2],[3, 4],[4, 3],[5, 0]], then the output will be 3, as The three friend groups are as below −" }, { "code": null, "e": 1583, "s": 1539, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1608, "s": 1583, "text": "nodes := size of friends" }, { "code": null, "e": 1668, "s": 1608, "text": "visited := a list of size same as nodes and fill with False" }, { "code": null, "e": 1677, "s": 1668, "text": "ans := 0" }, { "code": null, "e": 1734, "s": 1677, "text": "Define a function dfs() . This will take vertex, visited" }, { "code": null, "e": 1758, "s": 1734, "text": "visited[vertex] := True" }, { "code": null, "e": 1841, "s": 1758, "text": "for each nei in friends[vertex], doif visited[nei] is false, thendfs(nei, visited)" }, { "code": null, "e": 1889, "s": 1841, "text": "if visited[nei] is false, thendfs(nei, visited)" }, { "code": null, "e": 1907, "s": 1889, "text": "dfs(nei, visited)" }, { "code": null, "e": 1948, "s": 1907, "text": "From the main method, do the following −" }, { "code": null, "e": 2035, "s": 1948, "text": "for i in range 0 to nodes, doif visited[i] is false, thendfs(i, visited)ans := ans + 1" }, { "code": null, "e": 2093, "s": 2035, "text": "if visited[i] is false, thendfs(i, visited)ans := ans + 1" }, { "code": null, "e": 2109, "s": 2093, "text": "dfs(i, visited)" }, { "code": null, "e": 2124, "s": 2109, "text": "ans := ans + 1" }, { "code": null, "e": 2135, "s": 2124, "text": "return ans" }, { "code": null, "e": 2205, "s": 2135, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2216, "s": 2205, "text": " Live Demo" }, { "code": null, "e": 2731, "s": 2216, "text": "class Solution:\n def solve(self, friends):\n nodes = len(friends)\n visited = [False for _ in range(nodes)]\n ans = 0\n def dfs(vertex, visited): visited[vertex] = True\n for nei in friends[vertex]:\n if not visited[nei]:\n dfs(nei, visited)\n for i in range(nodes):\n if not visited[i]:\n dfs(i, visited)\n ans += 1\n return ans\nob = Solution()\nfriends = [ [0, 1, 5], [1, 0], [2], [3, 4], [4, 3], [5, 0] ]\nprint(ob.solve(friends))" }, { "code": null, "e": 2781, "s": 2731, "text": "[[0, 1, 5],\n[1, 0],\n[2],\n[3, 4],\n[4, 3],\n[5, 0]\n]" }, { "code": null, "e": 2783, "s": 2781, "text": "3" } ]
How to create an integer64 vector in R?
The integer64 vector contains vector values that represents signed integers with values that range from negative 9,223,372,036,854,775,808 to positive 9,223,372,036,854,775,807. To create an integer64 vector, we can use as.integer64 function of bit64 package. The difference between integer64 vector and others is that a large number of values can be stored in the vector. library(bit64) x1<-as.integer64(sample(0:9,200,replace=TRUE)) x1 integer64 [1] 4 3 1 3 8 8 4 5 6 2 8 7 5 0 2 4 8 4 6 7 3 9 5 2 1 1 5 7 6 0 3 9 9 8 1 0 0 [38] 6 8 8 5 8 7 1 9 8 9 2 5 6 7 9 5 9 8 6 3 5 6 1 7 7 6 8 6 9 0 9 8 2 4 9 8 5 [75] 5 8 7 7 4 2 7 9 5 7 9 6 0 7 4 1 0 0 4 7 0 3 7 3 4 0 8 0 4 3 5 2 7 2 5 6 8 [112] 9 9 1 5 5 7 7 2 1 4 5 3 1 3 4 3 3 1 7 2 2 8 2 1 0 0 9 6 8 1 8 6 0 6 1 0 0 [149] 6 2 3 8 3 4 9 2 7 5 3 1 8 4 2 6 9 2 2 2 1 9 2 6 7 6 3 3 1 8 0 1 3 1 4 6 0 [186] 3 5 8 2 0 1 2 8 0 8 8 9 5 1 0 x2<-as.integer64(sample(1:100,200,replace=TRUE)) > x2 integer64 [1] 41 98 21 92 52 50 49 93 31 46 33 71 21 59 87 7 16 10 [19] 43 51 76 29 33 80 56 85 42 89 45 96 71 56 42 70 76 31 [37] 55 76 100 75 87 95 27 53 71 51 56 90 9 3 41 9 8 32 [55] 94 39 74 13 24 93 7 37 60 41 38 23 25 31 54 96 31 36 [73] 72 30 21 98 16 25 7 28 98 80 56 20 66 55 76 14 91 87 [91] 15 71 46 6 21 79 54 29 58 81 18 60 31 5 34 51 9 93 [109] 58 95 72 26 99 25 53 27 10 77 24 35 87 11 11 5 16 55 [127] 82 70 30 44 49 33 61 69 46 10 42 44 64 73 93 87 94 72 [145] 77 78 6 37 82 71 63 75 65 97 94 90 64 42 91 30 21 64 [163] 24 74 21 11 95 33 35 85 14 38 87 46 73 82 21 38 77 84 [181] 8 95 48 61 75 32 70 51 29 49 17 94 36 41 30 46 69 36 [199] 31 2 x3<-as.integer64(sample(100:999,200)) x3 integer64 [1] 119 113 220 224 624 541 374 695 190 214 672 505 719 559 147 903 714 783 [19] 575 121 696 765 232 462 908 171 213 554 431 928 533 507 979 536 767 492 [37] 959 526 746 472 362 455 843 570 405 546 229 436 620 223 521 184 256 510 [55] 291 128 778 470 387 381 804 794 825 666 933 781 686 216 735 994 630 268 [73] 557 690 634 324 978 141 918 304 654 821 755 740 286 972 346 965 370 700 [91] 887 194 925 549 163 579 328 636 368 788 841 500 543 249 179 315 590 282 [109] 528 150 204 883 443 705 702 886 839 353 739 866 682 999 233 447 914 193 [127] 506 986 996 716 104 924 896 803 231 784 677 186 458 242 947 939 613 832 [145] 423 412 445 643 332 372 417 660 671 871 797 234 754 519 504 164 426 952 [163] 568 605 334 799 453 323 474 427 958 995 789 721 414 879 840 850 255 973 [181] 168 552 961 195 429 964 882 764 852 354 340 277 627 188 169 430 493 854 [199] 621 134 x4<-as.integer64(sample(rpois(5,20),200,replace=TRUE)) x4 integer64 [1] 24 17 17 18 18 24 18 24 17 24 24 24 18 24 17 17 17 24 24 18 24 24 17 24 24 [26] 24 17 18 17 24 24 17 24 17 18 17 18 24 24 18 24 17 17 24 24 17 24 18 18 17 [51] 24 24 17 24 17 24 24 17 17 17 17 17 24 17 24 24 17 17 24 17 24 24 17 17 17 [76] 24 17 24 24 17 24 17 24 17 18 17 17 17 24 24 17 17 18 18 17 18 24 17 17 17 [101] 17 24 24 17 24 24 17 24 17 24 17 24 24 24 17 17 17 18 17 17 24 24 17 17 17 [126] 24 24 24 17 24 17 24 17 18 24 17 18 17 24 18 18 24 17 17 17 18 17 17 24 24 [151] 17 24 17 17 17 18 24 24 17 24 24 18 17 17 17 18 24 17 17 18 18 17 24 18 18 [176] 24 17 24 24 24 17 18 24 17 17 18 24 24 18 24 17 24 18 24 17 17 17 17 17 24 x5<-as.integer64(sample(rnorm(10),200,replace=TRUE)) x5 integer64 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 [75] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 [112] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [149] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 [186] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 x6<-as.integer64(sample(rexp(10),200,replace=TRUE)) x6 integer64 [1] 1 0 1 1 0 0 0 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 [38] 1 0 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 1 1 0 0 0 1 0 [75] 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 1 0 1 0 1 0 0 0 1 0 1 0 1 1 1 0 0 0 0 0 0 0 [112] 1 0 0 0 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 1 0 1 [149] 0 1 1 0 1 1 0 1 0 1 0 1 0 0 1 1 1 0 0 0 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 [186] 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 x7<-as.integer64(sample(runif(10,2,5),200,replace=TRUE)) x7 integer64 [1] 3 2 3 4 3 3 3 3 2 2 3 2 3 4 3 3 3 3 4 2 2 3 2 2 3 2 4 2 4 4 4 3 2 4 4 2 2 [38] 3 4 2 3 4 4 4 4 4 4 4 2 2 3 3 3 3 4 4 3 2 2 2 4 3 3 3 3 3 2 3 2 2 3 3 3 3 [75] 2 4 4 4 4 3 3 3 4 2 2 3 3 4 3 2 3 3 4 4 4 3 3 2 4 2 4 4 2 4 4 3 2 3 4 4 4 [112] 4 3 3 3 3 3 4 4 3 2 3 2 2 2 3 3 4 3 4 3 3 4 2 4 4 4 3 2 3 3 3 4 3 3 3 3 3 [149] 2 3 2 3 3 3 3 3 4 3 2 3 3 4 3 2 4 2 3 3 2 4 4 2 2 4 4 4 3 3 3 4 2 3 3 2 3 [186] 4 2 4 3 3 2 2 2 3 3 3 2 3 3 2 x8<-as.integer64(sample(runif(10,0,5),200,replace=TRUE)) x8 integer64 [1] 3 1 2 0 3 1 2 0 4 3 0 0 1 2 1 2 2 0 2 0 1 4 0 0 0 3 1 0 0 3 4 4 0 1 1 0 1 [38] 4 2 1 0 0 0 4 0 2 0 3 1 0 1 2 2 2 4 2 1 0 1 1 1 1 0 1 1 2 1 3 1 1 0 0 0 4 [75] 0 0 3 1 2 2 2 2 0 0 0 4 1 0 1 3 1 1 0 0 2 4 1 1 0 2 0 1 4 4 0 2 3 1 0 0 1 [112] 3 0 1 2 4 0 3 0 4 0 0 0 0 4 0 1 2 1 4 1 4 2 2 1 4 1 1 2 1 3 1 0 3 1 2 2 4 [149] 3 0 2 4 0 3 4 4 1 1 2 2 3 0 1 0 2 2 1 2 0 0 2 3 1 2 4 0 0 0 4 1 0 2 4 1 1 [186] 3 0 1 0 2 4 0 1 3 4 4 1 1 0 2
[ { "code": null, "e": 1435, "s": 1062, "text": "The integer64 vector contains vector values that represents signed integers with values that range from negative 9,223,372,036,854,775,808 to positive 9,223,372,036,854,775,807. To create an integer64 vector, we can use as.integer64 function of bit64 package. The difference between integer64 vector and others is that a large number of values can be stored in the vector." }, { "code": null, "e": 1500, "s": 1435, "text": "library(bit64)\nx1<-as.integer64(sample(0:9,200,replace=TRUE))\nx1" }, { "code": null, "e": 1510, "s": 1500, "text": "integer64" }, { "code": null, "e": 1943, "s": 1510, "text": "[1] 4 3 1 3 8 8 4 5 6 2 8 7 5 0 2 4 8 4 6 7 3 9 5 2 1 1 5 7 6 0 3 9 9 8 1 0 0\n[38] 6 8 8 5 8 7 1 9 8 9 2 5 6 7 9 5 9 8 6 3 5 6 1 7 7 6 8 6 9 0 9 8 2 4 9 8 5\n[75] 5 8 7 7 4 2 7 9 5 7 9 6 0 7 4 1 0 0 4 7 0 3 7 3 4 0 8 0 4 3 5 2 7 2 5 6 8\n[112] 9 9 1 5 5 7 7 2 1 4 5 3 1 3 4 3 3 1 7 2 2 8 2 1 0 0 9 6 8 1 8 6 0 6 1 0 0\n[149] 6 2 3 8 3 4 9 2 7 5 3 1 8 4 2 6 9 2 2 2 1 9 2 6 7 6 3 3 1 8 0 1 3 1 4 6 0\n[186] 3 5 8 2 0 1 2 8 0 8 8 9 5 1 0" }, { "code": null, "e": 1997, "s": 1943, "text": "x2<-as.integer64(sample(1:100,200,replace=TRUE))\n> x2" }, { "code": null, "e": 2007, "s": 1997, "text": "integer64" }, { "code": null, "e": 2660, "s": 2007, "text": "[1] 41 98 21 92 52 50 49 93 31 46 33 71 21 59 87 7 16 10\n[19] 43 51 76 29 33 80 56 85 42 89 45 96 71 56 42 70 76 31\n[37] 55 76 100 75 87 95 27 53 71 51 56 90 9 3 41 9 8 32\n[55] 94 39 74 13 24 93 7 37 60 41 38 23 25 31 54 96 31 36\n[73] 72 30 21 98 16 25 7 28 98 80 56 20 66 55 76 14 91 87\n[91] 15 71 46 6 21 79 54 29 58 81 18 60 31 5 34 51 9 93\n[109] 58 95 72 26 99 25 53 27 10 77 24 35 87 11 11 5 16 55\n[127] 82 70 30 44 49 33 61 69 46 10 42 44 64 73 93 87 94 72\n[145] 77 78 6 37 82 71 63 75 65 97 94 90 64 42 91 30 21 64\n[163] 24 74 21 11 95 33 35 85 14 38 87 46 73 82 21 38 77 84\n[181] 8 95 48 61 75 32 70 51 29 49 17 94 36 41 30 46 69 36\n[199] 31 2" }, { "code": null, "e": 2701, "s": 2660, "text": "x3<-as.integer64(sample(100:999,200))\nx3" }, { "code": null, "e": 2711, "s": 2701, "text": "integer64" }, { "code": null, "e": 3577, "s": 2711, "text": "[1] 119 113 220 224 624 541 374 695 190 214 672 505 719 559 147 903 714 783\n[19] 575 121 696 765 232 462 908 171 213 554 431 928 533 507 979 536 767 492\n[37] 959 526 746 472 362 455 843 570 405 546 229 436 620 223 521 184 256 510\n[55] 291 128 778 470 387 381 804 794 825 666 933 781 686 216 735 994 630 268\n[73] 557 690 634 324 978 141 918 304 654 821 755 740 286 972 346 965 370 700\n[91] 887 194 925 549 163 579 328 636 368 788 841 500 543 249 179 315 590 282\n[109] 528 150 204 883 443 705 702 886 839 353 739 866 682 999 233 447 914 193\n[127] 506 986 996 716 104 924 896 803 231 784 677 186 458 242 947 939 613 832\n[145] 423 412 445 643 332 372 417 660 671 871 797 234 754 519 504 164 426 952\n[163] 568 605 334 799 453 323 474 427 958 995 789 721 414 879 840 850 255 973\n[181] 168 552 961 195 429 964 882 764 852 354 340 277 627 188 169 430 493 854\n[199] 621 134" }, { "code": null, "e": 3635, "s": 3577, "text": "x4<-as.integer64(sample(rpois(5,20),200,replace=TRUE))\nx4" }, { "code": null, "e": 3645, "s": 3635, "text": "integer64" }, { "code": null, "e": 4293, "s": 3645, "text": "[1] 24 17 17 18 18 24 18 24 17 24 24 24 18 24 17 17 17 24 24 18 24 24 17 24 24\n[26] 24 17 18 17 24 24 17 24 17 18 17 18 24 24 18 24 17 17 24 24 17 24 18 18 17\n[51] 24 24 17 24 17 24 24 17 17 17 17 17 24 17 24 24 17 17 24 17 24 24 17 17 17\n[76] 24 17 24 24 17 24 17 24 17 18 17 17 17 24 24 17 17 18 18 17 18 24 17 17 17\n[101] 17 24 24 17 24 24 17 24 17 24 17 24 24 24 17 17 17 18 17 17 24 24 17 17 17\n[126] 24 24 24 17 24 17 24 17 18 24 17 18 17 24 18 18 24 17 17 17 18 17 17 24 24\n[151] 17 24 17 17 17 18 24 24 17 24 24 18 17 17 17 18 24 17 17 18 18 17 24 18 18\n[176] 24 17 24 24 24 17 18 24 17 17 18 24 24 18 24 17 24 18 24 17 17 17 17 17 24" }, { "code": null, "e": 4349, "s": 4293, "text": "x5<-as.integer64(sample(rnorm(10),200,replace=TRUE))\nx5" }, { "code": null, "e": 4359, "s": 4349, "text": "integer64" }, { "code": null, "e": 4795, "s": 4359, "text": "[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0\n[75] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0\n[112] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n[149] 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0\n[186] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" }, { "code": null, "e": 4850, "s": 4795, "text": "x6<-as.integer64(sample(rexp(10),200,replace=TRUE))\nx6" }, { "code": null, "e": 4860, "s": 4850, "text": "integer64" }, { "code": null, "e": 5292, "s": 4860, "text": "[1] 1 0 1 1 0 0 0 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0\n[38] 1 0 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 1 0 1 1 0 0 0 1 0\n[75] 0 0 0 0 0 0 1 0 0 1 1 0 1 0 1 1 0 1 0 1 0 0 0 1 0 1 0 1 1 1 0 0 0 0 0 0 0\n[112] 1 0 0 0 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 0 1 0 1 0 1\n[149] 0 1 1 0 1 1 0 1 0 1 0 1 0 0 1 1 1 0 0 0 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0\n[186] 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0" }, { "code": null, "e": 5352, "s": 5292, "text": "x7<-as.integer64(sample(runif(10,2,5),200,replace=TRUE))\nx7" }, { "code": null, "e": 5362, "s": 5352, "text": "integer64" }, { "code": null, "e": 5794, "s": 5362, "text": "[1] 3 2 3 4 3 3 3 3 2 2 3 2 3 4 3 3 3 3 4 2 2 3 2 2 3 2 4 2 4 4 4 3 2 4 4 2 2\n[38] 3 4 2 3 4 4 4 4 4 4 4 2 2 3 3 3 3 4 4 3 2 2 2 4 3 3 3 3 3 2 3 2 2 3 3 3 3\n[75] 2 4 4 4 4 3 3 3 4 2 2 3 3 4 3 2 3 3 4 4 4 3 3 2 4 2 4 4 2 4 4 3 2 3 4 4 4\n[112] 4 3 3 3 3 3 4 4 3 2 3 2 2 2 3 3 4 3 4 3 3 4 2 4 4 4 3 2 3 3 3 4 3 3 3 3 3\n[149] 2 3 2 3 3 3 3 3 4 3 2 3 3 4 3 2 4 2 3 3 2 4 4 2 2 4 4 4 3 3 3 4 2 3 3 2 3\n[186] 4 2 4 3 3 2 2 2 3 3 3 2 3 3 2" }, { "code": null, "e": 5854, "s": 5794, "text": "x8<-as.integer64(sample(runif(10,0,5),200,replace=TRUE))\nx8" }, { "code": null, "e": 5864, "s": 5854, "text": "integer64" }, { "code": null, "e": 6296, "s": 5864, "text": "[1] 3 1 2 0 3 1 2 0 4 3 0 0 1 2 1 2 2 0 2 0 1 4 0 0 0 3 1 0 0 3 4 4 0 1 1 0 1\n[38] 4 2 1 0 0 0 4 0 2 0 3 1 0 1 2 2 2 4 2 1 0 1 1 1 1 0 1 1 2 1 3 1 1 0 0 0 4\n[75] 0 0 3 1 2 2 2 2 0 0 0 4 1 0 1 3 1 1 0 0 2 4 1 1 0 2 0 1 4 4 0 2 3 1 0 0 1\n[112] 3 0 1 2 4 0 3 0 4 0 0 0 0 4 0 1 2 1 4 1 4 2 2 1 4 1 1 2 1 3 1 0 3 1 2 2 4\n[149] 3 0 2 4 0 3 4 4 1 1 2 2 3 0 1 0 2 2 1 2 0 0 2 3 1 2 4 0 0 0 4 1 0 2 4 1 1\n[186] 3 0 1 0 2 4 0 1 3 4 4 1 1 0 2" } ]
Rust - Arithmetic Operators
Assume the values in variables a and b are 10 and 5 respectively. NOTE − The ++ and -- operators are not supported in Rust. fn main() { let num1 = 10 ; let num2 = 2; let mut res:i32; res = num1 + num2; println!("Sum: {} ",res); res = num1 - num2; println!("Difference: {} ",res) ; res = num1*num2 ; println!("Product: {} ",res) ; res = num1/num2 ; println!("Quotient: {} ",res); res = num1%num2 ; println!("Remainder: {} ",res); } Sum: 12 Difference: 8 Product: 20 Quotient: 5 Remainder: 0 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2153, "s": 2087, "text": "Assume the values in variables a and b are 10 and 5 respectively." }, { "code": null, "e": 2211, "s": 2153, "text": "NOTE − The ++ and -- operators are not supported in Rust." }, { "code": null, "e": 2562, "s": 2211, "text": "fn main() {\n let num1 = 10 ;\n let num2 = 2;\n let mut res:i32;\n\n res = num1 + num2;\n println!(\"Sum: {} \",res);\n\n res = num1 - num2;\n println!(\"Difference: {} \",res) ;\n\n res = num1*num2 ;\n println!(\"Product: {} \",res) ;\n\n res = num1/num2 ;\n println!(\"Quotient: {} \",res);\n\n res = num1%num2 ;\n println!(\"Remainder: {} \",res);\n}" }, { "code": null, "e": 2622, "s": 2562, "text": "Sum: 12\nDifference: 8\nProduct: 20\nQuotient: 5\nRemainder: 0\n" }, { "code": null, "e": 2657, "s": 2622, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2680, "s": 2657, "text": " Stone River ELearning" }, { "code": null, "e": 2712, "s": 2680, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 2723, "s": 2712, "text": " Ken Burke" }, { "code": null, "e": 2730, "s": 2723, "text": " Print" }, { "code": null, "e": 2741, "s": 2730, "text": " Add Notes" } ]
JSF - f:param
f:param tag provides the options to pass parameters to a component or pass request parameters. Pass parameter to a UI component <h:outputFormat value = "Hello {0}!."> <f:param value = "World" /> </h:outputFormat> Pass request parameter <h:commandButton id = "submit" value = "Show Message" action = "#{userData.showResult}"> <f:param name = "username" value = "JSF 2.0 User" /> </h:commandButton> id Identifier for a component binding Reference to the component that can be used in a backing bean name An optional name for this parameter component value The value stored in this component Let us create a test JSF application to test the above tag. package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; public String data = "1"; public String getData() { return data; } public void setData(String data) { this.data = data; } public String showResult() { FacesContext fc = FacesContext.getCurrentInstance(); Map<String,String> params = fc.getExternalContext().getRequestParameterMap(); data = params.get("username"); return "result"; } } <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF Tutorial!</title> </head> <body> <h2>f:param example</h2> <hr /> <h:form> <h:outputFormat value = "Hello {0}!."> <f:param value = "World" /> </h:outputFormat> <br/> <h:commandButton id = "submit" value = "Show Message" action = "#{userData.showResult}"> <f:param name = "username" value = "JSF 2.0 User" /> </h:commandButton> </h:form> </body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <head> <title>JSF Tutorial!</title> </head> <h:body> <h2>Result</h2> <hr /> #{userData.data} </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Press Show Message button and you'll see the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2047, "s": 1952, "text": "f:param tag provides the options to pass parameters to a component or pass request parameters." }, { "code": null, "e": 2080, "s": 2047, "text": "Pass parameter to a UI component" }, { "code": null, "e": 2174, "s": 2080, "text": "<h:outputFormat value = \"Hello {0}!.\"> \n <f:param value = \"World\" /> \n</h:outputFormat>" }, { "code": null, "e": 2197, "s": 2174, "text": "Pass request parameter" }, { "code": null, "e": 2369, "s": 2197, "text": "<h:commandButton id = \"submit\" \n value = \"Show Message\" action = \"#{userData.showResult}\"> \n <f:param name = \"username\" value = \"JSF 2.0 User\" /> \n</h:commandButton> " }, { "code": null, "e": 2372, "s": 2369, "text": "id" }, { "code": null, "e": 2399, "s": 2372, "text": "Identifier for a component" }, { "code": null, "e": 2407, "s": 2399, "text": "binding" }, { "code": null, "e": 2469, "s": 2407, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2474, "s": 2469, "text": "name" }, { "code": null, "e": 2520, "s": 2474, "text": "An optional name for this parameter component" }, { "code": null, "e": 2526, "s": 2520, "text": "value" }, { "code": null, "e": 2561, "s": 2526, "text": "The value stored in this component" }, { "code": null, "e": 2621, "s": 2561, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 3329, "s": 2621, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n public String data = \"1\";\n\n public String getData() {\n return data;\n }\n\n public void setData(String data) {\n this.data = data;\n }\n\n public String showResult() {\n FacesContext fc = FacesContext.getCurrentInstance();\n Map<String,String> params = \n fc.getExternalContext().getRequestParameterMap();\n data = params.get(\"username\"); \n return \"result\";\n }\n}" }, { "code": null, "e": 4020, "s": 3329, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n <h2>f:param example</h2>\n <hr />\n \n <h:form>\n <h:outputFormat value = \"Hello {0}!.\">\n <f:param value = \"World\" />\n </h:outputFormat>\n <br/>\n \n <h:commandButton id = \"submit\" \n value = \"Show Message\" action = \"#{userData.showResult}\">\n <f:param name = \"username\" value = \"JSF 2.0 User\" />\n </h:commandButton>\n </h:form>\n \n </body>\n</html>" }, { "code": null, "e": 4531, "s": 4020, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <h:body>\n <h2>Result</h2>\n <hr />\n #{userData.data}\n </h:body>\n</html> " }, { "code": null, "e": 4747, "s": 4531, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 4810, "s": 4747, "text": "Press Show Message button and you'll see the following result." }, { "code": null, "e": 4845, "s": 4810, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4860, "s": 4845, "text": " Chaand Sheikh" }, { "code": null, "e": 4867, "s": 4860, "text": " Print" }, { "code": null, "e": 4878, "s": 4867, "text": " Add Notes" } ]
mysqlbinlog - Unix, Linux Command
The server's binary log consists of files containing \(lqevents\(rq that describe modifications to database contents. The server writes these files in binary format. To display their contents in text format, use the mysqlbinlog utility. You can also use mysqlbinlog to display the contents of relay log files written by a slave server in a replication setup because relay logs have the same format as binary logs. The binary log and relay log are discussed further in Section 5.2.4, \(lqThe Binary Log\(rq, and Section 16.2.2, \(lqReplication Relay and Status Files\(rq. Invoke mysqlbinlog like this: shell> mysqlbinlog [options] log_file ... For example, to display the contents of the binary log file named binlog.000003, use this command: shell> mysqlbinlog binlog.0000003 The output includes events contained in binlog.000003. For statement-based logging, event information includes the SQL statement, the ID of the server on which it was executed, the timestamp when the statement was executed, how much time it took, and so forth. For row-based logging, the event indicates a row change rather than an SQL statement. See Section 16.1.2, \(lqReplication Formats\(rq, for information about logging modes. Events are preceded by header comments that provide additional information. For example: # at 141 #100309 9:28:36 server id 123 end_log_pos 245 Query thread_id=3350 exec_time=11 error_code=0 In the first line, the number following at indicates the starting position of the event in the binary log file. The second line starts with a date and time indicating when the statement started on the server where the event originated. For replication, this timestamp is propagated to slave servers. server id is the server_id value of the server where the event originated. end_log_pos indicates where the next event starts (that is, it is the end position of the current event + 1). thread_id indicates which thread executed the event. exec_time is the time spent executing the event, on a master server. On a slave, it is the difference of the end execution time on the slave minus the beginning execution time on the master. The difference serves as an indicator of how much replication lags behind the master. error_code indicates the result from executing the event. Zero means that no error occurred. The output from mysqlbinlog can be re-executed (for example, by using it as input to mysql) to redo the statements in the log. This is useful for recovery operations after a server crash. For other usage examples, see the discussion later in this section and in Section 6.5, \(lqPoint-in-Time (Incremental) Recovery Using the Binary Log\(rq. Normally, you use mysqlbinlog to read binary log files directly and apply them to the local MySQL server. It is also possible to read binary logs from a remote server by using the --read-from-remote-server option. To read remote binary logs, the connection parameter options can be given to indicate how to connect to the server. These options are --host, --password, --port, --protocol, --socket, and --user; they are ignored except when you also use the --read-from-remote-server option. mysqlbinlog supports the following options, which can be specified on the command line or in the [mysqlbinlog] and [client] option file groups. mysqlbinlog also supports the options for processing option files described at Section 4.2.3.3.1, \(lqCommand-Line Options that Affect Option-File Handling\(rq. o Display a help message and exit. o This option determines when events should be displayed encoded as base-64 strings using BINLOG statements. The option has these permissible values (not case sensitive): Note Automatic BINLOG display is the only safe behavior if you intend to use the output of mysqlbinlog to re-execute binary log file contents. The other option values are intended only for debugging or testing purposes because they may produce output that does not include all events in executable form. For examples that show the effect of --base64-output and --verbose on row event output, see the section called \(lqMYSQLBINLOG ROW EVENT DISPLAY\(rq. On a computer having multiple network interfaces, this option can be used to select which interface is employed when connecting to the MySQL server. This option is supported only in the version of mysqlbinlog that is supplied with MySQL Cluster, beginning with MySQL Cluster NDB 6.3.4. It is not available in standard MySQL 5.1 releases. The directory where character sets are installed. See Section 9.5, \(lqCharacter Set Configuration\(rq. This option causes mysqlbinlog to output entries from the binary log (local log only) that occur while db_name is been selected as the default database by USE. The --database option for mysqlbinlog is similar to the --binlog-do-db option for mysqld, but can be used to specify only one database. If --database is given multiple times, only the last instance is used. The effects of this option depend on whether the statement-based or row-based logging format is in use, in the same way that the effects of --binlog-do-db depend on whether statement-based or row-based logging is in use. o INSERT INTO test.t1 (i) VALUES(100); INSERT INTO db2.t2 (j) VALUES(200); USE test; INSERT INTO test.t1 (i) VALUES(101); INSERT INTO t1 (i) VALUES(102); INSERT INTO db2.t2 (j) VALUES(201); USE db2; INSERT INTO test.t1 (i) VALUES(103); INSERT INTO db2.t2 (j) VALUES(202); INSERT INTO t2 (j) VALUES(203); mysqlbinlog --database=test does not output the first two INSERT statements because there is no default database. It outputs the three INSERT statements following USE test, but not the three INSERT statements following USE db2. mysqlbinlog --database=db2 does not output the first two INSERT statements because there is no default database. It does not output the three INSERT statements following USE test, but does output the three INSERT statements following USE db2. Write a debugging log. A typical debug_options string is 'd:t:o,file_name'. The default is 'd:t:o,/tmp/mysqlbinlog.trace'. Print some debugging information when the program exits. This option was added in MySQL 5.1.21. Print debugging information and memory and CPU usage statistics when the program exits. This option was added in MySQL 5.1.21. Disable binary logging. This is useful for avoiding an endless loop if you use the --to-last-log option and are sending the output to the same MySQL server. This option also is useful when restoring after a crash to avoid duplication of the statements you have logged. This option requires that you have the SUPER privilege. It causes mysqlbinlog to include a SET sql_log_bin = 0 statement in its output to disable binary logging of the remaining output. The SET statement is ineffective unless you have the SUPER privilege. With this option, if mysqlbinlog reads a binary log event that it does not recognize, it prints a warning, ignores the event, and continues. Without this option, mysqlbinlog stops if it reads such an event. Display a hex dump of the log in comments, as described in the section called \(lqMYSQLBINLOG HEX DUMP FORMAT\(rq. The hex output can be helpful for replication debugging. This option was added in MySQL 5.1.2. Get the binary log from the MySQL server on the given host. Prepare local temporary files for LOAD DATA INFILE in the specified directory. Important These temporary files are not automatically removed by mysqlbinlog or any other MySQL program. Skip the first N entries in the log. The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, mysqlbinlog prompts for one. Specifying a password on the command line should be considered insecure. See Section 5.3.2.2, \(lqEnd-User Guidelines for Password Security\(rq. You can use an option file to avoid giving the password on the command line. The TCP/IP port number to use for connecting to a remote server. Deprecated. Use --start-position instead. --position is removed in MySQL 5.5. The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the permissible values, see Section 4.2.2, \(lqConnecting to the MySQL Server\(rq. Read the binary log from a MySQL server rather than reading a local log file. Any connection parameter options are ignored unless this option is given as well. These options are --host, --password, --port, --protocol, --socket, and --user. This option requires that the remote server be running. It works only for binary log files on the remote server, not relay log files. Direct output to the given file. Display only those events created by the server having the given server ID. This option is available as of MySQL 5.1.4. Use only the first N bits of the server_id to identify the server. If the binary log was written by a mysqld with server-id-bits set to less than 32 and user data stored in the most significant bit, running mysqlbinlog with --server-id-bits set to 32 enables this data to be seen. This option was added in MySQL Cluster NDB 7.0.17 and MySQL Cluster NDB 7.1.6, and is supported only by the versions of mysqlbinlog supplied with these and later releases of MySQL Cluster. Add a SET NAMES charset_name statement to the output to specify the character set to be used for processing log files. This option was added in MySQL 5.1.12. Display only the statements contained in the log, without any extra information or row-based events. This is for testing only, and should not be used in production systems. For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use. Start reading the binary log at the first event having a timestamp equal to or later than the datetime argument. The datetime value is relative to the local time zone on the machine where you run mysqlbinlog. The value should be in a format accepted for the DATETIME or TIMESTAMP data types. For example: shell> mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003 This option is useful for point-in-time recovery. See Section 6.3, \(lqExample Backup and Recovery Strategy\(rq. Start reading the binary log at the first event having a position equal to or greater than N. This option applies to the first log file named on the command line. This option is useful for point-in-time recovery. See Section 6.3, \(lqExample Backup and Recovery Strategy\(rq. Stop reading the binary log at the first event having a timestamp equal to or later than the datetime argument. This option is useful for point-in-time recovery. See the description of the --start-datetime option for information about the datetime value. This option is useful for point-in-time recovery. See Section 6.3, \(lqExample Backup and Recovery Strategy\(rq. Stop reading the binary log at the first event having a position equal to or greater than N. This option applies to the last log file named on the command line. This option is useful for point-in-time recovery. See Section 6.3, \(lqExample Backup and Recovery Strategy\(rq. Do not stop at the end of the requested binary log from a MySQL server, but rather continue printing until the end of the last binary log. If you send the output to the same MySQL server, this may lead to an endless loop. This option requires --read-from-remote-server. The MySQL user name to use when connecting to a remote server. Reconstruct row events and display them as commented SQL statements. If this option is given twice, the output includes comments to indicate column data types and some metadata. This option was added in MySQL 5.1.28. For examples that show the effect of --base64-output and --verbose on row event output, see the section called \(lqMYSQLBINLOG ROW EVENT DISPLAY\(rq. Display version information and exit. Specify the number of open file descriptors to reserve. You can pipe the output of mysqlbinlog into the mysql client to execute the events contained in the binary log. This technique is used to recover from a crash when you have an old backup (see Section 6.5, \(lqPoint-in-Time (Incremental) Recovery Using the Binary Log\(rq). For example: shell> mysqlbinlog binlog.000001 | mysql -u root -p Or: shell> mysqlbinlog binlog.[0-9]* | mysql -u root -p You can also redirect the output of mysqlbinlog to a text file instead, if you need to modify the statement log first (for example, to remove statements that you do not want to execute for some reason). After editing the file, execute the statements that it contains by using it as input to the mysql program: shell> mysqlbinlog binlog.000001 > tmpfile shell> ... edit tmpfile ... shell> mysql -u root -p < tmpfile When mysqlbinlog is invoked with the --start-position option, it displays only those events with an offset in the binary log greater than or equal to a given position (the given position must match the start of one event). It also has options to stop and start when it sees an event with a given date and time. This enables you to perform point-in-time recovery using the --stop-datetime option (to be able to say, for example, \(lqroll forward my databases to how they were today at 10:30 a.m.\(rq). If you have more than one binary log to execute on the MySQL server, the safe method is to process them all using a single connection to the server. Here is an example that demonstrates what may be unsafe: shell> mysqlbinlog binlog.000001 | mysql -u root -p # DANGER!! shell> mysqlbinlog binlog.000002 | mysql -u root -p # DANGER!! Processing binary logs this way using multiple connections to the server causes problems if the first log file contains a CREATE TEMPORARY TABLE statement and the second log contains a statement that uses the temporary table. When the first mysql process terminates, the server drops the temporary table. When the second mysql process attempts to use the table, the server reports \(lqunknown table.\(rq To avoid problems like this, use a single mysql process to execute the contents of all binary logs that you want to process. Here is one way to do so: shell> mysqlbinlog binlog.000001 binlog.000002 | mysql -u root -p Another approach is to write all the logs to a single file and then process the file: shell> mysqlbinlog binlog.000001 > /tmp/statements.sql shell> mysqlbinlog binlog.000002 >> /tmp/statements.sql shell> mysql -u root -p -e "source /tmp/statements.sql" mysqlbinlog can produce output that reproduces a LOAD DATA INFILE operation without the original data file. mysqlbinlog copies the data to a temporary file and writes a LOAD DATA LOCAL INFILE statement that refers to the file. The default location of the directory where these files are written is system-specific. To specify a directory explicitly, use the --local-load option. Because mysqlbinlog converts LOAD DATA INFILE statements to LOAD DATA LOCAL INFILE statements (that is, it adds LOCAL), both the client and the server that you use to process the statements must be configured with the LOCAL capability enabled. See Section 5.3.5, \(lqSecurity Issues with LOAD DATA LOCAL\(rq. The temporary files created for LOAD DATA LOCAL statements are not automatically deleted because they are needed until you actually execute those statements. You should delete the temporary files yourself after you no longer need the statement log. The files can be found in the temporary file directory and have names like original_file_name-#-#. The --hexdump option causes mysqlbinlog to produce a hex dump of the binary log contents: shell> mysqlbinlog --hexdump master-bin.000001 The hex output consists of comment lines beginning with #, so the output might look like this for the preceding command: /*!40019 SET @@session.max_insert_delayed_threads=0*/; /*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/; # at 4 #051024 17:24:13 server id 1 end_log_pos 98 # Position Timestamp Type Master ID Size Master Pos Flags # 00000004 9d fc 5c 43 0f 01 00 00 00 5e 00 00 00 62 00 00 00 00 00 # 00000017 04 00 35 2e 30 2e 31 35 2d 64 65 62 75 67 2d 6c |..5.0.15.debug.l| # 00000027 6f 67 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |og..............| # 00000037 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| # 00000047 00 00 00 00 9d fc 5c 43 13 38 0d 00 08 00 12 00 |.......C.8......| # 00000057 04 04 04 04 12 00 00 4b 00 04 1a |.......K...| # Start: binlog v 4, server v 5.0.15-debug-log created 051024 17:24:13 # at startup ROLLBACK; Hex dump output currently contains the elements in the following list. This format is subject to change. (For more information about binary log format, see \m[blue] http://forge.mysql.com/wiki/MySQL_Internals_Binary_Log\m[].) o o o o o o o The following examples illustrate how mysqlbinlog displays row events that specify data modifications. These correspond to events with the WRITE_ROWS_EVENT, UPDATE_ROWS_EVENT, and DELETE_ROWS_EVENT type codes. The --base64-output=DECODE-ROWS and --verbose options may be used to affect row event output. These options are available as of MySQL 5.1.28. Suppose that the server is using row-based binary logging and that you execute the following sequence of statements: CREATE TABLE t ( id INT NOT NULL, name VARCHAR(20) NOT NULL, date DATE NULL ) ENGINE = InnoDB; START TRANSACTION; INSERT INTO t VALUES(1, 'apple', NULL); UPDATE t SET name = 'pear', date = '2009-01-01' WHERE id = 1; DELETE FROM t WHERE id = 1; COMMIT; By default, mysqlbinlog displays row events encoded as base-64 strings using BINLOG statements. Omitting extraneous lines, the output for the row events produced by the preceding statement sequence looks like this: shell> mysqlbinlog log_file ... # at 218 #080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ== '/*!*/; ... # at 302 #080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP '/*!*/; ... # at 400 #080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP '/*!*/; To see the row events as comments in the form of \(lqpseudo-SQL\(rq statements, run mysqlbinlog with the --verbose or -v option. The output will contain lines beginning with ###: shell> mysqlbinlog -v log_file ... # at 218 #080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ== '/*!*/; ### INSERT INTO test.t ### SET ### @1=1 ### @2='apple' ### @3=NULL ... # at 302 #080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP '/*!*/; ### UPDATE test.t ### WHERE ### @1=1 ### @2='apple' ### @3=NULL ### SET ### @1=1 ### @2='pear' ### @3='2009:01:01' ... # at 400 #080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP '/*!*/; ### DELETE FROM test.t ### WHERE ### @1=1 ### @2='pear' ### @3='2009:01:01' Specify --verbose or -v twice to also display data types and some metadata for each column. The output will contain an additional comment following each column change: shell> mysqlbinlog -vv log_file ... # at 218 #080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ== '/*!*/; ### INSERT INTO test.t ### SET ### @1=1 /* INT meta=0 nullable=0 is_null=0 */ ### @2='apple' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */ ### @3=NULL /* VARSTRING(20) meta=0 nullable=1 is_null=1 */ ... # at 302 #080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP '/*!*/; ### UPDATE test.t ### WHERE ### @1=1 /* INT meta=0 nullable=0 is_null=0 */ ### @2='apple' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */ ### @3=NULL /* VARSTRING(20) meta=0 nullable=1 is_null=1 */ ### SET ### @1=1 /* INT meta=0 nullable=0 is_null=0 */ ### @2='pear' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */ ### @3='2009:01:01' /* DATE meta=0 nullable=1 is_null=0 */ ... # at 400 #080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F BINLOG ' fAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ= fAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP '/*!*/; ### DELETE FROM test.t ### WHERE ### @1=1 /* INT meta=0 nullable=0 is_null=0 */ ### @2='pear' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */ ### @3='2009:01:01' /* DATE meta=0 nullable=1 is_null=0 */ You can tell mysqlbinlog to suppress the BINLOG statements for row events by using the --base64-output=DECODE-ROWS option. This is similar to --base64-output=NEVER but does not exit with an error if a row event is found. The combination of --base64-output=DECODE-ROWS and --verbose provides a convenient way to see row events only as SQL statements: shell> mysqlbinlog -v --base64-output=DECODE-ROWS log_file ... # at 218 #080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F ### INSERT INTO test.t ### SET ### @1=1 ### @2='apple' ### @3=NULL ... # at 302 #080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F ### UPDATE test.t ### WHERE ### @1=1 ### @2='apple' ### @3=NULL ### SET ### @1=1 ### @2='pear' ### @3='2009:01:01' ... # at 400 #080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F ### DELETE FROM test.t ### WHERE ### @1=1 ### @2='pear' ### @3='2009:01:01' Note You should not suppress BINLOG statements if you intend to re-execute mysqlbinlog output. The SQL statements produced by --verbose for row events are much more readable than the corresponding BINLOG statements. However, they do not correspond exactly to the original SQL statements that generated the events. The following limitations apply: o o CHAR(4) CHARACTER SET latin1 CHAR(2) CHARACTER SET ucs2 Proper interpretation of row events requires the information from the format description event at the beginning of the binary log. Because mysqlbinlog does not know in advance whether the rest of the log contains row events, by default it displays the format description event using a BINLOG statement in the initial part of the output. If the binary log is known not to contain any events requiring a BINLOG statement (that is, no row events), the --base64-output=NEVER option can be used to prevent this header from being written. Copyright © 1997, 2011, Oracle and/or its affiliates. All rights reserved. This documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or see http://www.gnu.org/licenses/. 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": 11150, "s": 10577, "text": "\nThe server's binary log consists of files containing\n\\(lqevents\\(rq\nthat describe modifications to database contents. The server writes these files in binary format. To display their contents in text format, use the\nmysqlbinlog\nutility. You can also use\nmysqlbinlog\nto display the contents of relay log files written by a slave server in a replication setup because relay logs have the same format as binary logs. The binary log and relay log are discussed further in\nSection 5.2.4, \\(lqThe Binary Log\\(rq, and\nSection 16.2.2, \\(lqReplication Relay and Status Files\\(rq.\n" }, { "code": null, "e": 11182, "s": 11150, "text": "\nInvoke\nmysqlbinlog\nlike this:\n" }, { "code": null, "e": 11229, "s": 11186, "text": "shell> mysqlbinlog [options] log_file ...\n" }, { "code": null, "e": 11330, "s": 11229, "text": "\nFor example, to display the contents of the binary log file named\nbinlog.000003, use this command:\n" }, { "code": null, "e": 11369, "s": 11334, "text": "shell> mysqlbinlog binlog.0000003\n" }, { "code": null, "e": 11804, "s": 11369, "text": "\nThe output includes events contained in\nbinlog.000003. For statement-based logging, event information includes the SQL statement, the ID of the server on which it was executed, the timestamp when the statement was executed, how much time it took, and so forth. For row-based logging, the event indicates a row change rather than an SQL statement. See\nSection 16.1.2, \\(lqReplication Formats\\(rq, for information about logging modes.\n" }, { "code": null, "e": 11895, "s": 11804, "text": "\nEvents are preceded by header comments that provide additional information. For example:\n" }, { "code": null, "e": 12008, "s": 11899, "text": "# at 141\n#100309 9:28:36 server id 123 end_log_pos 245\n Query thread_id=3350 exec_time=11 error_code=0\n" }, { "code": null, "e": 12122, "s": 12008, "text": "\nIn the first line, the number following\nat\nindicates the starting position of the event in the binary log file.\n" }, { "code": null, "e": 12920, "s": 12122, "text": "\nThe second line starts with a date and time indicating when the statement started on the server where the event originated. For replication, this timestamp is propagated to slave servers.\nserver id\nis the\nserver_id\nvalue of the server where the event originated.\nend_log_pos\nindicates where the next event starts (that is, it is the end position of the current event + 1).\nthread_id\nindicates which thread executed the event.\nexec_time\nis the time spent executing the event, on a master server. On a slave, it is the difference of the end execution time on the slave minus the beginning execution time on the master. The difference serves as an indicator of how much replication lags behind the master.\nerror_code\nindicates the result from executing the event. Zero means that no error occurred.\n" }, { "code": null, "e": 13264, "s": 12920, "text": "\nThe output from\nmysqlbinlog\ncan be re-executed (for example, by using it as input to\nmysql) to redo the statements in the log. This is useful for recovery operations after a server crash. For other usage examples, see the discussion later in this section and in\nSection 6.5, \\(lqPoint-in-Time (Incremental) Recovery Using the Binary Log\\(rq.\n" }, { "code": null, "e": 13756, "s": 13264, "text": "\nNormally, you use\nmysqlbinlog\nto read binary log files directly and apply them to the local MySQL server. It is also possible to read binary logs from a remote server by using the\n--read-from-remote-server\noption. To read remote binary logs, the connection parameter options can be given to indicate how to connect to the server. These options are\n--host,\n--password,\n--port,\n--protocol,\n--socket, and\n--user; they are ignored except when you also use the\n--read-from-remote-server\noption.\n" }, { "code": null, "e": 14063, "s": 13756, "text": "\nmysqlbinlog\nsupports the following options, which can be specified on the command line or in the\n[mysqlbinlog]\nand\n[client]\noption file groups.\nmysqlbinlog\nalso supports the options for processing option files described at\nSection 4.2.3.3.1, \\(lqCommand-Line Options that Affect Option-File Handling\\(rq.\n" }, { "code": null, "e": 14069, "s": 14063, "text": "\n\no\n\n" }, { "code": null, "e": 14106, "s": 14071, "text": "\nDisplay a help message and exit.\n" }, { "code": null, "e": 14112, "s": 14106, "text": "\n\no\n\n" }, { "code": null, "e": 14285, "s": 14114, "text": "\nThis option determines when events should be displayed encoded as base-64 strings using\nBINLOG\nstatements. The option has these permissible values (not case sensitive):\n" }, { "code": null, "e": 14598, "s": 14289, "text": "\n\n\nNote\n\nAutomatic\nBINLOG\ndisplay is the only safe behavior if you intend to use the output of\nmysqlbinlog\nto re-execute binary log file contents. The other option values are intended only for debugging or testing purposes because they may produce output that does not include all events in executable form.\n" }, { "code": null, "e": 14764, "s": 14612, "text": "\nFor examples that show the effect of\n--base64-output\nand\n--verbose\non row event output, see\nthe section called \\(lqMYSQLBINLOG ROW EVENT DISPLAY\\(rq.\n" }, { "code": null, "e": 14919, "s": 14768, "text": "\nOn a computer having multiple network interfaces, this option can be used to select which interface is employed when connecting to the MySQL server.\n" }, { "code": null, "e": 15110, "s": 14919, "text": "\nThis option is supported only in the version of\nmysqlbinlog\nthat is supplied with MySQL Cluster, beginning with MySQL Cluster NDB 6.3.4. It is not available in standard MySQL 5.1 releases.\n" }, { "code": null, "e": 15220, "s": 15114, "text": "\nThe directory where character sets are installed. See\nSection 9.5, \\(lqCharacter Set Configuration\\(rq.\n" }, { "code": null, "e": 15386, "s": 15224, "text": "\nThis option causes\nmysqlbinlog\nto output entries from the binary log (local log only) that occur while\ndb_name\nis been selected as the default database by\nUSE.\n" }, { "code": null, "e": 15595, "s": 15386, "text": "\nThe\n--database\noption for\nmysqlbinlog\nis similar to the\n--binlog-do-db\noption for\nmysqld, but can be used to specify only one database. If\n--database\nis given multiple times, only the last instance is used.\n" }, { "code": null, "e": 15818, "s": 15595, "text": "\nThe effects of this option depend on whether the statement-based or row-based logging format is in use, in the same way that the effects of\n--binlog-do-db\ndepend on whether statement-based or row-based logging is in use.\n" }, { "code": null, "e": 15824, "s": 15818, "text": "\n\no\n\n" }, { "code": null, "e": 16154, "s": 15838, "text": "INSERT INTO test.t1 (i) VALUES(100);\nINSERT INTO db2.t2 (j) VALUES(200);\nUSE test;\nINSERT INTO test.t1 (i) VALUES(101);\nINSERT INTO t1 (i) VALUES(102);\nINSERT INTO db2.t2 (j) VALUES(201);\nUSE db2;\nINSERT INTO test.t1 (i) VALUES(103);\nINSERT INTO db2.t2 (j) VALUES(202);\nINSERT INTO t2 (j) VALUES(203);\n" }, { "code": null, "e": 16384, "s": 16154, "text": "\nmysqlbinlog --database=test\ndoes not output the first two\nINSERT\nstatements because there is no default database. It outputs the three\nINSERT\nstatements following\nUSE test, but not the three\nINSERT\nstatements following\nUSE db2.\n" }, { "code": null, "e": 16629, "s": 16384, "text": "\nmysqlbinlog --database=db2\ndoes not output the first two\nINSERT\nstatements because there is no default database. It does not output the three\nINSERT\nstatements following\nUSE test, but does output the three\nINSERT\nstatements following\nUSE db2.\n" }, { "code": null, "e": 16763, "s": 16638, "text": "\nWrite a debugging log. A typical\ndebug_options\nstring is\n'd:t:o,file_name'. The default is\n'd:t:o,/tmp/mysqlbinlog.trace'.\n" }, { "code": null, "e": 16865, "s": 16767, "text": "\nPrint some debugging information when the program exits. This option was added in MySQL 5.1.21.\n" }, { "code": null, "e": 16998, "s": 16869, "text": "\nPrint debugging information and memory and CPU usage statistics when the program exits. This option was added in MySQL 5.1.21.\n" }, { "code": null, "e": 17273, "s": 17002, "text": "\nDisable binary logging. This is useful for avoiding an endless loop if you use the\n--to-last-log\noption and are sending the output to the same MySQL server. This option also is useful when restoring after a crash to avoid duplication of the statements you have logged.\n" }, { "code": null, "e": 17531, "s": 17273, "text": "\nThis option requires that you have the\nSUPER\nprivilege. It causes\nmysqlbinlog\nto include a\nSET sql_log_bin = 0\nstatement in its output to disable binary logging of the remaining output. The\nSET\nstatement is ineffective unless you have the\nSUPER\nprivilege.\n" }, { "code": null, "e": 17744, "s": 17535, "text": "\nWith this option, if\nmysqlbinlog\nreads a binary log event that it does not recognize, it prints a warning, ignores the event, and continues. Without this option,\nmysqlbinlog\nstops if it reads such an event.\n" }, { "code": null, "e": 17960, "s": 17748, "text": "\nDisplay a hex dump of the log in comments, as described in\nthe section called \\(lqMYSQLBINLOG HEX DUMP FORMAT\\(rq. The hex output can be helpful for replication debugging. This option was added in MySQL 5.1.2.\n" }, { "code": null, "e": 18026, "s": 17964, "text": "\nGet the binary log from the MySQL server on the given host.\n" }, { "code": null, "e": 18112, "s": 18030, "text": "\nPrepare local temporary files for\nLOAD DATA INFILE\nin the specified directory.\n\n" }, { "code": null, "e": 18222, "s": 18112, "text": "\n\n\nImportant\n\nThese temporary files are not automatically removed by\nmysqlbinlog\nor any other MySQL program.\n" }, { "code": null, "e": 18267, "s": 18228, "text": "\nSkip the first\nN\nentries in the log.\n" }, { "code": null, "e": 18543, "s": 18271, "text": "\nThe password to use when connecting to the server. If you use the short option form (-p), you\ncannot\nhave a space between the option and the password. If you omit the\npassword\nvalue following the\n--password\nor\n-p\noption on the command line,\nmysqlbinlog\nprompts for one.\n" }, { "code": null, "e": 18767, "s": 18543, "text": "\nSpecifying a password on the command line should be considered insecure. See\nSection 5.3.2.2, \\(lqEnd-User Guidelines for Password Security\\(rq. You can use an option file to avoid giving the password on the command line.\n" }, { "code": null, "e": 18838, "s": 18771, "text": "\nThe TCP/IP port number to use for connecting to a remote server.\n" }, { "code": null, "e": 18922, "s": 18842, "text": "\nDeprecated. Use\n--start-position\ninstead.\n--position\nis removed in MySQL 5.5.\n" }, { "code": null, "e": 19209, "s": 18926, "text": "\nThe connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the permissible values, see\nSection 4.2.2, \\(lqConnecting to the MySQL Server\\(rq.\n" }, { "code": null, "e": 19455, "s": 19213, "text": "\nRead the binary log from a MySQL server rather than reading a local log file. Any connection parameter options are ignored unless this option is given as well. These options are\n--host,\n--password,\n--port,\n--protocol,\n--socket, and\n--user.\n" }, { "code": null, "e": 19591, "s": 19455, "text": "\nThis option requires that the remote server be running. It works only for binary log files on the remote server, not relay log files.\n" }, { "code": null, "e": 19630, "s": 19595, "text": "\nDirect output to the given file.\n" }, { "code": null, "e": 19756, "s": 19634, "text": "\nDisplay only those events created by the server having the given server ID. This option is available as of MySQL 5.1.4.\n" }, { "code": null, "e": 20043, "s": 19760, "text": "\nUse only the first\nN\nbits of the\nserver_id\nto identify the server. If the binary log was written by a\nmysqld\nwith server-id-bits set to less than 32 and user data stored in the most significant bit, running\nmysqlbinlog\nwith\n--server-id-bits\nset to 32 enables this data to be seen.\n" }, { "code": null, "e": 20234, "s": 20043, "text": "\nThis option was added in MySQL Cluster NDB 7.0.17 and MySQL Cluster NDB 7.1.6, and is supported only by the versions of\nmysqlbinlog\nsupplied with these and later releases of MySQL Cluster.\n" }, { "code": null, "e": 20398, "s": 20238, "text": "\nAdd a\nSET NAMES charset_name\nstatement to the output to specify the character set to be used for processing log files. This option was added in MySQL 5.1.12.\n" }, { "code": null, "e": 20577, "s": 20402, "text": "\nDisplay only the statements contained in the log, without any extra information or row-based events. This is for testing only, and should not be used in production systems.\n" }, { "code": null, "e": 20693, "s": 20581, "text": "\nFor connections to\nlocalhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.\n" }, { "code": null, "e": 21004, "s": 20697, "text": "\nStart reading the binary log at the first event having a timestamp equal to or later than the\ndatetime\nargument. The\ndatetime\nvalue is relative to the local time zone on the machine where you run\nmysqlbinlog. The value should be in a format accepted for the\nDATETIME\nor\nTIMESTAMP\ndata types. For example:\n" }, { "code": null, "e": 21081, "s": 21008, "text": "shell> mysqlbinlog --start-datetime=\"2005-12-25 11:25:56\" binlog.000003\n" }, { "code": null, "e": 21196, "s": 21081, "text": "\nThis option is useful for point-in-time recovery. See\nSection 6.3, \\(lqExample Backup and Recovery Strategy\\(rq.\n" }, { "code": null, "e": 21365, "s": 21200, "text": "\nStart reading the binary log at the first event having a position equal to or greater than\nN. This option applies to the first log file named on the command line.\n" }, { "code": null, "e": 21480, "s": 21365, "text": "\nThis option is useful for point-in-time recovery. See\nSection 6.3, \\(lqExample Backup and Recovery Strategy\\(rq.\n" }, { "code": null, "e": 21741, "s": 21484, "text": "\nStop reading the binary log at the first event having a timestamp equal to or later than the\ndatetime\nargument. This option is useful for point-in-time recovery. See the description of the\n--start-datetime\noption for information about the\ndatetime\nvalue.\n" }, { "code": null, "e": 21856, "s": 21741, "text": "\nThis option is useful for point-in-time recovery. See\nSection 6.3, \\(lqExample Backup and Recovery Strategy\\(rq.\n" }, { "code": null, "e": 22023, "s": 21860, "text": "\nStop reading the binary log at the first event having a position equal to or greater than\nN. This option applies to the last log file named on the command line.\n" }, { "code": null, "e": 22138, "s": 22023, "text": "\nThis option is useful for point-in-time recovery. See\nSection 6.3, \\(lqExample Backup and Recovery Strategy\\(rq.\n" }, { "code": null, "e": 22414, "s": 22142, "text": "\nDo not stop at the end of the requested binary log from a MySQL server, but rather continue printing until the end of the last binary log. If you send the output to the same MySQL server, this may lead to an endless loop. This option requires\n--read-from-remote-server.\n" }, { "code": null, "e": 22483, "s": 22418, "text": "\nThe MySQL user name to use when connecting to a remote server.\n" }, { "code": null, "e": 22706, "s": 22487, "text": "\nReconstruct row events and display them as commented SQL statements. If this option is given twice, the output includes comments to indicate column data types and some metadata. This option was added in MySQL 5.1.28.\n" }, { "code": null, "e": 22858, "s": 22706, "text": "\nFor examples that show the effect of\n--base64-output\nand\n--verbose\non row event output, see\nthe section called \\(lqMYSQLBINLOG ROW EVENT DISPLAY\\(rq.\n" }, { "code": null, "e": 22902, "s": 22862, "text": "\nDisplay version information and exit.\n" }, { "code": null, "e": 22964, "s": 22906, "text": "\nSpecify the number of open file descriptors to reserve.\n" }, { "code": null, "e": 23252, "s": 22964, "text": "\nYou can pipe the output of\nmysqlbinlog\ninto the\nmysql\nclient to execute the events contained in the binary log. This technique is used to recover from a crash when you have an old backup (see\nSection 6.5, \\(lqPoint-in-Time (Incremental) Recovery Using the Binary Log\\(rq). For example:\n" }, { "code": null, "e": 23308, "s": 23255, "text": "shell> mysqlbinlog binlog.000001 | mysql -u root -p\n" }, { "code": null, "e": 23314, "s": 23308, "text": "\nOr:\n" }, { "code": null, "e": 23370, "s": 23317, "text": "shell> mysqlbinlog binlog.[0-9]* | mysql -u root -p\n" }, { "code": null, "e": 23682, "s": 23370, "text": "\nYou can also redirect the output of\nmysqlbinlog\nto a text file instead, if you need to modify the statement log first (for example, to remove statements that you do not want to execute for some reason). After editing the file, execute the statements that it contains by using it as input to the\nmysql\nprogram:\n" }, { "code": null, "e": 23791, "s": 23685, "text": "shell> mysqlbinlog binlog.000001 > tmpfile\nshell> ... edit tmpfile ...\nshell> mysql -u root -p < tmpfile\n" }, { "code": null, "e": 24294, "s": 23791, "text": "\nWhen\nmysqlbinlog\nis invoked with the\n--start-position\noption, it displays only those events with an offset in the binary log greater than or equal to a given position (the given position must match the start of one event). It also has options to stop and start when it sees an event with a given date and time. This enables you to perform point-in-time recovery using the\n--stop-datetime\noption (to be able to say, for example,\n\\(lqroll forward my databases to how they were today at 10:30 a.m.\\(rq).\n" }, { "code": null, "e": 24502, "s": 24294, "text": "\nIf you have more than one binary log to execute on the MySQL server, the safe method is to process them all using a single connection to the server. Here is an example that demonstrates what may be\nunsafe:\n" }, { "code": null, "e": 24632, "s": 24505, "text": "shell> mysqlbinlog binlog.000001 | mysql -u root -p # DANGER!!\nshell> mysqlbinlog binlog.000002 | mysql -u root -p # DANGER!!\n" }, { "code": null, "e": 25038, "s": 24632, "text": "\nProcessing binary logs this way using multiple connections to the server causes problems if the first log file contains a\nCREATE TEMPORARY TABLE\nstatement and the second log contains a statement that uses the temporary table. When the first\nmysql\nprocess terminates, the server drops the temporary table. When the second\nmysql\nprocess attempts to use the table, the server reports\n\\(lqunknown table.\\(rq\n" }, { "code": null, "e": 25191, "s": 25038, "text": "\nTo avoid problems like this, use a\nsingle\nmysql\nprocess to execute the contents of all binary logs that you want to process. Here is one way to do so:\n" }, { "code": null, "e": 25261, "s": 25194, "text": "shell> mysqlbinlog binlog.000001 binlog.000002 | mysql -u root -p\n" }, { "code": null, "e": 25349, "s": 25261, "text": "\nAnother approach is to write all the logs to a single file and then process the file:\n" }, { "code": null, "e": 25521, "s": 25352, "text": "shell> mysqlbinlog binlog.000001 > /tmp/statements.sql\nshell> mysqlbinlog binlog.000002 >> /tmp/statements.sql\nshell> mysql -u root -p -e \"source /tmp/statements.sql\"\n" }, { "code": null, "e": 25902, "s": 25521, "text": "\nmysqlbinlog\ncan produce output that reproduces a\nLOAD DATA INFILE\noperation without the original data file.\nmysqlbinlog\ncopies the data to a temporary file and writes a\nLOAD DATA LOCAL INFILE\nstatement that refers to the file. The default location of the directory where these files are written is system-specific. To specify a directory explicitly, use the\n--local-load\noption.\n" }, { "code": null, "e": 26214, "s": 25902, "text": "\nBecause\nmysqlbinlog\nconverts\nLOAD DATA INFILE\nstatements to\nLOAD DATA LOCAL INFILE\nstatements (that is, it adds\nLOCAL), both the client and the server that you use to process the statements must be configured with the\nLOCAL\ncapability enabled. See\nSection 5.3.5, \\(lqSecurity Issues with LOAD DATA LOCAL\\(rq.\n\n" }, { "code": null, "e": 26567, "s": 26217, "text": "\nThe temporary files created for\nLOAD DATA LOCAL\nstatements are\nnot\nautomatically deleted because they are needed until you actually execute those statements. You should delete the temporary files yourself after you no longer need the statement log. The files can be found in the temporary file directory and have names like\noriginal_file_name-#-#.\n" }, { "code": null, "e": 26661, "s": 26569, "text": "\nThe\n--hexdump\noption causes\nmysqlbinlog\nto produce a hex dump of the binary log contents:\n" }, { "code": null, "e": 26713, "s": 26665, "text": "shell> mysqlbinlog --hexdump master-bin.000001\n" }, { "code": null, "e": 26836, "s": 26713, "text": "\nThe hex output consists of comment lines beginning with\n#, so the output might look like this for the preceding command:\n" }, { "code": null, "e": 27673, "s": 26840, "text": "/*!40019 SET @@session.max_insert_delayed_threads=0*/;\n/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;\n# at 4\n#051024 17:24:13 server id 1 end_log_pos 98\n# Position Timestamp Type Master ID Size Master Pos Flags\n# 00000004 9d fc 5c 43 0f 01 00 00 00 5e 00 00 00 62 00 00 00 00 00\n# 00000017 04 00 35 2e 30 2e 31 35 2d 64 65 62 75 67 2d 6c |..5.0.15.debug.l|\n# 00000027 6f 67 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |og..............|\n# 00000037 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|\n# 00000047 00 00 00 00 9d fc 5c 43 13 38 0d 00 08 00 12 00 |.......C.8......|\n# 00000057 04 04 04 04 12 00 00 4b 00 04 1a |.......K...|\n# Start: binlog v 4, server v 5.0.15-debug-log created 051024 17:24:13\n# at startup\nROLLBACK;\n" }, { "code": null, "e": 27901, "s": 27673, "text": "\nHex dump output currently contains the elements in the following list. This format is subject to change. (For more information about binary log format, see\n\\m[blue] http://forge.mysql.com/wiki/MySQL_Internals_Binary_Log\\m[].)\n" }, { "code": null, "e": 27907, "s": 27901, "text": "\n\no\n\n" }, { "code": null, "e": 27915, "s": 27909, "text": "\n\no\n\n" }, { "code": null, "e": 27923, "s": 27917, "text": "\n\no\n\n" }, { "code": null, "e": 27933, "s": 27927, "text": "\n\no\n\n" }, { "code": null, "e": 27941, "s": 27935, "text": "\n\no\n\n" }, { "code": null, "e": 27949, "s": 27943, "text": "\n\no\n\n" }, { "code": null, "e": 27957, "s": 27951, "text": "\n\no\n\n" }, { "code": null, "e": 28315, "s": 27961, "text": "\nThe following examples illustrate how\nmysqlbinlog\ndisplays row events that specify data modifications. These correspond to events with the\nWRITE_ROWS_EVENT,\nUPDATE_ROWS_EVENT, and\nDELETE_ROWS_EVENT\ntype codes. The\n--base64-output=DECODE-ROWS\nand\n--verbose\noptions may be used to affect row event output. These options are available as of MySQL 5.1.28.\n" }, { "code": null, "e": 28434, "s": 28315, "text": "\nSuppose that the server is using row-based binary logging and that you execute the following sequence of statements:\n" }, { "code": null, "e": 28699, "s": 28438, "text": "CREATE TABLE t\n(\n id INT NOT NULL,\n name VARCHAR(20) NOT NULL,\n date DATE NULL\n) ENGINE = InnoDB;\nSTART TRANSACTION;\nINSERT INTO t VALUES(1, 'apple', NULL);\nUPDATE t SET name = 'pear', date = '2009-01-01' WHERE id = 1;\nDELETE FROM t WHERE id = 1;\nCOMMIT;\n" }, { "code": null, "e": 28916, "s": 28699, "text": "\nBy default,\nmysqlbinlog\ndisplays row events encoded as base-64 strings using\nBINLOG\nstatements. Omitting extraneous lines, the output for the row events produced by the preceding statement sequence looks like this:\n" }, { "code": null, "e": 29681, "s": 28920, "text": "shell> mysqlbinlog log_file\n...\n# at 218\n#080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ==\n'/*!*/;\n...\n# at 302\n#080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP\n'/*!*/;\n...\n# at 400\n#080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP\n'/*!*/;\n" }, { "code": null, "e": 29862, "s": 29681, "text": "\nTo see the row events as comments in the form of\n\\(lqpseudo-SQL\\(rq\nstatements, run\nmysqlbinlog\nwith the\n--verbose\nor\n-v\noption. The output will contain lines beginning with\n###:\n" }, { "code": null, "e": 30912, "s": 29866, "text": "shell> mysqlbinlog -v log_file\n...\n# at 218\n#080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ==\n'/*!*/;\n### INSERT INTO test.t\n### SET\n### @1=1\n### @2='apple'\n### @3=NULL\n...\n# at 302\n#080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP\n'/*!*/;\n### UPDATE test.t\n### WHERE\n### @1=1\n### @2='apple'\n### @3=NULL\n### SET\n### @1=1\n### @2='pear'\n### @3='2009:01:01'\n...\n# at 400\n#080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP\n'/*!*/;\n### DELETE FROM test.t\n### WHERE\n### @1=1\n### @2='pear'\n### @3='2009:01:01'\n" }, { "code": null, "e": 31082, "s": 30912, "text": "\nSpecify\n--verbose\nor\n-v\ntwice to also display data types and some metadata for each column. The output will contain an additional comment following each column change:\n" }, { "code": null, "e": 32655, "s": 31086, "text": "shell> mysqlbinlog -vv log_file\n...\n# at 218\n#080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAANoAAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBcBAAAAKAAAAAIBAAAQABEAAAAAAAEAA//8AQAAAAVhcHBsZQ==\n'/*!*/;\n### INSERT INTO test.t\n### SET\n### @1=1 /* INT meta=0 nullable=0 is_null=0 */\n### @2='apple' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */\n### @3=NULL /* VARSTRING(20) meta=0 nullable=1 is_null=1 */\n...\n# at 302\n#080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAC4BAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBgBAAAANgAAAGQBAAAQABEAAAAAAAEAA////AEAAAAFYXBwbGX4AQAAAARwZWFyIbIP\n'/*!*/;\n### UPDATE test.t\n### WHERE\n### @1=1 /* INT meta=0 nullable=0 is_null=0 */\n### @2='apple' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */\n### @3=NULL /* VARSTRING(20) meta=0 nullable=1 is_null=1 */\n### SET\n### @1=1 /* INT meta=0 nullable=0 is_null=0 */\n### @2='pear' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */\n### @3='2009:01:01' /* DATE meta=0 nullable=1 is_null=0 */\n...\n# at 400\n#080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F\nBINLOG '\nfAS3SBMBAAAALAAAAJABAAAAABEAAAAAAAAABHRlc3QAAXQAAwMPCgIUAAQ=\nfAS3SBkBAAAAKgAAALoBAAAQABEAAAAAAAEAA//4AQAAAARwZWFyIbIP\n'/*!*/;\n### DELETE FROM test.t\n### WHERE\n### @1=1 /* INT meta=0 nullable=0 is_null=0 */\n### @2='pear' /* VARSTRING(20) meta=20 nullable=0 is_null=0 */\n### @3='2009:01:01' /* DATE meta=0 nullable=1 is_null=0 */\n" }, { "code": null, "e": 33007, "s": 32655, "text": "\nYou can tell\nmysqlbinlog\nto suppress the\nBINLOG\nstatements for row events by using the\n--base64-output=DECODE-ROWS\noption. This is similar to\n--base64-output=NEVER\nbut does not exit with an error if a row event is found. The combination of\n--base64-output=DECODE-ROWS\nand\n--verbose\nprovides a convenient way to see row events only as SQL statements:\n" }, { "code": null, "e": 33664, "s": 33011, "text": "shell> mysqlbinlog -v --base64-output=DECODE-ROWS log_file\n...\n# at 218\n#080828 15:03:08 server id 1 end_log_pos 258 Write_rows: table id 17 flags: STMT_END_F\n### INSERT INTO test.t\n### SET\n### @1=1\n### @2='apple'\n### @3=NULL\n...\n# at 302\n#080828 15:03:08 server id 1 end_log_pos 356 Update_rows: table id 17 flags: STMT_END_F\n### UPDATE test.t\n### WHERE\n### @1=1\n### @2='apple'\n### @3=NULL\n### SET\n### @1=1\n### @2='pear'\n### @3='2009:01:01'\n...\n# at 400\n#080828 15:03:08 server id 1 end_log_pos 442 Delete_rows: table id 17 flags: STMT_END_F\n### DELETE FROM test.t\n### WHERE\n### @1=1\n### @2='pear'\n### @3='2009:01:01'\n" }, { "code": null, "e": 33676, "s": 33667, "text": "\n\n\nNote\n" }, { "code": null, "e": 33768, "s": 33676, "text": "\nYou should not suppress\nBINLOG\nstatements if you intend to re-execute\nmysqlbinlog\noutput.\n" }, { "code": null, "e": 34024, "s": 33770, "text": "\nThe SQL statements produced by\n--verbose\nfor row events are much more readable than the corresponding\nBINLOG\nstatements. However, they do not correspond exactly to the original SQL statements that generated the events. The following limitations apply:\n" }, { "code": null, "e": 34030, "s": 34024, "text": "\n\no\n\n" }, { "code": null, "e": 34038, "s": 34032, "text": "\n\no\n\n" }, { "code": null, "e": 34109, "s": 34052, "text": "CHAR(4) CHARACTER SET latin1\nCHAR(2) CHARACTER SET ucs2\n" }, { "code": null, "e": 34452, "s": 34113, "text": "\nProper interpretation of row events requires the information from the format description event at the beginning of the binary log. Because\nmysqlbinlog\ndoes not know in advance whether the rest of the log contains row events, by default it displays the format description event using a\nBINLOG\nstatement in the initial part of the output.\n" }, { "code": null, "e": 34650, "s": 34452, "text": "\nIf the binary log is known not to contain any events requiring a\nBINLOG\nstatement (that is, no row events), the\n--base64-output=NEVER\noption can be used to prevent this header from being written.\n" }, { "code": null, "e": 34727, "s": 34650, "text": "\nCopyright © 1997, 2011, Oracle and/or its affiliates. All rights reserved.\n" }, { "code": null, "e": 34934, "s": 34727, "text": "\nThis documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License.\n" }, { "code": null, "e": 35175, "s": 34934, "text": "\nThis documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n" }, { "code": null, "e": 35416, "s": 35175, "text": "\nYou should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or see http://www.gnu.org/licenses/.\n" }, { "code": null, "e": 35435, "s": 35418, "text": "\nAdvertisements\n" }, { "code": null, "e": 35470, "s": 35435, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 35498, "s": 35470, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 35532, "s": 35498, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 35549, "s": 35532, "text": " Frahaan Hussain" }, { "code": null, "e": 35582, "s": 35549, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 35593, "s": 35582, "text": " Pradeep D" }, { "code": null, "e": 35628, "s": 35593, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 35644, "s": 35628, "text": " Musab Zayadneh" }, { "code": null, "e": 35677, "s": 35644, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 35689, "s": 35677, "text": " GUHARAJANM" }, { "code": null, "e": 35721, "s": 35689, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 35729, "s": 35721, "text": " Uplatz" }, { "code": null, "e": 35736, "s": 35729, "text": " Print" }, { "code": null, "e": 35747, "s": 35736, "text": " Add Notes" } ]
CSS Animations - GeeksforGeeks
02 Nov, 2021 CSS Animation: CSS Animations is a technique to change the appearance and behavior of various elements in web pages. It is used to control the elements by changing their motions or display. It has two parts, one which contains the CSS properties which describe the animation of the elements and the other contains certain keyframes which indicate the animation properties of the element and the specific time intervals at which those have to occur. The @keyframes rule: Keyframes are the foundations with the help of which CSS Animations works. They define the display of the animation at the respective stages of its whole duration. For example: In the following code, the paragraph changes its color with time. At 0% completion, it is red, at 50% completion it is of orange color and at full completion i.e. at 100%, it is brown. Example: This example describes the CSS Animation using the @keyframe rule. HTML <!DOCTYPE html><html> <head> <style> #gfg { animation-name: color; animation-duration: 25s; padding-top: 30px; padding-bottom: 30px; font-family: Times New Roman; } #geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; } #geeks1 { font-size: 17px; font-weight: bold; text-align: center; } @keyframes color { 0% { background-color: red; } 50% { background-color: orange; } 100% { background-color: brown; } } </style></head> <body> <div id="gfg"> <div id="geeks">GeeksforGeeks</div> <div id="geeks1">A computer science portal for geeks</div> </div></body> </html> Output: Animation Properties: There are certain animation properties given below: animation-name: It is used to specify the name of the @keyframes describing the animation. animation-name: animation_name; animation-duration: It is used to specify the time duration it takes animation to complete one cycle. Example: This example describes the CSS Animation Properties using animation-duration property. HTML <html> <head> <style> #gfg1 { animation-name: text; animation-duration: 5s; animation-iteration-count: infinite; } #geek1 { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; } #geek2 { font-size: 17px; font-weight: bold; text-align: center; } @keyframes text { from { margin-top: 400px; } to { margin-top: 0px; } } </style></head> <body> <div id="gfg1"> <div id="geek1">GeeksforGeeks</div> <div id="geek2">A computer science portal for geeks</div> </div></body> </html> Output: The animation will look like this: animation-timing-function: Specifies how the animation makes transitions through keyframes. It can have the following values: ease: The animation starts slowly, then fast, and then finally ends slowly (this is the default) linear: The animation plays with the same speed from start to end ease-in: The animation plays with a slow start ease-out: The animation plays with a slow end ease-in-out: The animation starts and ends slowly. Example: This example describes the CSS Animation Properties using the animation-timing-function property. HTML <!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 350px; animation-name: text; animation-duration: 4s; animation-iteration-count: infinite; background-color: rgb(255, 210, 85); } #one { animation-timing-function: ease; } #two { animation-timing-function: linear; } #three { animation-timing-function: ease-in; } #four { animation-timing-function: ease-out; } #five { animation-timing-function: ease-in-out; } @keyframes text { from { margin-left: 60%; } to { margin-left: 0%; } } </style></head> <body> <div class="geeks">GeeksforGeeks</div> <div class="geeks1">A computer science portal for geeks</div> <h2 id="one">This text is ease.</h2> <h2 id="two">This text is linear.</h2> <h2 id="three">This text is ease-in.</h2> <h2 id="four">This text is ease-out.</h2> <h2 id="five">This text is ease-in-out.</h2></body> </html> Output: animation-delay: It is used to specify the delay when the animation starts. Example: This example describes the CSS Animation Properties using the animation-delay property. HTML <!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } #one { animation-name: example; animation-duration: 10s; } #two { animation-name: example; animation-duration: 10s; animation-delay: 10s; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style></head> <body> <div class="geeks">GeeksforGeeks</div> <div class="geeks1">A computer science portal for geeks</div> <h2 id="one">Text animation without delayed.</h2> <h2 id="two">Text animation with 10 second delay.</h2> </body> </html> Output: animation-iteration-count: It is used to specify the number of times the animation will repeat. It can specify as infinite to repeat the animation indefinitely. Example: This example describes the CSS Animation Properties using an animation-iteration-count property. HTML <!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } #one { animation-name: example; animation-duration: 2s; animation-iteration-count: 2; } #two { animation-name: example; animation-duration: 2s; animation-iteration-count: infinite; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style></head> <body> <div class="geeks">GeeksforGeeks</div> <div class="geeks1">A computer science portal for geeks</div> <h2 id="one">This text changes its color two times.</h2> <h2 id="two">This text changes its color infinite times.</h2></body> </html> Output: animation-direction: Specifies the direction of the animation. It can have the following values: normal: The animation is played forward. This is the default value. reverse: The animation is played in the reverse direction i.e. backward. alternate: The animation is played forwards first, and then backward. alternate-reverse: The animation is played backward first, and then forwards. Example: This example describes the CSS Animation Properties using the animation-direction property. HTML <!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 100%; animation-name: text; animation-duration: 2s; animation-iteration-count: infinite; } #one { animation-direction: normal; } #two { animation-direction: reverse; } #three { animation-direction: alternate; } #four { animation-direction: alternate-reverse; } @keyframes text { from { margin-left: 60%; } to { margin-left: 0%; } } </style></head> <body> <div class="geeks">GeeksforGeeks</div> <div class="geeks1">A computer science portal for geeks</div> <h2 id="one">This text is normal.</h2> <h2 id="two">This text is reverse.</h2> <h2 id="three">This text is alternate.</h2> <h2 id="four">This text is alternate-reverse.</h2></body> </html> Output: animation-fill-mode: Specifies what values are applied by the animation before and after it is executed. none: Animation will not apply any properties to the element before or after it is executed. This is the default value. forwards: The element will retain the same animation properties of the last keyframe after the animation completes. backwards: The element will get the properties of the first keyframe before the start of the animation. both: The animation will follow the rules for both forwards and backward i.e. it will get the properties defined for the initial keyframe before the start and will retain the value of the last keyframe after the completion of the animation. Example: This example describes the CSS Animation Properties using an animation-fill-mode property. HTML <!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 400px; background-color: orange; animation-name: text; animation-duration: 3s; } #one { animation-fill-mode: none; } #two { animation-fill-mode: forwards; } #three { animation-fill-mode: backwards; animation-delay: 2s; } #four { animation-fill-mode: both; animation-delay: 2s; } @keyframes text { from { margin-left: 0%; background-color: #aaaaaa; } to { margin-left: 60%; background-color: #008000; } } </style></head> <body> <div class="geeks">GeeksforGeeks</div> <div class="geeks1">A computer science portal for geeks</div> <h2 id="one">none</h2> <h2 id="two">forwards</h2> <h2 id="three">backwards</h2> <h2 id="four">both</h2></body> </html> Output: animation-play-state: This allows you to play/pause the animation. Animation Shorthand Property: It is a shorthand way of implying the animation properties for a quicker code. The properties should be in the following order: animation: [animation-name] [animation-duration] [animation-timing-function] [animation-delay] [animation-iteration-count] [animation-direction] [animation-fill-mode] [animation-play-state]; For example, normally the animation code would be like this: Example: This example describes the CSS Animation Properties using an animation-play-state property, without animation shorthand property. HTML <!DOCTYPE html><html> <head> <style> #g4g { width: 400px; height: 100px; position: relative; animation-name: GFG; animation-duration: 5s; animation-timing-function: linear; animation-delay: 1s; animation-iteration-count: infinite; animation-direction: alternate; } @keyframes GFG { 0% { left: 0px; top: 0px; } 25% { left: 200px; top: 200px; } 50% { left: 200px; top: 0px; } 75% { left: 0px; top: 200px; } 100% { left: 0px; top: 0px; } } </style></head> <body> <img id="g4g" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png"></body> </html> Output: In shorthand the above HTML code can be written as: Example: This example describes the CSS Animation Properties using an animation-play-state property, with animation shorthand property. HTML <!DOCTYPE html><html> <head> <style> #geeks4g { width: 400px; height: 100px; position: relative; animation: GFG 5s linear 1s infinite alternate; } @keyframes GFG { 0% { left: 0px; top: 0px; } 25% { left: 200px; top: 200px; } 50% { left: 200px; top: 0px; } 75% { left: 0px; top: 200px; } 100% { left: 0px; top: 0px; } } </style></head> <body> <img id="geeks4g" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png"></body> </html> Output: Supported Browsers: Google Chrome 43.0 Microsoft Edge 12.0 Firefox 16.0 Safari 9.0 Opera 30.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks CSS-Advanced CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 27680, "s": 27652, "text": "\n02 Nov, 2021" }, { "code": null, "e": 28130, "s": 27680, "text": "CSS Animation: CSS Animations is a technique to change the appearance and behavior of various elements in web pages. It is used to control the elements by changing their motions or display. It has two parts, one which contains the CSS properties which describe the animation of the elements and the other contains certain keyframes which indicate the animation properties of the element and the specific time intervals at which those have to occur. " }, { "code": null, "e": 28514, "s": 28130, "text": "The @keyframes rule: Keyframes are the foundations with the help of which CSS Animations works. They define the display of the animation at the respective stages of its whole duration. For example: In the following code, the paragraph changes its color with time. At 0% completion, it is red, at 50% completion it is of orange color and at full completion i.e. at 100%, it is brown. " }, { "code": null, "e": 28590, "s": 28514, "text": "Example: This example describes the CSS Animation using the @keyframe rule." }, { "code": null, "e": 28595, "s": 28590, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #gfg { animation-name: color; animation-duration: 25s; padding-top: 30px; padding-bottom: 30px; font-family: Times New Roman; } #geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; } #geeks1 { font-size: 17px; font-weight: bold; text-align: center; } @keyframes color { 0% { background-color: red; } 50% { background-color: orange; } 100% { background-color: brown; } } </style></head> <body> <div id=\"gfg\"> <div id=\"geeks\">GeeksforGeeks</div> <div id=\"geeks1\">A computer science portal for geeks</div> </div></body> </html>", "e": 29434, "s": 28595, "text": null }, { "code": null, "e": 29442, "s": 29434, "text": "Output:" }, { "code": null, "e": 29516, "s": 29442, "text": "Animation Properties: There are certain animation properties given below:" }, { "code": null, "e": 29607, "s": 29516, "text": "animation-name: It is used to specify the name of the @keyframes describing the animation." }, { "code": null, "e": 29639, "s": 29607, "text": "animation-name: animation_name;" }, { "code": null, "e": 29741, "s": 29639, "text": "animation-duration: It is used to specify the time duration it takes animation to complete one cycle." }, { "code": null, "e": 29837, "s": 29741, "text": "Example: This example describes the CSS Animation Properties using animation-duration property." }, { "code": null, "e": 29842, "s": 29837, "text": "HTML" }, { "code": "<html> <head> <style> #gfg1 { animation-name: text; animation-duration: 5s; animation-iteration-count: infinite; } #geek1 { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; } #geek2 { font-size: 17px; font-weight: bold; text-align: center; } @keyframes text { from { margin-top: 400px; } to { margin-top: 0px; } } </style></head> <body> <div id=\"gfg1\"> <div id=\"geek1\">GeeksforGeeks</div> <div id=\"geek2\">A computer science portal for geeks</div> </div></body> </html>", "e": 30544, "s": 29842, "text": null }, { "code": null, "e": 30552, "s": 30544, "text": "Output:" }, { "code": null, "e": 30587, "s": 30552, "text": "The animation will look like this:" }, { "code": null, "e": 30715, "s": 30587, "text": "animation-timing-function: Specifies how the animation makes transitions through keyframes. It can have the following values: " }, { "code": null, "e": 30812, "s": 30715, "text": "ease: The animation starts slowly, then fast, and then finally ends slowly (this is the default)" }, { "code": null, "e": 30878, "s": 30812, "text": "linear: The animation plays with the same speed from start to end" }, { "code": null, "e": 30925, "s": 30878, "text": "ease-in: The animation plays with a slow start" }, { "code": null, "e": 30971, "s": 30925, "text": "ease-out: The animation plays with a slow end" }, { "code": null, "e": 31022, "s": 30971, "text": "ease-in-out: The animation starts and ends slowly." }, { "code": null, "e": 31129, "s": 31022, "text": "Example: This example describes the CSS Animation Properties using the animation-timing-function property." }, { "code": null, "e": 31134, "s": 31129, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 350px; animation-name: text; animation-duration: 4s; animation-iteration-count: infinite; background-color: rgb(255, 210, 85); } #one { animation-timing-function: ease; } #two { animation-timing-function: linear; } #three { animation-timing-function: ease-in; } #four { animation-timing-function: ease-out; } #five { animation-timing-function: ease-in-out; } @keyframes text { from { margin-left: 60%; } to { margin-left: 0%; } } </style></head> <body> <div class=\"geeks\">GeeksforGeeks</div> <div class=\"geeks1\">A computer science portal for geeks</div> <h2 id=\"one\">This text is ease.</h2> <h2 id=\"two\">This text is linear.</h2> <h2 id=\"three\">This text is ease-in.</h2> <h2 id=\"four\">This text is ease-out.</h2> <h2 id=\"five\">This text is ease-in-out.</h2></body> </html>", "e": 32497, "s": 31134, "text": null }, { "code": null, "e": 32505, "s": 32497, "text": "Output:" }, { "code": null, "e": 32581, "s": 32505, "text": "animation-delay: It is used to specify the delay when the animation starts." }, { "code": null, "e": 32678, "s": 32581, "text": "Example: This example describes the CSS Animation Properties using the animation-delay property." }, { "code": null, "e": 32683, "s": 32678, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } #one { animation-name: example; animation-duration: 10s; } #two { animation-name: example; animation-duration: 10s; animation-delay: 10s; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style></head> <body> <div class=\"geeks\">GeeksforGeeks</div> <div class=\"geeks1\">A computer science portal for geeks</div> <h2 id=\"one\">Text animation without delayed.</h2> <h2 id=\"two\">Text animation with 10 second delay.</h2> </body> </html>", "e": 33647, "s": 32683, "text": null }, { "code": null, "e": 33655, "s": 33647, "text": "Output:" }, { "code": null, "e": 33816, "s": 33655, "text": "animation-iteration-count: It is used to specify the number of times the animation will repeat. It can specify as infinite to repeat the animation indefinitely." }, { "code": null, "e": 33922, "s": 33816, "text": "Example: This example describes the CSS Animation Properties using an animation-iteration-count property." }, { "code": null, "e": 33927, "s": 33922, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } #one { animation-name: example; animation-duration: 2s; animation-iteration-count: 2; } #two { animation-name: example; animation-duration: 2s; animation-iteration-count: infinite; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style></head> <body> <div class=\"geeks\">GeeksforGeeks</div> <div class=\"geeks1\">A computer science portal for geeks</div> <h2 id=\"one\">This text changes its color two times.</h2> <h2 id=\"two\">This text changes its color infinite times.</h2></body> </html>", "e": 34954, "s": 33927, "text": null }, { "code": null, "e": 34962, "s": 34954, "text": "Output:" }, { "code": null, "e": 35060, "s": 34962, "text": "animation-direction: Specifies the direction of the animation. It can have the following values: " }, { "code": null, "e": 35128, "s": 35060, "text": "normal: The animation is played forward. This is the default value." }, { "code": null, "e": 35201, "s": 35128, "text": "reverse: The animation is played in the reverse direction i.e. backward." }, { "code": null, "e": 35271, "s": 35201, "text": "alternate: The animation is played forwards first, and then backward." }, { "code": null, "e": 35349, "s": 35271, "text": "alternate-reverse: The animation is played backward first, and then forwards." }, { "code": null, "e": 35450, "s": 35349, "text": "Example: This example describes the CSS Animation Properties using the animation-direction property." }, { "code": null, "e": 35455, "s": 35450, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 100%; animation-name: text; animation-duration: 2s; animation-iteration-count: infinite; } #one { animation-direction: normal; } #two { animation-direction: reverse; } #three { animation-direction: alternate; } #four { animation-direction: alternate-reverse; } @keyframes text { from { margin-left: 60%; } to { margin-left: 0%; } } </style></head> <body> <div class=\"geeks\">GeeksforGeeks</div> <div class=\"geeks1\">A computer science portal for geeks</div> <h2 id=\"one\">This text is normal.</h2> <h2 id=\"two\">This text is reverse.</h2> <h2 id=\"three\">This text is alternate.</h2> <h2 id=\"four\">This text is alternate-reverse.</h2></body> </html>", "e": 36661, "s": 35455, "text": null }, { "code": null, "e": 36669, "s": 36661, "text": "Output:" }, { "code": null, "e": 36775, "s": 36669, "text": "animation-fill-mode: Specifies what values are applied by the animation before and after it is executed. " }, { "code": null, "e": 36895, "s": 36775, "text": "none: Animation will not apply any properties to the element before or after it is executed. This is the default value." }, { "code": null, "e": 37011, "s": 36895, "text": "forwards: The element will retain the same animation properties of the last keyframe after the animation completes." }, { "code": null, "e": 37115, "s": 37011, "text": "backwards: The element will get the properties of the first keyframe before the start of the animation." }, { "code": null, "e": 37356, "s": 37115, "text": "both: The animation will follow the rules for both forwards and backward i.e. it will get the properties defined for the initial keyframe before the start and will retain the value of the last keyframe after the completion of the animation." }, { "code": null, "e": 37456, "s": 37356, "text": "Example: This example describes the CSS Animation Properties using an animation-fill-mode property." }, { "code": null, "e": 37461, "s": 37456, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .geeks { font-size: 40px; text-align: center; font-weight: bold; color: #090; padding-bottom: 5px; font-family: Times New Roman; } .geeks1 { font-size: 17px; font-weight: bold; text-align: center; font-family: Times New Roman; } h2 { width: 400px; background-color: orange; animation-name: text; animation-duration: 3s; } #one { animation-fill-mode: none; } #two { animation-fill-mode: forwards; } #three { animation-fill-mode: backwards; animation-delay: 2s; } #four { animation-fill-mode: both; animation-delay: 2s; } @keyframes text { from { margin-left: 0%; background-color: #aaaaaa; } to { margin-left: 60%; background-color: #008000; } } </style></head> <body> <div class=\"geeks\">GeeksforGeeks</div> <div class=\"geeks1\">A computer science portal for geeks</div> <h2 id=\"one\">none</h2> <h2 id=\"two\">forwards</h2> <h2 id=\"three\">backwards</h2> <h2 id=\"four\">both</h2></body> </html>", "e": 38705, "s": 37461, "text": null }, { "code": null, "e": 38713, "s": 38705, "text": "Output:" }, { "code": null, "e": 38780, "s": 38713, "text": "animation-play-state: This allows you to play/pause the animation." }, { "code": null, "e": 38938, "s": 38780, "text": "Animation Shorthand Property: It is a shorthand way of implying the animation properties for a quicker code. The properties should be in the following order:" }, { "code": null, "e": 39151, "s": 38938, "text": "animation: [animation-name] [animation-duration] [animation-timing-function] [animation-delay] \n [animation-iteration-count] [animation-direction] [animation-fill-mode] \n [animation-play-state];" }, { "code": null, "e": 39212, "s": 39151, "text": "For example, normally the animation code would be like this:" }, { "code": null, "e": 39351, "s": 39212, "text": "Example: This example describes the CSS Animation Properties using an animation-play-state property, without animation shorthand property." }, { "code": null, "e": 39356, "s": 39351, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #g4g { width: 400px; height: 100px; position: relative; animation-name: GFG; animation-duration: 5s; animation-timing-function: linear; animation-delay: 1s; animation-iteration-count: infinite; animation-direction: alternate; } @keyframes GFG { 0% { left: 0px; top: 0px; } 25% { left: 200px; top: 200px; } 50% { left: 200px; top: 0px; } 75% { left: 0px; top: 200px; } 100% { left: 0px; top: 0px; } } </style></head> <body> <img id=\"g4g\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png\"></body> </html>", "e": 40204, "s": 39356, "text": null }, { "code": null, "e": 40212, "s": 40204, "text": "Output:" }, { "code": null, "e": 40264, "s": 40212, "text": "In shorthand the above HTML code can be written as:" }, { "code": null, "e": 40400, "s": 40264, "text": "Example: This example describes the CSS Animation Properties using an animation-play-state property, with animation shorthand property." }, { "code": null, "e": 40405, "s": 40400, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> #geeks4g { width: 400px; height: 100px; position: relative; animation: GFG 5s linear 1s infinite alternate; } @keyframes GFG { 0% { left: 0px; top: 0px; } 25% { left: 200px; top: 200px; } 50% { left: 200px; top: 0px; } 75% { left: 0px; top: 200px; } 100% { left: 0px; top: 0px; } } </style></head> <body> <img id=\"geeks4g\" src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/GeeksforGeeksLogoHeader.png\"></body> </html>", "e": 41104, "s": 40405, "text": null }, { "code": null, "e": 41112, "s": 41104, "text": "Output:" }, { "code": null, "e": 41132, "s": 41112, "text": "Supported Browsers:" }, { "code": null, "e": 41151, "s": 41132, "text": "Google Chrome 43.0" }, { "code": null, "e": 41171, "s": 41151, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 41184, "s": 41171, "text": "Firefox 16.0" }, { "code": null, "e": 41195, "s": 41184, "text": "Safari 9.0" }, { "code": null, "e": 41206, "s": 41195, "text": "Opera 30.0" }, { "code": null, "e": 41343, "s": 41206, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 41364, "s": 41343, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 41377, "s": 41364, "text": "CSS-Advanced" }, { "code": null, "e": 41381, "s": 41377, "text": "CSS" }, { "code": null, "e": 41386, "s": 41381, "text": "HTML" }, { "code": null, "e": 41403, "s": 41386, "text": "Web Technologies" }, { "code": null, "e": 41408, "s": 41403, "text": "HTML" }, { "code": null, "e": 41506, "s": 41408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41515, "s": 41506, "text": "Comments" }, { "code": null, "e": 41528, "s": 41515, "text": "Old Comments" }, { "code": null, "e": 41590, "s": 41528, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 41640, "s": 41590, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 41698, "s": 41640, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 41746, "s": 41698, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 41783, "s": 41746, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 41845, "s": 41783, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 41895, "s": 41845, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 41955, "s": 41895, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 42003, "s": 41955, "text": "How to update Node.js and NPM to next version ?" } ]
How to create Empty Values String in JavaScript?
To create empty values string in JavaScript, you can try to run the following code − <html> <head> <script> var val; val = ""; document.write("Value: "+val); document.write("<br>Type: "+typeof val); </script> </head> <body> </body> </html>
[ { "code": null, "e": 1147, "s": 1062, "text": "To create empty values string in JavaScript, you can try to run the following code −" }, { "code": null, "e": 1362, "s": 1147, "text": "<html>\n <head>\n <script>\n var val;\n val = \"\";\n document.write(\"Value: \"+val);\n document.write(\"<br>Type: \"+typeof val);\n </script>\n </head>\n <body>\n </body>\n</html>" } ]
Report Data Sources
Datasources are structured data container. While generating the report, JasperReports engine obtains data from the datasources. Data can be obtained from the databases, XML files, arrays of objects, and collection of objects. We saw in the chapter Filling Reports, the fillReportXXX () method expects to receive a data source of the report, which has to fill, in the form of net.sf.jasperreports.engine.JRDataSource object or a java.sql.Connection (when the report data is found in a relational database). The JRDataSource interface has only two methods, which should be implemented − public boolean next() throws JRException; At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data. public boolean next() throws JRException; At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data. At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data. public Object getFieldValue(JRField jrField) throws JRException; This method provides the value for each report field in the current data source record. public Object getFieldValue(JRField jrField) throws JRException; This method provides the value for each report field in the current data source record. This method provides the value for each report field in the current data source record. The only way to retrieve data from the data source is by using the report fields. There are several default implementations of the JRDataSource interface, depending on the way, the records in the data source are acquired. The table given below summarizes the datasources and their implementation classes − Class JRResultSetDataSource craps a java.sql.ResultSet object. This is the most commonly used data source implementations when report data are extracted from a relational database. If a java.sql.Connection is passed to the engine instead, it executes first the related query and stores the returned java.sql.ResultSet object in a JRResultSetDataSource instance. Classes JRBeanArrayDataSource and JRBeanCollectionDataSource represent implementations that can wrap arrays and collections of JavaBean objects. Each object inside the array or the collection will be seen as one record in this type of data source. The mapping between a particular JavaBean property and the corresponding report field is made by naming conventions. The name of the report field must be the same as the name of the JavaBean property as specified by the JavaBeans specifications. In all the examples of this tutorial, we have used JRBeanCollectionDataSource. The implementation classes JRMapArrayDataSource and JRMapCollectionDataSource are useful if the parent application already stores the reporting data available in-memory as java.util.Map objects. Each Map object in the wrapped array or collection is considered a virtual record in the data source, and the value of each report field is extracted from the map using the report field named as the key. In many client-side applications, data is displayed in tabular format. A common requirement in many applications is to allow the user to print this tabular format as a report. Implementation class JRTableModelDataSource makes the task of generating reports from tabular format trivial for Swing applications. This class wraps a javax.swing.table.TableModel object. Columns in the wrapped TableModel object can be accessed either by their names or by their 0-based indexes. Class JRXmlDataSource is a data source implementation based on DOM, which uses XPath expressions to select data from the XML document. Records in the XML data source are represented by node elements selected through the XPath expression. Field values are retrieved from each record using the XPath expression provided by the field description (<fieldDescription> element in JRXML). XPath is a language used to navigate through an XML document's attributes and elements. More information about XPath can be found at http://www.w3.org/TR/xpath. JRCsvDataSource represents an implementation for data sources, which retrieve their data from structured text files; usually CSVs. Field values are retrieved using their column index. JRXlsDataSource represents an implementation for data sources, which retrieve their data from Excel documents. Report-field mapping for this data source implementation is also based on the field column index. The class JREmptyDataSource, simulates a data source with a given number of virtual empty records inside. It is used by the UI tools to offer basic report preview functionality, or in special report templates, or for testing and debugging purposes. The net.sf.jasperreports.engine.JRRewindableDataSource extends the basic JRDataSource interface. It adds only one method, called moveFirst (), to the interface. This method is intended to move the cursor to the first element in the datasource. Rewindable data sources are useful when working with sub-reports placed inside a band that is not allowed to split due to the isSplitAllowed="false" setting and there is not enough space on the current page for the sub report to be rendered. All the above data source implementations are rewindable except for the JRResultSetDataSource, as it does not support moving the record pointer back. This poses a problem only if this data source is used manually to wrap a java.sql.ResultSet before passing it to the sub-report. There is no problem, if the SQL query resides in the sub-report template, as the engine will execute it again when restarting the sub-report on the next page. The JasperReports library has an interface net.sf.jasperreports.engine.JRDataSourceProvider. This helps in creating and disposing of data source objects. When creating a report template using GUI tools, a special tool for customizing the report's data source is needed. JRDataSourceProvider is the standard way to plug custom data sources into a design tool. A custom implementation of this interface should implement the following methods that allow creating and disposing of data source objects and also methods for listing the available report fields inside the data source if possible − public boolean supportsGetFieldsOperation(); public JRField[] getFields(JasperReport report) throws JRException, UnsupportedOperationException; public JRDataSource create(JasperReport report) throws JRException; public void dispose(JRDataSource dataSource) throws JRException; Print Add Notes Bookmark this page
[ { "code": null, "e": 2760, "s": 2254, "text": "Datasources are structured data container. While generating the report, JasperReports engine obtains data from the datasources. Data can be obtained from the databases, XML files, arrays of objects, and collection of objects. We saw in the chapter Filling Reports, the fillReportXXX () method expects to receive a data source of the report, which has to fill, in the form of net.sf.jasperreports.engine.JRDataSource object or a java.sql.Connection (when the report data is found in a relational database)." }, { "code": null, "e": 2839, "s": 2760, "text": "The JRDataSource interface has only two methods, which should be implemented −" }, { "code": null, "e": 3017, "s": 2839, "text": "public boolean next() throws JRException;\n\nAt the report filling time, this method is called on the data source object by the reporting engine when iterating through the data.\n\n" }, { "code": null, "e": 3059, "s": 3017, "text": "public boolean next() throws JRException;" }, { "code": null, "e": 3192, "s": 3059, "text": "At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data." }, { "code": null, "e": 3325, "s": 3192, "text": "At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data." }, { "code": null, "e": 3481, "s": 3325, "text": "public Object getFieldValue(JRField jrField) throws JRException;\n\nThis method provides the value for each report field in the current data source record.\n\n" }, { "code": null, "e": 3546, "s": 3481, "text": "public Object getFieldValue(JRField jrField) throws JRException;" }, { "code": null, "e": 3634, "s": 3546, "text": "This method provides the value for each report field in the current data source record." }, { "code": null, "e": 3722, "s": 3634, "text": "This method provides the value for each report field in the current data source record." }, { "code": null, "e": 3944, "s": 3722, "text": "The only way to retrieve data from the data source is by using the report fields. There are several default implementations of the JRDataSource interface, depending on the way, the records in the data source are acquired." }, { "code": null, "e": 4028, "s": 3944, "text": "The table given below summarizes the datasources and their implementation classes −" }, { "code": null, "e": 4390, "s": 4028, "text": "Class JRResultSetDataSource craps a java.sql.ResultSet object. This is the most commonly used data source implementations when report data are extracted from a relational database. If a java.sql.Connection is passed to the engine instead, it executes first the related query and stores the returned java.sql.ResultSet object in a JRResultSetDataSource instance." }, { "code": null, "e": 4884, "s": 4390, "text": "Classes JRBeanArrayDataSource and JRBeanCollectionDataSource represent implementations that can wrap arrays and collections of JavaBean objects. Each object inside the array or the collection will be seen as one record in this type of data source. The mapping between a particular JavaBean property and the corresponding report field is made by naming conventions. The name of the report field must be the same as the name of the JavaBean property as specified by the JavaBeans specifications." }, { "code": null, "e": 4963, "s": 4884, "text": "In all the examples of this tutorial, we have used JRBeanCollectionDataSource." }, { "code": null, "e": 5362, "s": 4963, "text": "The implementation classes JRMapArrayDataSource and JRMapCollectionDataSource are useful if the parent application already stores the reporting data available in-memory as java.util.Map objects. Each Map object in the wrapped array or collection is considered a virtual record in the data source, and the value of each report field is extracted from the map using the report field named as the key." }, { "code": null, "e": 5836, "s": 5362, "text": "In many client-side applications, data is displayed in tabular format. A common requirement in many applications is to allow the user to print this tabular format as a report. Implementation class JRTableModelDataSource makes the task of generating reports from tabular format trivial for Swing applications. This class wraps a javax.swing.table.TableModel object. Columns in the wrapped TableModel object can be accessed either by their names or by their 0-based indexes.\n" }, { "code": null, "e": 6218, "s": 5836, "text": "Class JRXmlDataSource is a data source implementation based on DOM, which uses XPath expressions to select data from the XML document. Records in the XML data source are represented by node elements selected through the XPath expression. Field values are retrieved from each record using the XPath expression provided by the field description (<fieldDescription> element in JRXML)." }, { "code": null, "e": 6380, "s": 6218, "text": "XPath is a language used to navigate through an XML document's attributes and elements. More information about XPath can be found at http://www.w3.org/TR/xpath. " }, { "code": null, "e": 6564, "s": 6380, "text": "JRCsvDataSource represents an implementation for data sources, which retrieve their data from structured text files; usually CSVs. Field values are retrieved using their column index." }, { "code": null, "e": 6773, "s": 6564, "text": "JRXlsDataSource represents an implementation for data sources, which retrieve their data from Excel documents. Report-field mapping for this data source implementation is also based on the field column index." }, { "code": null, "e": 7022, "s": 6773, "text": "The class JREmptyDataSource, simulates a data source with a given number of virtual empty records inside. It is used by the UI tools to offer basic report preview functionality, or in special report templates, or for testing and debugging purposes." }, { "code": null, "e": 7266, "s": 7022, "text": "The net.sf.jasperreports.engine.JRRewindableDataSource extends the basic JRDataSource interface. It adds only one method, called moveFirst (), to the interface. This method is intended to move the cursor to the first element in the datasource." }, { "code": null, "e": 7508, "s": 7266, "text": "Rewindable data sources are useful when working with sub-reports placed inside a band that is not allowed to split due to the isSplitAllowed=\"false\" setting and there is not enough space on the current page for the sub report to be rendered." }, { "code": null, "e": 7946, "s": 7508, "text": "All the above data source implementations are rewindable except for the JRResultSetDataSource, as it does not support moving the record pointer back. This poses a problem only if this data source is used manually to wrap a java.sql.ResultSet before passing it to the sub-report. There is no problem, if the SQL query resides in the sub-report template, as the engine will execute it again when restarting the sub-report on the next page." }, { "code": null, "e": 8537, "s": 7946, "text": "The JasperReports library has an interface net.sf.jasperreports.engine.JRDataSourceProvider. This helps in creating and disposing of data source objects. When creating a report template using GUI tools, a special tool for customizing the report's data source is needed. JRDataSourceProvider is the standard way to plug custom data sources into a design tool. A custom implementation of this interface should implement the following methods that allow creating and disposing of data source objects and also methods for listing the available report fields inside the data source if possible −" }, { "code": null, "e": 8820, "s": 8537, "text": "public boolean supportsGetFieldsOperation();\n\npublic JRField[] getFields(JasperReport report)\n throws JRException, UnsupportedOperationException;\n\npublic JRDataSource create(JasperReport report) throws JRException;\n\npublic void dispose(JRDataSource dataSource) throws JRException;" }, { "code": null, "e": 8827, "s": 8820, "text": " Print" }, { "code": null, "e": 8838, "s": 8827, "text": " Add Notes" } ]
XML - DOM
The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them. A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based. The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application. The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM object and then extracts some information from it with JavaScript − <!DOCTYPE html> <html> <body> <h1>TutorialsPoint DOM example </h1> <div> <b>Name:</b> <span id = "name"></span><br> <b>Company:</b> <span id = "company"></span><br> <b>Phone:</b> <span id = "phone"></span> </div> <script> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","/xml/address.xml",false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; document.getElementById("name").innerHTML= xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue; document.getElementById("company").innerHTML= xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue; document.getElementById("phone").innerHTML= xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue; </script> </body> </html> Contents of address.xml are as follows − <?xml version = "1.0"?> <contact-info> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </contact-info> Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce the following output. Here, you can see how each of the child nodes is extracted to display their values. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2162, "s": 1961, "text": "The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy of informational units called nodes; DOM is a way of describing those nodes and the relationships between them." }, { "code": null, "e": 2435, "s": 2162, "text": "A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This hierarchy allows a developer to navigate through the tree looking for specific information. Because it is based on a hierarchy of information, the DOM is said to be tree based." }, { "code": null, "e": 2608, "s": 2435, "text": "The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move, or remove nodes in the tree at any point in order to create an application." }, { "code": null, "e": 2766, "s": 2608, "text": "The following example (sample.htm) parses an XML document (\"address.xml\") into an XML DOM object and then extracts some information from it with JavaScript −" }, { "code": null, "e": 3857, "s": 2766, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h1>TutorialsPoint DOM example </h1>\n <div>\n <b>Name:</b> <span id = \"name\"></span><br>\n <b>Company:</b> <span id = \"company\"></span><br>\n <b>Phone:</b> <span id = \"phone\"></span>\n </div>\n <script>\n if (window.XMLHttpRequest)\n {// code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp = new XMLHttpRequest();\n }\n else\n {// code for IE6, IE5\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xmlhttp.open(\"GET\",\"/xml/address.xml\",false);\n xmlhttp.send();\n xmlDoc = xmlhttp.responseXML;\n\n document.getElementById(\"name\").innerHTML=\n xmlDoc.getElementsByTagName(\"name\")[0].childNodes[0].nodeValue;\n document.getElementById(\"company\").innerHTML=\n xmlDoc.getElementsByTagName(\"company\")[0].childNodes[0].nodeValue;\n document.getElementById(\"phone\").innerHTML=\n xmlDoc.getElementsByTagName(\"phone\")[0].childNodes[0].nodeValue;\n </script>\n </body>\n</html>" }, { "code": null, "e": 3898, "s": 3857, "text": "Contents of address.xml are as follows −" }, { "code": null, "e": 4052, "s": 3898, "text": "<?xml version = \"1.0\"?>\n<contact-info>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</contact-info>" }, { "code": null, "e": 4242, "s": 4052, "text": "Now let us keep these two files sample.htm and address.xml in the same directory /xml and execute the sample.htm file by opening it in any browser. This should produce the following output." }, { "code": null, "e": 4326, "s": 4242, "text": "Here, you can see how each of the child nodes is extracted to display their values." }, { "code": null, "e": 4359, "s": 4326, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 4376, "s": 4359, "text": " Frahaan Hussain" }, { "code": null, "e": 4409, "s": 4376, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 4419, "s": 4409, "text": " YouAccel" }, { "code": null, "e": 4452, "s": 4419, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4469, "s": 4452, "text": " Jordan Stanchev" }, { "code": null, "e": 4502, "s": 4469, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4516, "s": 4502, "text": " Simon Sez IT" }, { "code": null, "e": 4523, "s": 4516, "text": " Print" }, { "code": null, "e": 4534, "s": 4523, "text": " Add Notes" } ]
User Similarity with Binary Data in Python | by Elise Landman | Towards Data Science
User clustering and computation of similarities has increasingly gained relevance within today’s industries. Customers are asked to give ratings on f. e. specific products, which are then compared to other customers’ ratings in order to find similarities among them. Most user clustering applications make use of scaled ratings, f. e. 0–5 stars, or rating scales of 1–10 like on IMDB. In these cases, we can easily apply measures like Euclidean Distance or Cosine Similarity to find how similar/different the user’s choices are. What if we don’t have such ratings and we are dealing with binary data? In this article I will show you why to be careful when using the Euclidean Distance measure on binary data, what measure to alternatively use for computing user similarity and how to create a ranking of these users. I will be using Python 3 with Scipy and Pandas. import scipy.spatialimport pandas as pd Let’s assume we have three users: A, B and C. These users all filled out a multiple-choice survey regarding their favorite fruits. The user choices can be interpreted as one-hot encoded vectors, whereas the ✔️ is replaced by a 1, and the ❌ by a 0. user_choices = [[1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]]df_choices = pd.DataFrame(user_choices, columns=['Apples', 'Bananas', 'Pineapples', 'Kiwis'], index=(["User A", "User B", "User C"])) Why are measures like Euclidean Distance or Cosine Similarity no appropriate measures for this dataset? From a first look at Table 1 we would suggest User A and User B to have a more similar taste, because they both chose “Apples” and “Bananas” as their favorite fruits. However, computing the Euclidean Distance between the users gives us the following results as shown in Table 2: euclidean = scipy.spatial.distance.cdist(df_choices, df_choices, metric='euclidean')user_distance = pd.DataFrame(euclidean, columns=df_choices.index.values, index=df_choices.index.values) Even though we see that User A and User B both chose more of the same fruits, Euclidean Distance returns an identical distance value of 1.00 for both User B and User C. Why is that so? Euclidean Distance considers joint absences (i. e. both users having a 0 on the same position). Therefore, it also considers User A and User C to be similar, because they both did not choose “Pineapples”. The same principle applies to Cosine Similarity as well. For some use-cases, Euclidean Distance may still be an appropriate measure for binary data, but for our use-case, it gives us wrong results. We do not want to assume users being similar based on selections they did not make. For our aim, we should turn to a measure called Jaccard Distance. TT (True True) is the number of times both users chose the same fruit (i. e. both have 1 at the same position). TF (True False) and FT (False True) are the number of times only one of the users chose a fruit (i. e. a 1 for one user and a 0 for the other on the same position). We do not consider the cases where both users did not choose a fruit. Now let’s look at how the Jaccard Distance rates the similarity of our users: jaccard = scipy.spatial.distance.cdist(df_choices, df_choices, metric='jaccard')user_distance = pd.DataFrame(jaccard, columns=data.index.values, index=data.index.values) From the above table we can see that, indeed, the Jaccard Distance rates User B as being more similar to User A, than User C to User A, because its distance value is lower. This is the result we want to achieve for our use-case. To finalize our task, let’s rank the users by their similarity and export them as a Python dictionary. # prepare a dictionaryuser_rankings = {}# iterate over the columns in the dataframefor user in user_distance.columns: # extract the distances of the column ranked by smallest distance = user_distance[user].nsmallest(len(user_distance)) # for each user, create a key in the dictionary and assign a # list that contains a ranking of its most similar users data = {user : [i for i in distance.index if i!=user]} user_rankings.update(data) The output dictionary will look as following: {'User A': ['User B', 'User C'], 'User B': ['User A', 'User C'], 'User C': ['User A', 'User B']} User A’s choices of favorite fruits are more similar to User B, than to User C. User B’s choices of favorite fruits are more similar to User A, than to User C.User C’s choices of favorite fruits are more similar to User A, than to User B. This article demonstrated how the Jaccard Distance can be an appropriate measure for computing similarities between binary vectors. Nevertheless, always make sure you choose your similarity/distance measures wisely depending on your type of dataset and on what goal you are trying to achieve. [1] A. S. Shirkhorshidi, S. Aghabozorgi S, T. Y. Wah, A Comparison Study on Similarity and Dissimilarity Measures in Clustering Continuous Data (2015), PLoS ONE 10(12): e0144059. [2] IBM, Distances Similarity Measures for Binary Data (2021)
[ { "code": null, "e": 439, "s": 172, "text": "User clustering and computation of similarities has increasingly gained relevance within today’s industries. Customers are asked to give ratings on f. e. specific products, which are then compared to other customers’ ratings in order to find similarities among them." }, { "code": null, "e": 773, "s": 439, "text": "Most user clustering applications make use of scaled ratings, f. e. 0–5 stars, or rating scales of 1–10 like on IMDB. In these cases, we can easily apply measures like Euclidean Distance or Cosine Similarity to find how similar/different the user’s choices are. What if we don’t have such ratings and we are dealing with binary data?" }, { "code": null, "e": 1037, "s": 773, "text": "In this article I will show you why to be careful when using the Euclidean Distance measure on binary data, what measure to alternatively use for computing user similarity and how to create a ranking of these users. I will be using Python 3 with Scipy and Pandas." }, { "code": null, "e": 1077, "s": 1037, "text": "import scipy.spatialimport pandas as pd" }, { "code": null, "e": 1208, "s": 1077, "text": "Let’s assume we have three users: A, B and C. These users all filled out a multiple-choice survey regarding their favorite fruits." }, { "code": null, "e": 1325, "s": 1208, "text": "The user choices can be interpreted as one-hot encoded vectors, whereas the ✔️ is replaced by a 1, and the ❌ by a 0." }, { "code": null, "e": 1600, "s": 1325, "text": "user_choices = [[1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]]df_choices = pd.DataFrame(user_choices, columns=['Apples', 'Bananas', 'Pineapples', 'Kiwis'], index=([\"User A\", \"User B\", \"User C\"]))" }, { "code": null, "e": 1704, "s": 1600, "text": "Why are measures like Euclidean Distance or Cosine Similarity no appropriate measures for this dataset?" }, { "code": null, "e": 1871, "s": 1704, "text": "From a first look at Table 1 we would suggest User A and User B to have a more similar taste, because they both chose “Apples” and “Bananas” as their favorite fruits." }, { "code": null, "e": 1983, "s": 1871, "text": "However, computing the Euclidean Distance between the users gives us the following results as shown in Table 2:" }, { "code": null, "e": 2272, "s": 1983, "text": "euclidean = scipy.spatial.distance.cdist(df_choices, df_choices, metric='euclidean')user_distance = pd.DataFrame(euclidean, columns=df_choices.index.values, index=df_choices.index.values)" }, { "code": null, "e": 2457, "s": 2272, "text": "Even though we see that User A and User B both chose more of the same fruits, Euclidean Distance returns an identical distance value of 1.00 for both User B and User C. Why is that so?" }, { "code": null, "e": 2860, "s": 2457, "text": "Euclidean Distance considers joint absences (i. e. both users having a 0 on the same position). Therefore, it also considers User A and User C to be similar, because they both did not choose “Pineapples”. The same principle applies to Cosine Similarity as well. For some use-cases, Euclidean Distance may still be an appropriate measure for binary data, but for our use-case, it gives us wrong results." }, { "code": null, "e": 2944, "s": 2860, "text": "We do not want to assume users being similar based on selections they did not make." }, { "code": null, "e": 3010, "s": 2944, "text": "For our aim, we should turn to a measure called Jaccard Distance." }, { "code": null, "e": 3357, "s": 3010, "text": "TT (True True) is the number of times both users chose the same fruit (i. e. both have 1 at the same position). TF (True False) and FT (False True) are the number of times only one of the users chose a fruit (i. e. a 1 for one user and a 0 for the other on the same position). We do not consider the cases where both users did not choose a fruit." }, { "code": null, "e": 3435, "s": 3357, "text": "Now let’s look at how the Jaccard Distance rates the similarity of our users:" }, { "code": null, "e": 3675, "s": 3435, "text": "jaccard = scipy.spatial.distance.cdist(df_choices, df_choices, metric='jaccard')user_distance = pd.DataFrame(jaccard, columns=data.index.values, index=data.index.values)" }, { "code": null, "e": 3904, "s": 3675, "text": "From the above table we can see that, indeed, the Jaccard Distance rates User B as being more similar to User A, than User C to User A, because its distance value is lower. This is the result we want to achieve for our use-case." }, { "code": null, "e": 4007, "s": 3904, "text": "To finalize our task, let’s rank the users by their similarity and export them as a Python dictionary." }, { "code": null, "e": 4467, "s": 4007, "text": "# prepare a dictionaryuser_rankings = {}# iterate over the columns in the dataframefor user in user_distance.columns: # extract the distances of the column ranked by smallest distance = user_distance[user].nsmallest(len(user_distance)) # for each user, create a key in the dictionary and assign a # list that contains a ranking of its most similar users data = {user : [i for i in distance.index if i!=user]} user_rankings.update(data)" }, { "code": null, "e": 4513, "s": 4467, "text": "The output dictionary will look as following:" }, { "code": null, "e": 4610, "s": 4513, "text": "{'User A': ['User B', 'User C'], 'User B': ['User A', 'User C'], 'User C': ['User A', 'User B']}" }, { "code": null, "e": 4849, "s": 4610, "text": "User A’s choices of favorite fruits are more similar to User B, than to User C. User B’s choices of favorite fruits are more similar to User A, than to User C.User C’s choices of favorite fruits are more similar to User A, than to User B." }, { "code": null, "e": 4981, "s": 4849, "text": "This article demonstrated how the Jaccard Distance can be an appropriate measure for computing similarities between binary vectors." }, { "code": null, "e": 5142, "s": 4981, "text": "Nevertheless, always make sure you choose your similarity/distance measures wisely depending on your type of dataset and on what goal you are trying to achieve." }, { "code": null, "e": 5321, "s": 5142, "text": "[1] A. S. Shirkhorshidi, S. Aghabozorgi S, T. Y. Wah, A Comparison Study on Similarity and Dissimilarity Measures in Clustering Continuous Data (2015), PLoS ONE 10(12): e0144059." } ]
BMI Calculator using Express.js - GeeksforGeeks
13 Oct, 2021 The Body Mass Index(BMI) is represented in terms of weight and height of an individual. It is the ratio of the weight of the body to the square of the height of the body in kilograms and meters respectively. BMI = (weight of body) / (height of body)2 Unit of weight: Kilogram(Kg); Unit of height: Meter(m); Unit of BMI is kg/m2 Approach: First, we write HTML code for creating a form in which we will take name, height(m), weight(kg) as input from the user. Import require modules and store it into app variable sends html and post the data on the specific route using this app.post("/bmicalculator", function (req, res) { heigh = parseFloat(req.body.Height); weigh = parseFloat(req.body.Weight); bmi = weigh / (heigh * heigh); Check Condition for BMI using formula. Step-1: HTML <!DOCTYPE html><html lang="en"> <head> <!-- title is used to provide a specific name to our web-page! --> <title>BMI-CALCULATOR</title> <!-- link function is used here, so that we can connect our css file with our html file externally --> <link rel="stylesheet" href="1.css" /> </head> <body> <div id="MAIN"> <h1 id="heading">BMI-CALCULATOR</h1> </div> <form action="/bmicalculator" method="post"> <input type="text" name="Name" placeholder="Enter your name!" /> <br /> <input id="Height" name="Height" placeholder="Enter your height(m)" /> <br /> <input id="Weight" name="Weight" placeholder="Enter your weight(kg)" /> <br /> <button class="btn" type="submit">Get-BMI</button> </form> </body></html> Output: SIMPLE FORM Let’s now write code for our calculations and functionalities which is the main part of our BMI-CALCULATOR. Step-2 Dependencies: express: npm install express bodyparser: npm install body-parser Javascript //importing modulesconst express = require("express");const bodyparser = require("body-parser"); // stores the express module into the app variable!const app = express();app.use(bodyparser.urlencoded({ extended: true })); //sends index.htmlapp.get("/bmicalculator", function (req, res) { res.sendFile(__dirname + "/" + "index.html");}); //this is used to post the data on the specific routeapp.post("/bmicalculator", function (req, res) { heigh = parseFloat(req.body.Height); weigh = parseFloat(req.body.Weight); bmi = weigh / (heigh * heigh); //number to string format bmi = bmi.toFixed(); req_name = req.body.Name; // CONDITION FOR BMI if (bmi < 19) { res.send("<h3>hey! " + req_name + " your BMI is around: " + bmi + "<centre><h1>You are Underweight!"); } else if (19 <= bmi && bmi < 25) { res.send("<h3>hey! " + req_name + " your BMI is around: " + bmi + "<centre><h1>You are Normalweight!"); } else if (25 <= bmi && bmi < 30) { res.send("<h3>hey! " + req_name + " your BMI is around: " + bmi + "<centre><h1>You are Overweight!"); } else { res.send("<h3>hey! " + req_name + " your BMI is around: " + bmi + "<centre><h1>You are Obese!"); }}); //this is used to listen a specific port!app.listen(7777, function () { console.log("port active at 7777");}); Output: Final Output: Output sagartomar9927 saurabh1990aror Express.js NodeJS-Questions Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function Express.js req.params Property JWT Authentication with Node.js Mongoose Populate() Method Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25028, "s": 25000, "text": "\n13 Oct, 2021" }, { "code": null, "e": 25236, "s": 25028, "text": "The Body Mass Index(BMI) is represented in terms of weight and height of an individual. It is the ratio of the weight of the body to the square of the height of the body in kilograms and meters respectively." }, { "code": null, "e": 25356, "s": 25236, "text": "BMI = (weight of body) / (height of body)2\nUnit of weight: Kilogram(Kg);\nUnit of height: Meter(m);\nUnit of BMI is kg/m2" }, { "code": null, "e": 25367, "s": 25356, "text": "Approach: " }, { "code": null, "e": 25487, "s": 25367, "text": "First, we write HTML code for creating a form in which we will take name, height(m), weight(kg) as input from the user." }, { "code": null, "e": 25541, "s": 25487, "text": "Import require modules and store it into app variable" }, { "code": null, "e": 25605, "s": 25541, "text": "sends html and post the data on the specific route using this " }, { "code": null, "e": 25771, "s": 25605, "text": "app.post(\"/bmicalculator\", function (req, res) {\n heigh = parseFloat(req.body.Height);\n weigh = parseFloat(req.body.Weight);\n bmi = weigh / (heigh * heigh);" }, { "code": null, "e": 25811, "s": 25771, "text": "Check Condition for BMI using formula. " }, { "code": null, "e": 25819, "s": 25811, "text": "Step-1:" }, { "code": null, "e": 25824, "s": 25819, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- title is used to provide a specific name to our web-page! --> <title>BMI-CALCULATOR</title> <!-- link function is used here, so that we can connect our css file with our html file externally --> <link rel=\"stylesheet\" href=\"1.css\" /> </head> <body> <div id=\"MAIN\"> <h1 id=\"heading\">BMI-CALCULATOR</h1> </div> <form action=\"/bmicalculator\" method=\"post\"> <input type=\"text\" name=\"Name\" placeholder=\"Enter your name!\" /> <br /> <input id=\"Height\" name=\"Height\" placeholder=\"Enter your height(m)\" /> <br /> <input id=\"Weight\" name=\"Weight\" placeholder=\"Enter your weight(kg)\" /> <br /> <button class=\"btn\" type=\"submit\">Get-BMI</button> </form> </body></html>", "e": 26825, "s": 25824, "text": null }, { "code": null, "e": 26833, "s": 26825, "text": "Output:" }, { "code": null, "e": 26845, "s": 26833, "text": "SIMPLE FORM" }, { "code": null, "e": 26953, "s": 26845, "text": "Let’s now write code for our calculations and functionalities which is the main part of our BMI-CALCULATOR." }, { "code": null, "e": 26960, "s": 26953, "text": "Step-2" }, { "code": null, "e": 27045, "s": 26960, "text": "Dependencies: \nexpress: npm install express\nbodyparser: npm install body-parser" }, { "code": null, "e": 27056, "s": 27045, "text": "Javascript" }, { "code": "//importing modulesconst express = require(\"express\");const bodyparser = require(\"body-parser\"); // stores the express module into the app variable!const app = express();app.use(bodyparser.urlencoded({ extended: true })); //sends index.htmlapp.get(\"/bmicalculator\", function (req, res) { res.sendFile(__dirname + \"/\" + \"index.html\");}); //this is used to post the data on the specific routeapp.post(\"/bmicalculator\", function (req, res) { heigh = parseFloat(req.body.Height); weigh = parseFloat(req.body.Weight); bmi = weigh / (heigh * heigh); //number to string format bmi = bmi.toFixed(); req_name = req.body.Name; // CONDITION FOR BMI if (bmi < 19) { res.send(\"<h3>hey! \" + req_name + \" your BMI is around: \" + bmi + \"<centre><h1>You are Underweight!\"); } else if (19 <= bmi && bmi < 25) { res.send(\"<h3>hey! \" + req_name + \" your BMI is around: \" + bmi + \"<centre><h1>You are Normalweight!\"); } else if (25 <= bmi && bmi < 30) { res.send(\"<h3>hey! \" + req_name + \" your BMI is around: \" + bmi + \"<centre><h1>You are Overweight!\"); } else { res.send(\"<h3>hey! \" + req_name + \" your BMI is around: \" + bmi + \"<centre><h1>You are Obese!\"); }}); //this is used to listen a specific port!app.listen(7777, function () { console.log(\"port active at 7777\");});", "e": 28514, "s": 27056, "text": null }, { "code": null, "e": 28524, "s": 28514, "text": "Output: " }, { "code": null, "e": 28540, "s": 28526, "text": "Final Output:" }, { "code": null, "e": 28549, "s": 28542, "text": "Output" }, { "code": null, "e": 28566, "s": 28551, "text": "sagartomar9927" }, { "code": null, "e": 28582, "s": 28566, "text": "saurabh1990aror" }, { "code": null, "e": 28593, "s": 28582, "text": "Express.js" }, { "code": null, "e": 28610, "s": 28593, "text": "NodeJS-Questions" }, { "code": null, "e": 28634, "s": 28610, "text": "Technical Scripter 2020" }, { "code": null, "e": 28642, "s": 28634, "text": "Node.js" }, { "code": null, "e": 28661, "s": 28642, "text": "Technical Scripter" }, { "code": null, "e": 28678, "s": 28661, "text": "Web Technologies" }, { "code": null, "e": 28776, "s": 28678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28813, "s": 28776, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28844, "s": 28813, "text": "Express.js req.params Property" }, { "code": null, "e": 28876, "s": 28844, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 28903, "s": 28876, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28950, "s": 28903, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 28992, "s": 28950, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29035, "s": 28992, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29097, "s": 29035, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29142, "s": 29097, "text": "Convert a string to an integer in JavaScript" } ]
groupmod command in Linux with examples - GeeksforGeeks
20 May, 2019 groupmod command in Linux is used to modify or change the existing group on Linux system. It can be handled by superuser or root user. Basically, it modifies a group definition on the system by modifying the right entry in the database of the group. Syntax: groupmod [option] GROUP Files: The groupmod command has following files. /etc/group: Group Account Information. /etc/gshadow: Secured group account information. /etc/login.def: Shadow passwd suite configuration. /etc/passwd: User account information. Exit Values: 0: Success. 2: Invalid command Syntax. 3: Invalid argument to option. 4: specified group doesn’t exist. 6: specified group doesn’t exist. 9: group name already in use. 10: can’t update group file. Options: There are following option available in groupmod command. -g, –gid GID: The group ID of the given GROUP will be changed to GID. -n, –new-name NEW_GROUP: The name of group will change into newname. -h, –help: This option display help massage and exist. -o, –non-unique: This option used with the -g option that allow to change the group GID to a non-unique value. -p, –password PASSWORD: This gives the encrypted password. -R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory. Example: Below command will change the group group_old to group_new using -n option. groupmod -n group_new group_old linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples
[ { "code": null, "e": 24644, "s": 24616, "text": "\n20 May, 2019" }, { "code": null, "e": 24894, "s": 24644, "text": "groupmod command in Linux is used to modify or change the existing group on Linux system. It can be handled by superuser or root user. Basically, it modifies a group definition on the system by modifying the right entry in the database of the group." }, { "code": null, "e": 24902, "s": 24894, "text": "Syntax:" }, { "code": null, "e": 24926, "s": 24902, "text": "groupmod [option] GROUP" }, { "code": null, "e": 24975, "s": 24926, "text": "Files: The groupmod command has following files." }, { "code": null, "e": 25014, "s": 24975, "text": "/etc/group: Group Account Information." }, { "code": null, "e": 25063, "s": 25014, "text": "/etc/gshadow: Secured group account information." }, { "code": null, "e": 25114, "s": 25063, "text": "/etc/login.def: Shadow passwd suite configuration." }, { "code": null, "e": 25153, "s": 25114, "text": "/etc/passwd: User account information." }, { "code": null, "e": 25166, "s": 25153, "text": "Exit Values:" }, { "code": null, "e": 25178, "s": 25166, "text": "0: Success." }, { "code": null, "e": 25205, "s": 25178, "text": "2: Invalid command Syntax." }, { "code": null, "e": 25236, "s": 25205, "text": "3: Invalid argument to option." }, { "code": null, "e": 25270, "s": 25236, "text": "4: specified group doesn’t exist." }, { "code": null, "e": 25304, "s": 25270, "text": "6: specified group doesn’t exist." }, { "code": null, "e": 25334, "s": 25304, "text": "9: group name already in use." }, { "code": null, "e": 25363, "s": 25334, "text": "10: can’t update group file." }, { "code": null, "e": 25430, "s": 25363, "text": "Options: There are following option available in groupmod command." }, { "code": null, "e": 25500, "s": 25430, "text": "-g, –gid GID: The group ID of the given GROUP will be changed to GID." }, { "code": null, "e": 25569, "s": 25500, "text": "-n, –new-name NEW_GROUP: The name of group will change into newname." }, { "code": null, "e": 25624, "s": 25569, "text": "-h, –help: This option display help massage and exist." }, { "code": null, "e": 25735, "s": 25624, "text": "-o, –non-unique: This option used with the -g option that allow to change the group GID to a non-unique value." }, { "code": null, "e": 25794, "s": 25735, "text": "-p, –password PASSWORD: This gives the encrypted password." }, { "code": null, "e": 25921, "s": 25794, "text": "-R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and use the configuration files from the CHROOT_DIR directory." }, { "code": null, "e": 26006, "s": 25921, "text": "Example: Below command will change the group group_old to group_new using -n option." }, { "code": null, "e": 26038, "s": 26006, "text": "groupmod -n group_new group_old" }, { "code": null, "e": 26052, "s": 26038, "text": "linux-command" }, { "code": null, "e": 26074, "s": 26052, "text": "Linux-system-commands" }, { "code": null, "e": 26081, "s": 26074, "text": "Picked" }, { "code": null, "e": 26092, "s": 26081, "text": "Linux-Unix" }, { "code": null, "e": 26190, "s": 26092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26228, "s": 26190, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26263, "s": 26228, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 26298, "s": 26263, "text": "tar command in Linux with examples" }, { "code": null, "e": 26339, "s": 26298, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 26375, "s": 26339, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26408, "s": 26375, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26446, "s": 26408, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26482, "s": 26446, "text": "diff command in Linux with examples" }, { "code": null, "e": 26520, "s": 26482, "text": "Conditional Statements | Shell Script" } ]
How to print integer array in android Log?
This example demonstrate about How to print integer array in android Log. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_marginTop="30dp" tools:context=".MainActivity"> <ListView android:id="@+id/list" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ListView> </LinearLayout> In the code, we have taken listview to show integer array Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class MainActivity extends AppCompatActivity { ListView list; int[] array = {2, 5, 6, 8, 0, 7, 9, 4}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = findViewById(R.id.list); ArrayList<String> arrayList = new ArrayList<String>(); for(int s:array) { arrayList.add(String.valueOf(s)); } Log.d("Array List: ", Arrays.toString(array)); ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); list.setAdapter(adapter); } } 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, we had shown integer array and now check log in the android studio as shown below – Click here to download the project code
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrate about How to print integer array in android Log." }, { "code": null, "e": 1265, "s": 1136, "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": 1329, "s": 1265, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 1871, "s": 1329, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"30dp\"\n tools:context=\".MainActivity\">\n <ListView\n android:id=\"@+id/list\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 1929, "s": 1871, "text": "In the code, we have taken listview to show integer array" }, { "code": null, "e": 1986, "s": 1929, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2961, "s": 1986, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\nimport android.widget.EditText;\nimport android.widget.ListView;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\n\npublic class MainActivity extends AppCompatActivity {\n ListView list;\n int[] array = {2, 5, 6, 8, 0, 7, 9, 4};\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n list = findViewById(R.id.list);\n ArrayList<String> arrayList = new ArrayList<String>();\n for(int s:array) {\n arrayList.add(String.valueOf(s));\n }\n Log.d(\"Array List: \", Arrays.toString(array));\n ArrayAdapter adapter = new ArrayAdapter<String>(this,\n android.R.layout.simple_list_item_1, arrayList);\n list.setAdapter(adapter);\n }\n}" }, { "code": null, "e": 3308, "s": 2961, "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": 3413, "s": 3308, "text": "In the above result, we had shown integer array and now check log in the android studio as shown below –" }, { "code": null, "e": 3453, "s": 3413, "text": "Click here to download the project code" } ]
Exit Status($?) variable in Linux - GeeksforGeeks
01 Oct, 2020 “$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process. By convention 0 is a successful exit and non-zero indicates some kind of error. It can be used to check if the previous command has been executed without any errors. If it has executed successfully then it stores 0. “$?” is also useful in shell scripts as a way to decide what to do depending on how the last executed command worked by checking the exit status. Working with “$?” operator 1. Its default value is 0 when the system starts and no command has been executed yet. Even if the last command has not been successfully executed and the system is restarted, we get its value as 0 when the following command is entered into the terminal. echo $? 2. It returns the exit status of the last executed command. In the example mentioned below, There is no command as eccho in UNIX and hence the last process was not successfully executed. So $? stores a non-zero value which is the exit status of the last executed command. eccho echo $? 3. In the example mentioned below, If the file exists (can be either directory or file), then the return value by the “ls” command will be 0 (i.e, the command has been successfully executed) else it will display a number which is non-zero. The number depends on the program. Referring to the image below, consider that by default “file” doesn’t exist then $? stores a return value of 2 (the command was not successfully executed) but once created using touch it displays 0 as the ls command returns 0 since the file exists. ls file echo $? touch file echo $? 4. Also, when we enter simple true and false values in the terminal,it displays 0 as true does nothing but exits with a status code 0. But if we give false then 1 will get printed as false exits with status code 1. true echo $? false echo $? linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C 'crontab' in Linux with Examples diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples tee command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 24382, "s": 24354, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25021, "s": 24382, "text": "“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process. By convention 0 is a successful exit and non-zero indicates some kind of error. It can be used to check if the previous command has been executed without any errors. If it has executed successfully then it stores 0. “$?” is also useful in shell scripts as a way to decide what to do depending on how the last executed command worked by checking the exit status." }, { "code": null, "e": 25048, "s": 25021, "text": "Working with “$?” operator" }, { "code": null, "e": 25304, "s": 25048, "text": "1. Its default value is 0 when the system starts and no command has been executed yet. Even if the last command has not been successfully executed and the system is restarted, we get its value as 0 when the following command is entered into the terminal. " }, { "code": null, "e": 25313, "s": 25304, "text": "echo $?\n" }, { "code": null, "e": 25586, "s": 25313, "text": "2. It returns the exit status of the last executed command. In the example mentioned below, There is no command as eccho in UNIX and hence the last process was not successfully executed. So $? stores a non-zero value which is the exit status of the last executed command. " }, { "code": null, "e": 25600, "s": 25586, "text": "eccho\necho $?" }, { "code": null, "e": 26124, "s": 25600, "text": "3. In the example mentioned below, If the file exists (can be either directory or file), then the return value by the “ls” command will be 0 (i.e, the command has been successfully executed) else it will display a number which is non-zero. The number depends on the program. Referring to the image below, consider that by default “file” doesn’t exist then $? stores a return value of 2 (the command was not successfully executed) but once created using touch it displays 0 as the ls command returns 0 since the file exists." }, { "code": null, "e": 26160, "s": 26124, "text": "ls file\necho $?\ntouch file \necho $?" }, { "code": null, "e": 26375, "s": 26160, "text": "4. Also, when we enter simple true and false values in the terminal,it displays 0 as true does nothing but exits with a status code 0. But if we give false then 1 will get printed as false exits with status code 1." }, { "code": null, "e": 26403, "s": 26375, "text": "true\necho $?\nfalse\necho $?\n" }, { "code": null, "e": 26417, "s": 26403, "text": "linux-command" }, { "code": null, "e": 26428, "s": 26417, "text": "Linux-Unix" }, { "code": null, "e": 26526, "s": 26428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26561, "s": 26526, "text": "tar command in Linux with examples" }, { "code": null, "e": 26597, "s": 26561, "text": "curl command in Linux with Examples" }, { "code": null, "e": 26635, "s": 26597, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26668, "s": 26635, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 26704, "s": 26668, "text": "diff command in Linux with examples" }, { "code": null, "e": 26742, "s": 26704, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 26777, "s": 26742, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26813, "s": 26777, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26848, "s": 26813, "text": "tee command in Linux with examples" } ]
How to drop duplicates and keep one in PySpark dataframe - GeeksforGeeks
17 Jun, 2021 In this article, we will discuss how to handle duplicate values in a pyspark dataframe. A dataset may contain repeated rows or repeated data points that are not useful for our task. These repeated values in our dataframe are called duplicate values. To handle duplicate values, we may use a strategy in which we keep the first occurrence of the values and drop the rest. dropduplicates(): Pyspark dataframe provides dropduplicates() function that is used to drop duplicate occurrences of data inside a dataframe. Syntax: dataframe_name.dropDuplicates(Column_name) The function takes Column names as parameters concerning which the duplicate values have to be removed. Creating Dataframe for demonstration: Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatType # Start spark session spark = SparkSession.builder.appName("Student_Info").getOrCreate() # Initialize our data data2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Ritika", 20, "CS32", 84, "Writing"), ("Atirikt", 4, "BB21", 58, "Doctor"), ("Atirikt", 4, "BB21", 78, "Doctor"), ("Ghanshyam", 4, "DD11", 38, "Lawyer"), ("Reshav", 18, "EE43", 56, "Timepass") ] # Define schema schema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True) ]) # read the dataframe df = spark.createDataFrame(data=data2, schema=schema) df.show() Output: Examples 1: This example illustrates the working of dropDuplicates() function over a single column parameter. The dataset is custom-built, so we had defined the schema and used spark.createDataFrame() function to create the dataframe. Python3 # drop duplicates df.dropDuplicates(['Roll Number']).show() # stop Session spark.stop() Output: From the above observation, it is clear that the rows with duplicate Roll Number were removed and only the first occurrence kept in the dataframe. Example 2: This example illustrates the working of dropDuplicates() function over multiple column parameters. The dataset is custom-built so we had defined the schema and used spark.createDataFrame() function to create the dataframe. Python3 # drop duplicates df.dropDuplicates(['Roll Number',"Name"]).show() # stop the session spark.stop() Output: From the above observation, it is clear that the data points with duplicate Roll Numbers and Names were removed and only the first occurrence kept in the dataframe. Note: The data having both the parameters as a duplicate was only removed. In the above example, the Column Name of “Ghanshyam” had a Roll Number duplicate value, but the Name was unique, so it was not removed from the dataframe. Thus, the function considers all the parameters not only one of them. Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe sum() function in Python Iterate over a list in Python How to Install PIP on Windows ? Deque in Python Python String | replace()
[ { "code": null, "e": 24559, "s": 24528, "text": " \n17 Jun, 2021\n" }, { "code": null, "e": 24809, "s": 24559, "text": "In this article, we will discuss how to handle duplicate values in a pyspark dataframe. A dataset may contain repeated rows or repeated data points that are not useful for our task. These repeated values in our dataframe are called duplicate values." }, { "code": null, "e": 24931, "s": 24809, "text": "To handle duplicate values, we may use a strategy in which we keep the first occurrence of the values and drop the rest. " }, { "code": null, "e": 25073, "s": 24931, "text": "dropduplicates(): Pyspark dataframe provides dropduplicates() function that is used to drop duplicate occurrences of data inside a dataframe." }, { "code": null, "e": 25124, "s": 25073, "text": "Syntax: dataframe_name.dropDuplicates(Column_name)" }, { "code": null, "e": 25228, "s": 25124, "text": "The function takes Column names as parameters concerning which the duplicate values have to be removed." }, { "code": null, "e": 25266, "s": 25228, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 25274, "s": 25266, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module \nimport pyspark \n \n# importing sparksession from pyspark.sql module \nfrom pyspark.sql import SparkSession \nfrom pyspark.sql.types import StructType, StructField, \nStringType, IntegerType, FloatType \n \n# Start spark session \nspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() \n \n# Initialize our data \ndata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), \n (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), \n (\"Ritika\", 20, \"CS32\", 84, \"Writing\"), \n (\"Atirikt\", 4, \"BB21\", 58, \"Doctor\"), \n (\"Atirikt\", 4, \"BB21\", 78, \"Doctor\"), \n (\"Ghanshyam\", 4, \"DD11\", 38, \"Lawyer\"), \n (\"Reshav\", 18, \"EE43\", 56, \"Timepass\") \n ] \n \n# Define schema \nschema = StructType([ \n StructField(\"Name\", StringType(), True), \n StructField(\"Roll Number\", IntegerType(), True), \n StructField(\"Class ID\", StringType(), True), \n StructField(\"Marks\", IntegerType(), True), \n StructField(\"Extracurricular\", StringType(), True) \n]) \n \n# read the dataframe \ndf = spark.createDataFrame(data=data2, schema=schema) \ndf.show() \n\n\n\n\n\n", "e": 26386, "s": 25284, "text": null }, { "code": null, "e": 26394, "s": 26386, "text": "Output:" }, { "code": null, "e": 26629, "s": 26394, "text": "Examples 1: This example illustrates the working of dropDuplicates() function over a single column parameter. The dataset is custom-built, so we had defined the schema and used spark.createDataFrame() function to create the dataframe." }, { "code": null, "e": 26637, "s": 26629, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# drop duplicates \ndf.dropDuplicates(['Roll Number']).show() \n \n# stop Session \nspark.stop()\n\n\n\n\n\n", "e": 26754, "s": 26647, "text": null }, { "code": null, "e": 26762, "s": 26754, "text": "Output:" }, { "code": null, "e": 26909, "s": 26762, "text": "From the above observation, it is clear that the rows with duplicate Roll Number were removed and only the first occurrence kept in the dataframe." }, { "code": null, "e": 27143, "s": 26909, "text": "Example 2: This example illustrates the working of dropDuplicates() function over multiple column parameters. The dataset is custom-built so we had defined the schema and used spark.createDataFrame() function to create the dataframe." }, { "code": null, "e": 27151, "s": 27143, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# drop duplicates \ndf.dropDuplicates(['Roll Number',\"Name\"]).show() \n \n# stop the session \nspark.stop()\n\n\n\n\n\n", "e": 27279, "s": 27161, "text": null }, { "code": null, "e": 27287, "s": 27279, "text": "Output:" }, { "code": null, "e": 27452, "s": 27287, "text": "From the above observation, it is clear that the data points with duplicate Roll Numbers and Names were removed and only the first occurrence kept in the dataframe." }, { "code": null, "e": 27752, "s": 27452, "text": "Note: The data having both the parameters as a duplicate was only removed. In the above example, the Column Name of “Ghanshyam” had a Roll Number duplicate value, but the Name was unique, so it was not removed from the dataframe. Thus, the function considers all the parameters not only one of them." }, { "code": null, "e": 27761, "s": 27752, "text": "\nPicked\n" }, { "code": null, "e": 27778, "s": 27761, "text": "\nPython-Pyspark\n" }, { "code": null, "e": 27787, "s": 27778, "text": "\nPython\n" }, { "code": null, "e": 27992, "s": 27787, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28010, "s": 27992, "text": "Python Dictionary" }, { "code": null, "e": 28032, "s": 28010, "text": "Enumerate() in Python" }, { "code": null, "e": 28067, "s": 28032, "text": "Read a file line by line in Python" }, { "code": null, "e": 28089, "s": 28067, "text": "Defaultdict in Python" }, { "code": null, "e": 28131, "s": 28089, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28156, "s": 28131, "text": "sum() function in Python" }, { "code": null, "e": 28186, "s": 28156, "text": "Iterate over a list in Python" }, { "code": null, "e": 28218, "s": 28186, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28234, "s": 28218, "text": "Deque in Python" } ]
How to get last day of a month from date in PHP ?
19 May, 2020 Given a date and the task is to print the last day of the month. We will use date() and strtotime() function to get the last day of the month. Used PHP functions: date() function: Format a local time/date. strtotime() function: Parse about any English textual datetime description into a Unix timestamp. Examples: Input: 2020-04-23 Output: Thursday Input: '2018-09-11' Output: Sunday Approach: Given a date stored in a variable as a string, the step is to convert it into date format using strtotime() function. Once we get the date, we will employ date() method.Syntax:date( $format, $timestamp ) date( $format, $timestamp ) Within $format, we will pass “Y-m-t” and within $timestamp the date taken above. In terms of date “Y” gives a full numeric representation of a year in 4 digits, “m” provides numeric representation of a month and “t” gives the number of days in the given month. By using “Y-m-t”, we will get the number of days in a month because of “t”, “m” and “Y” will provide the month and the year. The last step is to use the date() again with “l” for format and the date achieved above as $timestamp. Display the day. Program: <?php // Given a date in string format $datestring = '2020-04-23'; // Converting string to date$date = strtotime($datestring); // Last date of current month.$lastdate = strtotime(date("Y-m-t", $date )); // Day of the last date $day = date("l", $lastdate); echo $day;?> Thursday PHP-function 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2020" }, { "code": null, "e": 171, "s": 28, "text": "Given a date and the task is to print the last day of the month. We will use date() and strtotime() function to get the last day of the month." }, { "code": null, "e": 191, "s": 171, "text": "Used PHP functions:" }, { "code": null, "e": 234, "s": 191, "text": "date() function: Format a local time/date." }, { "code": null, "e": 332, "s": 234, "text": "strtotime() function: Parse about any English textual datetime description into a Unix timestamp." }, { "code": null, "e": 342, "s": 332, "text": "Examples:" }, { "code": null, "e": 413, "s": 342, "text": "Input: 2020-04-23\nOutput: Thursday\n\nInput: '2018-09-11'\nOutput: Sunday" }, { "code": null, "e": 423, "s": 413, "text": "Approach:" }, { "code": null, "e": 541, "s": 423, "text": "Given a date stored in a variable as a string, the step is to convert it into date format using strtotime() function." }, { "code": null, "e": 627, "s": 541, "text": "Once we get the date, we will employ date() method.Syntax:date( $format, $timestamp )" }, { "code": null, "e": 655, "s": 627, "text": "date( $format, $timestamp )" }, { "code": null, "e": 916, "s": 655, "text": "Within $format, we will pass “Y-m-t” and within $timestamp the date taken above. In terms of date “Y” gives a full numeric representation of a year in 4 digits, “m” provides numeric representation of a month and “t” gives the number of days in the given month." }, { "code": null, "e": 1041, "s": 916, "text": "By using “Y-m-t”, we will get the number of days in a month because of “t”, “m” and “Y” will provide the month and the year." }, { "code": null, "e": 1145, "s": 1041, "text": "The last step is to use the date() again with “l” for format and the date achieved above as $timestamp." }, { "code": null, "e": 1162, "s": 1145, "text": "Display the day." }, { "code": null, "e": 1171, "s": 1162, "text": "Program:" }, { "code": "<?php // Given a date in string format $datestring = '2020-04-23'; // Converting string to date$date = strtotime($datestring); // Last date of current month.$lastdate = strtotime(date(\"Y-m-t\", $date )); // Day of the last date $day = date(\"l\", $lastdate); echo $day;?>", "e": 1449, "s": 1171, "text": null }, { "code": null, "e": 1459, "s": 1449, "text": "Thursday\n" }, { "code": null, "e": 1472, "s": 1459, "text": "PHP-function" }, { "code": null, "e": 1479, "s": 1472, "text": "Picked" }, { "code": null, "e": 1483, "s": 1479, "text": "PHP" }, { "code": null, "e": 1496, "s": 1483, "text": "PHP Programs" }, { "code": null, "e": 1513, "s": 1496, "text": "Web Technologies" }, { "code": null, "e": 1540, "s": 1513, "text": "Web technologies Questions" }, { "code": null, "e": 1544, "s": 1540, "text": "PHP" } ]
Code Bloating in C++ with Examples
31 May, 2020 Code bloat is the production of code that is perceived as unnecessarily long, slow, or otherwise wasteful of resources. It is a problem in Software Development which makes the length of the code of software long unnecessarily. So for writing the quality code, we always avoid code bloating in our program. Following are some reasons for the Code Bloating: Headers: Suppose we have declare some functions in Header File as shown below:#include <vector> // Function to find the sum of elements// in a vectorinline int findSum(vector<int>& arr, int N){ int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; } return sum;} struct GfG { // Declare vector arr std::vector<int> arr; // Function int execute() const { return findSum(arr, arr.size()); }};In the above header file, both the functions execute() and findSum() compiles every time when we use the above header file in any source code separately. If we include any header file and doesn’t use any of the function from that header it will still compile the functionality and every other feature of the header files every time which slows the built time of every Software. When the project is large, it contains hundreds of source files, and every function defined in the header compiled hundreds of times. This practice of writing code for Software Development results in Code Bloating i.e., unnecessarily declaration of functionality. #include <vector> // Function to find the sum of elements// in a vectorinline int findSum(vector<int>& arr, int N){ int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; } return sum;} struct GfG { // Declare vector arr std::vector<int> arr; // Function int execute() const { return findSum(arr, arr.size()); }}; In the above header file, both the functions execute() and findSum() compiles every time when we use the above header file in any source code separately. If we include any header file and doesn’t use any of the function from that header it will still compile the functionality and every other feature of the header files every time which slows the built time of every Software. When the project is large, it contains hundreds of source files, and every function defined in the header compiled hundreds of times. This practice of writing code for Software Development results in Code Bloating i.e., unnecessarily declaration of functionality. Templates:In C++ we have built-in templates for functions and containers. Templates are the generalized form of functionality with different data types. Every instance of a template is a completely separate piece of code generated by the compiler.Consider below an example for templates:template <class T>T findSum(const T* arr, int num){ return accumulate(arr, arr + num, T(0));} template <class T, int N>struct GfG { T arr[N]; T run() const { T res = 0; for (int i = 0; i < N; i++) res += arr[i]; return res; }};In the above template function findSum() is compiled once per each used type of template parameter T.The function in GfG::run() is compiled as many times as there are different pairs for which the method run() is called. This function can take more time for changing values of N. There are various techniques to overcome this problem. The problem with headers also applies to templates, because templates are almost always defined in header files.There are two ways to overcome this problem:Define template functions in source file and explicitly instantiate them.Use extern template declarations in header, combined with explicit template instantiations in source files itself. template <class T>T findSum(const T* arr, int num){ return accumulate(arr, arr + num, T(0));} template <class T, int N>struct GfG { T arr[N]; T run() const { T res = 0; for (int i = 0; i < N; i++) res += arr[i]; return res; }}; In the above template function findSum() is compiled once per each used type of template parameter T.The function in GfG::run() is compiled as many times as there are different pairs for which the method run() is called. This function can take more time for changing values of N. There are various techniques to overcome this problem. The problem with headers also applies to templates, because templates are almost always defined in header files. There are two ways to overcome this problem: Define template functions in source file and explicitly instantiate them.Use extern template declarations in header, combined with explicit template instantiations in source files itself. Define template functions in source file and explicitly instantiate them. Use extern template declarations in header, combined with explicit template instantiations in source files itself. Program: #include <iostream>using namespace std; // Driver Codeint main(){ // Code Bloating string str("GeeksForGeeks"); // Print string str cout << str << endl; return 0;} GeeksForGeeks The above program will work perfectly and will print GeeksForGeeks. But there is a problem of code bloating in above program in first line of main function. The agenda of above program is to print the string GeeksForGeeks, So why we are creating object of string class as it result in creating string class object.We simply could write cout << "GeeksForGeeks" << endl; Effects of Code Bloat: It creates object of some classes unnecessarily that can make our software slow in execution. It is a problem in Software Development which made the length of code of software long unnecessarily. C++-Misc C++ C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ program for hashing with chaining
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2020" }, { "code": null, "e": 334, "s": 28, "text": "Code bloat is the production of code that is perceived as unnecessarily long, slow, or otherwise wasteful of resources. It is a problem in Software Development which makes the length of the code of software long unnecessarily. So for writing the quality code, we always avoid code bloating in our program." }, { "code": null, "e": 384, "s": 334, "text": "Following are some reasons for the Code Bloating:" }, { "code": null, "e": 1470, "s": 384, "text": "Headers: Suppose we have declare some functions in Header File as shown below:#include <vector> // Function to find the sum of elements// in a vectorinline int findSum(vector<int>& arr, int N){ int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; } return sum;} struct GfG { // Declare vector arr std::vector<int> arr; // Function int execute() const { return findSum(arr, arr.size()); }};In the above header file, both the functions execute() and findSum() compiles every time when we use the above header file in any source code separately. If we include any header file and doesn’t use any of the function from that header it will still compile the functionality and every other feature of the header files every time which slows the built time of every Software. When the project is large, it contains hundreds of source files, and every function defined in the header compiled hundreds of times. This practice of writing code for Software Development results in Code Bloating i.e., unnecessarily declaration of functionality." }, { "code": "#include <vector> // Function to find the sum of elements// in a vectorinline int findSum(vector<int>& arr, int N){ int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; } return sum;} struct GfG { // Declare vector arr std::vector<int> arr; // Function int execute() const { return findSum(arr, arr.size()); }};", "e": 1837, "s": 1470, "text": null }, { "code": null, "e": 2479, "s": 1837, "text": "In the above header file, both the functions execute() and findSum() compiles every time when we use the above header file in any source code separately. If we include any header file and doesn’t use any of the function from that header it will still compile the functionality and every other feature of the header files every time which slows the built time of every Software. When the project is large, it contains hundreds of source files, and every function defined in the header compiled hundreds of times. This practice of writing code for Software Development results in Code Bloating i.e., unnecessarily declaration of functionality." }, { "code": null, "e": 3720, "s": 2479, "text": "Templates:In C++ we have built-in templates for functions and containers. Templates are the generalized form of functionality with different data types. Every instance of a template is a completely separate piece of code generated by the compiler.Consider below an example for templates:template <class T>T findSum(const T* arr, int num){ return accumulate(arr, arr + num, T(0));} template <class T, int N>struct GfG { T arr[N]; T run() const { T res = 0; for (int i = 0; i < N; i++) res += arr[i]; return res; }};In the above template function findSum() is compiled once per each used type of template parameter T.The function in GfG::run() is compiled as many times as there are different pairs for which the method run() is called. This function can take more time for changing values of N. There are various techniques to overcome this problem. The problem with headers also applies to templates, because templates are almost always defined in header files.There are two ways to overcome this problem:Define template functions in source file and explicitly instantiate them.Use extern template declarations in header, combined with explicit template instantiations in source files itself." }, { "code": "template <class T>T findSum(const T* arr, int num){ return accumulate(arr, arr + num, T(0));} template <class T, int N>struct GfG { T arr[N]; T run() const { T res = 0; for (int i = 0; i < N; i++) res += arr[i]; return res; }};", "e": 3996, "s": 3720, "text": null }, { "code": null, "e": 4444, "s": 3996, "text": "In the above template function findSum() is compiled once per each used type of template parameter T.The function in GfG::run() is compiled as many times as there are different pairs for which the method run() is called. This function can take more time for changing values of N. There are various techniques to overcome this problem. The problem with headers also applies to templates, because templates are almost always defined in header files." }, { "code": null, "e": 4489, "s": 4444, "text": "There are two ways to overcome this problem:" }, { "code": null, "e": 4677, "s": 4489, "text": "Define template functions in source file and explicitly instantiate them.Use extern template declarations in header, combined with explicit template instantiations in source files itself." }, { "code": null, "e": 4751, "s": 4677, "text": "Define template functions in source file and explicitly instantiate them." }, { "code": null, "e": 4866, "s": 4751, "text": "Use extern template declarations in header, combined with explicit template instantiations in source files itself." }, { "code": null, "e": 4875, "s": 4866, "text": "Program:" }, { "code": "#include <iostream>using namespace std; // Driver Codeint main(){ // Code Bloating string str(\"GeeksForGeeks\"); // Print string str cout << str << endl; return 0;}", "e": 5057, "s": 4875, "text": null }, { "code": null, "e": 5072, "s": 5057, "text": "GeeksForGeeks\n" }, { "code": null, "e": 5408, "s": 5072, "text": "The above program will work perfectly and will print GeeksForGeeks. But there is a problem of code bloating in above program in first line of main function. The agenda of above program is to print the string GeeksForGeeks, So why we are creating object of string class as it result in creating string class object.We simply could write" }, { "code": null, "e": 5443, "s": 5408, "text": "cout << \"GeeksForGeeks\" << endl; \n" }, { "code": null, "e": 5466, "s": 5443, "text": "Effects of Code Bloat:" }, { "code": null, "e": 5560, "s": 5466, "text": "It creates object of some classes unnecessarily that can make our software slow in execution." }, { "code": null, "e": 5662, "s": 5560, "text": "It is a problem in Software Development which made the length of code of software long unnecessarily." }, { "code": null, "e": 5675, "s": 5662, "text": "C++-Misc C++" }, { "code": null, "e": 5679, "s": 5675, "text": "C++" }, { "code": null, "e": 5692, "s": 5679, "text": "C++ Programs" }, { "code": null, "e": 5696, "s": 5692, "text": "CPP" }, { "code": null, "e": 5794, "s": 5696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5818, "s": 5794, "text": "Sorting a vector in C++" }, { "code": null, "e": 5838, "s": 5818, "text": "Polymorphism in C++" }, { "code": null, "e": 5863, "s": 5838, "text": "std::string class in C++" }, { "code": null, "e": 5896, "s": 5863, "text": "Friend class and function in C++" }, { "code": null, "e": 5940, "s": 5896, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 5975, "s": 5940, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 6009, "s": 5975, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 6053, "s": 6009, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 6112, "s": 6053, "text": "How to return multiple values from a function in C or C++?" } ]
Python program to find the first day of given year
02 Aug, 2019 Given a year as input, write a Python to find the starting day of the given year. We will use Python datetime library in order to solve this problem. Example: Input : 2010 Output :Friday Input :2019 Output :Tuesday Below is the implementation: # Python program to find the first day of given year # import datetime libraryimport datetime def Startingday(year): # Creating an object for 1st January of that particular year # For that we are passing three argument (1) year (2) month # i.e 1 for january (3) date i.e 1 for starting day of # that particular year a = datetime.datetime(year, 1, 1) # for printing Startingday of a particular year # we are using a.strftime("% A") print("Starting day of year ", year, " is ", a.strftime("%A")) # Driver Codeyear = 2010Startingday(year) Starting day of year 2010 is Friday Python Calander-module Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Aug, 2019" }, { "code": null, "e": 202, "s": 52, "text": "Given a year as input, write a Python to find the starting day of the given year. We will use Python datetime library in order to solve this problem." }, { "code": null, "e": 211, "s": 202, "text": "Example:" }, { "code": null, "e": 269, "s": 211, "text": "Input : 2010\nOutput :Friday\n\nInput :2019\nOutput :Tuesday\n" }, { "code": null, "e": 298, "s": 269, "text": "Below is the implementation:" }, { "code": "# Python program to find the first day of given year # import datetime libraryimport datetime def Startingday(year): # Creating an object for 1st January of that particular year # For that we are passing three argument (1) year (2) month # i.e 1 for january (3) date i.e 1 for starting day of # that particular year a = datetime.datetime(year, 1, 1) # for printing Startingday of a particular year # we are using a.strftime(\"% A\") print(\"Starting day of year \", year, \" is \", a.strftime(\"%A\")) # Driver Codeyear = 2010Startingday(year)", "e": 871, "s": 298, "text": null }, { "code": null, "e": 911, "s": 871, "text": "Starting day of year 2010 is Friday\n" }, { "code": null, "e": 934, "s": 911, "text": "Python Calander-module" }, { "code": null, "e": 941, "s": 934, "text": "Python" }, { "code": null, "e": 957, "s": 941, "text": "Python Programs" }, { "code": null, "e": 1055, "s": 957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1087, "s": 1055, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1108, "s": 1087, "text": "Python OOPs Concepts" }, { "code": null, "e": 1135, "s": 1108, "text": "Python Classes and Objects" }, { "code": null, "e": 1158, "s": 1135, "text": "Introduction To PYTHON" }, { "code": null, "e": 1189, "s": 1158, "text": "Python | os.path.join() method" }, { "code": null, "e": 1211, "s": 1189, "text": "Defaultdict in Python" }, { "code": null, "e": 1250, "s": 1211, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1288, "s": 1250, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1325, "s": 1288, "text": "Python Program for Fibonacci numbers" } ]
map::begin() and end() in C++ STL
13 Jun, 2022 Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. begin() function is used to return an iterator pointing to the first element of the map container. begin() function returns a bidirectional iterator to the first element of the container. Syntax : mapname.begin() Parameters : No parameters are passed. Returns : This function returns a bidirectional iterator pointing to the first element. Examples: Input : mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; mymap.begin(); Output : returns an iterator to the element 'a' = 1 Input : mymap['d'] = 1; mymap.begin(); Output : returns an iterator to the element 'd' = 1 Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){ // declaration of map container map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; // using begin() to print map for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << " = " << it->second << '\n'; return 0;} Output: a = 1 b = 2 c = 3 end() function is used to return an iterator pointing to past the last element of the map container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator. Syntax : mapname.end() Parameters : No parameters are passed. Returns : This function returns a bidirectional iterator pointing to the next of last element. Examples: Input : mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; mymap.end(); Output : returns an iterator to next to c (after last element) Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // CPP program to illustrate// Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){ // declaration of map container map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; // using begin() to print map for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << " = " << it->second << '\n'; return 0;} Output: a = 1 b = 2 c = 3 Let us see the differences in a tabular form -: Its syntax is -: iterator begin(); mayank007rawa cpp-map STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 221, "s": 52, "text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values." }, { "code": null, "e": 418, "s": 221, "text": "begin() function is used to return an iterator pointing to the first element of the map container. begin() function returns a bidirectional iterator to the first element of the container. Syntax :" }, { "code": null, "e": 561, "s": 418, "text": "mapname.begin()\nParameters :\nNo parameters are passed.\nReturns :\nThis function returns a bidirectional\niterator pointing to the first element." }, { "code": null, "e": 571, "s": 561, "text": "Examples:" }, { "code": null, "e": 824, "s": 571, "text": "Input : mymap['a'] = 1;\n mymap['b'] = 2;\n mymap['c'] = 3;\n mymap.begin();\nOutput : returns an iterator to the element 'a' = 1\n\nInput : mymap['d'] = 1;\n mymap.begin();\nOutput : returns an iterator to the element 'd' = 1" }, { "code": null, "e": 932, "s": 824, "text": "Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 936, "s": 932, "text": "CPP" }, { "code": "// Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){ // declaration of map container map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; // using begin() to print map for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << \" = \" << it->second << '\\n'; return 0;}", "e": 1335, "s": 936, "text": null }, { "code": null, "e": 1343, "s": 1335, "text": "Output:" }, { "code": null, "e": 1361, "s": 1343, "text": "a = 1\nb = 2\nc = 3" }, { "code": null, "e": 1588, "s": 1361, "text": "end() function is used to return an iterator pointing to past the last element of the map container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator. Syntax :" }, { "code": null, "e": 1736, "s": 1588, "text": "mapname.end()\nParameters :\nNo parameters are passed.\nReturns :\nThis function returns a bidirectional\niterator pointing to the next of last element." }, { "code": null, "e": 1746, "s": 1736, "text": "Examples:" }, { "code": null, "e": 1907, "s": 1746, "text": "Input : mymap['a'] = 1;\n mymap['b'] = 2;\n mymap['c'] = 3;\n mymap.end();\nOutput : returns an iterator to next to c \n(after last element)" }, { "code": null, "e": 2015, "s": 1907, "text": "Errors and Exceptions 1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 2019, "s": 2015, "text": "CPP" }, { "code": "// CPP program to illustrate// Demonstrates begin() and end()#include <iostream>#include <map>using namespace std; int main(){ // declaration of map container map<char, int> mymap; mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; // using begin() to print map for (auto it = mymap.begin(); it != mymap.end(); ++it) cout << it->first << \" = \" << it->second << '\\n'; return 0;}", "e": 2446, "s": 2019, "text": null }, { "code": null, "e": 2454, "s": 2446, "text": "Output:" }, { "code": null, "e": 2472, "s": 2454, "text": "a = 1\nb = 2\nc = 3" }, { "code": null, "e": 2520, "s": 2472, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 2537, "s": 2520, "text": "Its syntax is -:" }, { "code": null, "e": 2555, "s": 2537, "text": "iterator begin();" }, { "code": null, "e": 2569, "s": 2555, "text": "mayank007rawa" }, { "code": null, "e": 2577, "s": 2569, "text": "cpp-map" }, { "code": null, "e": 2581, "s": 2577, "text": "STL" }, { "code": null, "e": 2585, "s": 2581, "text": "C++" }, { "code": null, "e": 2589, "s": 2585, "text": "STL" }, { "code": null, "e": 2593, "s": 2589, "text": "CPP" } ]
View Computer’s Important Network Information Using Python
11 Oct, 2020 While working in a network, we do some troubleshooting with the network or Internet problem. This time we need to check your own system network connection information. We can find the network connection in the Control Panel in Windows. The best way to find this information we can use ipconfig command in CMD. When you use ipconfig /all then you can get enough information to resolve your network problem. Examples: Method 1: We will use the subprocess module to interact with cmd and to retrieve information into your python ide. We can read the cmd command through the subprocess module. Approach: import moduleGet the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output()Now get the Split the string and arrange your data with your own needs. import module Get the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output() Now get the Split the string and arrange your data with your own needs. Python3 # import moduleimport subprocess # Traverse the ipconfig informationdata = subprocess.check_output(['ipconfig','/all']).decode('utf-8').split('\n') # Arrange the bytes datafor item in data: print(item.split('\r')[:-1]) Output: Method 2: Ifcfg module is a cross-platform (Windows/Unix) library for parsing ifconfig and ipconfig output in Python. It is useful for pulling information such as IP, Netmask, MAC Address, Hostname, etc. Installation: pip install ifcfg Implementation: Python3 import ifcfgprint(ifcfg.interfaces()) Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2020" }, { "code": null, "e": 196, "s": 28, "text": "While working in a network, we do some troubleshooting with the network or Internet problem. This time we need to check your own system network connection information." }, { "code": null, "e": 434, "s": 196, "text": "We can find the network connection in the Control Panel in Windows. The best way to find this information we can use ipconfig command in CMD. When you use ipconfig /all then you can get enough information to resolve your network problem." }, { "code": null, "e": 444, "s": 434, "text": "Examples:" }, { "code": null, "e": 454, "s": 444, "text": "Method 1:" }, { "code": null, "e": 618, "s": 454, "text": "We will use the subprocess module to interact with cmd and to retrieve information into your python ide. We can read the cmd command through the subprocess module." }, { "code": null, "e": 628, "s": 618, "text": "Approach:" }, { "code": null, "e": 796, "s": 628, "text": "import moduleGet the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output()Now get the Split the string and arrange your data with your own needs." }, { "code": null, "e": 810, "s": 796, "text": "import module" }, { "code": null, "e": 894, "s": 810, "text": "Get the output for the command “‘ipconfig’,’/all’ ” using subprocess.check_output()" }, { "code": null, "e": 966, "s": 894, "text": "Now get the Split the string and arrange your data with your own needs." }, { "code": null, "e": 974, "s": 966, "text": "Python3" }, { "code": "# import moduleimport subprocess # Traverse the ipconfig informationdata = subprocess.check_output(['ipconfig','/all']).decode('utf-8').split('\\n') # Arrange the bytes datafor item in data: print(item.split('\\r')[:-1])", "e": 1199, "s": 974, "text": null }, { "code": null, "e": 1207, "s": 1199, "text": "Output:" }, { "code": null, "e": 1217, "s": 1207, "text": "Method 2:" }, { "code": null, "e": 1411, "s": 1217, "text": "Ifcfg module is a cross-platform (Windows/Unix) library for parsing ifconfig and ipconfig output in Python. It is useful for pulling information such as IP, Netmask, MAC Address, Hostname, etc." }, { "code": null, "e": 1425, "s": 1411, "text": "Installation:" }, { "code": null, "e": 1445, "s": 1425, "text": "pip install ifcfg\n\n" }, { "code": null, "e": 1461, "s": 1445, "text": "Implementation:" }, { "code": null, "e": 1469, "s": 1461, "text": "Python3" }, { "code": "import ifcfgprint(ifcfg.interfaces())", "e": 1507, "s": 1469, "text": null }, { "code": null, "e": 1515, "s": 1507, "text": "Output:" }, { "code": null, "e": 1530, "s": 1515, "text": "python-utility" }, { "code": null, "e": 1537, "s": 1530, "text": "Python" } ]
Find Recurring Sequence in a Fraction
30 Jun, 2022 Given a fraction, find a recurring sequence of digits if it exists, otherwise, print “No recurring sequence”. Examples: Input : Numerator = 8, Denominator = 3 Output : Recurring sequence is 6 Explanation : 8/3 = 2.66666666....... Input : Numerator = 50, Denominator = 22 Output : Recurring sequence is 27 Explanation : 50/22 = 2.272727272..... Input : Numerator = 11, Denominator = 2 Output : No recurring sequence Explanation : 11/2 = 5.5 When does the fractional part repeat?Let us simulate the process of converting fractions to decimals. Let us look at the part where we have already figured out the integer part, which is floor(numerator/denominator). Now we are left with ( remainder = numerator%denominator ) / denominator. If you remember the process of converting to decimal, at each step we do the following : Multiply the remainder by 10.Append the remainder/denominator to the result.Remainder = remainder % denominator. Multiply the remainder by 10. Append the remainder/denominator to the result. Remainder = remainder % denominator. At any moment, if the remainder becomes 0, we are done.However, when there is a recurring sequence, the remainder never becomes 0. For example, if you look at 1/3, the remainder never becomes 0. Below is one important observation : If we start with the remainder ‘rem’ and if the remainder repeats at any point in time, the digits between the two occurrences of ‘rem’ keep repeating.So the idea is to store seen remainders in a map. Whenever a remainder repeats, we return the sequence before the next occurrence. Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to find repeating// sequence in a fraction#include <bits/stdc++.h>using namespace std; // This function returns repeating sequence of// a fraction. If repeating sequence doesn't// exits, then returns empty stringstring fractionToDecimal(int numr, int denr){ string res; // Initialize result // Create a map to store already // seen remainders remainder is used // as key and its position in // result is stored as value. // Note that we need // position for cases like 1/6. // In this case,the recurring sequence // doesn't start from first // remainder. map<int, int> mp; mp.clear(); // Find first remainder int rem = numr % denr; // Keep finding remainder until either remainder // becomes 0 or repeats while ((rem != 0) && (mp.find(rem) == mp.end())) { // Store this remainder mp[rem] = res.length(); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += to_string(res_part); // Update remainder rem = rem % denr; } return (rem == 0) ? "" : res.substr(mp[rem]);} // Driver codeint main(){ int numr = 50, denr = 22; string res = fractionToDecimal(numr, denr); if (res == "") cout << "No recurring sequence"; else cout << "Recurring sequence is " << res; return 0;} // Java program to find// repeating sequence// in a fractionimport java.util.*;class GFG { // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String static String fractionToDecimal(int numr, int denr) { // Initialize result String res = ""; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. HashMap<Integer, Integer> mp = new HashMap<>(); mp.clear(); // Find first remainder int rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 or repeats while ((rem != 0) && (!mp.containsKey(rem))) { // Store this remainder mp.put(rem, res.length()); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += String.valueOf(res_part); // Update remainder rem = rem % denr; } if (rem == 0) return ""; else if (mp.containsKey(rem)) return res.substring(mp.get(rem)); return ""; } // Driver code public static void main(String[] args) { int numr = 50, denr = 22; String res = fractionToDecimal(numr, denr); if (res == "") System.out.print("No recurring sequence"); else System.out.print("Recurring sequence is " + res); }} // This code is contributed by gauravrajput1 # Python3 program to find repeating# sequence in a fraction # This function returns repeating sequence# of a fraction.If repeating sequence doesn't# exits, then returns empty string def fractionToDecimal(numr, denr): # Initialize result res = "" # Create a map to store already seen # remainders. Remainder is used as key # and its position in result is stored # as value. Note that we need position # for cases like 1/6. In this case, # the recurring sequence doesn't start # from first remainder. mp = {} # Find first remainder rem = numr % denr # Keep finding remainder until either # remainder becomes 0 or repeats while ((rem != 0) and (rem not in mp)): # Store this remainder mp[rem] = len(res) # Multiply remainder with 10 rem = rem * 10 # Append rem / denr to result res_part = rem // denr res += str(res_part) # Update remainder rem = rem % denr if (rem == 0): return "" else: return res[mp[rem]:] # Driver codenumr, denr = 50, 22res = fractionToDecimal(numr, denr) if (res == ""): print("No recurring sequence")else: print("Recurring sequence is", res) # This code is contributed by divyeshrabadiya07 // C# program to find repeating sequence// in a fractionusing System;using System.Collections.Generic; class GFG { // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String static string fractionToDecimal(int numr, int denr) { // Initialize result string res = ""; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. Dictionary<int, int> mp = new Dictionary<int, int>(); // Find first remainder int rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 // or repeats while ((rem != 0) && (!mp.ContainsKey(rem))) { // Store this remainder mp[rem] = res.Length; // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += res_part.ToString(); // Update remainder rem = rem % denr; } if (rem == 0) return ""; else if (mp.ContainsKey(rem)) return res.Substring(mp[rem]); return ""; } // Driver code public static void Main(string[] args) { int numr = 50, denr = 22; string res = fractionToDecimal(numr, denr); if (res == "") Console.Write("No recurring sequence"); else Console.Write("Recurring sequence is " + res); }} // This code is contributed by rutvik_56 <script> // Javascript program to find// repeating sequence// in a fraction // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String function fractionToDecimal(numr, denr) { // Initialize result let res = ""; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. let mp = new Map(); mp.clear(); // Find first remainder let rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 or repeats while ((rem != 0) && (!mp.has(rem))) { // Store this remainder mp.set(rem, res.length); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result let res_part = Math.floor(rem / denr); res += res_part.toString(); // Update remainder rem = rem % denr; } if (rem == 0) return ""; else if (mp.has(rem)) return res.substr(mp.get(rem)); return ""; } // Driver program let numr = 50, denr = 22; let res = fractionToDecimal(numr, denr); if (res == "") document.write("No recurring sequence"); else document.write("Recurring sequence is " + res); </script> Recurring sequence is 27 This article is contributed by Dhruv Mahajan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. GauravRajput1 rutvik_56 divyeshrabadiya07 prajjwal21 dhawangupta08 target_2 motrocgabi hardikkoriintern Amazon Fraction Microsoft Hash Mathematical Amazon Microsoft Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 162, "s": 52, "text": "Given a fraction, find a recurring sequence of digits if it exists, otherwise, print “No recurring sequence”." }, { "code": null, "e": 172, "s": 162, "text": "Examples:" }, { "code": null, "e": 499, "s": 172, "text": "Input : Numerator = 8, Denominator = 3\nOutput : Recurring sequence is 6 \nExplanation : 8/3 = 2.66666666....... \n\nInput : Numerator = 50, Denominator = 22\nOutput : Recurring sequence is 27\nExplanation : 50/22 = 2.272727272..... \n\nInput : Numerator = 11, Denominator = 2\nOutput : No recurring sequence\nExplanation : 11/2 = 5.5" }, { "code": null, "e": 791, "s": 499, "text": "When does the fractional part repeat?Let us simulate the process of converting fractions to decimals. Let us look at the part where we have already figured out the integer part, which is floor(numerator/denominator). Now we are left with ( remainder = numerator%denominator ) / denominator. " }, { "code": null, "e": 881, "s": 791, "text": "If you remember the process of converting to decimal, at each step we do the following : " }, { "code": null, "e": 994, "s": 881, "text": "Multiply the remainder by 10.Append the remainder/denominator to the result.Remainder = remainder % denominator." }, { "code": null, "e": 1024, "s": 994, "text": "Multiply the remainder by 10." }, { "code": null, "e": 1072, "s": 1024, "text": "Append the remainder/denominator to the result." }, { "code": null, "e": 1109, "s": 1072, "text": "Remainder = remainder % denominator." }, { "code": null, "e": 1304, "s": 1109, "text": "At any moment, if the remainder becomes 0, we are done.However, when there is a recurring sequence, the remainder never becomes 0. For example, if you look at 1/3, the remainder never becomes 0." }, { "code": null, "e": 1624, "s": 1304, "text": "Below is one important observation : If we start with the remainder ‘rem’ and if the remainder repeats at any point in time, the digits between the two occurrences of ‘rem’ keep repeating.So the idea is to store seen remainders in a map. Whenever a remainder repeats, we return the sequence before the next occurrence. " }, { "code": null, "e": 1672, "s": 1624, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 1676, "s": 1672, "text": "C++" }, { "code": null, "e": 1681, "s": 1676, "text": "Java" }, { "code": null, "e": 1689, "s": 1681, "text": "Python3" }, { "code": null, "e": 1692, "s": 1689, "text": "C#" }, { "code": null, "e": 1703, "s": 1692, "text": "Javascript" }, { "code": "// C++ program to find repeating// sequence in a fraction#include <bits/stdc++.h>using namespace std; // This function returns repeating sequence of// a fraction. If repeating sequence doesn't// exits, then returns empty stringstring fractionToDecimal(int numr, int denr){ string res; // Initialize result // Create a map to store already // seen remainders remainder is used // as key and its position in // result is stored as value. // Note that we need // position for cases like 1/6. // In this case,the recurring sequence // doesn't start from first // remainder. map<int, int> mp; mp.clear(); // Find first remainder int rem = numr % denr; // Keep finding remainder until either remainder // becomes 0 or repeats while ((rem != 0) && (mp.find(rem) == mp.end())) { // Store this remainder mp[rem] = res.length(); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += to_string(res_part); // Update remainder rem = rem % denr; } return (rem == 0) ? \"\" : res.substr(mp[rem]);} // Driver codeint main(){ int numr = 50, denr = 22; string res = fractionToDecimal(numr, denr); if (res == \"\") cout << \"No recurring sequence\"; else cout << \"Recurring sequence is \" << res; return 0;}", "e": 3112, "s": 1703, "text": null }, { "code": "// Java program to find// repeating sequence// in a fractionimport java.util.*;class GFG { // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String static String fractionToDecimal(int numr, int denr) { // Initialize result String res = \"\"; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. HashMap<Integer, Integer> mp = new HashMap<>(); mp.clear(); // Find first remainder int rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 or repeats while ((rem != 0) && (!mp.containsKey(rem))) { // Store this remainder mp.put(rem, res.length()); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += String.valueOf(res_part); // Update remainder rem = rem % denr; } if (rem == 0) return \"\"; else if (mp.containsKey(rem)) return res.substring(mp.get(rem)); return \"\"; } // Driver code public static void main(String[] args) { int numr = 50, denr = 22; String res = fractionToDecimal(numr, denr); if (res == \"\") System.out.print(\"No recurring sequence\"); else System.out.print(\"Recurring sequence is \" + res); }} // This code is contributed by gauravrajput1", "e": 4932, "s": 3112, "text": null }, { "code": "# Python3 program to find repeating# sequence in a fraction # This function returns repeating sequence# of a fraction.If repeating sequence doesn't# exits, then returns empty string def fractionToDecimal(numr, denr): # Initialize result res = \"\" # Create a map to store already seen # remainders. Remainder is used as key # and its position in result is stored # as value. Note that we need position # for cases like 1/6. In this case, # the recurring sequence doesn't start # from first remainder. mp = {} # Find first remainder rem = numr % denr # Keep finding remainder until either # remainder becomes 0 or repeats while ((rem != 0) and (rem not in mp)): # Store this remainder mp[rem] = len(res) # Multiply remainder with 10 rem = rem * 10 # Append rem / denr to result res_part = rem // denr res += str(res_part) # Update remainder rem = rem % denr if (rem == 0): return \"\" else: return res[mp[rem]:] # Driver codenumr, denr = 50, 22res = fractionToDecimal(numr, denr) if (res == \"\"): print(\"No recurring sequence\")else: print(\"Recurring sequence is\", res) # This code is contributed by divyeshrabadiya07", "e": 6189, "s": 4932, "text": null }, { "code": "// C# program to find repeating sequence// in a fractionusing System;using System.Collections.Generic; class GFG { // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String static string fractionToDecimal(int numr, int denr) { // Initialize result string res = \"\"; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. Dictionary<int, int> mp = new Dictionary<int, int>(); // Find first remainder int rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 // or repeats while ((rem != 0) && (!mp.ContainsKey(rem))) { // Store this remainder mp[rem] = res.Length; // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result int res_part = rem / denr; res += res_part.ToString(); // Update remainder rem = rem % denr; } if (rem == 0) return \"\"; else if (mp.ContainsKey(rem)) return res.Substring(mp[rem]); return \"\"; } // Driver code public static void Main(string[] args) { int numr = 50, denr = 22; string res = fractionToDecimal(numr, denr); if (res == \"\") Console.Write(\"No recurring sequence\"); else Console.Write(\"Recurring sequence is \" + res); }} // This code is contributed by rutvik_56", "e": 7990, "s": 6189, "text": null }, { "code": "<script> // Javascript program to find// repeating sequence// in a fraction // This function returns repeating // sequence of a fraction. If // repeating sequence doesn't // exits, then returns empty String function fractionToDecimal(numr, denr) { // Initialize result let res = \"\"; // Create a map to store already // seen remainders. Remainder is // used as key and its position in // result is stored as value. // Note that we need position for // cases like 1/6. In this case, // the recurring sequence doesn't // start from first remainder. let mp = new Map(); mp.clear(); // Find first remainder let rem = numr % denr; // Keep finding remainder until // either remainder becomes 0 or repeats while ((rem != 0) && (!mp.has(rem))) { // Store this remainder mp.set(rem, res.length); // Multiply remainder with 10 rem = rem * 10; // Append rem / denr to result let res_part = Math.floor(rem / denr); res += res_part.toString(); // Update remainder rem = rem % denr; } if (rem == 0) return \"\"; else if (mp.has(rem)) return res.substr(mp.get(rem)); return \"\"; } // Driver program let numr = 50, denr = 22; let res = fractionToDecimal(numr, denr); if (res == \"\") document.write(\"No recurring sequence\"); else document.write(\"Recurring sequence is \" + res); </script>", "e": 9644, "s": 7990, "text": null }, { "code": null, "e": 9669, "s": 9644, "text": "Recurring sequence is 27" }, { "code": null, "e": 9840, "s": 9669, "text": "This article is contributed by Dhruv Mahajan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9854, "s": 9840, "text": "GauravRajput1" }, { "code": null, "e": 9864, "s": 9854, "text": "rutvik_56" }, { "code": null, "e": 9882, "s": 9864, "text": "divyeshrabadiya07" }, { "code": null, "e": 9893, "s": 9882, "text": "prajjwal21" }, { "code": null, "e": 9907, "s": 9893, "text": "dhawangupta08" }, { "code": null, "e": 9916, "s": 9907, "text": "target_2" }, { "code": null, "e": 9927, "s": 9916, "text": "motrocgabi" }, { "code": null, "e": 9944, "s": 9927, "text": "hardikkoriintern" }, { "code": null, "e": 9951, "s": 9944, "text": "Amazon" }, { "code": null, "e": 9960, "s": 9951, "text": "Fraction" }, { "code": null, "e": 9970, "s": 9960, "text": "Microsoft" }, { "code": null, "e": 9975, "s": 9970, "text": "Hash" }, { "code": null, "e": 9988, "s": 9975, "text": "Mathematical" }, { "code": null, "e": 9995, "s": 9988, "text": "Amazon" }, { "code": null, "e": 10005, "s": 9995, "text": "Microsoft" }, { "code": null, "e": 10010, "s": 10005, "text": "Hash" }, { "code": null, "e": 10023, "s": 10010, "text": "Mathematical" } ]
How to use Pagination in DataGrid Component in ReactJS ?
26 Apr, 2021 Pagination helps in viewing a segment of data from the assigned data source. Pagination improves the user experience as users can switch between pages to see data. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use Pagination in DataGrid Component. Approach: Follow these simple steps in order to use Pagination in DataGrid Component in ReactJS. In the following example, With the help of the rowsPerPageOptions prop, we can do the Pagination in DataGrid Component like we have passed [2, 5, 7] as a value which means we can show users the option to see 2 or 5 or 7 rows on a single page. The default pageSize is 100, but we can change this value with the pageSize prop. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/data-grid Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react';import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 170 }, { field: 'name', headerName: 'NAME', width: 170 }, { field: 'age', headerName: 'AGE', width: 170 },]; const rows = [ { id: 1, name: 'Gourav', age: 12 }, { id: 2, name: 'Geek', age: 43 }, { id: 3, name: 'Pranav', age: 41 }, { id: 4, name: 'Abhay', age: 34 }, { id: 5, name: 'Pranav', age: 73 }, { id: 6, name: 'Disha', age: 61 }, { id: 7, name: 'Raghav', age: 72 }, { id: 8, name: 'Amit', age: 24 }, { id: 9, name: 'Anuj', age: 48 },]; export default function App() { return ( <div style={{ height: 500, width: '80%' }}> <h4> How to use Pagination in DataGrid Component in ReactJS? </h4> <DataGrid rows={rows} columns={columns} pageSize={5} rowsPerPageOptions={[2, 5, 7]} /> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://material-ui.com/components/data-grid/pagination/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2021" }, { "code": null, "e": 376, "s": 28, "text": "Pagination helps in viewing a segment of data from the assigned data source. Pagination improves the user experience as users can switch between pages to see data. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use Pagination in DataGrid Component." }, { "code": null, "e": 798, "s": 376, "text": "Approach: Follow these simple steps in order to use Pagination in DataGrid Component in ReactJS. In the following example, With the help of the rowsPerPageOptions prop, we can do the Pagination in DataGrid Component like we have passed [2, 5, 7] as a value which means we can show users the option to see 2 or 5 or 7 rows on a single page. The default pageSize is 100, but we can change this value with the pageSize prop." }, { "code": null, "e": 848, "s": 798, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 943, "s": 848, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 1007, "s": 943, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1039, "s": 1007, "text": "npx create-react-app foldername" }, { "code": null, "e": 1152, "s": 1039, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 1252, "s": 1152, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 1266, "s": 1252, "text": "cd foldername" }, { "code": null, "e": 1408, "s": 1266, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid" }, { "code": null, "e": 1516, "s": 1408, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:" }, { "code": null, "e": 1551, "s": 1516, "text": "npm install @material-ui/data-grid" }, { "code": null, "e": 1603, "s": 1551, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1621, "s": 1603, "text": "Project Structure" }, { "code": null, "e": 1751, "s": 1621, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1758, "s": 1751, "text": "App.js" }, { "code": "import * as React from 'react';import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 170 }, { field: 'name', headerName: 'NAME', width: 170 }, { field: 'age', headerName: 'AGE', width: 170 },]; const rows = [ { id: 1, name: 'Gourav', age: 12 }, { id: 2, name: 'Geek', age: 43 }, { id: 3, name: 'Pranav', age: 41 }, { id: 4, name: 'Abhay', age: 34 }, { id: 5, name: 'Pranav', age: 73 }, { id: 6, name: 'Disha', age: 61 }, { id: 7, name: 'Raghav', age: 72 }, { id: 8, name: 'Amit', age: 24 }, { id: 9, name: 'Anuj', age: 48 },]; export default function App() { return ( <div style={{ height: 500, width: '80%' }}> <h4> How to use Pagination in DataGrid Component in ReactJS? </h4> <DataGrid rows={rows} columns={columns} pageSize={5} rowsPerPageOptions={[2, 5, 7]} /> </div> );}", "e": 2657, "s": 1758, "text": null }, { "code": null, "e": 2770, "s": 2657, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2780, "s": 2770, "text": "npm start" }, { "code": null, "e": 2879, "s": 2780, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2947, "s": 2879, "text": "Reference: https://material-ui.com/components/data-grid/pagination/" }, { "code": null, "e": 2959, "s": 2947, "text": "Material-UI" }, { "code": null, "e": 2975, "s": 2959, "text": "React-Questions" }, { "code": null, "e": 2983, "s": 2975, "text": "ReactJS" }, { "code": null, "e": 3000, "s": 2983, "text": "Web Technologies" } ]
How to detect network speed using JavaScript?
16 Jul, 2020 To detect the network speed using javascript, we will use the following approach. Approach: Open the web page for which you want to know the connection speed. The page should be the one for which you want to add the javascript code for detecting the speed. Assign or set up the address of the image which you want to use for speed test to the variable. The variables for storing the test’s start time, end time, and download size should be created. Set the “downloadSize” equivalent to the image file size(In bytes). The end of the download action is assigned to activate when the image downloading is completed. It calculates the speed of the download process, and converts it to “kbps” and “mbps”. Below is example illustrate the above approach:Example: <!DOCTYPE html><html> <head> <title> To detect network speed using JavaScript </title> </head> <body> <script type="text/javascript"> var userImageLink = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200714180638/CIP_Launch-banner.png"; var time_start, end_time; // The size in bytes var downloadSize = 5616998; var downloadImgSrc = new Image(); downloadImgSrc.onload = function () { end_time = new Date().getTime(); displaySpeed(); }; time_start = new Date().getTime(); downloadImgSrc.src = userImageLink; document.write("time start: " + time_start); document.write("<br>"); function displaySpeed() { var timeDuration = (end_time - time_start) / 1000; var loadedBits = downloadSize * 8; /* Converts a number into string using toFixed(2) rounding to 2 */ var bps = (loadedBits / timeDuration).toFixed(2); var speedInKbps = (bps / 1024).toFixed(2); var speedInMbps = (speedInKbps / 1024).toFixed(2); alert("Your internet connection speed is: \n" + bps + " bps\n" + speedInKbps + " kbps\n" + speedInMbps + " Mbps\n"); } </script> </body></html> Output: HTML-Misc javascript-basics JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 110, "s": 28, "text": "To detect the network speed using javascript, we will use the following approach." }, { "code": null, "e": 728, "s": 110, "text": "Approach: Open the web page for which you want to know the connection speed. The page should be the one for which you want to add the javascript code for detecting the speed. Assign or set up the address of the image which you want to use for speed test to the variable. The variables for storing the test’s start time, end time, and download size should be created. Set the “downloadSize” equivalent to the image file size(In bytes). The end of the download action is assigned to activate when the image downloading is completed. It calculates the speed of the download process, and converts it to “kbps” and “mbps”." }, { "code": null, "e": 784, "s": 728, "text": "Below is example illustrate the above approach:Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> To detect network speed using JavaScript </title> </head> <body> <script type=\"text/javascript\"> var userImageLink = \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200714180638/CIP_Launch-banner.png\"; var time_start, end_time; // The size in bytes var downloadSize = 5616998; var downloadImgSrc = new Image(); downloadImgSrc.onload = function () { end_time = new Date().getTime(); displaySpeed(); }; time_start = new Date().getTime(); downloadImgSrc.src = userImageLink; document.write(\"time start: \" + time_start); document.write(\"<br>\"); function displaySpeed() { var timeDuration = (end_time - time_start) / 1000; var loadedBits = downloadSize * 8; /* Converts a number into string using toFixed(2) rounding to 2 */ var bps = (loadedBits / timeDuration).toFixed(2); var speedInKbps = (bps / 1024).toFixed(2); var speedInMbps = (speedInKbps / 1024).toFixed(2); alert(\"Your internet connection speed is: \\n\" + bps + \" bps\\n\" + speedInKbps + \" kbps\\n\" + speedInMbps + \" Mbps\\n\"); } </script> </body></html>", "e": 2260, "s": 784, "text": null }, { "code": null, "e": 2268, "s": 2260, "text": "Output:" }, { "code": null, "e": 2278, "s": 2268, "text": "HTML-Misc" }, { "code": null, "e": 2296, "s": 2278, "text": "javascript-basics" }, { "code": null, "e": 2307, "s": 2296, "text": "JavaScript" }, { "code": null, "e": 2324, "s": 2307, "text": "Web Technologies" }, { "code": null, "e": 2351, "s": 2324, "text": "Web technologies Questions" }, { "code": null, "e": 2449, "s": 2351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2510, "s": 2449, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2550, "s": 2510, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2592, "s": 2550, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2633, "s": 2592, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2655, "s": 2633, "text": "JavaScript | Promises" }, { "code": null, "e": 2688, "s": 2655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2750, "s": 2688, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2811, "s": 2750, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2861, "s": 2811, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to get file extensions using JavaScript?
09 Aug, 2019 split() and pop() method substring() and lastIndexOf() method match() method with regular expression Above methods are described below one by one with the proper example. Using split() and pop() method:The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string.By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.The extension can then be got by popping from the array the last string with the pop() method. This is hence the file extension of the file selected.Syntax:fileName.split(separator, limit).pop();Example:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();"/> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.split('.').pop(); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output: The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file. The extension can then be got by popping from the array the last string with the pop() method. This is hence the file extension of the file selected. Syntax: fileName.split(separator, limit).pop(); Example: <!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();"/> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.split('.').pop(); document.querySelector('.output') .textContent = extension; }; </script></body> </html> Output: Using substring() and lastIndexOf() method:The full filename is first obtained after that substring() method is used to return the part of a string between the start and end indexes.The starting index is given by using the lastIndexOf() method. This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension.Syntax:fileName.substring(fileName.lastIndexOf(searchvalue, start);Example:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();" /> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.substring(fileName.lastIndexOf('.') + 1); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output: The starting index is given by using the lastIndexOf() method. This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension. Syntax: fileName.substring(fileName.lastIndexOf(searchvalue, start); Example: <!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();" /> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.substring(fileName.lastIndexOf('.') + 1); document.querySelector('.output') .textContent = extension; }; </script></body> </html> Output: match() method with regular expression:Regular expressions can be used to extract the file extension from the full filename. A new RegExp object is created with the regular expression “[^.]+$”. The caret(^) marks the start of a string. The period(.) after the caret specifies that the string is selected after the period. The plus(+) quantifier selects one or more words. The dollar($) is used to specify the end of the line. This expression selects the string after the period.The match() method is used to return the part of the string which matches the regular expression passed to it as a parameter. The full filename is passed to this method and the regular expression returns only the file extension.Syntax:fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); Example:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();"/> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output: Regular expressions can be used to extract the file extension from the full filename. A new RegExp object is created with the regular expression “[^.]+$”. The caret(^) marks the start of a string. The period(.) after the caret specifies that the string is selected after the period. The plus(+) quantifier selects one or more words. The dollar($) is used to specify the end of the line. This expression selects the string after the period. The match() method is used to return the part of the string which matches the regular expression passed to it as a parameter. The full filename is passed to this method and the regular expression returns only the file extension. Syntax: fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); Example: <!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <b>Here we will get "Extension" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type="file" id="file1" /> <input type="button" value="Check Extension" onclick="checkFileExtension();"/> </form> <p>The file extension is: <span class="output"></span></p> <script language="javascript"> function checkFileExtension() { fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); document.querySelector('.output') .textContent = extension; }; </script></body> </html> Output: mayank5326 JavaScript-Misc 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": "\n09 Aug, 2019" }, { "code": null, "e": 53, "s": 28, "text": "split() and pop() method" }, { "code": null, "e": 90, "s": 53, "text": "substring() and lastIndexOf() method" }, { "code": null, "e": 129, "s": 90, "text": "match() method with regular expression" }, { "code": null, "e": 199, "s": 129, "text": "Above methods are described below one by one with the proper example." }, { "code": null, "e": 1630, "s": 199, "text": "Using split() and pop() method:The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string.By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.The extension can then be got by popping from the array the last string with the pop() method. This is hence the file extension of the file selected.Syntax:fileName.split(separator, limit).pop();Example:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\"/> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.split('.').pop(); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output:" }, { "code": null, "e": 1765, "s": 1630, "text": "The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string." }, { "code": null, "e": 1928, "s": 1765, "text": "By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file." }, { "code": null, "e": 2078, "s": 1928, "text": "The extension can then be got by popping from the array the last string with the pop() method. This is hence the file extension of the file selected." }, { "code": null, "e": 2086, "s": 2078, "text": "Syntax:" }, { "code": null, "e": 2126, "s": 2086, "text": "fileName.split(separator, limit).pop();" }, { "code": null, "e": 2135, "s": 2126, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\"/> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.split('.').pop(); document.querySelector('.output') .textContent = extension; }; </script></body> </html>", "e": 3029, "s": 2135, "text": null }, { "code": null, "e": 3037, "s": 3029, "text": "Output:" }, { "code": null, "e": 4558, "s": 3037, "text": "Using substring() and lastIndexOf() method:The full filename is first obtained after that substring() method is used to return the part of a string between the start and end indexes.The starting index is given by using the lastIndexOf() method. This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension.Syntax:fileName.substring(fileName.lastIndexOf(searchvalue, start);Example:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\" /> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.substring(fileName.lastIndexOf('.') + 1); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output:" }, { "code": null, "e": 4896, "s": 4558, "text": "The starting index is given by using the lastIndexOf() method. This returns the index in the string where the string passed last occurs. The last index can be found by passing a period(.) to this method. The index is passed on to the substring() method, which returns the string from the period(.) to the end. This is the file extension." }, { "code": null, "e": 4904, "s": 4896, "text": "Syntax:" }, { "code": null, "e": 4965, "s": 4904, "text": "fileName.substring(fileName.lastIndexOf(searchvalue, start);" }, { "code": null, "e": 4974, "s": 4965, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\" /> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; extension = fileName.substring(fileName.lastIndexOf('.') + 1); document.querySelector('.output') .textContent = extension; }; </script></body> </html>", "e": 5894, "s": 4974, "text": null }, { "code": null, "e": 5902, "s": 5894, "text": "Output:" }, { "code": null, "e": 7685, "s": 5902, "text": "match() method with regular expression:Regular expressions can be used to extract the file extension from the full filename. A new RegExp object is created with the regular expression “[^.]+$”. The caret(^) marks the start of a string. The period(.) after the caret specifies that the string is selected after the period. The plus(+) quantifier selects one or more words. The dollar($) is used to specify the end of the line. This expression selects the string after the period.The match() method is used to return the part of the string which matches the regular expression passed to it as a parameter. The full filename is passed to this method and the regular expression returns only the file extension.Syntax:fileName = document.querySelector('#file1').value;\nregex = new RegExp('[^.]+$');\nextension = fileName.match(regex);\nExample:<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\"/> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); document.querySelector('.output') .textContent = extension; }; </script></body> </html>Output:" }, { "code": null, "e": 8125, "s": 7685, "text": "Regular expressions can be used to extract the file extension from the full filename. A new RegExp object is created with the regular expression “[^.]+$”. The caret(^) marks the start of a string. The period(.) after the caret specifies that the string is selected after the period. The plus(+) quantifier selects one or more words. The dollar($) is used to specify the end of the line. This expression selects the string after the period." }, { "code": null, "e": 8354, "s": 8125, "text": "The match() method is used to return the part of the string which matches the regular expression passed to it as a parameter. The full filename is passed to this method and the regular expression returns only the file extension." }, { "code": null, "e": 8362, "s": 8354, "text": "Syntax:" }, { "code": null, "e": 8479, "s": 8362, "text": "fileName = document.querySelector('#file1').value;\nregex = new RegExp('[^.]+$');\nextension = fileName.match(regex);\n" }, { "code": null, "e": 8488, "s": 8479, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>How to get file extensions using JavaScript? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>Here we will get \"Extension\" of selected file</b> <p>Select a file and click on the button to check the file extension.</p> <form> <input type=\"file\" id=\"file1\" /> <input type=\"button\" value=\"Check Extension\" onclick=\"checkFileExtension();\"/> </form> <p>The file extension is: <span class=\"output\"></span></p> <script language=\"javascript\"> function checkFileExtension() { fileName = document.querySelector('#file1').value; regex = new RegExp('[^.]+$'); extension = fileName.match(regex); document.querySelector('.output') .textContent = extension; }; </script></body> </html>", "e": 9427, "s": 8488, "text": null }, { "code": null, "e": 9435, "s": 9427, "text": "Output:" }, { "code": null, "e": 9446, "s": 9435, "text": "mayank5326" }, { "code": null, "e": 9462, "s": 9446, "text": "JavaScript-Misc" }, { "code": null, "e": 9469, "s": 9462, "text": "Picked" }, { "code": null, "e": 9480, "s": 9469, "text": "JavaScript" } ]
How to create Glowing Star effect using HTML and CSS? - GeeksforGeeks
14 Jul, 2020 The glowing star effect is one of the coolest effects that is used for dark themed websites. It is known as star effect because it has small glowing balls animated in different ways which looks like stars. This effect can be used for image slider, loader, and maybe as an showcase UI element. Approach: The approach is to create small balls using unordered list and then animating them using keyframes and n-th child property. Basic knowledge of these two properties is a prerequisite of going any further in this article. HTML Code: In this section, we have created an unordered list. <!DOCTYPE html><html><head><title>GLOWING STAR EFFECT</title></head><body><ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul></body></html> CSS Code: For CSS, follow the given below steps: Step 1: Align the list according to your need. We have aligned the list to the center of the page. Step 2: Remove all the list styles and give them circle shape using border-radius. Step 3: Use keyframes to animate the balls by increasing the scale. There is no fix way of doing this you can change scale on different frames as you like. Step 4: Use n-th child property to apply some delay between animation of each li element. Tip: This effect is one of the most versatile effects. You can change the type of animation on different frames or can change the delay. So, try out different values of the properties that are used in this article to find the best animation for yourself. Also this effect only looks good on a dark-theme page so don’t use it on light-themed websites. body { background: rgb(70, 69, 69); } ul { position: absolute; top: 50%; left: 50%; display: flex; } ul li { list-style: none; width: 40px; height: 40px; background: #fff; border-radius: 50%; animation: animate 1.7s ease-in-out infinite; } @keyframes animate { 0%, 40%, 100% { transform: scale(0.2); } 20% { transform: scale(1); } } ul li:nth-child(1) { animation-delay: -1.2s; background: yellow; box-shadow: 0 0 50px yellow; } ul li:nth-child(2) { animation-delay: -1s; background: rgb(99, 247, 136); box-shadow: 0 0 50px rgb(99, 247, 136); } ul li:nth-child(3) { animation-delay: -0.8s; background: rgb(30, 243, 225); box-shadow: 0 0 50px rgb(30, 243, 225); } ul li:nth-child(4) { animation-delay: -0.6s; background: rgb(241, 58, 58); box-shadow: 0 0 50px rgb(241, 58, 58); } ul li:nth-child(5) { animation-delay: -0.4s; background: rgb(247, 61, 176); box-shadow: 0 0 50px rgb(247, 61, 176); } Complete Code: It is the combination of the above two sections of code. <!DOCTYPE html><html><head><title>GLOWING STAR EFFECT</title> <style> body { background: rgb(70, 69, 69); } ul { position: absolute; top: 50%; left: 50%; display: flex; } ul li { list-style: none; width: 40px; height: 40px; background: #fff; border-radius: 50%; animation: animate 1.7s ease-in-out infinite; } @keyframes animate { 0%, 40%, 100% { transform: scale(0.2); } 20% { transform: scale(1); } } ul li:nth-child(1) { animation-delay: -1.2s; background: yellow; box-shadow: 0 0 50px yellow; } ul li:nth-child(2) { animation-delay: -1s; background: rgb(99, 247, 136); box-shadow: 0 0 50px rgb(99, 247, 136); } ul li:nth-child(3) { animation-delay: -0.8s; background: rgb(30, 243, 225); box-shadow: 0 0 50px rgb(30, 243, 225); } ul li:nth-child(4) { animation-delay: -0.6s; background: rgb(241, 58, 58); box-shadow: 0 0 50px rgb(241, 58, 58); } ul li:nth-child(5) { animation-delay: -0.4s; background: rgb(247, 61, 176); box-shadow: 0 0 50px rgb(247, 61, 176); } </style> </head><body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul></body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Advanced CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS Form validation using jQuery How to apply style to parent if it has child with CSS? How to auto-resize an image to fit a div container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24836, "s": 24808, "text": "\n14 Jul, 2020" }, { "code": null, "e": 25129, "s": 24836, "text": "The glowing star effect is one of the coolest effects that is used for dark themed websites. It is known as star effect because it has small glowing balls animated in different ways which looks like stars. This effect can be used for image slider, loader, and maybe as an showcase UI element." }, { "code": null, "e": 25359, "s": 25129, "text": "Approach: The approach is to create small balls using unordered list and then animating them using keyframes and n-th child property. Basic knowledge of these two properties is a prerequisite of going any further in this article." }, { "code": null, "e": 25422, "s": 25359, "text": "HTML Code: In this section, we have created an unordered list." }, { "code": "<!DOCTYPE html><html><head><title>GLOWING STAR EFFECT</title></head><body><ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul></body></html>", "e": 25607, "s": 25422, "text": null }, { "code": null, "e": 25656, "s": 25607, "text": "CSS Code: For CSS, follow the given below steps:" }, { "code": null, "e": 25755, "s": 25656, "text": "Step 1: Align the list according to your need. We have aligned the list to the center of the page." }, { "code": null, "e": 25838, "s": 25755, "text": "Step 2: Remove all the list styles and give them circle shape using border-radius." }, { "code": null, "e": 25994, "s": 25838, "text": "Step 3: Use keyframes to animate the balls by increasing the scale. There is no fix way of doing this you can change scale on different frames as you like." }, { "code": null, "e": 26085, "s": 25994, "text": "Step 4: Use n-th child property to apply some delay between animation of each li element." }, { "code": null, "e": 26437, "s": 26085, "text": "Tip: This effect is one of the most versatile effects. You can change the type of animation on different frames or can change the delay. So, try out different values of the properties that are used in this article to find the best animation for yourself. Also this effect only looks good on a dark-theme page so don’t use it on light-themed websites." }, { "code": "body { background: rgb(70, 69, 69); } ul { position: absolute; top: 50%; left: 50%; display: flex; } ul li { list-style: none; width: 40px; height: 40px; background: #fff; border-radius: 50%; animation: animate 1.7s ease-in-out infinite; } @keyframes animate { 0%, 40%, 100% { transform: scale(0.2); } 20% { transform: scale(1); } } ul li:nth-child(1) { animation-delay: -1.2s; background: yellow; box-shadow: 0 0 50px yellow; } ul li:nth-child(2) { animation-delay: -1s; background: rgb(99, 247, 136); box-shadow: 0 0 50px rgb(99, 247, 136); } ul li:nth-child(3) { animation-delay: -0.8s; background: rgb(30, 243, 225); box-shadow: 0 0 50px rgb(30, 243, 225); } ul li:nth-child(4) { animation-delay: -0.6s; background: rgb(241, 58, 58); box-shadow: 0 0 50px rgb(241, 58, 58); } ul li:nth-child(5) { animation-delay: -0.4s; background: rgb(247, 61, 176); box-shadow: 0 0 50px rgb(247, 61, 176); }", "e": 27614, "s": 26437, "text": null }, { "code": null, "e": 27686, "s": 27614, "text": "Complete Code: It is the combination of the above two sections of code." }, { "code": "<!DOCTYPE html><html><head><title>GLOWING STAR EFFECT</title> <style> body { background: rgb(70, 69, 69); } ul { position: absolute; top: 50%; left: 50%; display: flex; } ul li { list-style: none; width: 40px; height: 40px; background: #fff; border-radius: 50%; animation: animate 1.7s ease-in-out infinite; } @keyframes animate { 0%, 40%, 100% { transform: scale(0.2); } 20% { transform: scale(1); } } ul li:nth-child(1) { animation-delay: -1.2s; background: yellow; box-shadow: 0 0 50px yellow; } ul li:nth-child(2) { animation-delay: -1s; background: rgb(99, 247, 136); box-shadow: 0 0 50px rgb(99, 247, 136); } ul li:nth-child(3) { animation-delay: -0.8s; background: rgb(30, 243, 225); box-shadow: 0 0 50px rgb(30, 243, 225); } ul li:nth-child(4) { animation-delay: -0.6s; background: rgb(241, 58, 58); box-shadow: 0 0 50px rgb(241, 58, 58); } ul li:nth-child(5) { animation-delay: -0.4s; background: rgb(247, 61, 176); box-shadow: 0 0 50px rgb(247, 61, 176); } </style> </head><body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul></body></html>", "e": 29136, "s": 27686, "text": null }, { "code": null, "e": 29144, "s": 29136, "text": "Output:" }, { "code": null, "e": 29281, "s": 29144, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29294, "s": 29281, "text": "CSS-Advanced" }, { "code": null, "e": 29298, "s": 29294, "text": "CSS" }, { "code": null, "e": 29303, "s": 29298, "text": "HTML" }, { "code": null, "e": 29320, "s": 29303, "text": "Web Technologies" }, { "code": null, "e": 29325, "s": 29320, "text": "HTML" }, { "code": null, "e": 29423, "s": 29325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29464, "s": 29423, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 29501, "s": 29464, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29530, "s": 29501, "text": "Form validation using jQuery" }, { "code": null, "e": 29585, "s": 29530, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29647, "s": 29585, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 29707, "s": 29647, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29768, "s": 29707, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29821, "s": 29768, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29871, "s": 29821, "text": "How to Insert Form Data into Database using PHP ?" } ]
Solve sudokus automatically with Python and PyAutoGUI | Towards Data Science
In this article, I will introduce a walkthrough on making your very own script that solves sudoku puzzles. Furthermore, this script is enhanced with PyAutoGUI to make sudoku solving quite automatic (you only have to execute the code). I have divided the article in the following manner: Introduction to sudoku — this brief section covers the basic rules that must be kept in mind;Sudoku solving algorithm — this section starts with defining necessary data structures and we will create an algorithm that would solve any given puzzle;Automation — it’s cool if your script knows the step-by-step solution to a puzzle. It’s even cooler if your code interacts with a web page and solves the sudoku automatically. Introduction to sudoku — this brief section covers the basic rules that must be kept in mind; Sudoku solving algorithm — this section starts with defining necessary data structures and we will create an algorithm that would solve any given puzzle; Automation — it’s cool if your script knows the step-by-step solution to a puzzle. It’s even cooler if your code interacts with a web page and solves the sudoku automatically. I hope you have installed Python, Pillow, and PyAutoGUI module. If you don’t have the PyAutoGUI yet then you should follow the installation steps HERE. First things first. If you are not familiar with the rules of a sudoku puzzle, don’t be frightened. They are quite simple: You must fill the boxes of a 9x9 grid with numbers from 1 to 9 in a way that there are no recurring numbers in each row, column, and 3x3 block. If you take a look at the image, the only number that fits into the top left box is two since it’s the only one that doesn’t appear in this row, column and box. Let’s take a random sudoku puzzle from the Internet and try to solve it with Python. I propose that we handle this puzzle as a two-dimensional Python array where empty boxes are represented with zeros and other boxes with corresponding numbers. We should obtain the following: sudoku = [[8, 1, 0, 0, 3, 0, 0, 2, 7], [0, 6, 2, 0, 5, 0, 0, 9, 0], [0, 7, 0, 0, 0, 0, 0, 0, 0], [0, 9, 0, 6, 0, 0, 1, 0, 0], [1, 0, 0, 0, 2, 0, 0, 0, 4], [0, 0, 8, 0, 0, 5, 0, 7, 0], [0, 0, 0, 0, 0, 0, 0, 8, 0], [0, 2, 0, 0, 1, 0, 7, 5, 0], [3, 8, 0, 0, 7, 0, 0, 4, 2]] When trying to access a certain element from the i-th row and j-th column, you simply need to call sudoku[i][j] Sure, this two-dimensional python array does not look like real sudoku without any gridlines. Hence, it would be great to print out the current state of the puzzle. Below is the code example along with its output. def printsudoku(): print("\n\n\n\n\n") for i in range(len(sudoku)): line = "" if i == 3 or i == 6: print("---------------------") for j in range(len(sudoku[i])): if j == 3 or j == 6: line += "| " line += str(sudoku[i][j])+" " print(line) Let’s get to it! Now we are ready for a step-by-step algorithm-creation. Disclaimer: I did not create this sudoku-solving algorithm entirely myself. The idea and implementation were copied from MIT OpenCourseWare Youtube channel, more specifically from this video. Yet, it’s licensed as Creative Commons BY-NC-SA which gives me a green light for sharing. To solve a certain cell, we must first find the row and column number of a cell that’s empty. The following function does the trick. def findNextCellToFill(sudoku): for x in range(9): for y in range(9): if sudoku[x][y] == 0: return x, y return -1, -1 This iterates through all the columns in the first row, then second row and so on. Whenever it encounters an empty cell, the function returns the corresponding indexes. Simple! Suppose we have an entry e. We need a function that checks whether it violates the three main rules of sudoku when placed to the i-th row and j-th column. The following function returns True if none of the three rules are violated. Otherwise, the function will return False. def isValid(sudoku, i, j, e): rowOk = all([e != sudoku[i][x] for x in range(9)]) if rowOk: columnOk = all([e != sudoku[x][j] for x in range(9)]) if columnOk: secTopX, secTopY = 3*(i//3), 3*(j//3) for x in range(secTopX, secTopX+3): for y in range(secTopY, secTopY+3): if sudoku[x][y] == e: return False return True return False Three rules are examined: rowOk: this one checks if there are no repeating numbers in the i-th row;columnOk: this one makes sure if there are no repeating numbers in the j-th column;If both rowOk and columnOk are True then the lines 6–10 check if the entry fits a certain block. rowOk: this one checks if there are no repeating numbers in the i-th row; columnOk: this one makes sure if there are no repeating numbers in the j-th column; If both rowOk and columnOk are True then the lines 6–10 check if the entry fits a certain block. Now it’s all about solving the given sudoku. We’ll do it with the following function: def solveSudoku(sudoku, i=0, j=0): i, j = findNextCellToFill(sudoku) if i == -1: return True for e in range(1, 10): if isValid(sudoku, i, j, e): sudoku[i][j] = e if solveSudoku(sudoku, i, j): return True sudoku[i][j] = 0 return False The first three lines of the function make sure that we have an empty cell in our puzzle. If i is equal to -1 then we have completed solving our puzzle. If there is an empty cell at i-th row and j-th column then it will try to fit all the possible entries from 1 to 9 into this box. If the entry is valid (verified by the isValid function) then tries to solve the sudoku recursively under the assumption that this is a correct entry. If our assumption was incorrect then the 9-th line would return False and that sets the value of a cell in i-th row and j-th column to zero. To solve our sudoku, make the following function calls: solveSudoku(sudoku)printsudoku() The first one solves our puzzle and the latter shows the solution. Great! The automation part is divided into two sections: Locating the numbers on a sudoku grid. This way we can solve any sudoku without having to fill the sudoku variable manually.Filling the empty cells with numbers. Locating the numbers on a sudoku grid. This way we can solve any sudoku without having to fill the sudoku variable manually. Filling the empty cells with numbers. We are doing our automation by using the PyAutoGUI module. Please import it in your code. import pyautogui as pag We are about to solve a random sudoku puzzle from Websudoku. Open a random puzzle and save image snippets from every number. They all should be saved to the same folder as your Python script. Make sure that the file format is .png. The snippets may have different dimensions, as long as they all feature only a number on a white background. Let’s name them as “1.png”, “2.png”, etc. The PyAutoGUI module has a function that locates the given image on your screen. In my case for pos in pag.locateOnScreen("3.png"): print(pos) Returns all locations of number three on our screen: Box(left=1124, top=510, width=32, height=33)Box(left=959, top=845, width=32, height=33) The first two parameters (left and top) give us the pixel coordinates of the top-left corner of our image. The third and fourth give us the dimensions of our image but at the moment we are not going to need them. To get the locations of all the numbers, use the following: for i in range(1, 10): for pos in pag.locateAllOnScreen(str(i)+'.png'): print(pos) Since we are not going to use our previous sudoku array, let’s change all the numbers in this array to zero: sudoku = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] Now let’s define the pixel coordinates of two cells on our puzzle: top-left and bottom-right. In my case the numbers were: topleftx = 975toplefty = 507bottomrightx = 1307bottomrighty = 846 Now that we have them, let’s define the width and height of a box: boxwidth = (bottomrightx - topleftx)/8boxheight = (bottomrighty - toplefty)/8 Explanation: when looking at a row of cells, the distance from the leftmost to the rightmost cell is 8 box widths. The same goes for columns. Hence we must divide the coordinate difference by 8. Now we have to define a function that replaces zeros in sudoku array with the right numbers. def fillsudoku(nr, pos): global sudoku indexlocx = int((pos[0] - topleftx + boxwidth/2)//boxwidth) indexlocy = int((pos[1] - toplefty + boxheight/2)//boxwidth) sudoku[indexlocy][indexlocx] = nr I’m not going to explain the math but it takes a Box object and finds the “index-coordinates” of our number. If you have done everything correctly so far then it will work perfectly. Finally, let’s fill the array with information on our screen: for i in range(1, 10): for pos in pag.locateAllOnScreen(str(i)+'.png'): fillsudoku(i, pos) If you aren’t quick enough to jump from your IDE to web browser then add the following delay method to the beginning of your code: import timetime.sleep(5) #this makes a 5 second delay to executing the script Great! Now we have a method that uses screen information for filling our sudoku array. Since we have our solving algorithm then we can solve this instantly. We only need the following function to do so: def fillcell(nr, x, y): xcoord = topleftx + boxwidth * x ycoord = toplefty + boxheight * y pag.click(xcoord, ycoord) pag.press(str(nr)) Here we have three input parameters: nr: this is the number we want to insert; x: column index of the cell we are going to insert nr; y: row index of the cell we are going to insert nr; Lines 2–3 find the approximate coordinates of the midpoint of the cell we must insert our number. Lines 4–5 click on that cell and write that number. Oh yes! One more thing. Before solving the sudoku, please create a copy of the sudoku array. I’ll explain later. import copysudokucopy = copy.deepcopy(sudoku) To be on the same line, I’ll embed a Github gist below: So far we read the sudoku from our screen and solve it. We also have two identical arrays of our sudoku before trying to solve it: sudoku and sudokucopy. The sudokucopy was made to compare the initial and final state of our puzzle and fill the empty cells. for x in range(9): for y in range(9): if sudokucopy[x][y] == 0: fillcell(sudoku[x][y], y, x) Now it’s ready for execution and if your configurations are correct, then it should look like this: Of course, some improvements can be made: It takes me approximately 20 seconds to load the data from the screen to the sudoku array. You can use some different modules (or create your own) to make it faster.Modify the sudoku solving algorithm to make the automated solving part look a bit more like a human would think. No one in real life solves the puzzles as shown in the animation above. It takes me approximately 20 seconds to load the data from the screen to the sudoku array. You can use some different modules (or create your own) to make it faster. Modify the sudoku solving algorithm to make the automated solving part look a bit more like a human would think. No one in real life solves the puzzles as shown in the animation above. Feel free to modify this implementation and test it on different puzzles (even the most extreme ones). I’d like to thank you if you read the entire article. If you have any thoughts or have modified the code into something better, let me know about it in the comments section. :)
[ { "code": null, "e": 407, "s": 172, "text": "In this article, I will introduce a walkthrough on making your very own script that solves sudoku puzzles. Furthermore, this script is enhanced with PyAutoGUI to make sudoku solving quite automatic (you only have to execute the code)." }, { "code": null, "e": 459, "s": 407, "text": "I have divided the article in the following manner:" }, { "code": null, "e": 881, "s": 459, "text": "Introduction to sudoku — this brief section covers the basic rules that must be kept in mind;Sudoku solving algorithm — this section starts with defining necessary data structures and we will create an algorithm that would solve any given puzzle;Automation — it’s cool if your script knows the step-by-step solution to a puzzle. It’s even cooler if your code interacts with a web page and solves the sudoku automatically." }, { "code": null, "e": 975, "s": 881, "text": "Introduction to sudoku — this brief section covers the basic rules that must be kept in mind;" }, { "code": null, "e": 1129, "s": 975, "text": "Sudoku solving algorithm — this section starts with defining necessary data structures and we will create an algorithm that would solve any given puzzle;" }, { "code": null, "e": 1305, "s": 1129, "text": "Automation — it’s cool if your script knows the step-by-step solution to a puzzle. It’s even cooler if your code interacts with a web page and solves the sudoku automatically." }, { "code": null, "e": 1457, "s": 1305, "text": "I hope you have installed Python, Pillow, and PyAutoGUI module. If you don’t have the PyAutoGUI yet then you should follow the installation steps HERE." }, { "code": null, "e": 1580, "s": 1457, "text": "First things first. If you are not familiar with the rules of a sudoku puzzle, don’t be frightened. They are quite simple:" }, { "code": null, "e": 1724, "s": 1580, "text": "You must fill the boxes of a 9x9 grid with numbers from 1 to 9 in a way that there are no recurring numbers in each row, column, and 3x3 block." }, { "code": null, "e": 1885, "s": 1724, "text": "If you take a look at the image, the only number that fits into the top left box is two since it’s the only one that doesn’t appear in this row, column and box." }, { "code": null, "e": 2162, "s": 1885, "text": "Let’s take a random sudoku puzzle from the Internet and try to solve it with Python. I propose that we handle this puzzle as a two-dimensional Python array where empty boxes are represented with zeros and other boxes with corresponding numbers. We should obtain the following:" }, { "code": null, "e": 2532, "s": 2162, "text": "sudoku = [[8, 1, 0, 0, 3, 0, 0, 2, 7], [0, 6, 2, 0, 5, 0, 0, 9, 0], [0, 7, 0, 0, 0, 0, 0, 0, 0], [0, 9, 0, 6, 0, 0, 1, 0, 0], [1, 0, 0, 0, 2, 0, 0, 0, 4], [0, 0, 8, 0, 0, 5, 0, 7, 0], [0, 0, 0, 0, 0, 0, 0, 8, 0], [0, 2, 0, 0, 1, 0, 7, 5, 0], [3, 8, 0, 0, 7, 0, 0, 4, 2]]" }, { "code": null, "e": 2631, "s": 2532, "text": "When trying to access a certain element from the i-th row and j-th column, you simply need to call" }, { "code": null, "e": 2644, "s": 2631, "text": "sudoku[i][j]" }, { "code": null, "e": 2858, "s": 2644, "text": "Sure, this two-dimensional python array does not look like real sudoku without any gridlines. Hence, it would be great to print out the current state of the puzzle. Below is the code example along with its output." }, { "code": null, "e": 3178, "s": 2858, "text": "def printsudoku(): print(\"\\n\\n\\n\\n\\n\") for i in range(len(sudoku)): line = \"\" if i == 3 or i == 6: print(\"---------------------\") for j in range(len(sudoku[i])): if j == 3 or j == 6: line += \"| \" line += str(sudoku[i][j])+\" \" print(line)" }, { "code": null, "e": 3251, "s": 3178, "text": "Let’s get to it! Now we are ready for a step-by-step algorithm-creation." }, { "code": null, "e": 3533, "s": 3251, "text": "Disclaimer: I did not create this sudoku-solving algorithm entirely myself. The idea and implementation were copied from MIT OpenCourseWare Youtube channel, more specifically from this video. Yet, it’s licensed as Creative Commons BY-NC-SA which gives me a green light for sharing." }, { "code": null, "e": 3666, "s": 3533, "text": "To solve a certain cell, we must first find the row and column number of a cell that’s empty. The following function does the trick." }, { "code": null, "e": 3823, "s": 3666, "text": "def findNextCellToFill(sudoku): for x in range(9): for y in range(9): if sudoku[x][y] == 0: return x, y return -1, -1" }, { "code": null, "e": 4000, "s": 3823, "text": "This iterates through all the columns in the first row, then second row and so on. Whenever it encounters an empty cell, the function returns the corresponding indexes. Simple!" }, { "code": null, "e": 4275, "s": 4000, "text": "Suppose we have an entry e. We need a function that checks whether it violates the three main rules of sudoku when placed to the i-th row and j-th column. The following function returns True if none of the three rules are violated. Otherwise, the function will return False." }, { "code": null, "e": 4716, "s": 4275, "text": "def isValid(sudoku, i, j, e): rowOk = all([e != sudoku[i][x] for x in range(9)]) if rowOk: columnOk = all([e != sudoku[x][j] for x in range(9)]) if columnOk: secTopX, secTopY = 3*(i//3), 3*(j//3) for x in range(secTopX, secTopX+3): for y in range(secTopY, secTopY+3): if sudoku[x][y] == e: return False return True return False" }, { "code": null, "e": 4742, "s": 4716, "text": "Three rules are examined:" }, { "code": null, "e": 4995, "s": 4742, "text": "rowOk: this one checks if there are no repeating numbers in the i-th row;columnOk: this one makes sure if there are no repeating numbers in the j-th column;If both rowOk and columnOk are True then the lines 6–10 check if the entry fits a certain block." }, { "code": null, "e": 5069, "s": 4995, "text": "rowOk: this one checks if there are no repeating numbers in the i-th row;" }, { "code": null, "e": 5153, "s": 5069, "text": "columnOk: this one makes sure if there are no repeating numbers in the j-th column;" }, { "code": null, "e": 5250, "s": 5153, "text": "If both rowOk and columnOk are True then the lines 6–10 check if the entry fits a certain block." }, { "code": null, "e": 5336, "s": 5250, "text": "Now it’s all about solving the given sudoku. We’ll do it with the following function:" }, { "code": null, "e": 5644, "s": 5336, "text": "def solveSudoku(sudoku, i=0, j=0): i, j = findNextCellToFill(sudoku) if i == -1: return True for e in range(1, 10): if isValid(sudoku, i, j, e): sudoku[i][j] = e if solveSudoku(sudoku, i, j): return True sudoku[i][j] = 0 return False" }, { "code": null, "e": 5797, "s": 5644, "text": "The first three lines of the function make sure that we have an empty cell in our puzzle. If i is equal to -1 then we have completed solving our puzzle." }, { "code": null, "e": 6078, "s": 5797, "text": "If there is an empty cell at i-th row and j-th column then it will try to fit all the possible entries from 1 to 9 into this box. If the entry is valid (verified by the isValid function) then tries to solve the sudoku recursively under the assumption that this is a correct entry." }, { "code": null, "e": 6219, "s": 6078, "text": "If our assumption was incorrect then the 9-th line would return False and that sets the value of a cell in i-th row and j-th column to zero." }, { "code": null, "e": 6275, "s": 6219, "text": "To solve our sudoku, make the following function calls:" }, { "code": null, "e": 6308, "s": 6275, "text": "solveSudoku(sudoku)printsudoku()" }, { "code": null, "e": 6382, "s": 6308, "text": "The first one solves our puzzle and the latter shows the solution. Great!" }, { "code": null, "e": 6432, "s": 6382, "text": "The automation part is divided into two sections:" }, { "code": null, "e": 6594, "s": 6432, "text": "Locating the numbers on a sudoku grid. This way we can solve any sudoku without having to fill the sudoku variable manually.Filling the empty cells with numbers." }, { "code": null, "e": 6719, "s": 6594, "text": "Locating the numbers on a sudoku grid. This way we can solve any sudoku without having to fill the sudoku variable manually." }, { "code": null, "e": 6757, "s": 6719, "text": "Filling the empty cells with numbers." }, { "code": null, "e": 6847, "s": 6757, "text": "We are doing our automation by using the PyAutoGUI module. Please import it in your code." }, { "code": null, "e": 6871, "s": 6847, "text": "import pyautogui as pag" }, { "code": null, "e": 7103, "s": 6871, "text": "We are about to solve a random sudoku puzzle from Websudoku. Open a random puzzle and save image snippets from every number. They all should be saved to the same folder as your Python script. Make sure that the file format is .png." }, { "code": null, "e": 7254, "s": 7103, "text": "The snippets may have different dimensions, as long as they all feature only a number on a white background. Let’s name them as “1.png”, “2.png”, etc." }, { "code": null, "e": 7346, "s": 7254, "text": "The PyAutoGUI module has a function that locates the given image on your screen. In my case" }, { "code": null, "e": 7400, "s": 7346, "text": "for pos in pag.locateOnScreen(\"3.png\"): print(pos)" }, { "code": null, "e": 7453, "s": 7400, "text": "Returns all locations of number three on our screen:" }, { "code": null, "e": 7541, "s": 7453, "text": "Box(left=1124, top=510, width=32, height=33)Box(left=959, top=845, width=32, height=33)" }, { "code": null, "e": 7754, "s": 7541, "text": "The first two parameters (left and top) give us the pixel coordinates of the top-left corner of our image. The third and fourth give us the dimensions of our image but at the moment we are not going to need them." }, { "code": null, "e": 7814, "s": 7754, "text": "To get the locations of all the numbers, use the following:" }, { "code": null, "e": 7907, "s": 7814, "text": "for i in range(1, 10): for pos in pag.locateAllOnScreen(str(i)+'.png'): print(pos)" }, { "code": null, "e": 8016, "s": 7907, "text": "Since we are not going to use our previous sudoku array, let’s change all the numbers in this array to zero:" }, { "code": null, "e": 8386, "s": 8016, "text": "sudoku = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]" }, { "code": null, "e": 8509, "s": 8386, "text": "Now let’s define the pixel coordinates of two cells on our puzzle: top-left and bottom-right. In my case the numbers were:" }, { "code": null, "e": 8575, "s": 8509, "text": "topleftx = 975toplefty = 507bottomrightx = 1307bottomrighty = 846" }, { "code": null, "e": 8642, "s": 8575, "text": "Now that we have them, let’s define the width and height of a box:" }, { "code": null, "e": 8720, "s": 8642, "text": "boxwidth = (bottomrightx - topleftx)/8boxheight = (bottomrighty - toplefty)/8" }, { "code": null, "e": 8915, "s": 8720, "text": "Explanation: when looking at a row of cells, the distance from the leftmost to the rightmost cell is 8 box widths. The same goes for columns. Hence we must divide the coordinate difference by 8." }, { "code": null, "e": 9008, "s": 8915, "text": "Now we have to define a function that replaces zeros in sudoku array with the right numbers." }, { "code": null, "e": 9214, "s": 9008, "text": "def fillsudoku(nr, pos): global sudoku indexlocx = int((pos[0] - topleftx + boxwidth/2)//boxwidth) indexlocy = int((pos[1] - toplefty + boxheight/2)//boxwidth) sudoku[indexlocy][indexlocx] = nr" }, { "code": null, "e": 9397, "s": 9214, "text": "I’m not going to explain the math but it takes a Box object and finds the “index-coordinates” of our number. If you have done everything correctly so far then it will work perfectly." }, { "code": null, "e": 9459, "s": 9397, "text": "Finally, let’s fill the array with information on our screen:" }, { "code": null, "e": 9560, "s": 9459, "text": "for i in range(1, 10): for pos in pag.locateAllOnScreen(str(i)+'.png'): fillsudoku(i, pos)" }, { "code": null, "e": 9691, "s": 9560, "text": "If you aren’t quick enough to jump from your IDE to web browser then add the following delay method to the beginning of your code:" }, { "code": null, "e": 9770, "s": 9691, "text": "import timetime.sleep(5) #this makes a 5 second delay to executing the script" }, { "code": null, "e": 9973, "s": 9770, "text": "Great! Now we have a method that uses screen information for filling our sudoku array. Since we have our solving algorithm then we can solve this instantly. We only need the following function to do so:" }, { "code": null, "e": 10121, "s": 9973, "text": "def fillcell(nr, x, y): xcoord = topleftx + boxwidth * x ycoord = toplefty + boxheight * y pag.click(xcoord, ycoord) pag.press(str(nr))" }, { "code": null, "e": 10158, "s": 10121, "text": "Here we have three input parameters:" }, { "code": null, "e": 10200, "s": 10158, "text": "nr: this is the number we want to insert;" }, { "code": null, "e": 10255, "s": 10200, "text": "x: column index of the cell we are going to insert nr;" }, { "code": null, "e": 10307, "s": 10255, "text": "y: row index of the cell we are going to insert nr;" }, { "code": null, "e": 10457, "s": 10307, "text": "Lines 2–3 find the approximate coordinates of the midpoint of the cell we must insert our number. Lines 4–5 click on that cell and write that number." }, { "code": null, "e": 10570, "s": 10457, "text": "Oh yes! One more thing. Before solving the sudoku, please create a copy of the sudoku array. I’ll explain later." }, { "code": null, "e": 10616, "s": 10570, "text": "import copysudokucopy = copy.deepcopy(sudoku)" }, { "code": null, "e": 10672, "s": 10616, "text": "To be on the same line, I’ll embed a Github gist below:" }, { "code": null, "e": 10826, "s": 10672, "text": "So far we read the sudoku from our screen and solve it. We also have two identical arrays of our sudoku before trying to solve it: sudoku and sudokucopy." }, { "code": null, "e": 10929, "s": 10826, "text": "The sudokucopy was made to compare the initial and final state of our puzzle and fill the empty cells." }, { "code": null, "e": 11043, "s": 10929, "text": "for x in range(9): for y in range(9): if sudokucopy[x][y] == 0: fillcell(sudoku[x][y], y, x)" }, { "code": null, "e": 11143, "s": 11043, "text": "Now it’s ready for execution and if your configurations are correct, then it should look like this:" }, { "code": null, "e": 11185, "s": 11143, "text": "Of course, some improvements can be made:" }, { "code": null, "e": 11535, "s": 11185, "text": "It takes me approximately 20 seconds to load the data from the screen to the sudoku array. You can use some different modules (or create your own) to make it faster.Modify the sudoku solving algorithm to make the automated solving part look a bit more like a human would think. No one in real life solves the puzzles as shown in the animation above." }, { "code": null, "e": 11701, "s": 11535, "text": "It takes me approximately 20 seconds to load the data from the screen to the sudoku array. You can use some different modules (or create your own) to make it faster." }, { "code": null, "e": 11886, "s": 11701, "text": "Modify the sudoku solving algorithm to make the automated solving part look a bit more like a human would think. No one in real life solves the puzzles as shown in the animation above." }, { "code": null, "e": 11989, "s": 11886, "text": "Feel free to modify this implementation and test it on different puzzles (even the most extreme ones)." } ]
time.process_time() function in Python
In this tutorial, we are going to learn about the time.process_time() method. The method time.process_time() will return a float value of time in seconds of a system and user CPU time of the current process. Live Demo # importing the time module import time # printing the current process time print(time.process_time()) 1.171875 If you run the above code, then you will get the similar result as follows. 1.171875 Let's say we have a process that prints from in the given range. Let's find the time for that process. Understand the following code and run it. Live Demo # importing the time module import time # program to find the prime number def print_numbers(cap): for i in range(cap): print(i, end=' ') if __name__ == '__main__': number = 1000 # starting process start_time = time.process_time() print_numbers(number) # ending process end_time = time.process_time() print() print("Process time", end_time - start_time) If you run the above code, then you will get the similar result as follows. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 993 994 995 996 997 998 999 Process time 0.234375 If you have doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1140, "s": 1062, "text": "In this tutorial, we are going to learn about the time.process_time() method." }, { "code": null, "e": 1270, "s": 1140, "text": "The method time.process_time() will return a float value of time in seconds of a system and user CPU time of the current process." }, { "code": null, "e": 1281, "s": 1270, "text": " Live Demo" }, { "code": null, "e": 1393, "s": 1281, "text": "# importing the time module\nimport time\n# printing the current process time\nprint(time.process_time())\n1.171875" }, { "code": null, "e": 1469, "s": 1393, "text": "If you run the above code, then you will get the similar result as follows." }, { "code": null, "e": 1478, "s": 1469, "text": "1.171875" }, { "code": null, "e": 1623, "s": 1478, "text": "Let's say we have a process that prints from in the given range. Let's find the time for that\nprocess. Understand the following code and run it." }, { "code": null, "e": 1634, "s": 1623, "text": " Live Demo" }, { "code": null, "e": 2045, "s": 1634, "text": "# importing the time module\nimport time\n# program to find the prime number\ndef print_numbers(cap):\n for i in range(cap):\n print(i, end=' ')\n if __name__ == '__main__':\n number = 1000\n # starting process\n start_time = time.process_time()\n print_numbers(number)\n # ending process\n end_time = time.process_time()\n print()\n print(\"Process time\", end_time - start_time)" }, { "code": null, "e": 2121, "s": 2045, "text": "If you run the above code, then you will get the similar result as follows." }, { "code": null, "e": 6026, "s": 2121, "text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58\n59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86\n87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110\n111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131\n132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152\n153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173\n174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194\n195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215\n216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236\n237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257\n258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278\n279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299\n300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320\n321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341\n342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362\n363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383\n384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404\n405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425\n426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446\n447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467\n468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488\n489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509\n510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530\n531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551\n552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572\n573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593\n594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614\n615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635\n636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656\n657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677\n678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698\n699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719\n720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740\n741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761\n762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782\n783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803\n804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824\n825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845\n846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866\n867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887\n888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908\n909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929\n930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950\n951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971\n972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991\n993 994 995 996 997 998 999\nProcess time 0.234375" }, { "code": null, "e": 6099, "s": 6026, "text": "If you have doubts in the tutorial, mention them in the comment section." } ]
Java program to check whether the given number is an Armstrong number
An Armstrong number is a number which equals to the sum of the cubes of its individual digits. For example, 153 is an Armstrong number as − 153 = (1)3 + (5)3 + (3)3 153 1 + 125 + 27 154 153 1. Take integer variable Arms 2. Assign value to the variable 3. Split all digits of Arms 4. Find cube-value of each digits 5. Add all cube-values together 6. Save the output to Sum variable 7. If Sum equals to Arms print Armstrong Number 8. If Sum not equals to Arms print Not Armstrong Number import java.util.Scanner; public class ArmstrongNumber { public static void main(String args[]) { int number = 153; int check, rem, sum = 0; System.out.println("Enter the number to be verified:"); Scanner sc = new Scanner(System.in); number = sc.nextInt(); check = number; while(check != 0) { rem = check % 10; sum = sum + (rem * rem * rem); check = check / 10; } if(sum == number) System.out.println("Given number is an armstrong number."); else System.out.println("Given number is not an armstrong number."); } } Enter the number to be verified: 153 Given number is an armstrong number.
[ { "code": null, "e": 1202, "s": 1062, "text": "An Armstrong number is a number which equals to the sum of the cubes of its individual digits. For example, 153 is an Armstrong number as −" }, { "code": null, "e": 1252, "s": 1202, "text": "153 = (1)3 + (5)3 + (3)3\n153 1 + 125 + 27\n154 153" }, { "code": null, "e": 1547, "s": 1252, "text": "1. Take integer variable Arms\n2. Assign value to the variable\n3. Split all digits of Arms\n4. Find cube-value of each digits\n5. Add all cube-values together\n6. Save the output to Sum variable\n7. If Sum equals to Arms print Armstrong Number\n8. If Sum not equals to Arms print Not Armstrong Number" }, { "code": null, "e": 2173, "s": 1547, "text": "import java.util.Scanner;\npublic class ArmstrongNumber {\n public static void main(String args[]) {\n int number = 153;\n int check, rem, sum = 0;\n System.out.println(\"Enter the number to be verified:\");\n Scanner sc = new Scanner(System.in);\n number = sc.nextInt();\n check = number;\n while(check != 0) {\n rem = check % 10;\n sum = sum + (rem * rem * rem);\n check = check / 10;\n }\n if(sum == number)\n System.out.println(\"Given number is an armstrong number.\");\n else\n System.out.println(\"Given number is not an armstrong number.\");\n }\n}" }, { "code": null, "e": 2247, "s": 2173, "text": "Enter the number to be verified:\n153\nGiven number is an armstrong number." } ]
C++ Program to Implement Fermat’s Little Theorem
Fermat's little theorem is one of the fundamental results of elementary number theory and is the basis for the Fermat primality test. The theorem is named after Pierre de Fermat, who stated it in 1640. The Theorem states that if p is a prime number, then for any integer a, the number a p–a is an integer multiple of p. Begin Function power() is used to compute a raised to power b under modulo M function modInverse() to find modular inverse of a under modulo m : Let m is prime If a and m are relatively prime, then modulo inverse is a^(m - 2) mod m End #include <iostream> using namespace std; int pow(int a, int b, int M) { int x = 1, y = a; while (b > 0) { if (b % 2 == 1) { x = (x * y); if (x > M) x %= M; } y = (y * y); if (y > M) y %= M; b /= 2; } return x; } int modInverse(int a, int m) { return pow(a, m - 2, m); } int main() { int a, m; cout<<"Enter number to find modular multiplicative inverse: "; cin>>a; cout<<"Enter Modular Value: "; cin>>m; cout<<modInverse(a, m)<<endl; } Enter number to find modular multiplicative inverse: 26 Enter Modular Value: 7 3
[ { "code": null, "e": 1382, "s": 1062, "text": "Fermat's little theorem is one of the fundamental results of elementary number theory and is the basis for the Fermat primality test. The theorem is named after Pierre de Fermat, who stated it in 1640. The Theorem states that if p is a prime number, then for any integer a, the number a p–a is an integer multiple of p." }, { "code": null, "e": 1636, "s": 1382, "text": "Begin\n Function power() is used to compute a raised to power b under modulo M\n function modInverse() to find modular inverse of a under modulo m :\n Let m is prime\n If a and m are relatively prime, then\n modulo inverse is a^(m - 2) mod m\nEnd" }, { "code": null, "e": 2176, "s": 1636, "text": "#include <iostream>\nusing namespace std;\nint pow(int a, int b, int M) {\n int x = 1, y = a;\n while (b > 0) {\n if (b % 2 == 1) {\n x = (x * y);\n if (x > M)\n x %= M;\n }\n y = (y * y);\n if (y > M)\n y %= M;\n b /= 2;\n }\n return x;\n}\nint modInverse(int a, int m) {\n return pow(a, m - 2, m);\n}\nint main() {\n int a, m;\n cout<<\"Enter number to find modular multiplicative inverse: \";\n cin>>a;\n cout<<\"Enter Modular Value: \";\n cin>>m;\n cout<<modInverse(a, m)<<endl;\n}" }, { "code": null, "e": 2257, "s": 2176, "text": "Enter number to find modular multiplicative inverse: 26\nEnter Modular Value: 7\n3" } ]
C++ Vector Library - push_back() Function
The C++ function std::vector::push_back() inserts new element at the end of vector and increases size of vector by one. Following is the declaration for std::vector::push_back() function form std::vector header. void push_back (const value_type& val); void push_back (const value_type& val); void push_back (value_type&& val); None None. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::vector::push_back() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v; /* Insert 5 elements */ for (int i = 0; i < 5; ++i) v.push_back(i + 1); for (int i = 0; i < v.size(); ++i) cout << v[i] << endl; return 0; } Let us compile and run the above program, this will produce the following result − 1 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2723, "s": 2603, "text": "The C++ function std::vector::push_back() inserts new element at the end of vector and increases size of vector by one." }, { "code": null, "e": 2815, "s": 2723, "text": "Following is the declaration for std::vector::push_back() function form std::vector header." }, { "code": null, "e": 2856, "s": 2815, "text": "void push_back (const value_type& val);\n" }, { "code": null, "e": 2932, "s": 2856, "text": "void push_back (const value_type& val);\nvoid push_back (value_type&& val);\n" }, { "code": null, "e": 2937, "s": 2932, "text": "None" }, { "code": null, "e": 2943, "s": 2937, "text": "None." }, { "code": null, "e": 2988, "s": 2943, "text": "This member function never throws exception." }, { "code": null, "e": 3007, "s": 2988, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3083, "s": 3007, "text": "The following example shows the usage of std::vector::push_back() function." }, { "code": null, "e": 3347, "s": 3083, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v;\n\n /* Insert 5 elements */\n for (int i = 0; i < 5; ++i)\n v.push_back(i + 1);\n\n for (int i = 0; i < v.size(); ++i)\n cout << v[i] << endl;\n\n return 0;\n}" }, { "code": null, "e": 3430, "s": 3347, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3441, "s": 3430, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 3448, "s": 3441, "text": " Print" }, { "code": null, "e": 3459, "s": 3448, "text": " Add Notes" } ]
PL/SQL - Basic Syntax
In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts − Declarations This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program. Executable Commands This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed. Exception Handling This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the program. Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block − DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling> END; DECLARE message varchar2(20):= 'Hello, World!'; BEGIN dbms_output.put_line(message); END; / The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it produces the following result − Hello World PL/SQL procedure successfully completed. PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters. By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier. A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL − Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments. The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */. DECLARE -- variable declaration message varchar2(20):= 'Hello, World!'; BEGIN /* * PL/SQL executable statement(s) */ dbms_output.put_line(message); END; / When the above code is executed at the SQL prompt, it produces the following result − Hello World PL/SQL procedure successfully completed. A PL/SQL unit is any one of the following − PL/SQL block Function Package Package body Procedure Trigger Type Type body Each of these units will be discussed in the following chapters. Print Add Notes Bookmark this page
[ { "code": null, "e": 2291, "s": 2065, "text": "In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts −" }, { "code": null, "e": 2304, "s": 2291, "text": "Declarations" }, { "code": null, "e": 2471, "s": 2304, "text": "This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program." }, { "code": null, "e": 2491, "s": 2471, "text": "Executable Commands" }, { "code": null, "e": 2777, "s": 2491, "text": "This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed." }, { "code": null, "e": 2796, "s": 2777, "text": "Exception Handling" }, { "code": null, "e": 2923, "s": 2796, "text": "This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the program." }, { "code": null, "e": 3102, "s": 2923, "text": "Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −" }, { "code": null, "e": 3214, "s": 3102, "text": "DECLARE \n <declarations section> \nBEGIN \n <executable command(s)>\nEXCEPTION \n <exception handling> \nEND;\n" }, { "code": null, "e": 3319, "s": 3214, "text": "DECLARE \n message varchar2(20):= 'Hello, World!'; \nBEGIN \n dbms_output.put_line(message); \nEND; \n/ " }, { "code": null, "e": 3596, "s": 3319, "text": "The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3653, "s": 3596, "text": "Hello World \n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 3916, "s": 3653, "text": "PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters.\n" }, { "code": null, "e": 4080, "s": 3916, "text": "By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier." }, { "code": null, "e": 4176, "s": 4080, "text": "A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −" }, { "code": null, "e": 4372, "s": 4176, "text": "Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments." }, { "code": null, "e": 4636, "s": 4372, "text": "The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */." }, { "code": null, "e": 4820, "s": 4636, "text": "DECLARE \n -- variable declaration \n message varchar2(20):= 'Hello, World!'; \nBEGIN \n /* \n * PL/SQL executable statement(s) \n */ \n dbms_output.put_line(message); \nEND; \n/" }, { "code": null, "e": 4906, "s": 4820, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 4960, "s": 4906, "text": "Hello World\n\nPL/SQL procedure successfully completed." }, { "code": null, "e": 5004, "s": 4960, "text": "A PL/SQL unit is any one of the following −" }, { "code": null, "e": 5017, "s": 5004, "text": "PL/SQL block" }, { "code": null, "e": 5026, "s": 5017, "text": "Function" }, { "code": null, "e": 5034, "s": 5026, "text": "Package" }, { "code": null, "e": 5047, "s": 5034, "text": "Package body" }, { "code": null, "e": 5057, "s": 5047, "text": "Procedure" }, { "code": null, "e": 5065, "s": 5057, "text": "Trigger" }, { "code": null, "e": 5070, "s": 5065, "text": "Type" }, { "code": null, "e": 5080, "s": 5070, "text": "Type body" }, { "code": null, "e": 5145, "s": 5080, "text": "Each of these units will be discussed in the following chapters." }, { "code": null, "e": 5152, "s": 5145, "text": " Print" }, { "code": null, "e": 5163, "s": 5152, "text": " Add Notes" } ]
How to define a variable in C++?
To define a variable in C++, you need to use the following syntax − datatype variable_name; You need to know what type of data is your variable is going to hold and what it will be called. The variable name has constraints on what you can name it. Following are the rules for naming variables − Variable names in C++ can range from 1 to 255 characters. All variable names must begin with a letter of the alphabet or an underscore(_). After the first initial letter, variable names can also contain letters and numbers. Variable names are case sensitive. No spaces or special characters are allowed. You cannot use a C++ keyword (a reserved word) as a variable name. Here are some examples of acceptable variable names − mohd Piyush abc move_name a_123 myname50 _temp j a23b9 retVal Examples of defining variables − int my_var; float my_float; double num;
[ { "code": null, "e": 1131, "s": 1062, "text": "To define a variable in C++, you need to use the following syntax −" }, { "code": null, "e": 1155, "s": 1131, "text": "datatype variable_name;" }, { "code": null, "e": 1358, "s": 1155, "text": "You need to know what type of data is your variable is going to hold and what it will be called. The variable name has constraints on what you can name it. Following are the rules for naming variables −" }, { "code": null, "e": 1416, "s": 1358, "text": "Variable names in C++ can range from 1 to 255 characters." }, { "code": null, "e": 1497, "s": 1416, "text": "All variable names must begin with a letter of the alphabet or an underscore(_)." }, { "code": null, "e": 1584, "s": 1497, "text": "After the first initial letter, variable names can also contain letters and numbers. " }, { "code": null, "e": 1619, "s": 1584, "text": "Variable names are case sensitive." }, { "code": null, "e": 1664, "s": 1619, "text": "No spaces or special characters are allowed." }, { "code": null, "e": 1731, "s": 1664, "text": "You cannot use a C++ keyword (a reserved word) as a variable name." }, { "code": null, "e": 1785, "s": 1731, "text": "Here are some examples of acceptable variable names −" }, { "code": null, "e": 1878, "s": 1785, "text": "mohd Piyush abc move_name a_123\nmyname50 _temp j a23b9 retVal" }, { "code": null, "e": 1911, "s": 1878, "text": "Examples of defining variables −" }, { "code": null, "e": 1951, "s": 1911, "text": "int my_var;\nfloat my_float;\ndouble num;" } ]
How to Create 5 Star Skills Rating Bar using CSS ? - GeeksforGeeks
22 Oct, 2021 In this article, we will create a 5 Star Rating Bar using CSS and HTML. A 5-star rating bar is used to collect user opinions or feedback. Users can give a rating out of 5 as per their satisfaction. We will create the layout or design of the rating bar. Approach: For the Star Icons, we are using Font-Awesome Icon Library. Create the layout using HTML. For stylings use CSS properties. CSS library: To use Font Awesome Icons, we have to add the library in the HTML file using the link tag. <link href=”https://pro.fontawesome.com/releases/v5.10.0/css/all.css” rel=”stylesheet”/> By adding the link, we can access the icons provided by this library. You can get the link for your own project on the Font-Awesome website or you can use the same link as we have mentioned above. Syntax: To use Star Icon, use the following syntax. <i class="fas fa-star"></i> Note: Please refer to CSS Icons article for a better understanding. Example: We have created a 5 Star Rating Bar using the above approach. We have added a class clicked in the icon tag. This class is used to change the colour of the star. We have added the CSS properties in the style tag. HTML <!DOCTYPE html><html lang="en"> <head> <title>Rating Bar</title> <link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet" /> <style> .rating { font-size: 40px; } .clicked { color: rgb(135, 187, 32); } </style></head> <body> <h1>5 Star Rating Bar</h1> <div class="rating"> <i class="fa fa-star clicked"></i> <i class="fa fa-star clicked"></i> <i class="fa fa-star clicked"></i> <i class="fa fa-star clicked"></i> <i class="fa fa-star"></i> </div></body> </html> Output: 5 Star Rating Bar using CSS Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n22 Oct, 2021" }, { "code": null, "e": 26874, "s": 26621, "text": "In this article, we will create a 5 Star Rating Bar using CSS and HTML. A 5-star rating bar is used to collect user opinions or feedback. Users can give a rating out of 5 as per their satisfaction. We will create the layout or design of the rating bar." }, { "code": null, "e": 26884, "s": 26874, "text": "Approach:" }, { "code": null, "e": 26944, "s": 26884, "text": "For the Star Icons, we are using Font-Awesome Icon Library." }, { "code": null, "e": 26974, "s": 26944, "text": "Create the layout using HTML." }, { "code": null, "e": 27007, "s": 26974, "text": "For stylings use CSS properties." }, { "code": null, "e": 27111, "s": 27007, "text": "CSS library: To use Font Awesome Icons, we have to add the library in the HTML file using the link tag." }, { "code": null, "e": 27200, "s": 27111, "text": "<link href=”https://pro.fontawesome.com/releases/v5.10.0/css/all.css” rel=”stylesheet”/>" }, { "code": null, "e": 27397, "s": 27200, "text": "By adding the link, we can access the icons provided by this library. You can get the link for your own project on the Font-Awesome website or you can use the same link as we have mentioned above." }, { "code": null, "e": 27450, "s": 27397, "text": " Syntax: To use Star Icon, use the following syntax." }, { "code": null, "e": 27478, "s": 27450, "text": "<i class=\"fas fa-star\"></i>" }, { "code": null, "e": 27546, "s": 27478, "text": "Note: Please refer to CSS Icons article for a better understanding." }, { "code": null, "e": 27768, "s": 27546, "text": "Example: We have created a 5 Star Rating Bar using the above approach. We have added a class clicked in the icon tag. This class is used to change the colour of the star. We have added the CSS properties in the style tag." }, { "code": null, "e": 27773, "s": 27768, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Rating Bar</title> <link href=\"https://pro.fontawesome.com/releases/v5.10.0/css/all.css\" rel=\"stylesheet\" /> <style> .rating { font-size: 40px; } .clicked { color: rgb(135, 187, 32); } </style></head> <body> <h1>5 Star Rating Bar</h1> <div class=\"rating\"> <i class=\"fa fa-star clicked\"></i> <i class=\"fa fa-star clicked\"></i> <i class=\"fa fa-star clicked\"></i> <i class=\"fa fa-star clicked\"></i> <i class=\"fa fa-star\"></i> </div></body> </html>", "e": 28392, "s": 27773, "text": null }, { "code": null, "e": 28401, "s": 28392, "text": "Output: " }, { "code": null, "e": 28429, "s": 28401, "text": "5 Star Rating Bar using CSS" }, { "code": null, "e": 28566, "s": 28429, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28581, "s": 28566, "text": "CSS-Properties" }, { "code": null, "e": 28595, "s": 28581, "text": "CSS-Questions" }, { "code": null, "e": 28610, "s": 28595, "text": "HTML-Questions" }, { "code": null, "e": 28617, "s": 28610, "text": "Picked" }, { "code": null, "e": 28621, "s": 28617, "text": "CSS" }, { "code": null, "e": 28626, "s": 28621, "text": "HTML" }, { "code": null, "e": 28643, "s": 28626, "text": "Web Technologies" }, { "code": null, "e": 28648, "s": 28643, "text": "HTML" }, { "code": null, "e": 28746, "s": 28648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28785, "s": 28746, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28822, "s": 28785, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28851, "s": 28822, "text": "Form validation using jQuery" }, { "code": null, "e": 28886, "s": 28851, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28928, "s": 28886, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28988, "s": 28928, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29041, "s": 28988, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29102, "s": 29041, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29126, "s": 29102, "text": "REST API (Introduction)" } ]
Find ways an Integer can be expressed as sum of n-th power of unique natural numbers - GeeksforGeeks
17 Apr, 2022 Given two numbers x and n, find a number of ways x can be expressed as sum of n-th power of unique natural numbers. Examples : Input : x = 10, n = 2Output : 1Explanation: 10 = 12 + 32, Hence total 1 possibility Input : x = 100, n = 2Output : 3Explanation: 100 = 102 OR 62 + 82 OR 12 + 32 + 42 + 52 + 72 Hence total 3 possibilities The idea is simple. We iterate through all number starting from 1. For every number, we recursively try all greater numbers and if we are able to find sum, we increment result C++ Java Python3 C# PHP Javascript // C++ program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers.#include <bits/stdc++.h>using namespace std; // Function to calculate and return the// power of any given numberint power(int num, unsigned int n){ if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2);} // Function to check power representations recursivelyint checkRecursive(int x, int n, int curr_num = 1, int curr_sum = 0){ // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results;} // Driver Code.int main(){ int x = 10, n = 2; cout << checkRecursive(x, n); return 0;} // Java program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers. class GFG { // Function to calculate and return the // power of any given number static int power(int num, int n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2); } // Function to check power representations recursively static int checkRecursive(int x, int n, int curr_num, int curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. public static void main(String[] args) { int x = 10, n = 2; System.out.println(checkRecursive(x, n, 1, 0)); }} // This code is contributed by mits # Python3 program to count number of ways any# given integer x can be expressed as n-th# power of unique natural numbers. # Function to calculate and return the# power of any given number def power(num, n): if(n == 0): return 1 elif(n % 2 == 0): return power(num, n // 2) * power(num, n // 2) else: return num * power(num, n // 2) * power(num, n // 2) # Function to check power representations recursively def checkRecursive(x, n, curr_num=1, curr_sum=0): # Initialize number of ways to express # x as n-th powers of different natural # numbers results = 0 # Calling power of 'i' raised to 'n' p = power(curr_num, n) while(p + curr_sum < x): # Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum) curr_num = curr_num + 1 p = power(curr_num, n) # If sum of powers is equal to x # then increase the value of result. if(p + curr_sum == x): results = results + 1 # Return the final result return results # Driver Code.if __name__ == '__main__': x = 10 n = 2 print(checkRecursive(x, n)) # This code is contributed by# Sanjit_Prasad // C# program to count number of ways any// given integer x can be expressed as// n-th power of unique natural numbers.using System; class GFG { // Function to calculate and return // the power of any given number static int power(int num, int n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2); } // Function to check power // representations recursively static int checkRecursive(int x, int n, int curr_num, int curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. public static void Main() { int x = 10, n = 2; System.Console.WriteLine( checkRecursive(x, n, 1, 0)); }} // This code is contributed by mits <?php// PHP program to count// number of ways any// given integer x can// be expressed as n-th// power of unique// natural numbers. // Function to calculate and return// the power of any given numberfunction power($num, $n){ if ($n == 0) return 1; else if ($n % 2 == 0) return power($num, (int)($n / 2)) * power($num, (int)($n / 2)); else return $num * power($num, (int)($n / 2)) * power($num, (int)($n / 2));} // Function to check power// representations recursivelyfunction checkRecursive($x, $n, $curr_num = 1, $curr_sum = 0){ // Initialize number of // ways to express // x as n-th powers // of different natural // numbers $results = 0; // Calling power of 'i' // raised to 'n' $p = power($curr_num, $n); while ($p + $curr_sum < $x) { // Recursively check all // greater values of i $results += checkRecursive($x, $n, $curr_num + 1, $p + $curr_sum); $curr_num++; $p = power($curr_num, $n); } // If sum of powers // is equal to x // then increase the // value of result. if ($p + $curr_sum == $x) $results++; // Return the final result return $results;} // Driver Code.$x = 10; $n = 2;echo(checkRecursive($x, $n)); // This code is contributed by Ajit.?> <script>// javascript program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers. // Function to calculate and return the // power of any given number function power(num , n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, parseInt(n / 2)) * power(num, parseInt(n / 2)); else return num * power(num,parseInt(n / 2)) * power(num, parseInt(n / 2)); } // Function to check power representations recursively function checkRecursive(x , n , curr_num , curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers var results = 0; // Calling power of 'i' raised to 'n' var p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. var x = 10, n = 2; document.write(checkRecursive(x, n, 1, 0)); // This code is contributed by gauravrajput1</script> 1 Alternate Solution : Below is an alternate simpler solution provided by Shivam Kanodia. C++ C Java Python3 C# PHP Javascript // C++ program to find number of ways to express// a number as sum of n-th powers of numbers.#include<bits/stdc++.h>using namespace std; int res = 0;int checkRecursive(int num, int x, int k, int n){ if (x == 0) res++; int r = (int)floor(pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)pow(i, n); if (a >= 0) checkRecursive(num, x - (int)pow(i, n), i, n); } return res;} // Wrapper over checkRecursive()int check(int x, int n){ return checkRecursive(x, x, 0, n);} // Driver Codeint main(){ cout << (check(10, 2)); return 0;} // This code is contributed by mits // C program to find number of ways to express// a number as sum of n-th powers of numbers.#include <math.h>#include <stdio.h> int res = 0;int checkRecursive(int num, int x, int k, int n){ if (x == 0) res++; int r = (int)floor(pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)pow(i, n); if (a >= 0) checkRecursive(num, x - (int)pow(i, n), i, n); } return res;} // Wrapper over checkRecursive()int check(int x, int n){ return checkRecursive(x, x, 0, n);} // Driver Codeint main(){ printf("%d", (check(10, 2))); return 0;} // This code is contributed by Rohit Pradhan // Java program to find number of ways to express a// number as sum of n-th powers of numbers.import java.io.*;import java.util.*; public class Solution { static int res = 0; static int checkRecursive(int num, int x, int k, int n) { if (x == 0) res++; int r = (int)Math.floor(Math.pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)Math.pow(i, n); if (a >= 0) checkRecursive(num, x - (int)Math.pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() static int check(int x, int n) { return checkRecursive(x, x, 0, n); } public static void main(String[] args) { System.out.println(check(10, 2)); }} # Python 3 program to find number of ways to express# a number as sum of n-th powers of numbers. def checkRecursive(num, rem_num, next_int, n, ans=0): if (rem_num == 0): ans += 1 r = int(num**(1 / n)) for i in range(next_int + 1, r + 1): a = rem_num - int(i**n) if a >= 0: ans += checkRecursive(num, rem_num - int(i**n), i, n, 0) return ans # Wrapper over checkRecursive() def check(x, n): return checkRecursive(x, x, 0, n) # Driver Codeif __name__ == '__main__': print(check(10, 2)) # This code is contributed by# Surendra_Gangwar // C# program to find number of// ways to express a number as sum// of n-th powers of numbers.using System; class Solution { static int res = 0; static int checkRecursive(int num, int x, int k, int n) { if (x == 0) res++; int r = (int)Math.Floor(Math.Pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)Math.Pow(i, n); if (a >= 0) checkRecursive(num, x - (int)Math.Pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() static int check(int x, int n) { return checkRecursive(x, x, 0, n); } // Driver code public static void Main() { Console.WriteLine(check(10, 2)); }} // This code is contributed by vt_m. <?php// PHP program to find number// of ways to express a number// as sum of n-th powers of numbers.$res = 0; function checkRecursive($num, $x, $k, $n){ global $res; if ($x == 0) $res++; $r = (int)floor(pow($num, 1.0 / $n)); for ($i = $k + 1; $i <= $r; $i++) { $a = $x - (int)pow($i, $n); if ($a >= 0) checkRecursive($num, $x - (int)pow($i, $n), $i, $n); } return $res;} // Wrapper over// checkRecursive()function check($x, $n){ return checkRecursive($x, $x, 0, $n);} // Driver Codeecho (check(10, 2)); // This code is contributed by ajit?> <script> // JavaScript program for the above approach let res = 0; function checkRecursive(num, x, k, n) { if (x == 0) res++; let r = Math.floor(Math.pow(num, 1.0 / n)); for (let i = k + 1; i <= r; i++) { let a = x - Math.pow(i, n); if (a >= 0) checkRecursive(num, x - Math.pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() function check(x, n) { return checkRecursive(x, x, 0, n); } // Driver Code document.write(check(10, 2)); // This code is contributed by splevel62.</script> 1 Simple Recursive Solution: contributed by Ram Jondhale. C++ Java C# #include <iostream>#include<cmath>using namespace std; //Helper functionint getAllWaysHelper(int remainingSum, int power, int base){ //calculate power int result = pow(base, power); if(remainingSum == result) return 1; if(remainingSum < result) return 0; //Two recursive calls one to include current base's power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, base + 1); int y = getAllWaysHelper(remainingSum, power, base+1); return x + y;} int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1);} // Driver Code.int main(){ int x = 10, n = 2; cout << getAllWays(x, n); return 0;} // Java program to implement the approachimport java.io.*; class GFG { public static int getAllWaysHelper(int remainingSum, int power, int base) { // calculate power int result = (int)Math.pow(base, power); if (remainingSum == result) return 1; if (remainingSum < result) return 0; // Two recursive calls one to include current base's // power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, base + 1); int y = getAllWaysHelper(remainingSum, power, base + 1); return x + y; } public static int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1); } // Driver Code public static void main(String[] args) { int x = 10, n = 2; System.out.print(getAllWays(x, n)); }} // This code is contributed by Rohit Pradhan using System;class GFG { // Helper function static int getAllWaysHelper(int remainingSum, int power, int bases) { // calculate power int result = (int)Math.Pow(bases, power); if (remainingSum == result) return 1; if (remainingSum < result) return 0; // Two recursive calls one to include current base's // power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, bases + 1); int y = getAllWaysHelper(remainingSum, power, bases + 1); return x + y; } static int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1); } // Driver Code. public static int Main() { int x = 10, n = 2; Console.Write(getAllWays(x, n)); return 0; }} // This code is contributed by Taranpreet 1 This article is contributed by DANISH KALEEM. 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 jit_t Sanjit_Prasad Mithun Kumar SURENDRA_GANGWAR vikukej1241 splevel62 GauravRajput1 ramjondhale1 amartyaghoshgfg singhh3010 rohit768 Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find GCD or HCF of two numbers Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Recursion Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Program for Tower of Hanoi Program for Sum of the digits of a given number Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 25234, "s": 25206, "text": "\n17 Apr, 2022" }, { "code": null, "e": 25350, "s": 25234, "text": "Given two numbers x and n, find a number of ways x can be expressed as sum of n-th power of unique natural numbers." }, { "code": null, "e": 25362, "s": 25350, "text": "Examples : " }, { "code": null, "e": 25447, "s": 25362, "text": "Input : x = 10, n = 2Output : 1Explanation: 10 = 12 + 32, Hence total 1 possibility" }, { "code": null, "e": 25568, "s": 25447, "text": "Input : x = 100, n = 2Output : 3Explanation: 100 = 102 OR 62 + 82 OR 12 + 32 + 42 + 52 + 72 Hence total 3 possibilities" }, { "code": null, "e": 25744, "s": 25568, "text": "The idea is simple. We iterate through all number starting from 1. For every number, we recursively try all greater numbers and if we are able to find sum, we increment result" }, { "code": null, "e": 25748, "s": 25744, "text": "C++" }, { "code": null, "e": 25753, "s": 25748, "text": "Java" }, { "code": null, "e": 25761, "s": 25753, "text": "Python3" }, { "code": null, "e": 25764, "s": 25761, "text": "C#" }, { "code": null, "e": 25768, "s": 25764, "text": "PHP" }, { "code": null, "e": 25779, "s": 25768, "text": "Javascript" }, { "code": "// C++ program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers.#include <bits/stdc++.h>using namespace std; // Function to calculate and return the// power of any given numberint power(int num, unsigned int n){ if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2);} // Function to check power representations recursivelyint checkRecursive(int x, int n, int curr_num = 1, int curr_sum = 0){ // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results;} // Driver Code.int main(){ int x = 10, n = 2; cout << checkRecursive(x, n); return 0;}", "e": 27068, "s": 25779, "text": null }, { "code": "// Java program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers. class GFG { // Function to calculate and return the // power of any given number static int power(int num, int n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2); } // Function to check power representations recursively static int checkRecursive(int x, int n, int curr_num, int curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. public static void main(String[] args) { int x = 10, n = 2; System.out.println(checkRecursive(x, n, 1, 0)); }} // This code is contributed by mits", "e": 28579, "s": 27068, "text": null }, { "code": "# Python3 program to count number of ways any# given integer x can be expressed as n-th# power of unique natural numbers. # Function to calculate and return the# power of any given number def power(num, n): if(n == 0): return 1 elif(n % 2 == 0): return power(num, n // 2) * power(num, n // 2) else: return num * power(num, n // 2) * power(num, n // 2) # Function to check power representations recursively def checkRecursive(x, n, curr_num=1, curr_sum=0): # Initialize number of ways to express # x as n-th powers of different natural # numbers results = 0 # Calling power of 'i' raised to 'n' p = power(curr_num, n) while(p + curr_sum < x): # Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum) curr_num = curr_num + 1 p = power(curr_num, n) # If sum of powers is equal to x # then increase the value of result. if(p + curr_sum == x): results = results + 1 # Return the final result return results # Driver Code.if __name__ == '__main__': x = 10 n = 2 print(checkRecursive(x, n)) # This code is contributed by# Sanjit_Prasad", "e": 29775, "s": 28579, "text": null }, { "code": "// C# program to count number of ways any// given integer x can be expressed as// n-th power of unique natural numbers.using System; class GFG { // Function to calculate and return // the power of any given number static int power(int num, int n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, n / 2) * power(num, n / 2); else return num * power(num, n / 2) * power(num, n / 2); } // Function to check power // representations recursively static int checkRecursive(int x, int n, int curr_num, int curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers int results = 0; // Calling power of 'i' raised to 'n' int p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. public static void Main() { int x = 10, n = 2; System.Console.WriteLine( checkRecursive(x, n, 1, 0)); }} // This code is contributed by mits", "e": 31308, "s": 29775, "text": null }, { "code": "<?php// PHP program to count// number of ways any// given integer x can// be expressed as n-th// power of unique// natural numbers. // Function to calculate and return// the power of any given numberfunction power($num, $n){ if ($n == 0) return 1; else if ($n % 2 == 0) return power($num, (int)($n / 2)) * power($num, (int)($n / 2)); else return $num * power($num, (int)($n / 2)) * power($num, (int)($n / 2));} // Function to check power// representations recursivelyfunction checkRecursive($x, $n, $curr_num = 1, $curr_sum = 0){ // Initialize number of // ways to express // x as n-th powers // of different natural // numbers $results = 0; // Calling power of 'i' // raised to 'n' $p = power($curr_num, $n); while ($p + $curr_sum < $x) { // Recursively check all // greater values of i $results += checkRecursive($x, $n, $curr_num + 1, $p + $curr_sum); $curr_num++; $p = power($curr_num, $n); } // If sum of powers // is equal to x // then increase the // value of result. if ($p + $curr_sum == $x) $results++; // Return the final result return $results;} // Driver Code.$x = 10; $n = 2;echo(checkRecursive($x, $n)); // This code is contributed by Ajit.?>", "e": 32766, "s": 31308, "text": null }, { "code": "<script>// javascript program to count number of ways any// given integer x can be expressed as n-th// power of unique natural numbers. // Function to calculate and return the // power of any given number function power(num , n) { if (n == 0) return 1; else if (n % 2 == 0) return power(num, parseInt(n / 2)) * power(num, parseInt(n / 2)); else return num * power(num,parseInt(n / 2)) * power(num, parseInt(n / 2)); } // Function to check power representations recursively function checkRecursive(x , n , curr_num , curr_sum) { // Initialize number of ways to express // x as n-th powers of different natural // numbers var results = 0; // Calling power of 'i' raised to 'n' var p = power(curr_num, n); while (p + curr_sum < x) { // Recursively check all greater values of i results += checkRecursive(x, n, curr_num + 1, p + curr_sum); curr_num++; p = power(curr_num, n); } // If sum of powers is equal to x // then increase the value of result. if (p + curr_sum == x) results++; // Return the final result return results; } // Driver Code. var x = 10, n = 2; document.write(checkRecursive(x, n, 1, 0)); // This code is contributed by gauravrajput1</script>", "e": 34195, "s": 32766, "text": null }, { "code": null, "e": 34197, "s": 34195, "text": "1" }, { "code": null, "e": 34218, "s": 34197, "text": "Alternate Solution :" }, { "code": null, "e": 34285, "s": 34218, "text": "Below is an alternate simpler solution provided by Shivam Kanodia." }, { "code": null, "e": 34289, "s": 34285, "text": "C++" }, { "code": null, "e": 34291, "s": 34289, "text": "C" }, { "code": null, "e": 34296, "s": 34291, "text": "Java" }, { "code": null, "e": 34304, "s": 34296, "text": "Python3" }, { "code": null, "e": 34307, "s": 34304, "text": "C#" }, { "code": null, "e": 34311, "s": 34307, "text": "PHP" }, { "code": null, "e": 34322, "s": 34311, "text": "Javascript" }, { "code": "// C++ program to find number of ways to express// a number as sum of n-th powers of numbers.#include<bits/stdc++.h>using namespace std; int res = 0;int checkRecursive(int num, int x, int k, int n){ if (x == 0) res++; int r = (int)floor(pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)pow(i, n); if (a >= 0) checkRecursive(num, x - (int)pow(i, n), i, n); } return res;} // Wrapper over checkRecursive()int check(int x, int n){ return checkRecursive(x, x, 0, n);} // Driver Codeint main(){ cout << (check(10, 2)); return 0;} // This code is contributed by mits", "e": 34996, "s": 34322, "text": null }, { "code": "// C program to find number of ways to express// a number as sum of n-th powers of numbers.#include <math.h>#include <stdio.h> int res = 0;int checkRecursive(int num, int x, int k, int n){ if (x == 0) res++; int r = (int)floor(pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)pow(i, n); if (a >= 0) checkRecursive(num, x - (int)pow(i, n), i, n); } return res;} // Wrapper over checkRecursive()int check(int x, int n){ return checkRecursive(x, x, 0, n);} // Driver Codeint main(){ printf(\"%d\", (check(10, 2))); return 0;} // This code is contributed by Rohit Pradhan", "e": 35643, "s": 34996, "text": null }, { "code": "// Java program to find number of ways to express a// number as sum of n-th powers of numbers.import java.io.*;import java.util.*; public class Solution { static int res = 0; static int checkRecursive(int num, int x, int k, int n) { if (x == 0) res++; int r = (int)Math.floor(Math.pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)Math.pow(i, n); if (a >= 0) checkRecursive(num, x - (int)Math.pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() static int check(int x, int n) { return checkRecursive(x, x, 0, n); } public static void main(String[] args) { System.out.println(check(10, 2)); }}", "e": 36432, "s": 35643, "text": null }, { "code": "# Python 3 program to find number of ways to express# a number as sum of n-th powers of numbers. def checkRecursive(num, rem_num, next_int, n, ans=0): if (rem_num == 0): ans += 1 r = int(num**(1 / n)) for i in range(next_int + 1, r + 1): a = rem_num - int(i**n) if a >= 0: ans += checkRecursive(num, rem_num - int(i**n), i, n, 0) return ans # Wrapper over checkRecursive() def check(x, n): return checkRecursive(x, x, 0, n) # Driver Codeif __name__ == '__main__': print(check(10, 2)) # This code is contributed by# Surendra_Gangwar", "e": 37020, "s": 36432, "text": null }, { "code": "// C# program to find number of// ways to express a number as sum// of n-th powers of numbers.using System; class Solution { static int res = 0; static int checkRecursive(int num, int x, int k, int n) { if (x == 0) res++; int r = (int)Math.Floor(Math.Pow(num, 1.0 / n)); for (int i = k + 1; i <= r; i++) { int a = x - (int)Math.Pow(i, n); if (a >= 0) checkRecursive(num, x - (int)Math.Pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() static int check(int x, int n) { return checkRecursive(x, x, 0, n); } // Driver code public static void Main() { Console.WriteLine(check(10, 2)); }} // This code is contributed by vt_m.", "e": 37867, "s": 37020, "text": null }, { "code": "<?php// PHP program to find number// of ways to express a number// as sum of n-th powers of numbers.$res = 0; function checkRecursive($num, $x, $k, $n){ global $res; if ($x == 0) $res++; $r = (int)floor(pow($num, 1.0 / $n)); for ($i = $k + 1; $i <= $r; $i++) { $a = $x - (int)pow($i, $n); if ($a >= 0) checkRecursive($num, $x - (int)pow($i, $n), $i, $n); } return $res;} // Wrapper over// checkRecursive()function check($x, $n){ return checkRecursive($x, $x, 0, $n);} // Driver Codeecho (check(10, 2)); // This code is contributed by ajit?>", "e": 38596, "s": 37867, "text": null }, { "code": "<script> // JavaScript program for the above approach let res = 0; function checkRecursive(num, x, k, n) { if (x == 0) res++; let r = Math.floor(Math.pow(num, 1.0 / n)); for (let i = k + 1; i <= r; i++) { let a = x - Math.pow(i, n); if (a >= 0) checkRecursive(num, x - Math.pow(i, n), i, n); } return res; } // Wrapper over checkRecursive() function check(x, n) { return checkRecursive(x, x, 0, n); } // Driver Code document.write(check(10, 2)); // This code is contributed by splevel62.</script>", "e": 39244, "s": 38596, "text": null }, { "code": null, "e": 39246, "s": 39244, "text": "1" }, { "code": null, "e": 39273, "s": 39246, "text": "Simple Recursive Solution:" }, { "code": null, "e": 39302, "s": 39273, "text": "contributed by Ram Jondhale." }, { "code": null, "e": 39306, "s": 39302, "text": "C++" }, { "code": null, "e": 39311, "s": 39306, "text": "Java" }, { "code": null, "e": 39314, "s": 39311, "text": "C#" }, { "code": "#include <iostream>#include<cmath>using namespace std; //Helper functionint getAllWaysHelper(int remainingSum, int power, int base){ //calculate power int result = pow(base, power); if(remainingSum == result) return 1; if(remainingSum < result) return 0; //Two recursive calls one to include current base's power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, base + 1); int y = getAllWaysHelper(remainingSum, power, base+1); return x + y;} int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1);} // Driver Code.int main(){ int x = 10, n = 2; cout << getAllWays(x, n); return 0;}", "e": 40011, "s": 39314, "text": null }, { "code": "// Java program to implement the approachimport java.io.*; class GFG { public static int getAllWaysHelper(int remainingSum, int power, int base) { // calculate power int result = (int)Math.pow(base, power); if (remainingSum == result) return 1; if (remainingSum < result) return 0; // Two recursive calls one to include current base's // power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, base + 1); int y = getAllWaysHelper(remainingSum, power, base + 1); return x + y; } public static int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1); } // Driver Code public static void main(String[] args) { int x = 10, n = 2; System.out.print(getAllWays(x, n)); }} // This code is contributed by Rohit Pradhan", "e": 40924, "s": 40011, "text": null }, { "code": "using System;class GFG { // Helper function static int getAllWaysHelper(int remainingSum, int power, int bases) { // calculate power int result = (int)Math.Pow(bases, power); if (remainingSum == result) return 1; if (remainingSum < result) return 0; // Two recursive calls one to include current base's // power in sum another to exclude int x = getAllWaysHelper(remainingSum - result, power, bases + 1); int y = getAllWaysHelper(remainingSum, power, bases + 1); return x + y; } static int getAllWays(int sum, int power) { return getAllWaysHelper(sum, power, 1); } // Driver Code. public static int Main() { int x = 10, n = 2; Console.Write(getAllWays(x, n)); return 0; }} // This code is contributed by Taranpreet", "e": 41884, "s": 40924, "text": null }, { "code": null, "e": 41886, "s": 41884, "text": "1" }, { "code": null, "e": 42308, "s": 41886, "text": "This article is contributed by DANISH KALEEM. 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": 42313, "s": 42308, "text": "vt_m" }, { "code": null, "e": 42319, "s": 42313, "text": "jit_t" }, { "code": null, "e": 42333, "s": 42319, "text": "Sanjit_Prasad" }, { "code": null, "e": 42346, "s": 42333, "text": "Mithun Kumar" }, { "code": null, "e": 42363, "s": 42346, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 42375, "s": 42363, "text": "vikukej1241" }, { "code": null, "e": 42385, "s": 42375, "text": "splevel62" }, { "code": null, "e": 42399, "s": 42385, "text": "GauravRajput1" }, { "code": null, "e": 42412, "s": 42399, "text": "ramjondhale1" }, { "code": null, "e": 42428, "s": 42412, "text": "amartyaghoshgfg" }, { "code": null, "e": 42439, "s": 42428, "text": "singhh3010" }, { "code": null, "e": 42448, "s": 42439, "text": "rohit768" }, { "code": null, "e": 42461, "s": 42448, "text": "Mathematical" }, { "code": null, "e": 42471, "s": 42461, "text": "Recursion" }, { "code": null, "e": 42484, "s": 42471, "text": "Mathematical" }, { "code": null, "e": 42494, "s": 42484, "text": "Recursion" }, { "code": null, "e": 42592, "s": 42494, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42601, "s": 42592, "text": "Comments" }, { "code": null, "e": 42614, "s": 42601, "text": "Old Comments" }, { "code": null, "e": 42656, "s": 42614, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 42680, "s": 42656, "text": "Merge two sorted arrays" }, { "code": null, "e": 42723, "s": 42680, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 42737, "s": 42723, "text": "Prime Numbers" }, { "code": null, "e": 42786, "s": 42737, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 42796, "s": 42786, "text": "Recursion" }, { "code": null, "e": 42881, "s": 42796, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 42908, "s": 42881, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 42956, "s": 42908, "text": "Program for Sum of the digits of a given number" } ]
AngularJS - HTML DOM
The following directives are used to bind application data to the attributes of HTML DOM elements − ng-disabled disables a given control. ng-show shows a given control. ng-hide hides a given control. ng-click represents a AngularJS click event. Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation. <input type = "checkbox" ng-model = "enableDisableButton">Disable Button <button ng-disabled = "enableDisableButton">Click Me!</button> Add ng-show attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation. <input type = "checkbox" ng-model = "showHide1">Show Button <button ng-show = "showHide1">Click Me!</button> Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation. <input type = "checkbox" ng-model = "showHide2">Hide Button <button ng-hide = "showHide2">Click Me!</button> Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and see the variation. <p>Total click: {{ clickCounter }}</p> <button ng-click = "clickCounter = clickCounter + 1">Click Me!</button> The following example shows use of all the above mentioned directives. <html> <head> <title>AngularJS HTML DOM</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = ""> <table border = "0"> <tr> <td><input type = "checkbox" ng-model = "enableDisableButton">Disable Button</td> <td><button ng-disabled = "enableDisableButton">Click Me!</button></td> </tr> <tr> <td><input type = "checkbox" ng-model = "showHide1">Show Button</td> <td><button ng-show = "showHide1">Click Me!</button></td> </tr> <tr> <td><input type = "checkbox" ng-model = "showHide2">Hide Button</td> <td><button ng-hide = "showHide2">Click Me!</button></td> </tr> <tr> <td><p>Total click: {{ clickCounter }}</p></td> <td><button ng-click = "clickCounter = clickCounter + 1">Click Me!</button></td> </tr> </table> </div> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </body> </html> Open the file testAngularJS.htm in a web browser and see the result. Total click: {{ clickCounter }} 16 Lectures 1.5 hours Anadi Sharma 40 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2799, "s": 2699, "text": "The following directives are used to bind application data to the attributes of HTML DOM elements −" }, { "code": null, "e": 2811, "s": 2799, "text": "ng-disabled" }, { "code": null, "e": 2837, "s": 2811, "text": "disables a given control." }, { "code": null, "e": 2845, "s": 2837, "text": "ng-show" }, { "code": null, "e": 2868, "s": 2845, "text": "shows a given control." }, { "code": null, "e": 2876, "s": 2868, "text": "ng-hide" }, { "code": null, "e": 2899, "s": 2876, "text": "hides a given control." }, { "code": null, "e": 2908, "s": 2899, "text": "ng-click" }, { "code": null, "e": 2944, "s": 2908, "text": "represents a AngularJS click event." }, { "code": null, "e": 3061, "s": 2944, "text": "Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation." }, { "code": null, "e": 3198, "s": 3061, "text": "<input type = \"checkbox\" ng-model = \"enableDisableButton\">Disable Button\n<button ng-disabled = \"enableDisableButton\">Click Me!</button>\n" }, { "code": null, "e": 3311, "s": 3198, "text": "Add ng-show attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation." }, { "code": null, "e": 3421, "s": 3311, "text": "<input type = \"checkbox\" ng-model = \"showHide1\">Show Button\n<button ng-show = \"showHide1\">Click Me!</button>\n" }, { "code": null, "e": 3534, "s": 3421, "text": "Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation." }, { "code": null, "e": 3644, "s": 3534, "text": "<input type = \"checkbox\" ng-model = \"showHide2\">Hide Button\n<button ng-hide = \"showHide2\">Click Me!</button>\n" }, { "code": null, "e": 3751, "s": 3644, "text": "Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and see the variation." }, { "code": null, "e": 3863, "s": 3751, "text": "<p>Total click: {{ clickCounter }}</p>\n<button ng-click = \"clickCounter = clickCounter + 1\">Click Me!</button>\n" }, { "code": null, "e": 3934, "s": 3863, "text": "The following example shows use of all the above mentioned directives." }, { "code": null, "e": 5091, "s": 3934, "text": "<html>\n <head>\n <title>AngularJS HTML DOM</title>\n </head>\n \n <body>\n <h2>AngularJS Sample Application</h2>\n \n <div ng-app = \"\">\n <table border = \"0\">\n <tr>\n <td><input type = \"checkbox\" ng-model = \"enableDisableButton\">Disable Button</td>\n <td><button ng-disabled = \"enableDisableButton\">Click Me!</button></td>\n </tr>\n <tr>\n <td><input type = \"checkbox\" ng-model = \"showHide1\">Show Button</td>\n <td><button ng-show = \"showHide1\">Click Me!</button></td>\n </tr>\n <tr>\n <td><input type = \"checkbox\" ng-model = \"showHide2\">Hide Button</td>\n <td><button ng-hide = \"showHide2\">Click Me!</button></td>\n </tr>\n <tr>\n <td><p>Total click: {{ clickCounter }}</p></td>\n <td><button ng-click = \"clickCounter = clickCounter + 1\">Click Me!</button></td>\n </tr>\n </table>\n </div>\n \n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 5160, "s": 5091, "text": "Open the file testAngularJS.htm in a web browser and see the result." }, { "code": null, "e": 5192, "s": 5160, "text": "Total click: {{ clickCounter }}" }, { "code": null, "e": 5227, "s": 5192, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5241, "s": 5227, "text": " Anadi Sharma" }, { "code": null, "e": 5276, "s": 5241, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5296, "s": 5276, "text": " Skillbakerystudios" }, { "code": null, "e": 5303, "s": 5296, "text": " Print" }, { "code": null, "e": 5314, "s": 5303, "text": " Add Notes" } ]
JSON with Java
This chapter covers how to encode and decode JSON objects using Java programming language. Let's start with preparing the environment to start our programming with Java for JSON. Before you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH. JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding. On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject. Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap. import org.json.simple.JSONObject; class JsonEncodeDemo { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); System.out.print(obj); } } On compiling and executing the above program the following result will be generated − {"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"} Following is another example that shows a JSON object streaming using Java JSONObject − import org.json.simple.JSONObject; class JsonEncodeDemo { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name","foo"); obj.put("num",new Integer(100)); obj.put("balance",new Double(1000.21)); obj.put("is_vip",new Boolean(true)); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); System.out.print(jsonText); } } On compiling and executing the above program, the following result is generated − {"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"} The following example makes use of JSONObject and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List. import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; class JsonDecodeDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; try{ Object obj = parser.parse(s); JSONArray array = (JSONArray)obj; System.out.println("The 2nd element of array"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2 = (JSONObject)array.get(1); System.out.println("Field \"1\""); System.out.println(obj2.get("1")); s = "{}"; obj = parser.parse(s); System.out.println(obj); s = "[5,]"; obj = parser.parse(s); System.out.println(obj); s = "[5,,2]"; obj = parser.parse(s); System.out.println(obj); }catch(ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } } On compiling and executing the above program, the following result will be generated − The 2nd element of array {"1":{"2":{"3":{"4":[5,{"6":7}]}}}} Field "1" {"2":{"3":{"4":[5,{"6":7}]}}} {} [5] [5,2] 20 Lectures 1 hours Laurence Svekis 16 Lectures 1 hours Laurence Svekis 10 Lectures 1 hours Laurence Svekis 23 Lectures 2.5 hours Laurence Svekis 9 Lectures 48 mins Nilay Mehta 18 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1959, "s": 1780, "text": "This chapter covers how to encode and decode JSON objects using Java programming language. Let's start with preparing the environment to start our programming with Java for JSON." }, { "code": null, "e": 2235, "s": 1959, "text": "Before you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH." }, { "code": null, "e": 2386, "s": 2235, "text": "JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding." }, { "code": null, "e": 2552, "s": 2386, "text": "On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.json.simple.JSONObject." }, { "code": null, "e": 2847, "s": 2552, "text": "Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap." }, { "code": null, "e": 3191, "s": 2847, "text": "import org.json.simple.JSONObject;\n\nclass JsonEncodeDemo {\n\n public static void main(String[] args) {\n JSONObject obj = new JSONObject();\n\n obj.put(\"name\", \"foo\");\n obj.put(\"num\", new Integer(100));\n obj.put(\"balance\", new Double(1000.21));\n obj.put(\"is_vip\", new Boolean(true));\n\n System.out.print(obj);\n }\n}" }, { "code": null, "e": 3277, "s": 3191, "text": "On compiling and executing the above program the following result will be generated −" }, { "code": null, "e": 3339, "s": 3277, "text": "{\"balance\": 1000.21, \"num\":100, \"is_vip\":true, \"name\":\"foo\"}\n" }, { "code": null, "e": 3427, "s": 3339, "text": "Following is another example that shows a JSON object streaming using Java JSONObject −" }, { "code": null, "e": 3898, "s": 3427, "text": "import org.json.simple.JSONObject;\n\nclass JsonEncodeDemo {\n\n public static void main(String[] args) {\n\t\n JSONObject obj = new JSONObject();\n\n obj.put(\"name\",\"foo\");\n obj.put(\"num\",new Integer(100));\n obj.put(\"balance\",new Double(1000.21));\n obj.put(\"is_vip\",new Boolean(true));\n\n StringWriter out = new StringWriter();\n obj.writeJSONString(out);\n \n String jsonText = out.toString();\n System.out.print(jsonText);\n }\n}" }, { "code": null, "e": 3980, "s": 3898, "text": "On compiling and executing the above program, the following result is generated −" }, { "code": null, "e": 4042, "s": 3980, "text": "{\"balance\": 1000.21, \"num\":100, \"is_vip\":true, \"name\":\"foo\"}\n" }, { "code": null, "e": 4237, "s": 4042, "text": "The following example makes use of JSONObject and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List." }, { "code": null, "e": 5367, "s": 4237, "text": "import org.json.simple.JSONObject;\nimport org.json.simple.JSONArray;\nimport org.json.simple.parser.ParseException;\nimport org.json.simple.parser.JSONParser;\n\nclass JsonDecodeDemo {\n\n public static void main(String[] args) {\n\t\n JSONParser parser = new JSONParser();\n String s = \"[0,{\\\"1\\\":{\\\"2\\\":{\\\"3\\\":{\\\"4\\\":[5,{\\\"6\\\":7}]}}}}]\";\n\t\t\n try{\n Object obj = parser.parse(s);\n JSONArray array = (JSONArray)obj;\n\t\t\t\n System.out.println(\"The 2nd element of array\");\n System.out.println(array.get(1));\n System.out.println();\n\n JSONObject obj2 = (JSONObject)array.get(1);\n System.out.println(\"Field \\\"1\\\"\");\n System.out.println(obj2.get(\"1\")); \n\n s = \"{}\";\n obj = parser.parse(s);\n System.out.println(obj);\n\n s = \"[5,]\";\n obj = parser.parse(s);\n System.out.println(obj);\n\n s = \"[5,,2]\";\n obj = parser.parse(s);\n System.out.println(obj);\n }catch(ParseException pe) {\n\t\t\n System.out.println(\"position: \" + pe.getPosition());\n System.out.println(pe);\n }\n }\n}" }, { "code": null, "e": 5454, "s": 5367, "text": "On compiling and executing the above program, the following result will be generated −" }, { "code": null, "e": 5570, "s": 5454, "text": "The 2nd element of array\n{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}\n\nField \"1\"\n{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}\n{}\n[5]\n[5,2]\n" }, { "code": null, "e": 5603, "s": 5570, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 5620, "s": 5603, "text": " Laurence Svekis" }, { "code": null, "e": 5653, "s": 5620, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5670, "s": 5653, "text": " Laurence Svekis" }, { "code": null, "e": 5703, "s": 5670, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5720, "s": 5703, "text": " Laurence Svekis" }, { "code": null, "e": 5755, "s": 5720, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5772, "s": 5755, "text": " Laurence Svekis" }, { "code": null, "e": 5803, "s": 5772, "text": "\n 9 Lectures \n 48 mins\n" }, { "code": null, "e": 5816, "s": 5803, "text": " Nilay Mehta" }, { "code": null, "e": 5851, "s": 5816, "text": "\n 18 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5874, "s": 5851, "text": " Stone River ELearning" }, { "code": null, "e": 5881, "s": 5874, "text": " Print" }, { "code": null, "e": 5892, "s": 5881, "text": " Add Notes" } ]
How to detect when cancel is clicked on file input using JavaScript ? - GeeksforGeeks
11 Jun, 2020 This article describes the method to handle a situation when the user tries to input a file and later fails to upload the file. It gives the status to the user that the file is not uploaded. This may be useful in situations when an important file needs to be submitted or the application requires the file for its functionality. Note: This method works best with WebKit browsers such as Google Chrome and Safari. It may not work reliably with Mozilla Firefox. Example: HTML Code: The following code is defines in the HTML of the page. <input type='file' id='theFile' onclick="initialize()" /> Explanation: The property value type=”file” tells that the type of input the user enters is a file. The property value id=”theFile” is used to link the JavaScript code to it using getElementById() method. The property value onclick=”initialize()” is used to specify the function call when the user has clicked on the input. JavaScript Code: javascript // Get the file input elementvar theFile = document.getElementById('theFile'); // Define a function to be called// when the input is focusedfunction initialize() { document.body.onfocus = checkIt; console.log('initializing');} // Define a function to check if// the user failed to upload filefunction checkIt() { // Check if the number of files // is not zero if (theFile.value.length) { alert('Files Loaded'); } // Alert the user if the number // of file is zero else { alert('Cancel clicked'); } document.body.onfocus = null; console.log('checked');} Explanation for the initialize() function: The variable theFile is created and the input element is selected using its id. The “document.body.onfocus = checkIt” line defines that the onfocus event is fired when an element gets focused. Explanation for checkIt() function: When the user uploads any file, the length of the files is found using theFile.value.length property. As this value becomes non-zero, the condition gets satisfied and an alert box appears that shows “Files Loaded”. When the user does not upload a file, then the length of the files is a zero value. Due to this, the condition does not get satisfied and an alert box appears that shows “Cancel clicked”. Complete Code: In this section, we will combine the above two sections of code to detect when cancel is clicked on file input. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title> How to detect when cancel is clicked on file input? </title></head> <body> <input type='file' id='theFile' onclick="initialize()" /> <script> // Get the file input element var theFile = document.getElementById('theFile'); // Define a function to be called // when the input is focused function initialize() { document.body.onfocus = checkIt; console.log('initializing'); } // Define a function to check if // the user failed to upload file function checkIt() { // Check if the number of files // is not zero if (theFile.value.length) { alert('Files Loaded'); } // Alert the user if the number // of file is zero else { alert('Cancel clicked'); } document.body.onfocus = null; console.log('checked'); } </script></body> </html> Output: File input for the user to select a file: Alert when the user has failed to input the file: On successful upload, the file name appears as intended: HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n11 Jun, 2020" }, { "code": null, "e": 26469, "s": 26139, "text": "This article describes the method to handle a situation when the user tries to input a file and later fails to upload the file. It gives the status to the user that the file is not uploaded. This may be useful in situations when an important file needs to be submitted or the application requires the file for its functionality. " }, { "code": null, "e": 26600, "s": 26469, "text": "Note: This method works best with WebKit browsers such as Google Chrome and Safari. It may not work reliably with Mozilla Firefox." }, { "code": null, "e": 26609, "s": 26600, "text": "Example:" }, { "code": null, "e": 26675, "s": 26609, "text": "HTML Code: The following code is defines in the HTML of the page." }, { "code": "<input type='file' id='theFile' onclick=\"initialize()\" />", "e": 26733, "s": 26675, "text": null }, { "code": null, "e": 26746, "s": 26733, "text": "Explanation:" }, { "code": null, "e": 26833, "s": 26746, "text": "The property value type=”file” tells that the type of input the user enters is a file." }, { "code": null, "e": 26938, "s": 26833, "text": "The property value id=”theFile” is used to link the JavaScript code to it using getElementById() method." }, { "code": null, "e": 27057, "s": 26938, "text": "The property value onclick=”initialize()” is used to specify the function call when the user has clicked on the input." }, { "code": null, "e": 27074, "s": 27057, "text": "JavaScript Code:" }, { "code": null, "e": 27085, "s": 27074, "text": "javascript" }, { "code": "// Get the file input elementvar theFile = document.getElementById('theFile'); // Define a function to be called// when the input is focusedfunction initialize() { document.body.onfocus = checkIt; console.log('initializing');} // Define a function to check if// the user failed to upload filefunction checkIt() { // Check if the number of files // is not zero if (theFile.value.length) { alert('Files Loaded'); } // Alert the user if the number // of file is zero else { alert('Cancel clicked'); } document.body.onfocus = null; console.log('checked');} ", "e": 27698, "s": 27085, "text": null }, { "code": null, "e": 27741, "s": 27698, "text": "Explanation for the initialize() function:" }, { "code": null, "e": 27821, "s": 27741, "text": "The variable theFile is created and the input element is selected using its id." }, { "code": null, "e": 27934, "s": 27821, "text": "The “document.body.onfocus = checkIt” line defines that the onfocus event is fired when an element gets focused." }, { "code": null, "e": 27970, "s": 27934, "text": "Explanation for checkIt() function:" }, { "code": null, "e": 28185, "s": 27970, "text": "When the user uploads any file, the length of the files is found using theFile.value.length property. As this value becomes non-zero, the condition gets satisfied and an alert box appears that shows “Files Loaded”." }, { "code": null, "e": 28373, "s": 28185, "text": "When the user does not upload a file, then the length of the files is a zero value. Due to this, the condition does not get satisfied and an alert box appears that shows “Cancel clicked”." }, { "code": null, "e": 28500, "s": 28373, "text": "Complete Code: In this section, we will combine the above two sections of code to detect when cancel is clicked on file input." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title> How to detect when cancel is clicked on file input? </title></head> <body> <input type='file' id='theFile' onclick=\"initialize()\" /> <script> // Get the file input element var theFile = document.getElementById('theFile'); // Define a function to be called // when the input is focused function initialize() { document.body.onfocus = checkIt; console.log('initializing'); } // Define a function to check if // the user failed to upload file function checkIt() { // Check if the number of files // is not zero if (theFile.value.length) { alert('Files Loaded'); } // Alert the user if the number // of file is zero else { alert('Cancel clicked'); } document.body.onfocus = null; console.log('checked'); } </script></body> </html>", "e": 29703, "s": 28500, "text": null }, { "code": null, "e": 29711, "s": 29703, "text": "Output:" }, { "code": null, "e": 29755, "s": 29711, "text": "File input for the user to select a file: " }, { "code": null, "e": 29806, "s": 29755, "text": "Alert when the user has failed to input the file: " }, { "code": null, "e": 29863, "s": 29806, "text": "On successful upload, the file name appears as intended:" }, { "code": null, "e": 29873, "s": 29863, "text": "HTML-Misc" }, { "code": null, "e": 29889, "s": 29873, "text": "JavaScript-Misc" }, { "code": null, "e": 29896, "s": 29889, "text": "Picked" }, { "code": null, "e": 29901, "s": 29896, "text": "HTML" }, { "code": null, "e": 29912, "s": 29901, "text": "JavaScript" }, { "code": null, "e": 29929, "s": 29912, "text": "Web Technologies" }, { "code": null, "e": 29956, "s": 29929, "text": "Web technologies Questions" }, { "code": null, "e": 29961, "s": 29956, "text": "HTML" }, { "code": null, "e": 30059, "s": 29961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30083, "s": 30059, "text": "REST API (Introduction)" }, { "code": null, "e": 30124, "s": 30083, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 30161, "s": 30124, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30190, "s": 30161, "text": "Form validation using jQuery" }, { "code": null, "e": 30210, "s": 30190, "text": "Angular File Upload" }, { "code": null, "e": 30250, "s": 30210, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30295, "s": 30250, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30356, "s": 30295, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30428, "s": 30356, "text": "Differences between Functional Components and Class Components in React" } ]
How do you apply PCA to Logistic Regression to remove Multicollinearity? | by Rukshan Pramoditha | Towards Data Science
Multicollinearity occurs when features (input variables) are highly correlated with one or more of the other features in the dataset. It affects the performance of regression and classification models. PCA (Principal Component Analysis) takes advantage of multicollinearity and combines the highly correlated variables into a set of uncorrelated variables. Therefore, PCA can effectively eliminate multicollinearity between features. In this post, we’ll build a logistic regression model on a classification dataset called breast_cancer data. The initial model can be considered as the base model. Then, we’ll apply PCA on breast_cancer data and build the logistic regression model again. After that, we’ll compare the performance between the base model and this model. Finally, we’ll build a machine learning Pipeline to combine the multiple steps of applying logistic regression with PCA. After reading this post, you’ll be able to apply PCA to logistic regression models. Let’s get started! This dataset is one of the built-in datasets in Scikit-learn. According to the Scikit-learn documentation, it has 30 features of 569 samples. The target variable has 2 classes called 0 (not having breast cancer) and 1 (having breast cancer). Since the target variable has only 2 classes, the dataset is used for binary classification. There are no missing values in the dataset. All the values are numerical. Therefore, no cleaning is required! The heatmap can be used to visualize the correlation coefficients of continuous variables with a beautiful colourmap. As you can see in the heatmap, some of the features in the dataset are highly correlated with each other. So, there exists multicollinearity. The following code block builds a logistic regression model on breast_cancer data. The base model is very good. It is not overfitting. It performs well on new unseen data. Let’s see whether we can improve the performance of the model by applying PCA. PCA is a linear dimensionality reduction technique (algorithm) that transforms a set of correlated variables (p) into a smaller k (k<p) number of uncorrelated variables called principal components while retaining as much of the variation in the original dataset as possible. In the context of Machine Learning (ML), PCA is an unsupervised machine learning algorithm which is used for dimensionality reduction. If the variables are not measured on a similar scale, we need to do feature scaling before applying PCA for our data. This is because PCA directions are highly sensitive to the scale of the data. The most important part in PCA is selecting the best number of components for the given dataset. First, we apply PCA keeping all components equal to the original number of dimensions (i.e., 30) and see how well PCA captures the variance of our data. The first component alone captures about 44% variability in the data and the second one captures about 19% variability in the data and so on. The first 6 components together capture about 88.76% variability in the data. We’re interested to keep the first 6 components. Now, we get the transformed dataset with 6 components. For this, we need to run PCA again by setting n_components=6. Now, we can use this transformed dataset instead of the original breast_cancer dataset to build a logistic regression model. Here are the differences between the two datasets. The original dataset has 30 features while the transformed dataset has 6 components. The transformed dataset only captures about 88.76% variability in the original dataset. The corresponding values of the two datasets are completely different. Some variables in the original dataset are highly correlated with one or more of the other variables (multicollinearity). No variable in the transformed dataset is correlated with one or more of the other variables. fig = plt.figure(figsize=(10, 8))sns.heatmap(X_pca.corr(), annot=True) We cannot see any correlation between components. This is because PCA has transformed the set of correlated variables in the original dataset into a set of uncorrelated variables. The following code block builds a logistic regression model on the transformed dataset (the dataset obtained by applying PCA). You can compare this output with the previous output of our base model. The test accuracy has increased by 3%. Both false positives and false negatives have also been reduced. However, the transformed dataset (the dataset obtained by applying PCA), only captures about 88.76% variability in the original dataset. Therefore, what’s the reason behind the performance increase in this model? The obvious answer is PCA has effectively eliminated the multicollinearity! A machine learning Pipeline simplifies the entire process by combining the multiple steps of applying logistic regression with PCA. Here are the steps: The log_reg_model Pipeline simplifies the training process by sequentially applying a list of transformers and a final predictor. In our Pipeline: StandardScaler() is a transformer.PCA() is a transformer.LogisticRegression() is a predictor. StandardScaler() is a transformer. PCA() is a transformer. LogisticRegression() is a predictor. Now, we can train all the estimators by a single .fit() call. log_reg_model.fit(X,y) Now, we’ve done the job promised in the introduction. PCA is useful to remove multicollinearity. It acts as a data preprocessing step. PCA has many other use cases. It is just one of the dimensionality reduction techniques. You can find more about those things by reading the following article written by me: towardsdatascience.com My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee. Sign-up link: https://rukshanpramoditha.medium.com/membership Thank you so much for your continuous support! See you in the next story. Happy learning to everyone! Special credit goes to Gabriella Clare Marino on Unsplash who provides me with the cover image for this post. The written content, code samples, other images and content links provided in this post are copyrighted by the author.
[ { "code": null, "e": 606, "s": 172, "text": "Multicollinearity occurs when features (input variables) are highly correlated with one or more of the other features in the dataset. It affects the performance of regression and classification models. PCA (Principal Component Analysis) takes advantage of multicollinearity and combines the highly correlated variables into a set of uncorrelated variables. Therefore, PCA can effectively eliminate multicollinearity between features." }, { "code": null, "e": 1147, "s": 606, "text": "In this post, we’ll build a logistic regression model on a classification dataset called breast_cancer data. The initial model can be considered as the base model. Then, we’ll apply PCA on breast_cancer data and build the logistic regression model again. After that, we’ll compare the performance between the base model and this model. Finally, we’ll build a machine learning Pipeline to combine the multiple steps of applying logistic regression with PCA. After reading this post, you’ll be able to apply PCA to logistic regression models." }, { "code": null, "e": 1166, "s": 1147, "text": "Let’s get started!" }, { "code": null, "e": 1611, "s": 1166, "text": "This dataset is one of the built-in datasets in Scikit-learn. According to the Scikit-learn documentation, it has 30 features of 569 samples. The target variable has 2 classes called 0 (not having breast cancer) and 1 (having breast cancer). Since the target variable has only 2 classes, the dataset is used for binary classification. There are no missing values in the dataset. All the values are numerical. Therefore, no cleaning is required!" }, { "code": null, "e": 1729, "s": 1611, "text": "The heatmap can be used to visualize the correlation coefficients of continuous variables with a beautiful colourmap." }, { "code": null, "e": 1871, "s": 1729, "text": "As you can see in the heatmap, some of the features in the dataset are highly correlated with each other. So, there exists multicollinearity." }, { "code": null, "e": 1954, "s": 1871, "text": "The following code block builds a logistic regression model on breast_cancer data." }, { "code": null, "e": 2122, "s": 1954, "text": "The base model is very good. It is not overfitting. It performs well on new unseen data. Let’s see whether we can improve the performance of the model by applying PCA." }, { "code": null, "e": 2825, "s": 2122, "text": "PCA is a linear dimensionality reduction technique (algorithm) that transforms a set of correlated variables (p) into a smaller k (k<p) number of uncorrelated variables called principal components while retaining as much of the variation in the original dataset as possible. In the context of Machine Learning (ML), PCA is an unsupervised machine learning algorithm which is used for dimensionality reduction. If the variables are not measured on a similar scale, we need to do feature scaling before applying PCA for our data. This is because PCA directions are highly sensitive to the scale of the data. The most important part in PCA is selecting the best number of components for the given dataset." }, { "code": null, "e": 2978, "s": 2825, "text": "First, we apply PCA keeping all components equal to the original number of dimensions (i.e., 30) and see how well PCA captures the variance of our data." }, { "code": null, "e": 3247, "s": 2978, "text": "The first component alone captures about 44% variability in the data and the second one captures about 19% variability in the data and so on. The first 6 components together capture about 88.76% variability in the data. We’re interested to keep the first 6 components." }, { "code": null, "e": 3364, "s": 3247, "text": "Now, we get the transformed dataset with 6 components. For this, we need to run PCA again by setting n_components=6." }, { "code": null, "e": 3540, "s": 3364, "text": "Now, we can use this transformed dataset instead of the original breast_cancer dataset to build a logistic regression model. Here are the differences between the two datasets." }, { "code": null, "e": 3625, "s": 3540, "text": "The original dataset has 30 features while the transformed dataset has 6 components." }, { "code": null, "e": 3713, "s": 3625, "text": "The transformed dataset only captures about 88.76% variability in the original dataset." }, { "code": null, "e": 3784, "s": 3713, "text": "The corresponding values of the two datasets are completely different." }, { "code": null, "e": 4000, "s": 3784, "text": "Some variables in the original dataset are highly correlated with one or more of the other variables (multicollinearity). No variable in the transformed dataset is correlated with one or more of the other variables." }, { "code": null, "e": 4083, "s": 4000, "text": "fig = plt.figure(figsize=(10, 8))sns.heatmap(X_pca.corr(), annot=True)" }, { "code": null, "e": 4263, "s": 4083, "text": "We cannot see any correlation between components. This is because PCA has transformed the set of correlated variables in the original dataset into a set of uncorrelated variables." }, { "code": null, "e": 4390, "s": 4263, "text": "The following code block builds a logistic regression model on the transformed dataset (the dataset obtained by applying PCA)." }, { "code": null, "e": 4855, "s": 4390, "text": "You can compare this output with the previous output of our base model. The test accuracy has increased by 3%. Both false positives and false negatives have also been reduced. However, the transformed dataset (the dataset obtained by applying PCA), only captures about 88.76% variability in the original dataset. Therefore, what’s the reason behind the performance increase in this model? The obvious answer is PCA has effectively eliminated the multicollinearity!" }, { "code": null, "e": 5007, "s": 4855, "text": "A machine learning Pipeline simplifies the entire process by combining the multiple steps of applying logistic regression with PCA. Here are the steps:" }, { "code": null, "e": 5154, "s": 5007, "text": "The log_reg_model Pipeline simplifies the training process by sequentially applying a list of transformers and a final predictor. In our Pipeline:" }, { "code": null, "e": 5248, "s": 5154, "text": "StandardScaler() is a transformer.PCA() is a transformer.LogisticRegression() is a predictor." }, { "code": null, "e": 5283, "s": 5248, "text": "StandardScaler() is a transformer." }, { "code": null, "e": 5307, "s": 5283, "text": "PCA() is a transformer." }, { "code": null, "e": 5344, "s": 5307, "text": "LogisticRegression() is a predictor." }, { "code": null, "e": 5406, "s": 5344, "text": "Now, we can train all the estimators by a single .fit() call." }, { "code": null, "e": 5429, "s": 5406, "text": "log_reg_model.fit(X,y)" }, { "code": null, "e": 5483, "s": 5429, "text": "Now, we’ve done the job promised in the introduction." }, { "code": null, "e": 5738, "s": 5483, "text": "PCA is useful to remove multicollinearity. It acts as a data preprocessing step. PCA has many other use cases. It is just one of the dimensionality reduction techniques. You can find more about those things by reading the following article written by me:" }, { "code": null, "e": 5761, "s": 5738, "text": "towardsdatascience.com" }, { "code": null, "e": 5923, "s": 5761, "text": "My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee." }, { "code": null, "e": 5985, "s": 5923, "text": "Sign-up link: https://rukshanpramoditha.medium.com/membership" }, { "code": null, "e": 6087, "s": 5985, "text": "Thank you so much for your continuous support! See you in the next story. Happy learning to everyone!" } ]
Tomohiko Sakamoto's Algorithm- Finding the day of the week - GeeksforGeeks
07 Apr, 2021 Given any date according to the Gregorian Calendar, the task is to return the day(Monday, Tuesday...etc) on that particular day. Examples: Input : Date: 13 July 2017 [13.07.2017] Output : 4 i.e Thursday Input : Date: 15 August 2012 [15.08.2012] Output : 3 i.e Wednesday Input : Date: 24 December 2456 [24.12.2456] Output : 0 i.e Sunday Although there are a plenty of methods to solve this question but one of the least known and most powerful method is Tomohiko Sakamoto’s Algorithm. Explanation Jan 1st 1 AD is a Monday in Gregorian calendar. Let us consider the first case in which we do not have leap years, hence total number of days in each year is 365.January has 31 days i.e 7*4+3 days so the day on 1st feb will always be 3 days ahead of the day on 1st January.Now february has 28 days(excluding leap years) which is exact multiple of 7 (7*4=28) Hence there will be no change in the month of march and it will also be 3 days ahead of the day on 1st January of that respective year.Considering this pattern, if we create an array of the leading number of days for each month then it will be given as t[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5}. Now let us look at the real case when there are leap years. Every 4 years, our calculation will gain one extra day. Except every 100 years when it doesn’t. Except every 400 years when it does. How do we put in these additional days? Well, just add y/4 – y/100 + y/400. Note that all division is integer division. This adds exactly the required number of leap days.But here is a problem, the leap day is 29 Feb and not 0 January.This means that the current year should not be counted for the leap day calculation for the first two months.Suppose that if the month were January or February, we subtracted 1 from the year. This means that during these months, the y/4 value would be that of the previous year and would not be counted. If we subtract 1 from the t[] values of every month after February? That would fill the gap, and the leap year problem is solved.That is, we need to make the following changes: 1.t[] now becomes {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}. 2.if m corresponds to Jan/Feb (that is, month<3) we decrement y by 1. 3.the annual increment inside the modulus is now y + y/4 – y/100 + y/400 in place of y. Below is the implementation of this Algorithm: C++ Java Python3 C# PHP Javascript // A CPP program to implement// the Tomohiko Sakamoto Algorithm#include <bits/stdc++.h>using namespace std; // function to implement tomohiko// sakamoto algorithmint day_of_the_week(int y, int m, int d){ // array with leading number of days values int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return ((y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7);} // Driver Codeint main(void){ int day = 13, month = 7, year = 2017; cout<<(day_of_the_week(year, month, day)); return 0 ;} // This code is contributed by Nikita Tiwari. // A java program to implement// the Tomohiko Sakamoto Algorithm class tomohiko_sakamoto{ // function to implement tomohiko sakamoto algorithm public static int day_of_the_week(int y, int m, int d) { // array with leading number of days values int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver Code public static void main(String args[]) { int day = 13, month = 7, year = 2017; System.out.println(day_of_the_week(year, month, day)); }} # A Python 3 program to implement# the Tomohiko Sakamoto Algorithm # function to implement tomohiko# sakamoto algorithmdef day_of_the_week(y, m, d) : # array with leading number of days values t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] # if month is less than 3 reduce year by 1 if (m < 3) : y = y - 1 return (y + y // 4 - y // 100 + y // 400 + t[m - 1] + d) % 7 # Driver Codeday = 13month = 7year = 2017 print(day_of_the_week(year, month, day)) # This code is contributed by Nikita Tiwari. // A C# program to implement// the Tomohiko Sakamoto Algorithmusing System; class GFG { // function to implement tomohiko // sakamoto algorithm public static int day_of_the_week(int y, int m, int d) { // array with leading number of days // values int []t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce // year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver Code public static void Main() { int day = 13, month = 7, year = 2017; Console.WriteLine(day_of_the_week(year, month, day)); }} // This code is contributed by vt_m. <?php// PHP program to implement// the Tomohiko Sakamoto Algorithm // function to implement tomohiko// sakamoto algorithmfunction day_of_the_week($y, $m, $d){ // array with leading number // of days values $t = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4); // if month is less than // 3 reduce year by 1 if ($m < 3) $y -= 1; return (($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7);} // Driver Code $day = 13; $month = 7; $year = 2017; echo day_of_the_week($year, $month, $day); // This code is contributed by ajit.?> <script> // JavaScript program to implement// the Tomohiko Sakamoto Algorithm // function to implement tomohiko sakamoto algorithm function day_of_the_week(y, m, d) { // array with leading number of days values let t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ]; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver code let day = 13, month = 7, year = 2017; document.write(Math.round(day_of_the_week(year, month, day))); </script> Output: 4 jit_t AjiteshSingla ShubhamRathi1 Akanksha_Rai susmitakundugoaldanga date-time-program Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Operators in C / C++ Find minimum number of coins that make a given value Program to find sum of elements in a given array Minimum number of jumps to reach end Program to print prime numbers from 1 to N.
[ { "code": null, "e": 25933, "s": 25905, "text": "\n07 Apr, 2021" }, { "code": null, "e": 26074, "s": 25933, "text": "Given any date according to the Gregorian Calendar, the task is to return the day(Monday, Tuesday...etc) on that particular day. Examples: " }, { "code": null, "e": 26274, "s": 26074, "text": "Input : Date: 13 July 2017 [13.07.2017]\nOutput : 4 i.e Thursday\n\nInput : Date: 15 August 2012 [15.08.2012]\nOutput : 3 i.e Wednesday\n\nInput : Date: 24 December 2456 [24.12.2456]\nOutput : 0 i.e Sunday" }, { "code": null, "e": 28214, "s": 26274, "text": "Although there are a plenty of methods to solve this question but one of the least known and most powerful method is Tomohiko Sakamoto’s Algorithm. Explanation Jan 1st 1 AD is a Monday in Gregorian calendar. Let us consider the first case in which we do not have leap years, hence total number of days in each year is 365.January has 31 days i.e 7*4+3 days so the day on 1st feb will always be 3 days ahead of the day on 1st January.Now february has 28 days(excluding leap years) which is exact multiple of 7 (7*4=28) Hence there will be no change in the month of march and it will also be 3 days ahead of the day on 1st January of that respective year.Considering this pattern, if we create an array of the leading number of days for each month then it will be given as t[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5}. Now let us look at the real case when there are leap years. Every 4 years, our calculation will gain one extra day. Except every 100 years when it doesn’t. Except every 400 years when it does. How do we put in these additional days? Well, just add y/4 – y/100 + y/400. Note that all division is integer division. This adds exactly the required number of leap days.But here is a problem, the leap day is 29 Feb and not 0 January.This means that the current year should not be counted for the leap day calculation for the first two months.Suppose that if the month were January or February, we subtracted 1 from the year. This means that during these months, the y/4 value would be that of the previous year and would not be counted. If we subtract 1 from the t[] values of every month after February? That would fill the gap, and the leap year problem is solved.That is, we need to make the following changes: 1.t[] now becomes {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}. 2.if m corresponds to Jan/Feb (that is, month<3) we decrement y by 1. 3.the annual increment inside the modulus is now y + y/4 – y/100 + y/400 in place of y. " }, { "code": null, "e": 28263, "s": 28214, "text": "Below is the implementation of this Algorithm: " }, { "code": null, "e": 28267, "s": 28263, "text": "C++" }, { "code": null, "e": 28272, "s": 28267, "text": "Java" }, { "code": null, "e": 28280, "s": 28272, "text": "Python3" }, { "code": null, "e": 28283, "s": 28280, "text": "C#" }, { "code": null, "e": 28287, "s": 28283, "text": "PHP" }, { "code": null, "e": 28298, "s": 28287, "text": "Javascript" }, { "code": "// A CPP program to implement// the Tomohiko Sakamoto Algorithm#include <bits/stdc++.h>using namespace std; // function to implement tomohiko// sakamoto algorithmint day_of_the_week(int y, int m, int d){ // array with leading number of days values int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return ((y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7);} // Driver Codeint main(void){ int day = 13, month = 7, year = 2017; cout<<(day_of_the_week(year, month, day)); return 0 ;} // This code is contributed by Nikita Tiwari.", "e": 28931, "s": 28298, "text": null }, { "code": "// A java program to implement// the Tomohiko Sakamoto Algorithm class tomohiko_sakamoto{ // function to implement tomohiko sakamoto algorithm public static int day_of_the_week(int y, int m, int d) { // array with leading number of days values int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver Code public static void main(String args[]) { int day = 13, month = 7, year = 2017; System.out.println(day_of_the_week(year, month, day)); }}", "e": 29603, "s": 28931, "text": null }, { "code": "# A Python 3 program to implement# the Tomohiko Sakamoto Algorithm # function to implement tomohiko# sakamoto algorithmdef day_of_the_week(y, m, d) : # array with leading number of days values t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] # if month is less than 3 reduce year by 1 if (m < 3) : y = y - 1 return (y + y // 4 - y // 100 + y // 400 + t[m - 1] + d) % 7 # Driver Codeday = 13month = 7year = 2017 print(day_of_the_week(year, month, day)) # This code is contributed by Nikita Tiwari.", "e": 30153, "s": 29603, "text": null }, { "code": "// A C# program to implement// the Tomohiko Sakamoto Algorithmusing System; class GFG { // function to implement tomohiko // sakamoto algorithm public static int day_of_the_week(int y, int m, int d) { // array with leading number of days // values int []t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce // year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver Code public static void Main() { int day = 13, month = 7, year = 2017; Console.WriteLine(day_of_the_week(year, month, day)); }} // This code is contributed by vt_m.", "e": 31022, "s": 30153, "text": null }, { "code": "<?php// PHP program to implement// the Tomohiko Sakamoto Algorithm // function to implement tomohiko// sakamoto algorithmfunction day_of_the_week($y, $m, $d){ // array with leading number // of days values $t = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4); // if month is less than // 3 reduce year by 1 if ($m < 3) $y -= 1; return (($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7);} // Driver Code $day = 13; $month = 7; $year = 2017; echo day_of_the_week($year, $month, $day); // This code is contributed by ajit.?>", "e": 31632, "s": 31022, "text": null }, { "code": "<script> // JavaScript program to implement// the Tomohiko Sakamoto Algorithm // function to implement tomohiko sakamoto algorithm function day_of_the_week(y, m, d) { // array with leading number of days values let t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ]; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; } // Driver code let day = 13, month = 7, year = 2017; document.write(Math.round(day_of_the_week(year, month, day))); </script>", "e": 32240, "s": 31632, "text": null }, { "code": null, "e": 32249, "s": 32240, "text": "Output: " }, { "code": null, "e": 32253, "s": 32249, "text": " 4 " }, { "code": null, "e": 32261, "s": 32255, "text": "jit_t" }, { "code": null, "e": 32275, "s": 32261, "text": "AjiteshSingla" }, { "code": null, "e": 32289, "s": 32275, "text": "ShubhamRathi1" }, { "code": null, "e": 32302, "s": 32289, "text": "Akanksha_Rai" }, { "code": null, "e": 32324, "s": 32302, "text": "susmitakundugoaldanga" }, { "code": null, "e": 32342, "s": 32324, "text": "date-time-program" }, { "code": null, "e": 32355, "s": 32342, "text": "Mathematical" }, { "code": null, "e": 32368, "s": 32355, "text": "Mathematical" }, { "code": null, "e": 32466, "s": 32368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32490, "s": 32466, "text": "Merge two sorted arrays" }, { "code": null, "e": 32533, "s": 32490, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32547, "s": 32533, "text": "Prime Numbers" }, { "code": null, "e": 32620, "s": 32547, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32663, "s": 32620, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32684, "s": 32663, "text": "Operators in C / C++" }, { "code": null, "e": 32737, "s": 32684, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 32786, "s": 32737, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32823, "s": 32786, "text": "Minimum number of jumps to reach end" } ]
Deep Q Learning for the CartPole. The purpose of this post is to... | by Rita Kurban | Towards Data Science
The purpose of this post is to introduce the concept of Deel Q Learning and use it to solve the CartPole environment from the OpenAI Gym. The post will consist of the following components: Open AI Gym Environment IntroRandom Baseline StrategyDeep Q LearningDeep Q Learning with Replay MemoryDouble Deep Q LearningSoft Updates Open AI Gym Environment Intro Random Baseline Strategy Deep Q Learning Deep Q Learning with Replay Memory Double Deep Q Learning Soft Updates The CartPole environment consists of a pole which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. The state space is represented by four values: cart position, cart velocity, pole angle, and the velocity of the tip of the pole. The action space consists of two actions: moving left or moving right. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. The cell below plots a bunch of example frames from the environment: # Demonstrationenv = gym.envs.make("CartPole-v1")def get_screen(): ''' Extract one step of the simulation.''' screen = env.render(mode='rgb_array').transpose((2, 0, 1)) screen = np.ascontiguousarray(screen, dtype=np.float32) / 255. return torch.from_numpy(screen)# Speify the number of simulation stepsnum_steps = 2# Show several stepsfor i in range(num_steps): clear_output(wait=True) env.reset() plt.figure() plt.imshow(get_screen().cpu().permute(1, 2, 0).numpy(), interpolation='none') plt.title('CartPole-v0 Environment') plt.xticks([]) plt.yticks([]) plt.show() Dependent on the number of episodes, the output will look something like this: As we can see, the agent is untrained yet, so it cannot make more than a couple of steps. We will soon explore some of the strategies that will drastically improve performance. But first, let’s define the plotting function that will help us analyze results: def plot_res(values, title=''): ''' Plot the reward curve and histogram of results over time.''' # Update the window after each episode clear_output(wait=True) # Define the figure f, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,5)) f.suptitle(title) ax[0].plot(values, label='score per run') ax[0].axhline(195, c='red',ls='--', label='goal') ax[0].set_xlabel('Episodes') ax[0].set_ylabel('Reward') x = range(len(values)) ax[0].legend() # Calculate the trend try: z = np.polyfit(x, values, 1) p = np.poly1d(z) ax[0].plot(x,p(x),"--", label='trend') except: print('') # Plot the histogram of results ax[1].hist(values[-50:]) ax[1].axvline(195, c='red', label='goal') ax[1].set_xlabel('Scores per Last 50 Episodes') ax[1].set_ylabel('Frequency') ax[1].legend() plt.show() The resulting plot consists of two subplots. The first one plots the total reward the agent accumulates over time, while the other plot shows a histogram of the agent’s total rewards for the last 50 episodes. We’ll see some of the graphs when we’ll analyze our strategies. Before implementing any deep learning approaches, I wrote a simple strategy where the action is sampled randomly from the action space. This approach will serve as a baseline for other strategies and will make it easier to understand how to work with the agent using the Open AI Gym environment. def random_search(env, episodes, title='Random Strategy'): """ Random search strategy implementation.""" final = [] for episode in range(episodes): state = env.reset() done = False total = 0 while not done: # Sample random actions action = env.action_space.sample() # Take action and extract results next_state, reward, done, _ = env.step(action) # Update reward total += reward if done: break # Add to the final reward final.append(total) plot_res(final,title) return final One environment step returns several values, such as the next_state, reward, and whether the simulation is done. The plot below represents the total accumulated reward over 150 episodes (simulation runs): The plot above presents the random strategy. As expected, it’s impossible to solve the environment using this approach. The agent is not learning from their experience. Despite being lucky sometimes (getting a reward of almost 75), their average performance is as low as 10 steps. The main idea behind Q-learning is that we have a function Q:State×Action→R, which can tell the agent what actions will result in what rewards. If we know the value of Q, it is possible to construct a policy that maximizes rewards: π(s)=argmaxa Q(s,a) However, in the real world, we don’t have access to full information, that’s why we need to come up with ways of approximating Q. One traditional method is creating a lookup table where the values of Q are updated after each of the agent’s actions. However, this approach is slow and does not scale to large action and state spaces. Since neural networks are universal function approximators, I will train a network that can approximate Q. The DQL class implementation consists of a simple neural network implemented in PyTorch that has two main methods — predict and update. The network takes the agent’s state as an input and returns the Q values for each of the actions. The maximum Q value is selected by the agent to perform the next action: class DQL(): ''' Deep Q Neural Network class. ''' def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05): self.criterion = torch.nn.MSELoss() self.model = torch.nn.Sequential( torch.nn.Linear(state_dim, hidden_dim), torch.nn.LeakyReLU(), torch.nn.Linear(hidden_dim, hidden_dim*2), torch.nn.LeakyReLU(), torch.nn.Linear(hidden_dim*2, action_dim) ) self.optimizer = torch.optim.Adam(self.model.parameters(), lr)def update(self, state, y): """Update the weights of the network given a training sample. """ y_pred = self.model(torch.Tensor(state)) loss = self.criterion(y_pred, Variable(torch.Tensor(y))) self.optimizer.zero_grad() loss.backward() self.optimizer.step()def predict(self, state): """ Compute Q values for all actions using the DQL. """ with torch.no_grad(): return self.model(torch.Tensor(state)) The q_learning function is the main loop for all the algorithms that follow. It has many parameters, namely: - env represents the Open Ai Gym environment that we want to solve (CartPole.)- episodesstand for the number of games we want to play.- gammais a discounting factor that is multiplied by future rewards to dampen these rewards’ effect on the agent. It is designed to make future rewards worth less than immediate rewards.- epsilonrepresents the proportion of random actions relative to actions that are informed by existing “knowledge” that the agent accumulates during the episode. This strategy is called “Greedy Search Policy.” Before playing the game, the agent doesn’t have any experience, so it is common to set epsilon to higher values and then gradually decrease its value. - eps_decay indicates the speed at which the epsilon decreases as the agent learns. 0.99 comes from the original DQN paper. I will explain other parameters later on when we will get to the corresponding agents. def q_learning(env, model, episodes, gamma=0.9, epsilon=0.3, eps_decay=0.99, replay=False, replay_size=20, title = 'DQL', double=False, n_update=10, soft=False): """Deep Q Learning algorithm using the DQN. """ final = [] memory = [] for episode in range(episodes): if double and not soft: # Update target network every n_update steps if episode % n_update == 0: model.target_update() if double and soft: model.target_update() # Reset state state = env.reset() done = False total = 0 while not done: # Implement greedy search policy if random.random() < epsilon: action = env.action_space.sample() else: q_values = model.predict(state) action = torch.argmax(q_values).item() # Take action and add reward to total next_state, reward, done, _ = env.step(action) # Update total and memory total += reward memory.append((state, action, next_state, reward, done)) q_values = model.predict(state).tolist() if done: if not replay: q_values[action] = reward # Update network weights model.update(state, q_values) breakif replay: # Update network weights using replay memory model.replay(memory, replay_size, gamma) else: # Update network weights using the last step only q_values_next = model.predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item() model.update(state, q_values)state = next_state # Update epsilon epsilon = max(epsilon * eps_decay, 0.01) final.append(total) plot_res(final, title) return final The most straightforward agent updates its Q-values based on its most recent observation. It doesn’t have any memory, but it learns by first exploring the environment and then gradually decreasing its epsilon value to make informed decisions. Let’s evaluate the performance of such an agent: The graph above shows that the performance of the agent has significantly improved. It got to 175 steps, which, as we’ve seen before, is impossible for a random agent. The trend line is also positive, and we can see that the performance increases over time. At the same time, the agent didn’t manage to get above the goal line after 150 epochs, and its average performance is still around 15 steps, so there is enough room for improvement. The approximation of Q using one sample at a time is not very effective. The graph above is a nice illustration of that. The network managed to achieve a much better performance compared to a random agent. However, it couldn’t get to the threshold line of 195 steps. I implemented experience replay to improve network stability and make sure previous experiences are not discarded but used in training. Experience replay stores the agent’s experiences in memory. Batches of experiences are randomly sampled from memory and are used to train the neural network. Such learning consists of two phases — gaining experience and updating the model. The size of the replay controls the number of experiences that are used for the network update. Memory is an array that stores the agent’s state, reward, and action, as well as whether the action finished the game and the next state. # Expand DQL class with a replay function.class DQN_replay(DQN): def replay(self, memory, size, gamma=0.9): """ Add experience replay to the DQN network class. """ # Make sure the memory is big enough if len(memory) >= size: states = [] targets = [] # Sample a batch of experiences from the agent's memory batch = random.sample(memory, size) # Extract information from the data for state, action, next_state, reward, done in batch: states.append(state) # Predict q_values q_values = self.predict(state).tolist() if done: q_values[action] = reward else: q_values_next = self.predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item()targets.append(q_values)self.update(states, targets) As expected, the neural network with the replay seems to be much more robust and smart compared to its counterpart that only remembers the last action. After approximately 60 episodes, the agent managed to achieve the winning threshold and remain at this level. It also managed to achieve the highest reward possible — 500. Traditional Deep Q Learning tends to overestimate the reward, which leads to unstable training and lower quality policy. Let’s consider the equation for the Q value: The last part of the equation takes the estimate of the maximum value. This procedure results in systematic overestimation, which introduces a maximization bias. Since Q-learning involves learning estimates from estimates, such overestimation is especially worrying. To avoid such a situation, I will define a new target network. The Q values will be taken from this new network, which is meant to reflect the state of the main DQN. However, it doesn’t have identical weights because it’s only updated after a certain number of episodes. This idea has been first introduced in Hasselt et al., 2015.The addition of the target network might slow down the training since the target network is not continuously updated. However, it should have a more robust performance over time. n_update from the q_learning loop specifies the interval after which the target network should be updated. class DQN_double(DQN): def __init__(self, state_dim, action_dim, hidden_dim, lr): super().__init__(state_dim, action_dim, hidden_dim, lr) self.target = copy.deepcopy(self.model) def target_predict(self, s): ''' Use target network to make predicitons.''' with torch.no_grad(): return self.target(torch.Tensor(s)) def target_update(self): ''' Update target network with the model weights.''' self.target.load_state_dict(self.model.state_dict()) def replay(self, memory, size, gamma=1.0): ''' Add experience replay to the DQL network class.''' if len(memory) >= size: # Sample experiences from the agent's memory data = random.sample(memory, size) states = [] targets = [] # Extract datapoints from the data for state, action, next_state, reward, done in data: states.append(state) q_values = self.predict(state).tolist() if done: q_values[action] = reward else: # The only difference between the simple replay is in this line # It ensures that next q values are predicted with the target network. q_values_next = self.target_predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item()targets.append(q_values)self.update(states, targets) Double DQL with replay has outperformed the previous version and has consistently performed above 300 steps. The performance also seems to be a bit more stable, thanks to the separation of action selection and evaluation. Finally, let’s explore the last modification to the DQL agent. The method used to update the target network implemented above was introduced in the original DQN paper. In this section, we will explore another well-established method of updating the target network weights. Instead of updating weights after a certain number of steps, we will incrementally update the target network after every run using the following formula: target_weights = target_weights * (1-TAU) + model_weights * TAU where 0 < TAU < 1 This method of updating the target network is known as “soft target network updates” and was introduced in Lillicrap et al., 2016. This method implementation is shown below: class DQN_double_soft(DQN_double): def target_update(self, TAU=0.1): ''' Update the targer gradually. ''' # Extract parameters model_params = self.model.named_parameters() target_params = self.target.named_parameters() updated_params = dict(target_params)for model_name, model_param in model_params: if model_name in target_params: # Update parameter updated_params[model_name].data.copy_((TAU)*model_param.data + (1-TAU)*target_params[model_param].data)self.target.load_state_dict(updated_params) The network with soft target updates performed quite well. However, it doesn’t seem to be better than hard weight updates. This gif illustrates the performance of a trained agent: The implementation of the experience replay and the target network have significantly improved the performance of a Deep Q Learning agent in the Open AI CartPole environment. Some other modifications to the agent, such as Dueling Network Architectures (Wang et al., 2015), can be added to this implementation to improve the agent’s performance. The algorithm is also generalizable to other environments. Feel free to test how well it solves other tasks! Link to the notebook: https://github.com/ritakurban/Practical-Data-Science/blob/master/DQL_CartPole.ipynb (1) Reinforcement Q-Learning from Scratch in Python with OpenAI Gym. (2019). Learndatasci.com. Retrieved 9 December 2019, from https://www.learndatasci.com/tutorials/reinforcement-q-learning-scratch-python-openai-gym/ (2) Paszke, A., (2019). Reinforcement Learning (DQN) tutorial. Retrieved from: https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html (3) Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., ... & Wierstra, D. (2015). Continuous control with deep reinforcement learning. arXiv preprint arXiv:1509.02971. (4) Van Hasselt, H., Guez, A., & Silver, D. (2016, March). Deep reinforcement learning with double q-learning. In Thirtieth AAAI conference on artificial intelligence. (5) Wang, Z., Schaul, T., Hessel, M., Van Hasselt, H., Lanctot, M., & De Freitas, N. (2015). Dueling network architectures for deep reinforcement learning. arXiv preprint arXiv:1511.06581. (6) Double DQN Implementation to Solve OpenAI Gym’s CartPole v-0. (2019). Medium. Retrieved 20 December 2019, from https://medium.com/@leosimmons/double-dqn-implementation-to-solve-openai-gyms-cartpole-v-0-df554cd0614d
[ { "code": null, "e": 310, "s": 172, "text": "The purpose of this post is to introduce the concept of Deel Q Learning and use it to solve the CartPole environment from the OpenAI Gym." }, { "code": null, "e": 361, "s": 310, "text": "The post will consist of the following components:" }, { "code": null, "e": 498, "s": 361, "text": "Open AI Gym Environment IntroRandom Baseline StrategyDeep Q LearningDeep Q Learning with Replay MemoryDouble Deep Q LearningSoft Updates" }, { "code": null, "e": 528, "s": 498, "text": "Open AI Gym Environment Intro" }, { "code": null, "e": 553, "s": 528, "text": "Random Baseline Strategy" }, { "code": null, "e": 569, "s": 553, "text": "Deep Q Learning" }, { "code": null, "e": 604, "s": 569, "text": "Deep Q Learning with Replay Memory" }, { "code": null, "e": 627, "s": 604, "text": "Double Deep Q Learning" }, { "code": null, "e": 640, "s": 627, "text": "Soft Updates" }, { "code": null, "e": 1275, "s": 640, "text": "The CartPole environment consists of a pole which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. The state space is represented by four values: cart position, cart velocity, pole angle, and the velocity of the tip of the pole. The action space consists of two actions: moving left or moving right. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center." }, { "code": null, "e": 1344, "s": 1275, "text": "The cell below plots a bunch of example frames from the environment:" }, { "code": null, "e": 1961, "s": 1344, "text": "# Demonstrationenv = gym.envs.make(\"CartPole-v1\")def get_screen(): ''' Extract one step of the simulation.''' screen = env.render(mode='rgb_array').transpose((2, 0, 1)) screen = np.ascontiguousarray(screen, dtype=np.float32) / 255. return torch.from_numpy(screen)# Speify the number of simulation stepsnum_steps = 2# Show several stepsfor i in range(num_steps): clear_output(wait=True) env.reset() plt.figure() plt.imshow(get_screen().cpu().permute(1, 2, 0).numpy(), interpolation='none') plt.title('CartPole-v0 Environment') plt.xticks([]) plt.yticks([]) plt.show()" }, { "code": null, "e": 2040, "s": 1961, "text": "Dependent on the number of episodes, the output will look something like this:" }, { "code": null, "e": 2298, "s": 2040, "text": "As we can see, the agent is untrained yet, so it cannot make more than a couple of steps. We will soon explore some of the strategies that will drastically improve performance. But first, let’s define the plotting function that will help us analyze results:" }, { "code": null, "e": 3175, "s": 2298, "text": "def plot_res(values, title=''): ''' Plot the reward curve and histogram of results over time.''' # Update the window after each episode clear_output(wait=True) # Define the figure f, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,5)) f.suptitle(title) ax[0].plot(values, label='score per run') ax[0].axhline(195, c='red',ls='--', label='goal') ax[0].set_xlabel('Episodes') ax[0].set_ylabel('Reward') x = range(len(values)) ax[0].legend() # Calculate the trend try: z = np.polyfit(x, values, 1) p = np.poly1d(z) ax[0].plot(x,p(x),\"--\", label='trend') except: print('') # Plot the histogram of results ax[1].hist(values[-50:]) ax[1].axvline(195, c='red', label='goal') ax[1].set_xlabel('Scores per Last 50 Episodes') ax[1].set_ylabel('Frequency') ax[1].legend() plt.show()" }, { "code": null, "e": 3448, "s": 3175, "text": "The resulting plot consists of two subplots. The first one plots the total reward the agent accumulates over time, while the other plot shows a histogram of the agent’s total rewards for the last 50 episodes. We’ll see some of the graphs when we’ll analyze our strategies." }, { "code": null, "e": 3744, "s": 3448, "text": "Before implementing any deep learning approaches, I wrote a simple strategy where the action is sampled randomly from the action space. This approach will serve as a baseline for other strategies and will make it easier to understand how to work with the agent using the Open AI Gym environment." }, { "code": null, "e": 4390, "s": 3744, "text": "def random_search(env, episodes, title='Random Strategy'): \"\"\" Random search strategy implementation.\"\"\" final = [] for episode in range(episodes): state = env.reset() done = False total = 0 while not done: # Sample random actions action = env.action_space.sample() # Take action and extract results next_state, reward, done, _ = env.step(action) # Update reward total += reward if done: break # Add to the final reward final.append(total) plot_res(final,title) return final" }, { "code": null, "e": 4595, "s": 4390, "text": "One environment step returns several values, such as the next_state, reward, and whether the simulation is done. The plot below represents the total accumulated reward over 150 episodes (simulation runs):" }, { "code": null, "e": 4876, "s": 4595, "text": "The plot above presents the random strategy. As expected, it’s impossible to solve the environment using this approach. The agent is not learning from their experience. Despite being lucky sometimes (getting a reward of almost 75), their average performance is as low as 10 steps." }, { "code": null, "e": 5108, "s": 4876, "text": "The main idea behind Q-learning is that we have a function Q:State×Action→R, which can tell the agent what actions will result in what rewards. If we know the value of Q, it is possible to construct a policy that maximizes rewards:" }, { "code": null, "e": 5128, "s": 5108, "text": "π(s)=argmaxa Q(s,a)" }, { "code": null, "e": 5568, "s": 5128, "text": "However, in the real world, we don’t have access to full information, that’s why we need to come up with ways of approximating Q. One traditional method is creating a lookup table where the values of Q are updated after each of the agent’s actions. However, this approach is slow and does not scale to large action and state spaces. Since neural networks are universal function approximators, I will train a network that can approximate Q." }, { "code": null, "e": 5875, "s": 5568, "text": "The DQL class implementation consists of a simple neural network implemented in PyTorch that has two main methods — predict and update. The network takes the agent’s state as an input and returns the Q values for each of the actions. The maximum Q value is selected by the agent to perform the next action:" }, { "code": null, "e": 6954, "s": 5875, "text": "class DQL(): ''' Deep Q Neural Network class. ''' def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05): self.criterion = torch.nn.MSELoss() self.model = torch.nn.Sequential( torch.nn.Linear(state_dim, hidden_dim), torch.nn.LeakyReLU(), torch.nn.Linear(hidden_dim, hidden_dim*2), torch.nn.LeakyReLU(), torch.nn.Linear(hidden_dim*2, action_dim) ) self.optimizer = torch.optim.Adam(self.model.parameters(), lr)def update(self, state, y): \"\"\"Update the weights of the network given a training sample. \"\"\" y_pred = self.model(torch.Tensor(state)) loss = self.criterion(y_pred, Variable(torch.Tensor(y))) self.optimizer.zero_grad() loss.backward() self.optimizer.step()def predict(self, state): \"\"\" Compute Q values for all actions using the DQL. \"\"\" with torch.no_grad(): return self.model(torch.Tensor(state))" }, { "code": null, "e": 7063, "s": 6954, "text": "The q_learning function is the main loop for all the algorithms that follow. It has many parameters, namely:" }, { "code": null, "e": 7868, "s": 7063, "text": "- env represents the Open Ai Gym environment that we want to solve (CartPole.)- episodesstand for the number of games we want to play.- gammais a discounting factor that is multiplied by future rewards to dampen these rewards’ effect on the agent. It is designed to make future rewards worth less than immediate rewards.- epsilonrepresents the proportion of random actions relative to actions that are informed by existing “knowledge” that the agent accumulates during the episode. This strategy is called “Greedy Search Policy.” Before playing the game, the agent doesn’t have any experience, so it is common to set epsilon to higher values and then gradually decrease its value. - eps_decay indicates the speed at which the epsilon decreases as the agent learns. 0.99 comes from the original DQN paper." }, { "code": null, "e": 7955, "s": 7868, "text": "I will explain other parameters later on when we will get to the corresponding agents." }, { "code": null, "e": 9999, "s": 7955, "text": "def q_learning(env, model, episodes, gamma=0.9, epsilon=0.3, eps_decay=0.99, replay=False, replay_size=20, title = 'DQL', double=False, n_update=10, soft=False): \"\"\"Deep Q Learning algorithm using the DQN. \"\"\" final = [] memory = [] for episode in range(episodes): if double and not soft: # Update target network every n_update steps if episode % n_update == 0: model.target_update() if double and soft: model.target_update() # Reset state state = env.reset() done = False total = 0 while not done: # Implement greedy search policy if random.random() < epsilon: action = env.action_space.sample() else: q_values = model.predict(state) action = torch.argmax(q_values).item() # Take action and add reward to total next_state, reward, done, _ = env.step(action) # Update total and memory total += reward memory.append((state, action, next_state, reward, done)) q_values = model.predict(state).tolist() if done: if not replay: q_values[action] = reward # Update network weights model.update(state, q_values) breakif replay: # Update network weights using replay memory model.replay(memory, replay_size, gamma) else: # Update network weights using the last step only q_values_next = model.predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item() model.update(state, q_values)state = next_state # Update epsilon epsilon = max(epsilon * eps_decay, 0.01) final.append(total) plot_res(final, title) return final" }, { "code": null, "e": 10291, "s": 9999, "text": "The most straightforward agent updates its Q-values based on its most recent observation. It doesn’t have any memory, but it learns by first exploring the environment and then gradually decreasing its epsilon value to make informed decisions. Let’s evaluate the performance of such an agent:" }, { "code": null, "e": 10731, "s": 10291, "text": "The graph above shows that the performance of the agent has significantly improved. It got to 175 steps, which, as we’ve seen before, is impossible for a random agent. The trend line is also positive, and we can see that the performance increases over time. At the same time, the agent didn’t manage to get above the goal line after 150 epochs, and its average performance is still around 15 steps, so there is enough room for improvement." }, { "code": null, "e": 11134, "s": 10731, "text": "The approximation of Q using one sample at a time is not very effective. The graph above is a nice illustration of that. The network managed to achieve a much better performance compared to a random agent. However, it couldn’t get to the threshold line of 195 steps. I implemented experience replay to improve network stability and make sure previous experiences are not discarded but used in training." }, { "code": null, "e": 11608, "s": 11134, "text": "Experience replay stores the agent’s experiences in memory. Batches of experiences are randomly sampled from memory and are used to train the neural network. Such learning consists of two phases — gaining experience and updating the model. The size of the replay controls the number of experiences that are used for the network update. Memory is an array that stores the agent’s state, reward, and action, as well as whether the action finished the game and the next state." }, { "code": null, "e": 12556, "s": 11608, "text": "# Expand DQL class with a replay function.class DQN_replay(DQN): def replay(self, memory, size, gamma=0.9): \"\"\" Add experience replay to the DQN network class. \"\"\" # Make sure the memory is big enough if len(memory) >= size: states = [] targets = [] # Sample a batch of experiences from the agent's memory batch = random.sample(memory, size) # Extract information from the data for state, action, next_state, reward, done in batch: states.append(state) # Predict q_values q_values = self.predict(state).tolist() if done: q_values[action] = reward else: q_values_next = self.predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item()targets.append(q_values)self.update(states, targets)" }, { "code": null, "e": 12880, "s": 12556, "text": "As expected, the neural network with the replay seems to be much more robust and smart compared to its counterpart that only remembers the last action. After approximately 60 episodes, the agent managed to achieve the winning threshold and remain at this level. It also managed to achieve the highest reward possible — 500." }, { "code": null, "e": 13046, "s": 12880, "text": "Traditional Deep Q Learning tends to overestimate the reward, which leads to unstable training and lower quality policy. Let’s consider the equation for the Q value:" }, { "code": null, "e": 13313, "s": 13046, "text": "The last part of the equation takes the estimate of the maximum value. This procedure results in systematic overestimation, which introduces a maximization bias. Since Q-learning involves learning estimates from estimates, such overestimation is especially worrying." }, { "code": null, "e": 13823, "s": 13313, "text": "To avoid such a situation, I will define a new target network. The Q values will be taken from this new network, which is meant to reflect the state of the main DQN. However, it doesn’t have identical weights because it’s only updated after a certain number of episodes. This idea has been first introduced in Hasselt et al., 2015.The addition of the target network might slow down the training since the target network is not continuously updated. However, it should have a more robust performance over time." }, { "code": null, "e": 13930, "s": 13823, "text": "n_update from the q_learning loop specifies the interval after which the target network should be updated." }, { "code": null, "e": 15417, "s": 13930, "text": "class DQN_double(DQN): def __init__(self, state_dim, action_dim, hidden_dim, lr): super().__init__(state_dim, action_dim, hidden_dim, lr) self.target = copy.deepcopy(self.model) def target_predict(self, s): ''' Use target network to make predicitons.''' with torch.no_grad(): return self.target(torch.Tensor(s)) def target_update(self): ''' Update target network with the model weights.''' self.target.load_state_dict(self.model.state_dict()) def replay(self, memory, size, gamma=1.0): ''' Add experience replay to the DQL network class.''' if len(memory) >= size: # Sample experiences from the agent's memory data = random.sample(memory, size) states = [] targets = [] # Extract datapoints from the data for state, action, next_state, reward, done in data: states.append(state) q_values = self.predict(state).tolist() if done: q_values[action] = reward else: # The only difference between the simple replay is in this line # It ensures that next q values are predicted with the target network. q_values_next = self.target_predict(next_state) q_values[action] = reward + gamma * torch.max(q_values_next).item()targets.append(q_values)self.update(states, targets)" }, { "code": null, "e": 15702, "s": 15417, "text": "Double DQL with replay has outperformed the previous version and has consistently performed above 300 steps. The performance also seems to be a bit more stable, thanks to the separation of action selection and evaluation. Finally, let’s explore the last modification to the DQL agent." }, { "code": null, "e": 16066, "s": 15702, "text": "The method used to update the target network implemented above was introduced in the original DQN paper. In this section, we will explore another well-established method of updating the target network weights. Instead of updating weights after a certain number of steps, we will incrementally update the target network after every run using the following formula:" }, { "code": null, "e": 16130, "s": 16066, "text": "target_weights = target_weights * (1-TAU) + model_weights * TAU" }, { "code": null, "e": 16148, "s": 16130, "text": "where 0 < TAU < 1" }, { "code": null, "e": 16322, "s": 16148, "text": "This method of updating the target network is known as “soft target network updates” and was introduced in Lillicrap et al., 2016. This method implementation is shown below:" }, { "code": null, "e": 16909, "s": 16322, "text": "class DQN_double_soft(DQN_double): def target_update(self, TAU=0.1): ''' Update the targer gradually. ''' # Extract parameters model_params = self.model.named_parameters() target_params = self.target.named_parameters() updated_params = dict(target_params)for model_name, model_param in model_params: if model_name in target_params: # Update parameter updated_params[model_name].data.copy_((TAU)*model_param.data + (1-TAU)*target_params[model_param].data)self.target.load_state_dict(updated_params)" }, { "code": null, "e": 17032, "s": 16909, "text": "The network with soft target updates performed quite well. However, it doesn’t seem to be better than hard weight updates." }, { "code": null, "e": 17089, "s": 17032, "text": "This gif illustrates the performance of a trained agent:" }, { "code": null, "e": 17543, "s": 17089, "text": "The implementation of the experience replay and the target network have significantly improved the performance of a Deep Q Learning agent in the Open AI CartPole environment. Some other modifications to the agent, such as Dueling Network Architectures (Wang et al., 2015), can be added to this implementation to improve the agent’s performance. The algorithm is also generalizable to other environments. Feel free to test how well it solves other tasks!" }, { "code": null, "e": 17649, "s": 17543, "text": "Link to the notebook: https://github.com/ritakurban/Practical-Data-Science/blob/master/DQL_CartPole.ipynb" }, { "code": null, "e": 17867, "s": 17649, "text": "(1) Reinforcement Q-Learning from Scratch in Python with OpenAI Gym. (2019). Learndatasci.com. Retrieved 9 December 2019, from https://www.learndatasci.com/tutorials/reinforcement-q-learning-scratch-python-openai-gym/" }, { "code": null, "e": 18019, "s": 17867, "text": "(2) Paszke, A., (2019). Reinforcement Learning (DQN) tutorial. Retrieved from: https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html" }, { "code": null, "e": 18212, "s": 18019, "text": "(3) Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., ... & Wierstra, D. (2015). Continuous control with deep reinforcement learning. arXiv preprint arXiv:1509.02971." }, { "code": null, "e": 18380, "s": 18212, "text": "(4) Van Hasselt, H., Guez, A., & Silver, D. (2016, March). Deep reinforcement learning with double q-learning. In Thirtieth AAAI conference on artificial intelligence." }, { "code": null, "e": 18569, "s": 18380, "text": "(5) Wang, Z., Schaul, T., Hessel, M., Van Hasselt, H., Lanctot, M., & De Freitas, N. (2015). Dueling network architectures for deep reinforcement learning. arXiv preprint arXiv:1511.06581." } ]
smartctl - Unix, Linux Command
smartctl is a command line utility designed to perform SMART tasks such as printing the SMART self-test and error logs, enabling and disabling SMART automatic testing, and initiating device self-tests. Note: if the user issues a SMART command that is (apparently) not implemented by the device, smartctl will print a warning message but issue the command anyway (see the -T, --tolerance option below). This should not cause problems: on most devices, unimplemented SMART commands issued to a drive are ignored and/or return an error. smartctl also provides support for polling TapeAlert messages from SCSI tape drives and changers. The user must specify the device to be controlled or interrogated as the final argument to smartctl. Device paths are as follows: Alternatively, drive letters "X:" or "X:\" may be used to specify the physical drive behind a mounted partition. For disks behind 3ware 9000 controllers use "/dev/sd[a-z],N" where N specifies the disk number (3ware 'port') behind the controller providing the logical drive ('unit') specified by "/dev/sd[a-z]". Alternatively, use "/dev/tw_cli/cx/py" for controller x, port y to run the 'tw_cli' tool and parse the output. This provides limited monitoring ('-i', '-c', '-A' below) if SMART support is missing in the driver. Use "/dev/tw_cli/stdin" or "/dev/tw_cli/clip" to parse CLI or 3DM output from standard input or clipboard. The option '-d 3ware,N' is not necessary on Windows. The prefix "/dev/" is optional. Based on the device path, smartctl will guess the device type (ATA or SCSI). If necessary, the '-d' option can be used to over-ride this guess Note that the printed output of smartctl displays most numerical values in base 10 (decimal), but some values are displayed in base 16 (hexadecimal). To distinguish them, the base 16 values are always displayed with a leading "0x", for example: "0xff". This man page follows the same convention. The options are grouped below into several categories. smartctl will execute the corresponding commands in the order: INFORMATION, ENABLE/DISABLE, DISPLAY DATA, RUN/ABORT TESTS. SCSI devices only accept the options -h, -V, -i, -a, -A, -d, -s, -S,-H, -t, -C, -l background, -l error, -l selftest, -r, and -X. TapeAlert devices only accept the options -h, -V, -i, -a, -A, -d, -s, -S, -t, -l error, -l selftest, -r, and -H. Long options are not supported on all systems. Use 'smartctl -h' to see the available options. '-H -i -c -A -l error -l selftest -l selective' '-H -i -A -l error -l selftest'. errorsonly - only print: For the '-l error' option, if nonzero, the number of errors recorded in the SMART error log and the power-on time when they occurred; For the '-l selftest' option, errors recorded in the device self-test log; For the '-H' option, SMART "disk failing" status or device Attributes (pre-failure or usage) which failed either now or in the past; For the '-A' option, device Attributes (pre-failure or usage) which failed either now or in the past. silent - print no output. The only way to learn about what was found is to use the exit status of smartctl (see RETURN VALUES below). noserial - Do not print the serial number of the device. The 'sat' device type is for ATA disks that have a SCSI to ATA Translation (SAT) Layer (SATL) between the disk and the operating system. SAT defines two ATA PASS THROUGH SCSI commands, one 12 bytes long and the other 16 bytes long that smartctl will utilize when this device type is selected. The default is the 16 byte variant which can be overridden with either '-d sat,12' or '-d sat,16'. Under Linux, to look at SATA disks behind Marvell SATA controllers (using Marvell’s 'linuxIAL' driver rather than libata driver) use '-d marvell'. Such controllers show up as Marvell Technology Group Ltd. SATA I or II controllers using lspci, or using lspci -n show a vendor ID 0x11ab and a device ID of either 0x5040, 0x5041, 0x5080, 0x5081, 0x6041 or 0x6081. The 'linuxIAL' driver seems not (yet?) available in the Linux kernel source tree, but should be available from system vendors (ftp://ftp.aslab.com/ is known to provide a patch with the driver). Under Linux and FreeBSD, to look at ATA disks behind 3ware SCSI RAID controllers, use syntax such as: smartctl -a -d 3ware,2 /dev/sda smartctl -a -d 3ware,0 /dev/twe0 smartctl -a -d 3ware,1 /dev/twa0 Note that if the special character device nodes /dev/twa? and /dev/twe? do not exist, or exist with the incorrect major or minor numbers, smartctl will recreate them on the fly. Typically /dev/twa0 refers to the first 9000-series controller, /dev/twa1 refers to the second 9000 series controller, and so on. Likewise /dev/twe0 refers to the first 6/7/8000-series controller, /dev/twa1 refers to the second 6/7/8000 series controller, and so on. Note that for the 6/7/8000 controllers, any of the physical disks can be queried or examined using any of the 3ware’s SCSI logical device /dev/sd? entries. Thus, if logical device /dev/sda is made up of two physical disks (3ware ports zero and one) and logical device /dev/sdb is made up of two other physical disks (3ware ports two and three) then you can examine the SMART data on any of the four physical disks using either SCSI device /dev/sda or /dev/sdb. If you need to know which logical SCSI device a particular physical disk (3ware port) is associated with, use the dmesg or SYSLOG output to show which SCSI ID corresponds to a particular 3ware unit, and then use the 3ware CLI or 3dm tool to determine which ports (physical disks) correspond to particular 3ware units. If the value of N corresponds to a port that does not exist on the 3ware controller, or to a port that does not physically have a disk attached to it, the behavior of smartctl depends upon the specific controller model, firmware, Linux kernel and platform. In some cases you will get a warning message that the device does not exist. In other cases you will be presented with 'void' data for a non-existent device. Note that if the /dev/sd? addressing form is used, then older 3w-xxxx drivers do not pass the "Enable Autosave" ('-S on') and "Enable Automatic Offline" ('-o on') commands to the disk, and produce these types of harmless syslog error messages instead: "3w-xxxx: tw_ioctl(): Passthru size (123392) too big". This can be fixed by upgrading to version 1.02.00.037 or later of the 3w-xxxx driver, or by applying a patch to older versions. See http://smartmontools.sourceforge.net/ for instructions. Alternatively, use the character device /dev/twe0-15 interface. The selective self-test functions ('-t select,A-B') are only supported using the character device interface /dev/twa0-15 and /dev/twe0-15. The necessary WRITE LOG commands can not be passed through the SCSI interface. 3ware controllers are supported under Linux, FreeBSD and Windows. To look at (S)ATA disks behind HighPoint RocketRAID controllers, use syntax such as: smartctl -a -d hpt,1/3 /dev/sda smartctl -a -d hpt,1/2/3 /dev/sda HighPoint RocketRAID controllers are currently ONLY supported under Linux. cciss controllers are currently ONLY supported under Linux. The behavior of smartctl depends upon whether the command is "optional" or "mandatory". Here "mandatory" means "required by the ATA/ATAPI-5 Specification if the device implements the SMART command set" and "optional" means "not required by the ATA/ATAPI-5 Specification even if the device implements the SMART command set." The "mandatory" ATA and SMART commands are: (1) ATA IDENTIFY DEVICE, (2) SMART ENABLE/DISABLE ATTRIBUTE AUTOSAVE, (3) SMART ENABLE/DISABLE, and (4) SMART RETURN STATUS. The valid arguments to this option are: normal - exit on failure of any mandatory SMART command, and ignore all failures of optional SMART commands. This is the default. Note that on some devices, issuing unimplemented optional SMART commands doesn't cause an error. This can result in misleading smartctl messages such as "Feature X not implemented", followed shortly by "Feature X: enabled". In most such cases, contrary to the final message, Feature X is not enabled. conservative - exit on failure of any optional SMART command. permissive - ignore failure(s) of mandatory SMART commands. This option may be given more than once. Each additional use of this option will cause one more additional failure to be ignored. Note that the use of this option can lead to messages like "Feature X not implemented", followed shortly by "Error: unable to enable Feature X". In a few such cases, contrary to the final message, Feature X is enabled. verypermissive - equivalent to giving a large number of '-T permissive' options: ignore failures of any number of mandatory SMART commands. Please see the note above. The valid arguments to this option are: warn - report the incorrect checksum but carry on in spite of it. This is the default. exit - exit smartctl. ignore - continue silently without issuing a warning. ioctl - report all ioctl() transactions. ataioctl - report only ioctl() transactions with ATA devices. scsiioctl - report only ioctl() transactions with SCSI devices. Invoking this once shows the SCSI commands in hex and the corresponding status. Invoking it a second time adds a hex listing of the first 64 bytes of data send to, or received from the device. Any argument may include a positive integer to specify the level of detail that should be reported. The argument should be followed by a comma then the integer with no spaces. For example, ataioctl,2 The default level is 1, so '-r ataioctl,1' and '-r ataioctl' are equivalent. For testing purposes, the output of '-r ataioctl,2' can later be parsed by smartctl itself if '-' is used as device path argument. The ATA command input parameters, sector data and return values are reconstructed from the debug report read from stdin. Then smartctl internally simulates an ATA device with the same behaviour. This is does not work for SCSI devices yet. never - check the device always, but print the power mode if '-i' is specified. sleep - check the device unless it is in SLEEP mode. standby - check the device unless it is in SLEEP or STANDBY mode. In these modes most disks are not spinning, so if you want to prevent a disk from spinning up, this is probably what you want. idle - check the device unless it is in SLEEP, STANDBY or IDLE mode. In the IDLE state, most disks are still spinning, so this is probably not what you want. Note that the SMART automatic offline test command is listed as "Obsolete" in every version of the ATA and ATA/ATAPI Specifications. It was originally part of the SFF-8035i Revision 2.0 specification, but was never part of any ATA specification. However it is implemented and used by many vendors. [Good documentation can be found in IBM's Official Published Disk Specifications. For example the IBM Travelstar 40GNX Hard Disk Drive Specifications (Revision 1.1, 22 April 2002, Publication # 1541, Document S07N-7715-02) page 164. You can also read the SFF-8035i Specification -- see REFERENCES below.] You can tell if automatic offline testing is supported by seeing if this command enables and disables it, as indicated by the 'Auto Offline Data Collection' part of the SMART capabilities report (displayed with '-c'). SMART provides three basic categories of testing. The first category, called "online" testing, has no effect on the performance of the device. It is turned on by the '-s on' option. The second category of testing is called "offline" testing. This type of test can, in principle, degrade the device performance. The '-o on' option causes this offline testing to be carried out, automatically, on a regular scheduled basis. Normally, the disk will suspend offline testing while disk accesses are taking place, and then automatically resume it when the disk would otherwise be idle, so in practice it has little effect. Note that a one-time offline test can also be carried out immediately upon receipt of a user command. See the '-t offline' option below, which causes a one-time offline test to be carried out immediately. The choice (made by the SFF-8035i and ATA specification authors) of the word testing for these first two categories is unfortunate, and often leads to confusion. In fact these first two categories of online and offline testing could have been more accurately described as online and offline data collection. The results of this automatic or immediate offline testing (data collection) are reflected in the values of the SMART Attributes. Thus, if problems or errors are detected, the values of these Attributes will go below their failure thresholds; some types of errors may also appear in the SMART error log. These are visible with the '-A' and '-l error' options respectively. Some SMART attribute values are updated only during off-line data collection activities; the rest are updated during normal operation of the device or during both normal operation and off-line testing. The Attribute value table produced by the '-A' option indicates this in the UPDATED column. Attributes of the first type are labeled "Offline" and Attributes of the second type are labeled "Always". The third category of testing (and the only category for which the word 'testing' is really an appropriate choice) is "self" testing. This third type of test is only performed (immediately) when a command to run it is issued. The '-t' and '-X' options can be used to carry out and abort such self-tests; please see below for further details. Any errors detected in the self testing will be shown in the SMART self-test log, which can be examined using the '-l selftest' option. Note: in this manual page, the word "Test" is used in connection with the second category just described, e.g. for the "offline" testing. The words "Self-test" are used in connection with the third category. For SCSI devices this toggles the value of the Global Logging Target Save Disabled (GLTSD) bit in the Control Mode Page. Some disk manufacturers set this bit by default. This prevents error counters, power-up hours and other useful data from being placed in non-volatile storage, so these values may be reset to zero the next time the device is power-cycled. If the GLTSD bit is set then 'smartctl -a' will issue a warning. Use on to clear the GLTSD bit and thus enable saving counters to non-volatile storage. For extreme streaming-video type applications you might consider using off to set the GLTSD bit. If the device reports failing health status, this means either that the device has already failed, or that it is predicting its own failure within the next 24 hours. If this happens, use the '-a' option to get more information, and get your data off the disk and to someplace safe as soon as you can. Note that the time required to run the Self-tests (listed in minutes) are fixed. However the time required to run the Immediate Offline Test (listed in seconds) is variable. This means that if you issue a command to perform an Immediate Offline test with the '-t offline' option, then the time may jump to a larger value and then count down as the Immediate Offline Test is carried out. Please see REFERENCES below for further information about the the flags and capabilities described by this option. Each Attribute has a "Raw" value, printed under the heading "RAW_VALUE", and a "Normalized" value printed under the heading "VALUE". [Note: smartctl prints these values in base-10.] In the example just given, the "Raw Value" for Attribute 12 would be the actual number of times that the disk has been power-cycled, for example 365 if the disk has been turned on once per day for exactly one year. Each vendor uses their own algorithm to convert this "Raw" value to a "Normalized" value in the range from 1 to 254. Please keep in mind that smartctl only reports the different Attribute types, values, and thresholds as read from the device. It does not carry out the conversion between "Raw" and "Normalized" values: this is done by the disk's firmware. The conversion from Raw value to a quantity with physical units is not specified by the SMART standard. In most cases, the values printed by smartctl are sensible. For example the temperature Attribute generally has its raw value equal to the temperature in Celsius. However in some cases vendors use unusual conventions. For example the Hitachi disk on my laptop reports its power-on hours in minutes, not hours. Some IBM disks track three temperatures rather than one, in their raw values. And so on. Each Attribute also has a Threshold value (whose range is 0 to 255) which is printed under the heading "THRESH". If the Normalized value is less than or equal to the Threshold value, then the Attribute is said to have failed. If the Attribute is a pre-failure Attribute, then disk failure is imminent. Each Attribute also has a "Worst" value shown under the heading "WORST". This is the smallest (closest to failure) value that the disk has recorded at any time during its lifetime when SMART was enabled. [Note however that some vendors firmware may actually increase the "Worst" value for some "rate-type" Attributes.] The Attribute table printed out by smartctl also shows the "TYPE" of the Attribute. Attributes are one of two possible types: Pre-failure or Old age. Pre-failure Attributes are ones which, if less than or equal to their threshold values, indicate pending disk failure. Old age, or usage Attributes, are ones which indicate end-of-product life from old-age or normal aging and wearout, if the Attribute value is less than or equal to the threshold. Please note: the fact that an Attribute is of type ’Pre-fail’ does not mean that your disk is about to fail! It only has this meaning if the Attribute's current Normalized value is less than or equal to the threshold value. If the Attribute's current Normalized value is less than or equal to the threshold value, then the "WHEN_FAILED" column will display "FAILING_NOW". If not, but the worst recorded value is less than or equal to the threshold value, then this column will display "In_the_past". If the "WHEN_FAILED" column has no entry (indicated by a dash: '-') then this Attribute is OK now (not failing) and has also never failed in the past. The table column labeled "UPDATED" shows if the SMART Attribute values are updated during both normal operation and off-line testing, or only during offline testing. The former are labeled "Always" and the latter are labeled "Offline". So to summarize: the Raw Attribute values are the ones that might have a real physical interpretation, such as "Temperature Celsius", "Hours", or "Start-Stop Cycles". Each manufacturer converts these, using their detailed knowledge of the disk's operations and failure modes, to Normalized Attribute values in the range 1-254. The current and worst (lowest measured) of these Normalized Attribute values are stored on the disk, along with a Threshold value that the manufacturer has determined will indicate that the disk is going to fail, or that it has exceeded its design age or aging limit. smartctl does not calculate any of the Attribute values, thresholds, or types, it merely reports them from the SMART data on the device. Note that starting with ATA/ATAPI-4, revision 4, the meaning of these Attribute fields has been made entirely vendor-specific. However most ATA/ATAPI-5 disks seem to respect their meaning, so we have retained the option of printing the Attribute values. For SCSI devices the "attributes" are obtained from the temperature and start-stop cycle counter log pages. Certain vendor specific attributes are listed if recognised. The attributes are output in a relatively free format (compared with ATA disk attributes). error - prints only the SMART error log. SMART disks maintain a log of the most recent five non-trivial errors. For each of these errors, the disk power-on lifetime at which the error occurred is recorded, as is the device status (idle, standby, etc) at the time of the error. For some common types of errors, the Error Register (ER) and Status Register (SR) values are decoded and printed as text. The meanings of these are: ABRT: Command ABoRTed AMNF: Address Mark Not Found CCTO: Command Completion Timed Out EOM: End Of Media ICRC: Interface Cyclic Redundancy Code (CRC) error IDNF: IDentity Not Found ILI: (packet command-set specific) MC: Media Changed MCR: Media Change Request NM: No Media obs: obsolete TK0NF: TracK 0 Not Found UNC: UNCorrectable Error in Data WP: Media is Write Protected The ATA Specification (ATA-5 Revision 1c, Section 8.41.6.8.2) says: "Error log structures shall include UNC errors, IDNF errors for which the address requested was valid, servo errors, write fault errors, etc. Error log data structures shall not include errors attributed to the receipt of faulty commands such as command codes not implemented by the device or requests with invalid parameters or invalid addresses." The definitions of these terms are: UNC (UNCorrectable): data is uncorrectable. This refers to data which has been read from the disk, but for which the Error Checking and Correction (ECC) codes are inconsistent. In effect, this means that the data can not be read. IDNF (ID Not Found): user-accessible address could not be found. For READ LOG type commands, IDNF can also indicate that a device data log structure checksum was incorrect. If the command that caused the error was a READ or WRITE command, then the Logical Block Address (LBA) at which the error occurred will be printed in base 10 and base 16. The LBA is a linear address, which counts 512-byte sectors on the disk, starting from zero. (Because of the limitations of the SMART error log, if the LBA is greater than 0xfffffff, then either no error log entry will be made, or the error log entry will have an incorrect LBA. This may happen for drives with a capacity greater than 128 GiB or 137 GB.) On Linux systems the smartmontools web page has instructions about how to convert the LBA address to the name of the disk file containing the erroneous disk sector. Please note that some manufacturers ignore the ATA specifications, and make entries in the error log if the device receives a command which is not implemented or is not valid. error [SCSI] - prints the error counter log pages for reads, write and verifies. The verify row is only output if it has an element other than zero. selftest - prints the SMART self-test log. The disk maintains a self-test log showing the results of the self tests, which can be run using the '-t' option described below. For each of the most recent twenty-one self-tests, the log shows the type of test (short or extended, off-line or captive) and the final status of the test. If the test did not complete successfully, then the percentage of the test remaining is shown. The time at which the test took place, measured in hours of disk lifetime, is also printed. If any errors were detected, the Logical Block Address (LBA) of the first error is printed in decimal notation. On Linux systems the smartmontools web page has instructions about how to convert this LBA address to the name of the disk file containing the erroneous block. selftest [SCSI] - the self-test log for a SCSI device has a slightly different format than for an ATA device. For each of the most recent twenty self-tests, it shows the type of test and the status (final or in progress) of the test. SCSI standards use the terms "foreground" and "background" (rather than ATA's corresponding "captive" and "off-line") and "short" and "long" (rather than ATA's corresponding "short" and "extended") to describe the type of the test. The printed segment number is only relevant when a test fails in the third or later test segment. It identifies the test that failed and consists of either the number of the segment that failed during the test, or the number of the test that failed and the number of the segment in which the test was run, using a vendor-specific method of putting both numbers into a single byte. The Logical Block Address (LBA) of the first error is printed in hexadecimal notation. On Linux systems the smartmontools web page has instructions about how to convert this LBA address to the name of the disk file containing the erroneous block. If provided, the SCSI Sense Key (SK), Additional Sense Code (ASC) and Additional Sense Code Qualifier (ASQ) are also printed. The self tests can be run using the '-t' option described below (using the ATA test terminology). selective [ATA] - Some ATA-7 disks (example: Maxtor) also maintain a selective self-test log. Please see the '-t select' option below for a description of selective self-tests. The selective self-test log shows the start/end Logical Block Addresses (LBA) of each of the five test spans, and their current test status. If the span is being tested or the remainder of the disk is being read-scanned, the current 65536-sector block of LBAs being tested is also displayed. The selective self-test log also shows if a read-scan of the remainder of the disk will be carried out after the selective self-test has completed (see '-t afterselect' option) and the time delay before restarting this read-scan if it is interrupted (see '-t pending' option). This is a new smartmontools feature; please report unusual or incorrect behavior to the smartmontools-support mailing list. directory - if the device supports the General Purpose Logging feature set (ATA-6 and ATA-7 only) then this prints the Log Directory (the log at address 0). The Log Directory shows what logs are available and their length in sectors (512 bytes). The contents of the logs at address 1 [Summary SMART error log] and at address 6 [SMART self-test log] may be printed using the previously-described error and selftest arguments to this option. [Please note: this is a new, experimental feature. We would like to add support for printing the contents of extended and comprehensive SMART self-test and error logs. If your disk supports these, and you would like to assist, please contact the smartmontools developers.] background [SCSI] - the background scan results log outputs information derived from Background Media Scans (BMS) done after power up and/or periodocally (e.g. every 24 hours) on recent SCSI disks. If supported, the BMS status is output first, indicating whether a background scan is currently underway (and if so a progress percentage), the amount of time the disk has been powered up and the number of scans already completed. Then there is a header and a line for each background scan "event". These will typically be either recovered or unrecoverable errors. That latter group may need some attention. There is a description of the background scan mechansim in section 4.18 of SBC-3 revision 6 (see www.t10.org ). scttemp, scttempsts, scttemphist [ATA] - [NEW EXPERIMENTAL SMARTCTL FEATURE] prints the disk temperature information provided by the SMART Command Transport (SCT) commands. The option 'scttempsts' prints current temperature and temperature ranges returned by the SCT Status command, 'scttemphist' prints temperature limits and the temperature history table returned by the SCT Data Table command, and 'scttemp' prints both. The temperature values are preserved across power cycles. The default temperature logging interval is 1 minute and can be configured with the '-t scttempint,N[,p]' option, see below. The SCT commands are specified in the proposed ATA-8 Command Set (ACS), and are already implemented in some recent ATA-7 disks. help - Prints (to STDOUT) a list of all valid arguments to this option, then exits. 9,minutes - Raw Attribute number 9 is power-on time in minutes. Its raw value will be displayed in the form "Xh+Ym". Here X is hours, and Y is minutes in the range 0-59 inclusive. Y is always printed with two digits, for example "06" or "31" or "00". 9,seconds - Raw Attribute number 9 is power-on time in seconds. Its raw value will be displayed in the form "Xh+Ym+Zs". Here X is hours, Y is minutes in the range 0-59 inclusive, and Z is seconds in the range 0-59 inclusive. Y and Z are always printed with two digits, for example "06" or "31" or "00". 9,halfminutes - Raw Attribute number 9 is power-on time, measured in units of 30 seconds. This format is used by some Samsung disks. Its raw value will be displayed in the form "Xh+Ym". Here X is hours, and Y is minutes in the range 0-59 inclusive. Y is always printed with two digits, for example "06" or "31" or "00". 9,temp - Raw Attribute number 9 is the disk temperature in Celsius. 192,emergencyretractcyclect - Raw Attribute number 192 is the Emergency Retract Cycle Count. 193,loadunload - Raw Attribute number 193 contains two values. The first is the number of load cycles. The second is the number of unload cycles. The difference between these two values is the number of times that the drive was unexpectedly powered off (also called an emergency unload). As a rule of thumb, the mechanical stress created by one emergency unload is equivalent to that created by one hundred normal unloads. 194,10xCelsius - Raw Attribute number 194 is ten times the disk temperature in Celsius. This is used by some Samsung disks (example: model SV1204H with RK100-13 firmware). 194,unknown - Raw Attribute number 194 is NOT the disk temperature, and its interpretation is unknown. This is primarily useful for the -P (presets) option. 198,offlinescanuncsectorct - Raw Attribute number 198 is the Offline Scan UNC Sector Count. 200,writeerrorcount - Raw Attribute number 200 is the Write Error Count. 201,detectedtacount - Raw Attribute number 201 is the Detected TA Count. 220,temp - Raw Attribute number 220 is the disk temperature in Celsius. Note: a table of hard drive models, listing which Attribute corresponds to temperature, can be found at: http://www.guzu.net/linux/hddtemp.db N,raw8 - Print the Raw value of Attribute N as six 8-bit unsigned base-10 integers. This may be useful for decoding the meaning of the Raw value. The form 'N,raw8' prints Raw values for ALL Attributes in this form. The form (for example) '123,raw8' only prints the Raw value for Attribute 123 in this form. N,raw16 - Print the Raw value of Attribute N as three 16-bit unsigned base-10 integers. This may be useful for decoding the meaning of the Raw value. The form 'N,raw16' prints Raw values for ALL Attributes in this form. The form (for example) '123,raw16' only prints the Raw value for Attribute 123 in this form. N,raw48 - Print the Raw value of Attribute N as a 48-bit unsigned base-10 integer. This may be useful for decoding the meaning of the Raw value. The form 'N,raw48' prints Raw values for ALL Attributes in this form. The form (for example) '123,raw48' only prints the Raw value for Attribute 123 in this form. none - Assume that the device firmware obeys the ATA specifications. This is the default, unless the device has presets for '-F' in the device database (see note below). samsung - In some Samsung disks (example: model SV4012H Firmware Version: RM100-08) some of the two- and four-byte quantities in the SMART data structures are byte-swapped (relative to the ATA specification). Enabling this option tells smartctl to evaluate these quantities in byte-reversed order. Some signs that your disk needs this option are (1) no self-test log printed, even though you have run self-tests; (2) very large numbers of ATA errors reported in the ATA error log; (3) strange and impossible values for the ATA error log timestamps. samsung2 - In more recent Samsung disks (firmware revisions ending in "-23") the number of ATA errors reported is byte swapped. Enabling this option tells smartctl to evaluate this quantity in byte-reversed order. An indication that your Samsung disk needs this option is that the self-test log is printed correctly, but there are a very large number of errors in the SMART error log. This is because the error count is byte swapped. Thus a disk with five errors (0x0005) will appear to have 20480 errors (0x5000). samsung3 - Some Samsung disks (at least SP2514N with Firmware VF100-37) report a self-test still in progress with 0% remaining when the test was already completed. Enabling this option modifies the output of the self-test execution status (see options '-c' or '-a' above) accordingly. Note that an explicit '-F' option on the command line will over-ride any preset values for '-F' (see the '-P' option below). swapid - Fixes byte swapped ATA identify strings (device name, serial number, firmware version) returned by some buggy device drivers. smartctl can automatically set appropriate options for known drives. For example, the Maxtor 4D080H4 uses Attribute 9 to stores power-on time in minutes whereas most drives use that Attribute to store the power-on time in hours. The command-line option '-v 9,minutes' ensures that smartctl correctly interprets Attribute 9 in this case, but that option is preset for the Maxtor 4D080H4 and so need not be specified by the user on the smartctl command line. The argument show will show any preset options for your drive and the argument showall will show all known drives in the smartmontools database, along with their preset options. If there are no presets for your drive and you think there should be (for example, a -v or -F option is needed to get smartctl to display correct values) then please contact the smartmontools developers so that this information can be added to the smartmontools database. Contact information is at the end of this man page. The valid arguments to this option are: use - if a drive is recognized, then use the stored presets for it. This is the default. Note that presets will NOT over-ride additional Attribute interpretation ('-v N,something') command-line options or explicit '-F' command-line options.. ignore - do not use presets. show - show if the drive is recognized in the database, and if so, its presets, then exit. showall - list all recognized drives, and the presets that are set for them, then exit. The '-P showall' option takes up to two optional arguments to match a specific drive type and firmware version. The command: smartctl -P showall smartctl -P showall 'MODEL' smartctl -P showall 'MODEL' 'FIRMWARE' The valid arguments to this option are: offline - runs SMART Immediate Offline Test. This immediately starts the test described above. This command can be given during normal system operation. The effects of this test are visible only in that it updates the SMART Attribute values, and if errors are found they will appear in the SMART error log, visible with the '-l error' option. [In the case of SCSI devices runs the default self test in foreground. No entry is placed in the self test log.] If the '-c' option to smartctl shows that the device has the "Suspend Offline collection upon new command" capability then you can track the progress of the Immediate Offline test using the '-c' option to smartctl. If the '-c' option show that the device has the "Abort Offline collection upon new command" capability then most commands will abort the Immediate Offline Test, so you should not try to track the progress of the test with '-c', as it will abort the test. short - runs SMART Short Self Test (usually under ten minutes). [Note: in the case of SCSI devices, this command option runs the "Background short" self-test.] This command can be given during normal system operation (unless run in captive mode - see the '-C' option below). This is a test in a different category than the immediate or automatic offline tests. The "Self" tests check the electrical and mechanical performance as well as the read performance of the disk. Their results are reported in the Self Test Error Log, readable with the '-l selftest' option. Note that on some disks the progress of the self-test can be monitored by watching this log during the self-test; with other disks use the '-c' option to monitor progress. long - runs SMART Extended Self Test (tens of minutes). [Note: in the case of SCSI devices, this command option runs the "Background long" self-test.] This is a longer and more thorough version of the Short Self Test described above. Note that this command can be given during normal system operation (unless run in captive mode - see the '-C' option below). conveyance - [ATA ONLY] runs a SMART Conveyance Self Test (minutes). This self-test routine is intended to identify damage incurred during transporting of the device. This self-test routine should take on the order of minutes to complete. Note that this command can be given during normal system operation (unless run in captive mode - see the '-C' option below). select,N-M, select,N+SIZE - [ATA ONLY] [EXPERIMENTAL SMARTCTL FEATURE] runs a SMART Selective Self Test, to test a range of disk Logical Block Addresses (LBAs), rather than the entire disk. Each range of LBAs that is checked is called a "span" and is specified by a starting LBA (N) and an ending LBA (M) with N less than or equal to M. The range can also be specified as N+SIZE. A span at the end of a disk can be specified by N-max. For example the commands: smartctl -t select,10-20 /dev/hda smartctl -t select,10+11 /dev/hda smartctl -t select,100000000-max /dev/hda smartctl -t select,0-100 -t select,1000-2000 /dev/hda smartctl -t select,0-10 -t select,5-15 -t select,10-20 /dev/hda Selective self tests are particularly useful as disk capacities increase: an extended self test (smartctl -t long) can take several hours. Selective self-tests are helpful if (based on SYSLOG error messages, previous failed self-tests, or SMART error log entries) you suspect that a disk is having problems at a particular range of Logical Block Addresses (LBAs). Selective self-tests can be run during normal system operation (unless done in captive mode - see the '-C' option below). [Note: To use this feature on Linux, the kernel must be compiled with the configuration option CONFIG_IDE_TASKFILE_IO enabled. Please report unusual or incorrect behavior to the smartmontools-support mailing list.] The following variants of the selective self-test command use spans based on the ranges from past tests already stored on the disk: select,redo[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] redo the last SMART Selective Self Test using the same LBA range. The starting LBA is identical to the LBA used by last test, same for ending LBA unless a new span size is specified by optional +SIZE argument. For example the commands: smartctl -t select,10-20 /dev/hda smartctl -t select,redo /dev/hda smartctl -t select,redo+20 /dev/hda smartctl -t select,10-20 /dev/hda smartctl -t select,10-20 /dev/hda smartctl -t select,10-29 /dev/hda select,next[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] runs a SMART Selective Self Test on the LBA range which follows the range of the last test. The starting LBA is set to (ending LBA +1) of the last test. A new span size may be specified by the optional +SIZE argument. For example the commands: smartctl -t select,0-999 /dev/hda smartctl -t select,next /dev/hda smartctl -t select,next+2000 /dev/hda smartctl -t select,0-999 /dev/hda smartctl -t select,1000-1999 /dev/hda smartctl -t select,2000-3999 /dev/hda If the last test ended at the last LBA of the disk, the new range starts at LBA 0. The span size of the last span of a disk is adjusted such that the total number of spans to check the full disk will not be changed by future uses of '-t select,next'. select,cont[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] performs a 'redo' (above) if the self test status reports that the last test was aborted by the host. Otherwise it run the 'next' (above) test. afterselect,on - [ATA ONLY] perform an offline read scan after a Selective Self-test has completed. This option must be used together with one or more of the select,N-M options above. If the LBAs that have been specified in the Selective self-test pass the test with no errors found, then read scan the remainder of the disk. If the device is powered-cycled while this read scan is in progress, the read scan will be automatically resumed after a time specified by the pending timer (see below). The value of this option is preserved between selective self-tests. afterselect,off - [ATA ONLY] do not read scan the remainder of the disk after a Selective self-test has completed. This option must be use together with one or more of the select,N-M options above. The value of this option is preserved between selective self-tests. pending,N - [ATA ONLY] set the pending offline read scan timer to N minutes. Here N is an integer in the range from 0 to 65535 inclusive. If the device is powered off during a read scan after a Selective self-test, then resume the test automatically N minutes after power-up. This option must be use together with one or more of the select,N-M options above. The value of this option is preserved between selective self-tests. scttempint,N[,p] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] set the time interval for SCT temperature logging to N minutes. If ',p' is specified, the setting is preserved across power cycles. Otherwise, the setting is volatile and will be reverted to default (1 minute), or last non-volatile setting by the next hard reset. This command also clears the temperature history table. See '-l scttemp' above for more information about SCT temperature logging. WARNING: Tests run in captive mode may busy out the drive for the length of the test. Only run captive tests on drives without any mounted partitions! smartctl -a /dev/hda smartctl -s off /dev/hdd smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda smartctl -t long /dev/hdc smartctl -s on -t offline /dev/hda smartctl -A -v 9,minutes /dev/hda smartctl -q errorsonly -H -l selftest /dev/hda smartctl -q silent -a /dev/hda smartctl -a -d 3ware,0 /dev/sda smartctl -a -d 3ware,0 /dev/twe0 smartctl -a -d 3ware,0 /dev/twa0 smartctl -t short -d 3ware,3 /dev/sdb smartctl -a -d hpt,1/3 /dev/sda smartctl -t short -d hpt,1/1/2 /dev/sda smartctl -t short -d hpt,1/1/2 /dev/sda smartctl -t select,10-100 -t select,30-300 -t afterselect,on -t pending,45 /dev/hda smartctl -a -d cciss,0 /dev/cciss/c0d0 To test within the shell for whether or not the different bits are turned on or off, you can use the following type of construction (this is bash syntax): smartstat=$(($? & 8)) Casper Dik (Solaris SCSI interface) Christian Franke (Windows interface and Cygwin package) Douglas Gilbert (SCSI subsystem) Guido Guenther (Autoconf/Automake packaging) Geoffrey Keating (Darwin ATA interface) Eduard Martinescu (FreeBSD interface) Frédéric L. W. Meunier (Web site and Mailing list) Keiji Sawada (Solaris ATA interface) Sergey Svishchev (NetBSD interface) David Snyder and Sergey Svishchev (OpenBSD interface) Phil Williams (User interface and drive database) Yuri Dario (OS/2, eComStation interface) Shengfeng Zhou (Linux Highpoint RocketRaid interface) If you would like to understand better how SMART works, and what it does, a good place to start is with Sections 4.8 and 6.54 of the first volume of the 'AT Attachment with Packet Interface-7' (ATA/ATAPI-7) specification. This documents the SMART functionality which the smartmontools utilities provide access to. You can find Revision 4b of this document at http://www.t13.org/docs2004/d1532v1r4b-ATA-ATAPI-7.pdf . Earlier and later versions of this Specification are available from the T13 web site http://www.t13.org/ . The functioning of SMART was originally defined by the SFF-8035i revision 2 and the SFF-8055i revision 1.4 specifications. These are publications of the Small Form Factors (SFF) Committee. Links to these documents may be found in the References section of the smartmontools home page at http://smartmontools.sourceforge.net/ . 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": 11122, "s": 10585, "text": "\nsmartctl is a command line utility designed to perform SMART\ntasks such as printing the SMART self-test and error logs, enabling\nand disabling SMART automatic testing, and initiating device\nself-tests. Note: if the user issues a SMART command that is\n(apparently) not implemented by the device, smartctl will print\na warning message but issue the command anyway (see the -T,\n--tolerance option below). This should not cause problems: on\nmost devices, unimplemented SMART commands issued to a drive are\nignored and/or return an error.\n" }, { "code": null, "e": 11222, "s": 11122, "text": "\nsmartctl also provides support for polling TapeAlert messages\nfrom SCSI tape drives and changers.\n" }, { "code": null, "e": 11355, "s": 11222, "text": "\nThe user must specify the device to be controlled or interrogated as\nthe final argument to smartctl. Device paths are as follows:\n" }, { "code": null, "e": 11470, "s": 11355, "text": "\nAlternatively, drive letters \"X:\" or \"X:\\\" may be used to\nspecify the physical drive behind a mounted partition.\n" }, { "code": null, "e": 12074, "s": 11470, "text": "\nFor disks behind 3ware 9000 controllers use \"/dev/sd[a-z],N\" where\nN specifies the disk number (3ware 'port') behind the controller\nproviding the logical drive ('unit') specified by \"/dev/sd[a-z]\".\nAlternatively, use \"/dev/tw_cli/cx/py\" for controller x, port y\nto run the 'tw_cli' tool and parse the output. This provides limited\nmonitoring ('-i', '-c', '-A' below) if SMART support is missing\nin the driver. Use \"/dev/tw_cli/stdin\" or \"/dev/tw_cli/clip\"\nto parse CLI or 3DM output from standard input or clipboard.\nThe option '-d 3ware,N' is not necessary on Windows.\nThe prefix \"/dev/\" is optional.\n" }, { "code": null, "e": 12220, "s": 12074, "text": "\nBased on the device path, smartctl will guess the device type\n(ATA or SCSI). If necessary, the '-d' option can be used to over-ride\nthis guess\n" }, { "code": null, "e": 12519, "s": 12220, "text": "\nNote that the printed output of smartctl displays most numerical\nvalues in base 10 (decimal), but some values are displayed in base 16\n(hexadecimal). To distinguish them, the base 16 values are always\ndisplayed with a leading \"0x\", for example: \"0xff\". This man\npage follows the same convention.\n" }, { "code": null, "e": 12704, "s": 12523, "text": "\nThe options are grouped below into several categories. smartctl\nwill execute the corresponding commands in the order: INFORMATION,\nENABLE/DISABLE, DISPLAY DATA, RUN/ABORT TESTS.\n" }, { "code": null, "e": 12950, "s": 12704, "text": "\nSCSI devices only accept the options -h, -V, -i, -a, -A, -d,\n-s, -S,-H, -t, -C, -l background, -l error, -l selftest, -r,\nand -X. TapeAlert devices only accept the options -h, -V,\n-i, -a, -A, -d, -s, -S, -t, -l error, -l selftest, -r,\nand -H.\n" }, { "code": null, "e": 13055, "s": 12950, "text": "\nLong options are not supported on all systems. Use\n'smartctl -h' to see the available options.\n" }, { "code": null, "e": 13106, "s": 13057, "text": "'-H -i -c -A -l error -l selftest -l selective'\n" }, { "code": null, "e": 13140, "s": 13106, "text": "'-H -i -A -l error -l selftest'.\n" }, { "code": null, "e": 13613, "s": 13142, "text": "\nerrorsonly - only print: For the '-l error' option, if nonzero, the number\nof errors recorded in the SMART error log and the power-on time when\nthey occurred; For the '-l selftest' option, errors recorded in the device\nself-test log; For the '-H' option, SMART \"disk failing\" status or device\nAttributes (pre-failure or usage) which failed either now or in the\npast; For the '-A' option, device Attributes (pre-failure or usage)\nwhich failed either now or in the past.\n" }, { "code": null, "e": 13750, "s": 13613, "text": "\nsilent - print no output. The only way to learn about what was found is to\nuse the exit status of smartctl (see RETURN VALUES below).\n" }, { "code": null, "e": 13809, "s": 13750, "text": "\nnoserial - Do not print the serial number of the device.\n" }, { "code": null, "e": 14205, "s": 13811, "text": "\nThe 'sat' device type is for ATA disks that have a SCSI to ATA\nTranslation (SAT) Layer (SATL) between the disk and the operating system.\nSAT defines two ATA PASS THROUGH SCSI commands, one 12 bytes long and\nthe other 16 bytes long that smartctl will utilize when this device\ntype is selected. The default is the 16 byte variant which can be\noverridden with either '-d sat,12' or '-d sat,16'.\n" }, { "code": null, "e": 14762, "s": 14205, "text": "\nUnder Linux, to look at SATA disks behind Marvell SATA controllers\n(using Marvell’s 'linuxIAL' driver rather than libata driver) use '-d marvell'. Such\ncontrollers show up as Marvell Technology Group Ltd. SATA I or II controllers\nusing lspci, or using lspci -n show a vendor ID 0x11ab and a device ID of\neither 0x5040, 0x5041, 0x5080, 0x5081, 0x6041 or 0x6081. The 'linuxIAL' driver\nseems not (yet?) available in the Linux kernel source tree, but should be available\nfrom system vendors (ftp://ftp.aslab.com/ is known to provide a patch with the driver).\n" }, { "code": null, "e": 14866, "s": 14762, "text": "\nUnder Linux and FreeBSD, to look at ATA disks behind 3ware SCSI RAID controllers,\nuse syntax such as:\n" }, { "code": null, "e": 14899, "s": 14866, "text": "smartctl -a -d 3ware,2 /dev/sda\n" }, { "code": null, "e": 14933, "s": 14899, "text": "smartctl -a -d 3ware,0 /dev/twe0\n" }, { "code": null, "e": 14967, "s": 14933, "text": "smartctl -a -d 3ware,1 /dev/twa0\n" }, { "code": null, "e": 15415, "s": 14967, "text": "\nNote that if the special character device nodes /dev/twa? and\n/dev/twe? do not exist, or exist with the incorrect major or minor\nnumbers, smartctl will recreate them on the fly. Typically /dev/twa0\nrefers to the first 9000-series controller, /dev/twa1 refers to the\nsecond 9000 series controller, and so on. Likewise /dev/twe0 refers to\nthe first 6/7/8000-series controller, /dev/twa1 refers to the second\n6/7/8000 series controller, and so on.\n" }, { "code": null, "e": 16199, "s": 15415, "text": "\nNote that for the 6/7/8000 controllers, any of the physical\ndisks can be queried or examined using any of the 3ware’s SCSI\nlogical device /dev/sd? entries. Thus, if logical device /dev/sda is\nmade up of two physical disks (3ware ports zero and one) and logical\ndevice /dev/sdb is made up of two other physical disks (3ware ports\ntwo and three) then you can examine the SMART data on any of the\nfour physical disks using either SCSI device /dev/sda or\n/dev/sdb. If you need to know which logical SCSI device a particular\nphysical disk (3ware port) is associated with, use the dmesg or SYSLOG\noutput to show which SCSI ID corresponds to a particular 3ware unit,\nand then use the 3ware CLI or 3dm tool to determine which ports\n(physical disks) correspond to particular 3ware units.\n" }, { "code": null, "e": 16617, "s": 16199, "text": "\nIf the value of N corresponds to a port that does not exist on\nthe 3ware controller, or to a port that does not physically have a\ndisk attached to it, the behavior of smartctl depends upon the\nspecific controller model, firmware, Linux kernel and platform. In\nsome cases you will get a warning message that the device does not\nexist. In other cases you will be presented with 'void' data for a\nnon-existent device.\n" }, { "code": null, "e": 17179, "s": 16617, "text": "\nNote that if the /dev/sd? addressing form is used, then older 3w-xxxx\ndrivers do not pass the \"Enable Autosave\"\n('-S on') and \"Enable Automatic Offline\" ('-o on')\ncommands to the disk, and produce these types of harmless syslog error\nmessages instead: \"3w-xxxx: tw_ioctl(): Passthru size (123392) too\nbig\". This can be fixed by upgrading to version 1.02.00.037 or\nlater of the 3w-xxxx driver, or by applying a patch to older\nversions. See http://smartmontools.sourceforge.net/ for\ninstructions. Alternatively, use the character device /dev/twe0-15 interface.\n" }, { "code": null, "e": 17399, "s": 17179, "text": "\nThe selective self-test functions ('-t select,A-B') are only supported\nusing the character device interface /dev/twa0-15 and /dev/twe0-15.\nThe necessary WRITE LOG commands can not be passed through the SCSI\ninterface.\n" }, { "code": null, "e": 17467, "s": 17399, "text": "\n3ware controllers are supported under Linux, FreeBSD and Windows. " }, { "code": null, "e": 17554, "s": 17467, "text": "\nTo look at (S)ATA disks behind HighPoint RocketRAID controllers, use syntax\nsuch as:\n" }, { "code": null, "e": 17587, "s": 17554, "text": "smartctl -a -d hpt,1/3 /dev/sda\n" }, { "code": null, "e": 17622, "s": 17587, "text": "smartctl -a -d hpt,1/2/3 /dev/sda\n" }, { "code": null, "e": 17699, "s": 17622, "text": "\nHighPoint RocketRAID controllers are currently ONLY supported under Linux. " }, { "code": null, "e": 17761, "s": 17699, "text": "\ncciss controllers are currently ONLY supported under Linux. " }, { "code": null, "e": 18259, "s": 17763, "text": "\nThe behavior of smartctl depends upon whether the command is\n\"optional\" or \"mandatory\". Here \"mandatory\" means\n\"required by the ATA/ATAPI-5 Specification if the device implements\nthe SMART command set\" and \"optional\" means \"not required by the\nATA/ATAPI-5 Specification even if the device implements the SMART\ncommand set.\" The \"mandatory\" ATA and SMART commands are: (1)\nATA IDENTIFY DEVICE, (2) SMART ENABLE/DISABLE ATTRIBUTE AUTOSAVE, (3)\nSMART ENABLE/DISABLE, and (4) SMART RETURN STATUS.\n" }, { "code": null, "e": 18301, "s": 18259, "text": "\nThe valid arguments to this option are:\n" }, { "code": null, "e": 18737, "s": 18301, "text": "\nnormal - exit on failure of any mandatory SMART command, and ignore\nall failures of optional SMART commands. This is the default.\nNote that on some devices, issuing unimplemented optional SMART\ncommands doesn't cause an error. This can result in misleading\nsmartctl messages such as \"Feature X not implemented\", followed\nshortly by \"Feature X: enabled\". In most such cases, contrary to the\nfinal message, Feature X is not enabled.\n" }, { "code": null, "e": 18801, "s": 18737, "text": "\nconservative - exit on failure of any optional SMART command.\n" }, { "code": null, "e": 19216, "s": 18801, "text": "\npermissive - ignore failure(s) of mandatory SMART commands. This option\nmay be given more than once. Each additional use of this option will\ncause one more additional failure to be ignored. Note that the use of\nthis option can lead to messages like \"Feature X not implemented\",\nfollowed shortly by \"Error: unable to enable Feature X\". In a few\nsuch cases, contrary to the final message, Feature X is enabled.\n" }, { "code": null, "e": 19385, "s": 19216, "text": "\nverypermissive - equivalent to giving a large number of '-T permissive' options:\nignore failures of any number of mandatory SMART commands.\nPlease see the note above.\n" }, { "code": null, "e": 19429, "s": 19387, "text": "\nThe valid arguments to this option are:\n" }, { "code": null, "e": 19519, "s": 19429, "text": "\nwarn - report the incorrect checksum but carry on in spite of it. This is the\ndefault.\n" }, { "code": null, "e": 19543, "s": 19519, "text": "\nexit - exit smartctl.\n" }, { "code": null, "e": 19599, "s": 19543, "text": "\nignore - continue silently without issuing a warning.\n" }, { "code": null, "e": 19644, "s": 19601, "text": "\nioctl - report all ioctl() transactions.\n" }, { "code": null, "e": 19708, "s": 19644, "text": "\nataioctl - report only ioctl() transactions with ATA devices.\n" }, { "code": null, "e": 19967, "s": 19708, "text": "\nscsiioctl - report only ioctl() transactions with SCSI devices. Invoking this once\nshows the SCSI commands in hex and the corresponding status. Invoking\nit a second time adds a hex listing of the first 64 bytes of data send to,\nor received from the device.\n" }, { "code": null, "e": 20248, "s": 19967, "text": "\nAny argument may include a positive integer to specify the level of detail\nthat should be reported. The argument should be followed by a comma then\nthe integer with no spaces. For example,\nataioctl,2 The default\nlevel is 1, so '-r ataioctl,1' and '-r ataioctl' are equivalent.\n" }, { "code": null, "e": 20620, "s": 20248, "text": "\nFor testing purposes, the output of '-r ataioctl,2' can later be parsed\nby smartctl itself if '-' is used as device path argument.\nThe ATA command input parameters, sector data and return values are\nreconstructed from the debug report read from stdin.\nThen smartctl internally simulates an ATA device with the same\nbehaviour. This is does not work for SCSI devices yet.\n" }, { "code": null, "e": 20704, "s": 20622, "text": "\nnever - check the device always, but print the power mode if '-i' is\nspecified.\n" }, { "code": null, "e": 20759, "s": 20704, "text": "\nsleep - check the device unless it is in SLEEP mode.\n" }, { "code": null, "e": 20955, "s": 20759, "text": "\nstandby - check the device unless it is in SLEEP or STANDBY mode. In\nthese modes most disks are not spinning, so if you want to prevent\na disk from spinning up, this is probably what you want.\n" }, { "code": null, "e": 21115, "s": 20955, "text": "\nidle - check the device unless it is in SLEEP, STANDBY or IDLE mode.\nIn the IDLE state, most disks are still spinning, so this is probably\nnot what you want.\n" }, { "code": null, "e": 21942, "s": 21117, "text": "\nNote that the SMART automatic offline test command is listed as\n\"Obsolete\" in every version of the ATA and ATA/ATAPI Specifications.\nIt was originally part of the SFF-8035i Revision 2.0 specification,\nbut was never part of any ATA specification. However it is\nimplemented and used by many vendors. [Good documentation can be found\nin IBM's Official Published Disk Specifications. For example the IBM\nTravelstar 40GNX Hard Disk Drive Specifications (Revision 1.1, 22\nApril 2002, Publication # 1541, Document S07N-7715-02) page 164. You\ncan also read the SFF-8035i Specification -- see REFERENCES below.]\nYou can tell if automatic offline testing is supported by seeing if\nthis command enables and disables it, as indicated by the 'Auto\nOffline Data Collection' part of the SMART capabilities report\n(displayed with '-c').\n" }, { "code": null, "e": 22128, "s": 21942, "text": "\nSMART provides three basic categories of testing. The\nfirst category, called \"online\" testing, has no effect on the\nperformance of the device. It is turned on by the '-s on' option.\n" }, { "code": null, "e": 22774, "s": 22128, "text": "\nThe second category of testing is called \"offline\" testing. This\ntype of test can, in principle, degrade the device performance. The\n'-o on' option causes this offline testing to be carried out,\nautomatically, on a regular scheduled basis. Normally, the disk will\nsuspend offline testing while disk accesses are taking place, and then\nautomatically resume it when the disk would otherwise be idle, so in\npractice it has little effect. Note that a one-time offline test can\nalso be carried out immediately upon receipt of a user command. See\nthe '-t offline' option below, which causes a one-time offline test\nto be carried out immediately.\n" }, { "code": null, "e": 23085, "s": 22774, "text": "\nThe choice (made by the SFF-8035i and ATA specification authors) of\nthe word testing for these first two categories is unfortunate,\nand often leads to confusion. In fact these first two categories of\nonline and offline testing could have been more accurately described\nas online and offline data collection.\n" }, { "code": null, "e": 23460, "s": 23085, "text": "\nThe results of this automatic or immediate offline testing (data\ncollection) are reflected in the values of the SMART Attributes.\nThus, if problems or errors are detected, the values of these\nAttributes will go below their failure thresholds; some types of\nerrors may also appear in the SMART error log. These are visible with\nthe '-A' and '-l error' options respectively.\n" }, { "code": null, "e": 23865, "s": 23460, "text": "\nSome SMART attribute values are updated only during off-line data\ncollection activities; the rest are updated during normal operation of\nthe device or during both normal operation and off-line testing. The\nAttribute value table produced by the '-A' option indicates this in\nthe UPDATED column. Attributes of the first type are labeled\n\"Offline\" and Attributes of the second type are labeled \"Always\".\n" }, { "code": null, "e": 24211, "s": 23865, "text": "\nThe third category of testing (and the only category for\nwhich the word 'testing' is really an appropriate choice) is \"self\"\ntesting. This third type of test is only performed (immediately) when\na command to run it is issued. The '-t' and '-X' options can be\nused to carry out and abort such self-tests; please see below for\nfurther details.\n" }, { "code": null, "e": 24349, "s": 24211, "text": "\nAny errors detected in the self testing will be shown in the\nSMART self-test log, which can be examined using the '-l selftest'\noption.\n" }, { "code": null, "e": 24560, "s": 24349, "text": "\nNote: in this manual page, the word \"Test\" is used in\nconnection with the second category just described, e.g. for the\n\"offline\" testing. The words \"Self-test\" are used in\nconnection with the third category.\n" }, { "code": null, "e": 25171, "s": 24560, "text": "\nFor SCSI devices this toggles the value of the Global Logging Target\nSave Disabled (GLTSD) bit in the Control Mode Page. Some disk\nmanufacturers set this bit by default. This prevents error counters,\npower-up hours and other useful data from being placed in non-volatile\nstorage, so these values may be reset to zero the next time the device\nis power-cycled. If the GLTSD bit is set then 'smartctl -a' will\nissue a warning. Use on to clear the GLTSD bit and thus enable\nsaving counters to non-volatile storage. For extreme streaming-video\ntype applications you might consider using off to set the GLTSD\nbit.\n" }, { "code": null, "e": 25477, "s": 25173, "text": "\nIf the device reports failing health status, this means\neither that the device has already failed,\nor that it is predicting its own failure within the next 24 hours. If\nthis happens, use the '-a' option to get more information, and\nget your data off the disk and to someplace safe as soon as you can. " }, { "code": null, "e": 25984, "s": 25477, "text": "\nNote that the time required to run the Self-tests (listed in minutes)\nare fixed. However the time required to run the Immediate Offline\nTest (listed in seconds) is variable. This means that if you issue a\ncommand to perform an Immediate Offline test with the '-t offline' option,\nthen the time may jump to a larger value and then count down as the\nImmediate Offline Test is carried out. Please see REFERENCES below\nfor further information about the the flags and capabilities described\nby this option.\n" }, { "code": null, "e": 26744, "s": 25984, "text": "\nEach Attribute has a \"Raw\" value, printed under the heading\n\"RAW_VALUE\", and a \"Normalized\" value printed under the heading\n\"VALUE\". [Note: smartctl prints these values in base-10.] In\nthe example just given, the \"Raw Value\" for Attribute 12 would be the\nactual number of times that the disk has been power-cycled, for\nexample 365 if the disk has been turned on once per day for exactly\none year. Each vendor uses their own algorithm to convert this \"Raw\"\nvalue to a \"Normalized\" value in the range from 1 to 254. Please keep\nin mind that smartctl only reports the different Attribute\ntypes, values, and thresholds as read from the device. It does\nnot carry out the conversion between \"Raw\" and \"Normalized\"\nvalues: this is done by the disk's firmware.\n" }, { "code": null, "e": 27252, "s": 26744, "text": "\nThe conversion from Raw value to a quantity with physical units is\nnot specified by the SMART standard. In most cases, the values printed\nby smartctl are sensible. For example the temperature Attribute\ngenerally has its raw value equal to the temperature in Celsius.\nHowever in some cases vendors use unusual conventions. For example\nthe Hitachi disk on my laptop reports its power-on hours in minutes,\nnot hours. Some IBM disks track three temperatures rather than one, in\ntheir raw values. And so on.\n" }, { "code": null, "e": 27558, "s": 27252, "text": "\nEach Attribute also has a Threshold value (whose range is 0 to 255)\nwhich is printed under the heading \"THRESH\". If the Normalized value\nis less than or equal to the Threshold value, then the Attribute\nis said to have failed. If the Attribute is a pre-failure Attribute,\nthen disk failure is imminent.\n" }, { "code": null, "e": 27881, "s": 27558, "text": "\nEach Attribute also has a \"Worst\" value shown under the heading\n\"WORST\". This is the smallest (closest to failure) value that the\ndisk has recorded at any time during its lifetime when SMART was\nenabled. [Note however that some vendors firmware may actually\nincrease the \"Worst\" value for some \"rate-type\" Attributes.]\n" }, { "code": null, "e": 28559, "s": 27881, "text": "\nThe Attribute table printed out by smartctl also shows the\n\"TYPE\" of the Attribute. Attributes are one of two possible types:\nPre-failure or Old age. Pre-failure Attributes are ones which, if\nless than or equal to their threshold values, indicate pending disk\nfailure. Old age, or usage Attributes, are ones which indicate\nend-of-product life from old-age or normal aging and wearout, if\nthe Attribute value is less than or equal to the threshold. Please\nnote: the fact that an Attribute is of type ’Pre-fail’ does\nnot mean that your disk is about to fail! It only has this\nmeaning if the Attribute's current Normalized value is less than or\nequal to the threshold value.\n" }, { "code": null, "e": 28989, "s": 28559, "text": "\nIf the Attribute's current Normalized value is less than or equal to\nthe threshold value, then the \"WHEN_FAILED\" column will display\n\"FAILING_NOW\". If not, but the worst recorded value is less than or\nequal to the threshold value, then this column will display\n\"In_the_past\". If the \"WHEN_FAILED\" column has no entry (indicated by\na dash: '-') then this Attribute is OK now (not failing) and has\nalso never failed in the past.\n" }, { "code": null, "e": 29228, "s": 28989, "text": "\nThe table column labeled \"UPDATED\" shows if the SMART Attribute values\nare updated during both normal operation and off-line testing, or\nonly during offline testing. The former are labeled \"Always\" and the\nlatter are labeled \"Offline\".\n" }, { "code": null, "e": 29964, "s": 29228, "text": "\nSo to summarize: the Raw Attribute values are the ones that might have\na real physical interpretation, such as \"Temperature Celsius\",\n\"Hours\", or \"Start-Stop Cycles\". Each manufacturer converts these,\nusing their detailed knowledge of the disk's operations and failure\nmodes, to Normalized Attribute values in the range 1-254. The\ncurrent and worst (lowest measured) of these Normalized Attribute\nvalues are stored on the disk, along with a Threshold value that the\nmanufacturer has determined will indicate that the disk is going to\nfail, or that it has exceeded its design age or aging limit.\nsmartctl does not calculate any of the Attribute values,\nthresholds, or types, it merely reports them from the SMART data on\nthe device.\n" }, { "code": null, "e": 30221, "s": 29964, "text": "\nNote that starting with ATA/ATAPI-4, revision 4, the meaning of these\nAttribute fields has been made entirely vendor-specific. However most\nATA/ATAPI-5 disks seem to respect their meaning, so we have retained\nthe option of printing the Attribute values.\n" }, { "code": null, "e": 30483, "s": 30221, "text": "\nFor SCSI devices the \"attributes\" are obtained from the temperature\nand start-stop cycle counter log pages. Certain vendor specific\nattributes are listed if recognised. The attributes are output in a\nrelatively free format (compared with ATA disk attributes).\n" }, { "code": null, "e": 30913, "s": 30483, "text": "\nerror - prints only the SMART error log. SMART disks maintain a log of the\nmost recent five non-trivial errors. For each of these errors, the\ndisk power-on lifetime at which the error occurred is recorded, as is\nthe device status (idle, standby, etc) at the time of the error. For\nsome common types of errors, the Error Register (ER) and Status\nRegister (SR) values are decoded and printed as text. The meanings of these\nare:\n" }, { "code": null, "e": 31353, "s": 30913, "text": " ABRT: Command ABoRTed\n AMNF: Address Mark Not Found\n CCTO: Command Completion Timed Out\n EOM: End Of Media\n ICRC: Interface Cyclic Redundancy Code (CRC) error\n IDNF: IDentity Not Found\n ILI: (packet command-set specific)\n MC: Media Changed\n MCR: Media Change Request\n NM: No Media\n obs: obsolete\n TK0NF: TracK 0 Not Found\n UNC: UNCorrectable Error in Data\n WP: Media is Write Protected\n" }, { "code": null, "e": 32216, "s": 31353, "text": "\nThe ATA Specification (ATA-5 Revision 1c, Section 8.41.6.8.2) says:\n\"Error log structures shall include UNC errors, IDNF errors for\nwhich the address requested was valid, servo errors, write fault\nerrors, etc. Error log data structures shall not include errors\nattributed to the receipt of faulty commands such as command codes not\nimplemented by the device or requests with invalid parameters or\ninvalid addresses.\" The definitions of these terms are:\n\nUNC (UNCorrectable): data is uncorrectable. This refers\nto data which has been read from the disk, but for which the Error\nChecking and Correction (ECC) codes are inconsistent. In effect, this\nmeans that the data can not be read.\n\nIDNF (ID Not Found): user-accessible address could\nnot be found. For READ LOG type commands, IDNF can also indicate\nthat a device data log structure checksum was incorrect.\n" }, { "code": null, "e": 32910, "s": 32216, "text": "\nIf the command that caused the error was a READ or WRITE command, then\nthe Logical Block Address (LBA) at which the error occurred will be\nprinted in base 10 and base 16. The LBA is a linear address, which\ncounts 512-byte sectors on the disk, starting from zero. (Because of\nthe limitations of the SMART error log, if the LBA is greater than\n0xfffffff, then either no error log entry will be made, or the error\nlog entry will have an incorrect LBA. This may happen for drives with\na capacity greater than 128 GiB or 137 GB.) On Linux systems the\nsmartmontools web page has instructions about how to convert the LBA\naddress to the name of the disk file containing the erroneous disk\nsector.\n" }, { "code": null, "e": 33088, "s": 32910, "text": "\nPlease note that some manufacturers ignore the ATA\nspecifications, and make entries in the error log if the device\nreceives a command which is not implemented or is not valid.\n" }, { "code": null, "e": 33239, "s": 33088, "text": "\nerror [SCSI] - prints the error counter log pages for reads, write and verifies.\nThe verify row is only output if it has an element other than zero.\n" }, { "code": null, "e": 34035, "s": 33239, "text": "\nselftest - prints the SMART self-test log. The disk maintains a self-test log\nshowing the results of the self tests, which can be run using the\n'-t' option described below. For each of the most recent\ntwenty-one self-tests, the log shows the type of test (short or\nextended, off-line or captive) and the final status of the test. If\nthe test did not complete successfully, then the percentage of the\ntest remaining is shown. The time at which the test took place,\nmeasured in hours of disk lifetime, is also printed. If any errors\nwere detected, the Logical Block Address (LBA) of the first error is\nprinted in decimal notation. On Linux systems the smartmontools\nweb page has instructions about how to convert this LBA address to the\nname of the disk file containing the erroneous block.\n" }, { "code": null, "e": 35360, "s": 34035, "text": "\nselftest [SCSI] - the self-test log for a SCSI device has a slightly different format\nthan for an ATA device. For each of the most recent twenty\nself-tests, it shows the type of test and the status (final or in\nprogress) of the test. SCSI standards use the terms \"foreground\" and\n\"background\" (rather than ATA's corresponding \"captive\" and\n\"off-line\") and \"short\" and \"long\" (rather than ATA's corresponding\n\"short\" and \"extended\") to describe the type of the test. The printed\nsegment number is only relevant when a test fails in the third or\nlater test segment. It identifies the test that failed and consists\nof either the number of the segment that failed during the test, or\nthe number of the test that failed and the number of the segment in\nwhich the test was run, using a vendor-specific method of putting both\nnumbers into a single byte. The Logical Block Address (LBA) of the\nfirst error is printed in hexadecimal notation. On Linux systems the\nsmartmontools web page has instructions about how to convert this LBA\naddress to the name of the disk file containing the erroneous block.\nIf provided, the SCSI Sense Key (SK), Additional Sense Code (ASC) and\nAdditional Sense Code Qualifier (ASQ) are also printed. The self tests\ncan be run using the '-t' option described below (using the ATA\ntest terminology).\n" }, { "code": null, "e": 36235, "s": 35360, "text": "\nselective [ATA] - Some ATA-7 disks (example: Maxtor) also maintain a selective\nself-test log. Please see the '-t select' option below for a\ndescription of selective self-tests. The selective self-test log\nshows the start/end Logical Block Addresses (LBA) of each of the five\ntest spans, and their current test status. If the span is being\ntested or the remainder of the disk is being read-scanned, the\ncurrent 65536-sector block of LBAs being tested is also displayed.\nThe selective self-test log also shows if a read-scan of the\nremainder of the disk will be carried out after the selective\nself-test has completed (see '-t afterselect' option) and the time\ndelay before restarting this read-scan if it is interrupted (see\n'-t pending' option). This is a new smartmontools feature; please\nreport unusual or incorrect behavior to the smartmontools-support\nmailing list.\n" }, { "code": null, "e": 36954, "s": 36235, "text": "\ndirectory - if the device supports the General Purpose Logging feature set\n(ATA-6 and ATA-7 only) then this prints the Log Directory (the log at\naddress 0). The Log Directory shows what logs are available and their\nlength in sectors (512 bytes). The contents of the logs at address 1\n[Summary SMART error log] and at address 6 [SMART self-test log] may\nbe printed using the previously-described\nerror and\nselftest arguments to this option. [Please note: this is a new, experimental\nfeature. We would like to add support for printing the contents of\nextended and comprehensive SMART self-test and error logs. If your\ndisk supports these, and you would like to assist, please contact the\nsmartmontools developers.]\n" }, { "code": null, "e": 37674, "s": 36954, "text": "\nbackground [SCSI] - the background scan results log outputs information derived from\nBackground Media Scans (BMS) done after power up and/or periodocally (e.g.\nevery 24 hours) on recent SCSI disks. If supported, the BMS status\nis output first, indicating whether a background scan is currently\nunderway (and if so a progress percentage), the amount of time the disk\nhas been powered up and the number of scans already completed. Then there\nis a header and a line for each background scan \"event\". These will\ntypically be either recovered or unrecoverable errors. That latter group\nmay need some attention. There is a description of the background scan\nmechansim in section 4.18 of SBC-3 revision 6 (see www.t10.org ).\n" }, { "code": null, "e": 38411, "s": 37674, "text": "\nscttemp, scttempsts, scttemphist [ATA] - [NEW EXPERIMENTAL SMARTCTL FEATURE] prints the disk temperature\ninformation provided by the SMART Command Transport (SCT) commands.\nThe option 'scttempsts' prints current temperature and temperature\nranges returned by the SCT Status command, 'scttemphist' prints\ntemperature limits and the temperature history table returned by\nthe SCT Data Table command, and 'scttemp' prints both.\nThe temperature values are preserved across power cycles.\nThe default temperature logging interval is 1 minute and can be\nconfigured with the '-t scttempint,N[,p]' option, see below.\nThe SCT commands are specified in the proposed ATA-8 Command Set\n(ACS), and are already implemented in some recent ATA-7 disks.\n" }, { "code": null, "e": 38499, "s": 38413, "text": "\nhelp - Prints (to STDOUT) a list of all valid arguments to this option,\nthen exits.\n" }, { "code": null, "e": 38755, "s": 38499, "text": "\n9,minutes - Raw Attribute number 9 is power-on time in minutes. Its raw value\nwill be displayed in the form \"Xh+Ym\". Here X is hours, and Y is\nminutes in the range 0-59 inclusive. Y is always printed with two\ndigits, for example \"06\" or \"31\" or \"00\".\n" }, { "code": null, "e": 39063, "s": 38755, "text": "\n9,seconds - Raw Attribute number 9 is power-on time in seconds. Its raw value\nwill be displayed in the form \"Xh+Ym+Zs\". Here X is hours, Y is\nminutes in the range 0-59 inclusive, and Z is seconds in the range\n0-59 inclusive. Y and Z are always printed with two digits, for\nexample \"06\" or \"31\" or \"00\".\n" }, { "code": null, "e": 39389, "s": 39063, "text": "\n9,halfminutes - Raw Attribute number 9 is power-on time, measured in units of 30\nseconds. This format is used by some Samsung disks. Its raw value\nwill be displayed in the form \"Xh+Ym\". Here X is hours, and Y is\nminutes in the range 0-59 inclusive. Y is always printed with two\ndigits, for example \"06\" or \"31\" or \"00\".\n" }, { "code": null, "e": 39459, "s": 39389, "text": "\n9,temp - Raw Attribute number 9 is the disk temperature in Celsius.\n" }, { "code": null, "e": 39554, "s": 39459, "text": "\n192,emergencyretractcyclect - Raw Attribute number 192 is the Emergency Retract Cycle Count.\n" }, { "code": null, "e": 39980, "s": 39554, "text": "\n193,loadunload - Raw Attribute number 193 contains two values. The first is the\nnumber of load cycles. The second is the number of unload cycles.\nThe difference between these two values is the number of times that\nthe drive was unexpectedly powered off (also called an emergency\nunload). As a rule of thumb, the mechanical stress created by one\nemergency unload is equivalent to that created by one hundred normal\nunloads.\n" }, { "code": null, "e": 40155, "s": 39980, "text": "\n194,10xCelsius - Raw Attribute number 194 is ten times the disk temperature in\nCelsius. This is used by some Samsung disks (example: model SV1204H\nwith RK100-13 firmware).\n" }, { "code": null, "e": 40314, "s": 40155, "text": "\n194,unknown - Raw Attribute number 194 is NOT the disk temperature, and its\ninterpretation is unknown. This is primarily useful for the -P\n(presets) option.\n" }, { "code": null, "e": 40408, "s": 40314, "text": "\n198,offlinescanuncsectorct - Raw Attribute number 198 is the Offline Scan UNC Sector Count.\n" }, { "code": null, "e": 40483, "s": 40408, "text": "\n200,writeerrorcount - Raw Attribute number 200 is the Write Error Count.\n" }, { "code": null, "e": 40558, "s": 40483, "text": "\n201,detectedtacount - Raw Attribute number 201 is the Detected TA Count.\n" }, { "code": null, "e": 40632, "s": 40558, "text": "\n220,temp - Raw Attribute number 220 is the disk temperature in Celsius.\n" }, { "code": null, "e": 40776, "s": 40632, "text": "\nNote: a table of hard drive models, listing which Attribute\ncorresponds to temperature, can be found at:\nhttp://www.guzu.net/linux/hddtemp.db\n" }, { "code": null, "e": 41088, "s": 40776, "text": "\nN,raw8 - Print the Raw value of Attribute N as six 8-bit unsigned base-10\nintegers. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw8' prints Raw values for ALL Attributes in this\nform. The form (for example) '123,raw8' only prints the Raw value for\nAttribute 123 in this form.\n" }, { "code": null, "e": 41406, "s": 41088, "text": "\nN,raw16 - Print the Raw value of Attribute N as three 16-bit unsigned base-10\nintegers. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw16' prints Raw values for ALL Attributes in this\nform. The form (for example) '123,raw16' only prints the Raw value for\nAttribute 123 in this form.\n" }, { "code": null, "e": 41719, "s": 41406, "text": "\nN,raw48 - Print the Raw value of Attribute N as a 48-bit unsigned base-10\ninteger. This may be useful for decoding the meaning of the Raw\nvalue. The form 'N,raw48' prints Raw values for ALL Attributes in\nthis form. The form (for example) '123,raw48' only prints the Raw\nvalue for Attribute 123 in this form.\n" }, { "code": null, "e": 41894, "s": 41721, "text": "\nnone - Assume that the device firmware obeys the ATA specifications. This\nis the default, unless the device has presets for '-F' in the\ndevice database (see note below).\n" }, { "code": null, "e": 42446, "s": 41894, "text": "\nsamsung - In some Samsung disks (example: model SV4012H Firmware Version:\nRM100-08) some of the two- and four-byte quantities in the SMART data\nstructures are byte-swapped (relative to the ATA specification).\nEnabling this option tells smartctl to evaluate these quantities\nin byte-reversed order. Some signs that your disk needs this option\nare (1) no self-test log printed, even though you have run self-tests;\n(2) very large numbers of ATA errors reported in the ATA error log;\n(3) strange and impossible values for the ATA error log timestamps.\n" }, { "code": null, "e": 42966, "s": 42446, "text": "\nsamsung2 - In more recent Samsung disks (firmware revisions ending in \"-23\")\nthe number of ATA errors reported is byte swapped. Enabling this\noption tells smartctl to evaluate this quantity in\nbyte-reversed order. An indication that your Samsung disk needs this\noption is that the self-test log is printed correctly, but there are a\nvery large number of errors in the SMART error log. This is because\nthe error count is byte swapped. Thus a disk with five errors\n(0x0005) will appear to have 20480 errors (0x5000).\n" }, { "code": null, "e": 43253, "s": 42966, "text": "\nsamsung3 - Some Samsung disks (at least SP2514N with Firmware VF100-37) report\na self-test still in progress with 0% remaining when the test was already\ncompleted. Enabling this option modifies the output of the self-test\nexecution status (see options '-c' or '-a' above) accordingly.\n" }, { "code": null, "e": 43380, "s": 43253, "text": "\nNote that an explicit '-F' option on the command line will\nover-ride any preset values for '-F' (see the '-P' option\nbelow).\n" }, { "code": null, "e": 43517, "s": 43380, "text": "\nswapid - Fixes byte swapped ATA identify strings (device name, serial number,\nfirmware version) returned by some buggy device drivers.\n" }, { "code": null, "e": 43980, "s": 43519, "text": "\nsmartctl can automatically set appropriate options for known\ndrives. For example, the Maxtor 4D080H4 uses Attribute 9 to stores\npower-on time in minutes whereas most drives use that Attribute to\nstore the power-on time in hours. The command-line option '-v\n9,minutes' ensures that smartctl correctly interprets Attribute\n9 in this case, but that option is preset for the Maxtor 4D080H4 and\nso need not be specified by the user on the smartctl command\nline.\n" }, { "code": null, "e": 44486, "s": 43980, "text": "\nThe argument\nshow will show any preset options for your drive and the argument\nshowall will show all known drives in the smartmontools database, along\nwith their preset options. If there are no presets for your drive and\nyou think there should be (for example, a -v or -F option is needed\nto get smartctl to display correct values) then please contact\nthe smartmontools developers so that this information can be\nadded to the smartmontools database. Contact information is at the\nend of this man page.\n" }, { "code": null, "e": 44528, "s": 44486, "text": "\nThe valid arguments to this option are:\n" }, { "code": null, "e": 44773, "s": 44528, "text": "\nuse - if a drive is recognized, then use the stored presets for it. This\nis the default. Note that presets will NOT over-ride additional\nAttribute interpretation ('-v N,something') command-line options or\nexplicit '-F' command-line options..\n" }, { "code": null, "e": 44804, "s": 44773, "text": "\nignore - do not use presets.\n" }, { "code": null, "e": 44897, "s": 44804, "text": "\nshow - show if the drive is recognized in the database, and if so, its\npresets, then exit.\n" }, { "code": null, "e": 44987, "s": 44897, "text": "\nshowall - list all recognized drives, and the presets that are set for them,\nthen exit.\n" }, { "code": null, "e": 45114, "s": 44987, "text": "\nThe '-P showall' option takes up to two optional arguments to\nmatch a specific drive type and firmware version. The command:\n" }, { "code": null, "e": 45137, "s": 45114, "text": " smartctl -P showall\n" }, { "code": null, "e": 45168, "s": 45137, "text": " smartctl -P showall 'MODEL'\n" }, { "code": null, "e": 45210, "s": 45168, "text": " smartctl -P showall 'MODEL' 'FIRMWARE'\n" }, { "code": null, "e": 45255, "s": 45212, "text": "\nThe valid arguments to this option are: \n" }, { "code": null, "e": 45716, "s": 45255, "text": "\noffline - runs SMART Immediate Offline Test. This immediately\nstarts the test described above. This command can be given during\nnormal system operation. The effects of this test are visible only in\nthat it updates the SMART Attribute values, and if errors are\nfound they will appear in the SMART error log, visible with the '-l error'\noption. [In the case of SCSI devices runs the default self test in\nforeground. No entry is placed in the self test log.]\n" }, { "code": null, "e": 46189, "s": 45716, "text": "\nIf the '-c' option to smartctl shows that the device has the\n\"Suspend Offline collection upon new command\" capability then you can\ntrack the progress of the Immediate Offline test using the '-c'\noption to smartctl. If the '-c' option show that the device\nhas the \"Abort Offline collection upon new command\" capability then\nmost commands will abort the Immediate Offline Test, so you should not\ntry to track the progress of the test with '-c', as it will abort\nthe test.\n" }, { "code": null, "e": 46933, "s": 46189, "text": "\nshort - runs SMART Short Self Test (usually under ten minutes).\n[Note: in the case of SCSI devices,\nthis command option runs the \"Background short\" self-test.]\nThis command can be given during normal system operation (unless run in\ncaptive mode - see the '-C' option below). This is a\ntest in a different category than the immediate or automatic offline\ntests. The \"Self\" tests check the electrical and mechanical\nperformance as well as the read performance of the disk. Their\nresults are reported in the Self Test Error Log, readable with\nthe '-l selftest' option. Note that on some disks the progress of the\nself-test can be monitored by watching this log during the self-test; with other disks\nuse the '-c' option to monitor progress.\n" }, { "code": null, "e": 47295, "s": 46933, "text": "\nlong - runs SMART Extended Self Test (tens of minutes).\n[Note: in the case of SCSI devices,\nthis command option runs the \"Background long\" self-test.]\nThis is a\nlonger and more thorough version of the Short Self Test described\nabove. Note that this command can be given during normal\nsystem operation (unless run in captive mode - see the '-C' option below).\n" }, { "code": null, "e": 47663, "s": 47295, "text": "\nconveyance - [ATA ONLY] runs a SMART Conveyance Self Test (minutes). This\nself-test routine is intended to identify damage incurred during\ntransporting of the device. This self-test routine should take on the\norder of minutes to complete. Note that this command can be given\nduring normal system operation (unless run in captive mode - see the\n'-C' option below).\n" }, { "code": null, "e": 48101, "s": 47663, "text": "\nselect,N-M, select,N+SIZE - [ATA ONLY] [EXPERIMENTAL SMARTCTL FEATURE] runs a SMART\nSelective Self Test, to test a range of disk Logical Block\nAddresses (LBAs), rather than the entire disk. Each range of LBAs\nthat is checked is called a \"span\" and is specified by a starting LBA\n(N) and an ending LBA (M) with N less than or equal to M. The range\ncan also be specified as N+SIZE. A span at the end of a disk can\nbe specified by N-max.\n" }, { "code": null, "e": 48129, "s": 48101, "text": "\nFor example the commands:\n" }, { "code": null, "e": 48202, "s": 48129, "text": " smartctl -t select,10-20 /dev/hda\n smartctl -t select,10+11 /dev/hda\n" }, { "code": null, "e": 48247, "s": 48202, "text": " smartctl -t select,100000000-max /dev/hda\n" }, { "code": null, "e": 48304, "s": 48247, "text": " smartctl -t select,0-100 -t select,1000-2000 /dev/hda\n" }, { "code": null, "e": 48371, "s": 48304, "text": " smartctl -t select,0-10 -t select,5-15 -t select,10-20 /dev/hda\n" }, { "code": null, "e": 48738, "s": 48371, "text": "\nSelective self tests are particularly useful as disk capacities\nincrease: an extended self test (smartctl -t long) can take several\nhours. Selective self-tests are helpful if (based on SYSLOG error\nmessages, previous failed self-tests, or SMART error log entries) you\nsuspect that a disk is having problems at a particular range of\nLogical Block Addresses (LBAs).\n" }, { "code": null, "e": 48862, "s": 48738, "text": "\nSelective self-tests can be run during normal system operation (unless\ndone in captive mode - see the '-C' option below).\n" }, { "code": null, "e": 49080, "s": 48862, "text": "\n[Note: To use this feature on Linux, the kernel must be compiled with\nthe configuration option CONFIG_IDE_TASKFILE_IO enabled. Please report\nunusual or incorrect behavior to the smartmontools-support mailing list.]\n" }, { "code": null, "e": 49214, "s": 49080, "text": "\nThe following variants of the selective self-test command use spans based\non the ranges from past tests already stored on the disk:\n" }, { "code": null, "e": 49494, "s": 49214, "text": "\nselect,redo[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] redo the last SMART\nSelective Self Test using the same LBA range. The starting LBA is identical\nto the LBA used by last test, same for ending LBA unless a new span size\nis specified by optional +SIZE argument.\n" }, { "code": null, "e": 49522, "s": 49494, "text": "\nFor example the commands:\n" }, { "code": null, "e": 49632, "s": 49522, "text": " smartctl -t select,10-20 /dev/hda\n smartctl -t select,redo /dev/hda\n smartctl -t select,redo+20 /dev/hda\n" }, { "code": null, "e": 49741, "s": 49632, "text": " smartctl -t select,10-20 /dev/hda\n smartctl -t select,10-20 /dev/hda\n smartctl -t select,10-29 /dev/hda\n" }, { "code": null, "e": 50029, "s": 49741, "text": "\nselect,next[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] runs a SMART Selective\nSelf Test on the LBA range which follows the range of the last test. The\nstarting LBA is set to (ending LBA +1) of the last test. A new span size\nmay be specified by the optional +SIZE argument.\n" }, { "code": null, "e": 50057, "s": 50029, "text": "\nFor example the commands:\n" }, { "code": null, "e": 50169, "s": 50057, "text": " smartctl -t select,0-999 /dev/hda\n smartctl -t select,next /dev/hda\n smartctl -t select,next+2000 /dev/hda\n" }, { "code": null, "e": 50286, "s": 50169, "text": " smartctl -t select,0-999 /dev/hda\n smartctl -t select,1000-1999 /dev/hda\n smartctl -t select,2000-3999 /dev/hda\n" }, { "code": null, "e": 50539, "s": 50286, "text": "\nIf the last test ended at the last LBA of the disk, the new range starts\nat LBA 0. The span size of the last span of a disk is adjusted such that\nthe total number of spans to check the full disk will not be changed\nby future uses of '-t select,next'.\n" }, { "code": null, "e": 50753, "s": 50539, "text": "\nselect,cont[+SIZE] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] performs a 'redo'\n(above) if the self test status reports that the last test was aborted\nby the host. Otherwise it run the 'next' (above) test.\n" }, { "code": null, "e": 51321, "s": 50753, "text": "\nafterselect,on - [ATA ONLY] perform an offline read scan after a Selective Self-test\nhas completed. This option must be used together with one or more of\nthe select,N-M options above. If the LBAs that have been\nspecified in the Selective self-test pass the test with no errors\nfound, then read scan the remainder of the disk. If the device\nis powered-cycled while this read scan is in progress, the read scan\nwill be automatically resumed after a time specified by the pending\ntimer (see below). The value of this option is preserved between\nselective self-tests.\n" }, { "code": null, "e": 51591, "s": 51321, "text": "\nafterselect,off - [ATA ONLY] do not read scan the remainder of the disk after a\nSelective self-test has completed. This option must be use together\nwith one or more of the select,N-M options above. The value of this\noption is preserved between selective self-tests.\n" }, { "code": null, "e": 52022, "s": 51591, "text": "\npending,N - [ATA ONLY] set the pending offline read scan timer to N minutes.\nHere N is an integer in the range from 0 to 65535 inclusive. If the\ndevice is powered off during a read scan after a Selective self-test,\nthen resume the test automatically N minutes after power-up. This\noption must be use together with one or more of the select,N-M\noptions above. The value of this option is preserved between selective\nself-tests.\n" }, { "code": null, "e": 52485, "s": 52022, "text": "\nscttempint,N[,p] - [ATA ONLY] [NEW EXPERIMENTAL SMARTCTL FEATURE] set the time interval\nfor SCT temperature logging to N minutes. If ',p' is specified, the\nsetting is preserved across power cycles. Otherwise, the setting is\nvolatile and will be reverted to default (1 minute), or last\nnon-volatile setting by the next hard reset. This command also clears\nthe temperature history table. See '-l scttemp' above for more\ninformation about SCT temperature logging.\n" }, { "code": null, "e": 52641, "s": 52487, "text": "\nWARNING: Tests run in captive mode may busy out the drive for the\nlength of the test. Only run captive tests on drives without any\nmounted partitions!\n" }, { "code": null, "e": 52666, "s": 52643, "text": "smartctl -a /dev/hda \n" }, { "code": null, "e": 52695, "s": 52668, "text": "smartctl -s off /dev/hdd \n" }, { "code": null, "e": 52759, "s": 52697, "text": "smartctl --smart=on --offlineauto=on --saveauto=on /dev/hda \n" }, { "code": null, "e": 52789, "s": 52761, "text": "smartctl -t long /dev/hdc \n" }, { "code": null, "e": 52828, "s": 52791, "text": "smartctl -s on -t offline /dev/hda \n" }, { "code": null, "e": 52866, "s": 52830, "text": "smartctl -A -v 9,minutes /dev/hda \n" }, { "code": null, "e": 52917, "s": 52868, "text": "smartctl -q errorsonly -H -l selftest /dev/hda \n" }, { "code": null, "e": 52952, "s": 52919, "text": "smartctl -q silent -a /dev/hda \n" }, { "code": null, "e": 52988, "s": 52954, "text": "smartctl -a -d 3ware,0 /dev/sda \n" }, { "code": null, "e": 53025, "s": 52990, "text": "smartctl -a -d 3ware,0 /dev/twe0 \n" }, { "code": null, "e": 53062, "s": 53027, "text": "smartctl -a -d 3ware,0 /dev/twa0 \n" }, { "code": null, "e": 53104, "s": 53064, "text": "smartctl -t short -d 3ware,3 /dev/sdb \n" }, { "code": null, "e": 53140, "s": 53106, "text": "smartctl -a -d hpt,1/3 /dev/sda \n" }, { "code": null, "e": 53183, "s": 53140, "text": "\nsmartctl -t short -d hpt,1/1/2 /dev/sda \n" }, { "code": null, "e": 53226, "s": 53183, "text": "\nsmartctl -t short -d hpt,1/1/2 /dev/sda \n" }, { "code": null, "e": 53314, "s": 53228, "text": "smartctl -t select,10-100 -t select,30-300 -t afterselect,on -t pending,45 /dev/hda \n" }, { "code": null, "e": 53357, "s": 53316, "text": "smartctl -a -d cciss,0 /dev/cciss/c0d0 \n" }, { "code": null, "e": 53516, "s": 53359, "text": "\nTo test within the shell for whether or not the different bits are\nturned on or off, you can use the following type of construction (this\nis bash syntax):\n" }, { "code": null, "e": 53540, "s": 53516, "text": "smartstat=$(($? & 8)) \n" }, { "code": null, "e": 54124, "s": 53550, "text": "Casper Dik (Solaris SCSI interface)\nChristian Franke (Windows interface and Cygwin package)\nDouglas Gilbert (SCSI subsystem)\nGuido Guenther (Autoconf/Automake packaging)\nGeoffrey Keating (Darwin ATA interface)\nEduard Martinescu (FreeBSD interface)\nFrédéric L. W. Meunier (Web site and Mailing list)\nKeiji Sawada (Solaris ATA interface)\nSergey Svishchev (NetBSD interface)\nDavid Snyder and Sergey Svishchev (OpenBSD interface)\nPhil Williams (User interface and drive database)\nYuri Dario (OS/2, eComStation interface)\nShengfeng Zhou (Linux Highpoint RocketRaid interface)\n" }, { "code": null, "e": 54657, "s": 54130, "text": "\nIf you would like to understand better how SMART works, and what it\ndoes, a good place to start is with Sections 4.8 and 6.54 of the first\nvolume of the 'AT Attachment with Packet Interface-7' (ATA/ATAPI-7)\nspecification. This documents the SMART functionality which the\nsmartmontools utilities provide access to. You can find\nRevision 4b of this document at\nhttp://www.t13.org/docs2004/d1532v1r4b-ATA-ATAPI-7.pdf .\nEarlier and later versions of this Specification are available from\nthe T13 web site http://www.t13.org/ .\n" }, { "code": null, "e": 54988, "s": 54657, "text": "\nThe functioning of SMART was originally defined by the SFF-8035i\nrevision 2 and the SFF-8055i revision 1.4 specifications. These are\npublications of the Small Form Factors (SFF) Committee. Links to\nthese documents may be found in the References section of the\nsmartmontools home page at\nhttp://smartmontools.sourceforge.net/ .\n" }, { "code": null, "e": 55007, "s": 54990, "text": "\nAdvertisements\n" }, { "code": null, "e": 55042, "s": 55007, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 55070, "s": 55042, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 55104, "s": 55070, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 55121, "s": 55104, "text": " Frahaan Hussain" }, { "code": null, "e": 55154, "s": 55121, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 55165, "s": 55154, "text": " Pradeep D" }, { "code": null, "e": 55200, "s": 55165, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 55216, "s": 55200, "text": " Musab Zayadneh" }, { "code": null, "e": 55249, "s": 55216, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 55261, "s": 55249, "text": " GUHARAJANM" }, { "code": null, "e": 55293, "s": 55261, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 55301, "s": 55293, "text": " Uplatz" }, { "code": null, "e": 55308, "s": 55301, "text": " Print" }, { "code": null, "e": 55319, "s": 55308, "text": " Add Notes" } ]
How to append element in the list using Python?
There may arise some situations where we need to add or append an element at the end of a list. We’ll use append() method in Python which adds an item to the end of the list. The length of the list increases by one. list.append(item) The single parameter item is the item to be added at the end of the list. The item can be number, string, another list, dictionary etc. We can append an element at the end of a list using the append() method. The element is appended and the size of the list is increased. Live Demo colors=["red","blue","black"] print("List",colors) print("Size of list", len(colors)) colors.append("white") print("Updated list",colors) print("Size of updated list",len(colors)) List ['red', 'blue', 'black'] Size of list 3 Updated list ['red', 'blue', 'black', 'white'] Size of updated list 4 The append() method can also add another list to the end of the list. Live Demo colors=["red","blue","black"] print("List",colors) fruits=["apple","grapes","mango"] colors.append(fruits) print("Updated list",colors) List ['red', 'blue', 'black'] Updated list ['red', 'blue', 'black', ['apple', 'grapes', 'mango']] The extend() method also adds elements at the end of the list. This is different from append(). The extend() method iterates over its argument and adds each element into the list. The length of the list increases by the length of elements of the argument. list.extend(iterable) The iterable can be a string or another list. The string is an iterable. Thus, extending a list with a string will append all the characters of the string at the end of the list. The length of the list increases by the length of the string in the argument. Live Demo colors=["red","blue","black"] print("List",colors) print("Size of list", len(colors)) colors.extend("white") print("Updated list",colors) print("Size of updated list",len(colors)) List ['red', 'blue', 'black'] Size of list 3 Updated list ['red', 'blue', 'black', 'w', 'h', 'i', 't', 'e'] Size of updated list 8 The list is iterable. Extending list with another list will append all the elements of the argument list at the end of the existing list. The size of the list increases by the size of the list in the argument. Live Demo colors=["red","blue","black"] print("List",colors) print("Size of list", len(colors)) colors2=["white","pink","orange"] colors.extend(colors2) print("Updated list",colors) print("Size of updated list",len(colors)) List ['red', 'blue', 'black'] Size of list 3 Updated list ['red', 'blue', 'black', 'white', 'pink', 'orange'] Size of updated list 6 The append() and extend() have different functionalities. The append() and extend() have different functionalities. The append() method adds the argument as a single element whereas the extend() iterates over the argument and adds each element at the end of the list. The append() method adds the argument as a single element whereas the extend() iterates over the argument and adds each element at the end of the list. The append() method increases the length of the list by one whereas the extend() increases the length of the list by length of the argument element. The append() method increases the length of the list by one whereas the extend() increases the length of the list by length of the argument element. The append() has constant time complexity i.e. O(1) whereas extend() has time complexity O(k) where k is the length of the argument. The append() has constant time complexity i.e. O(1) whereas extend() has time complexity O(k) where k is the length of the argument.
[ { "code": null, "e": 1237, "s": 1062, "text": "There may arise some situations where we need to add or append an element at the end of a list. We’ll use append() method in Python which adds an item to the end of the list." }, { "code": null, "e": 1278, "s": 1237, "text": "The length of the list increases by one." }, { "code": null, "e": 1296, "s": 1278, "text": "list.append(item)" }, { "code": null, "e": 1432, "s": 1296, "text": "The single parameter item is the item to be added at the end of the list. The item can be number, string, another list, dictionary etc." }, { "code": null, "e": 1568, "s": 1432, "text": "We can append an element at the end of a list using the append() method. The element is appended and the size of the list is increased." }, { "code": null, "e": 1579, "s": 1568, "text": " Live Demo" }, { "code": null, "e": 1759, "s": 1579, "text": "colors=[\"red\",\"blue\",\"black\"]\nprint(\"List\",colors)\nprint(\"Size of list\", len(colors))\ncolors.append(\"white\")\nprint(\"Updated list\",colors)\nprint(\"Size of updated list\",len(colors))" }, { "code": null, "e": 1874, "s": 1759, "text": "List ['red', 'blue', 'black']\nSize of list 3\nUpdated list ['red', 'blue', 'black', 'white']\nSize of updated list 4" }, { "code": null, "e": 1944, "s": 1874, "text": "The append() method can also add another list to the end of the list." }, { "code": null, "e": 1955, "s": 1944, "text": " Live Demo" }, { "code": null, "e": 2091, "s": 1955, "text": "colors=[\"red\",\"blue\",\"black\"]\nprint(\"List\",colors)\nfruits=[\"apple\",\"grapes\",\"mango\"]\ncolors.append(fruits)\nprint(\"Updated list\",colors)" }, { "code": null, "e": 2189, "s": 2091, "text": "List ['red', 'blue', 'black']\nUpdated list ['red', 'blue', 'black', ['apple', 'grapes', 'mango']]" }, { "code": null, "e": 2445, "s": 2189, "text": "The extend() method also adds elements at the end of the list. This is different from append(). The extend() method iterates over its argument and adds each element into the list. The length of the list increases by the length of elements of the argument." }, { "code": null, "e": 2467, "s": 2445, "text": "list.extend(iterable)" }, { "code": null, "e": 2513, "s": 2467, "text": "The iterable can be a string or another list." }, { "code": null, "e": 2724, "s": 2513, "text": "The string is an iterable. Thus, extending a list with a string will append all the characters of the string at the end of the list. The length of the list increases by the length of the string in the argument." }, { "code": null, "e": 2735, "s": 2724, "text": " Live Demo" }, { "code": null, "e": 2915, "s": 2735, "text": "colors=[\"red\",\"blue\",\"black\"]\nprint(\"List\",colors)\nprint(\"Size of list\", len(colors))\ncolors.extend(\"white\")\nprint(\"Updated list\",colors)\nprint(\"Size of updated list\",len(colors))" }, { "code": null, "e": 3046, "s": 2915, "text": "List ['red', 'blue', 'black']\nSize of list 3\nUpdated list ['red', 'blue', 'black', 'w', 'h', 'i', 't', 'e']\nSize of updated list 8" }, { "code": null, "e": 3256, "s": 3046, "text": "The list is iterable. Extending list with another list will append all the elements of the argument list at the end of the existing list. The size of the list increases by the size of the list in the argument." }, { "code": null, "e": 3267, "s": 3256, "text": " Live Demo" }, { "code": null, "e": 3481, "s": 3267, "text": "colors=[\"red\",\"blue\",\"black\"]\nprint(\"List\",colors)\nprint(\"Size of list\", len(colors))\ncolors2=[\"white\",\"pink\",\"orange\"]\ncolors.extend(colors2)\nprint(\"Updated list\",colors)\nprint(\"Size of updated list\",len(colors))" }, { "code": null, "e": 3614, "s": 3481, "text": "List ['red', 'blue', 'black']\nSize of list 3\nUpdated list ['red', 'blue', 'black', 'white', 'pink', 'orange']\nSize of updated list 6" }, { "code": null, "e": 3672, "s": 3614, "text": "The append() and extend() have different functionalities." }, { "code": null, "e": 3730, "s": 3672, "text": "The append() and extend() have different functionalities." }, { "code": null, "e": 3882, "s": 3730, "text": "The append() method adds the argument as a single element whereas the extend() iterates over the argument and adds each element at the end of the list." }, { "code": null, "e": 4034, "s": 3882, "text": "The append() method adds the argument as a single element whereas the extend() iterates over the argument and adds each element at the end of the list." }, { "code": null, "e": 4183, "s": 4034, "text": "The append() method increases the length of the list by one whereas the extend() increases the length of the list by length of the argument element." }, { "code": null, "e": 4332, "s": 4183, "text": "The append() method increases the length of the list by one whereas the extend() increases the length of the list by length of the argument element." }, { "code": null, "e": 4465, "s": 4332, "text": "The append() has constant time complexity i.e. O(1) whereas extend() has time complexity O(k) where k is the length of the argument." }, { "code": null, "e": 4598, "s": 4465, "text": "The append() has constant time complexity i.e. O(1) whereas extend() has time complexity O(k) where k is the length of the argument." } ]
Python Pandas - Return a new Timedelta with milliseconds ceiling resolution
To return a new Timedelta ceiled to this resolution, use the timedelta.ceil() method. For milliseconds ceiling resolution, set the freq parameter to the value ms. At first, import the required libraries − import pandas as pd TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns') Display the Timedelta print("Timedelta...\n", timedelta) Return the ceiled Timestamp with milliseconds ceiling resolution timedelta.ceil(freq='ms') Following is the code import pandas as pd # TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s # create a Timedelta object timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns') # display the Timedelta print("Timedelta...\n", timedelta) # return the ceiled Timestamp # with milliseconds ceiling resolution res = timedelta.ceil(freq='ms') # display the ceiled Timestamp print("\nTimedelta (milliseconds ceiled)...\n", res) This will produce the following code Timedelta... 2 days 10:45:20.035000055 Timedelta (milliseconds ceiled)... 2 days 10:45:20.036000
[ { "code": null, "e": 1225, "s": 1062, "text": "To return a new Timedelta ceiled to this resolution, use the timedelta.ceil() method. For milliseconds ceiling resolution, set the freq parameter to the value ms." }, { "code": null, "e": 1267, "s": 1225, "text": "At first, import the required libraries −" }, { "code": null, "e": 1287, "s": 1267, "text": "import pandas as pd" }, { "code": null, "e": 1407, "s": 1287, "text": "TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s. Create a Timedelta object" }, { "code": null, "e": 1476, "s": 1407, "text": "timedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')\n" }, { "code": null, "e": 1498, "s": 1476, "text": "Display the Timedelta" }, { "code": null, "e": 1533, "s": 1498, "text": "print(\"Timedelta...\\n\", timedelta)" }, { "code": null, "e": 1598, "s": 1533, "text": "Return the ceiled Timestamp with milliseconds ceiling resolution" }, { "code": null, "e": 1625, "s": 1598, "text": "timedelta.ceil(freq='ms')\n" }, { "code": null, "e": 1647, "s": 1625, "text": "Following is the code" }, { "code": null, "e": 2106, "s": 1647, "text": "import pandas as pd\n\n# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s\n# create a Timedelta object\ntimedelta = pd.Timedelta('2 days 10 hours 45 min 20 s 35 ms 55 ns')\n\n# display the Timedelta\nprint(\"Timedelta...\\n\", timedelta)\n\n# return the ceiled Timestamp\n# with milliseconds ceiling resolution\nres = timedelta.ceil(freq='ms')\n\n# display the ceiled Timestamp\nprint(\"\\nTimedelta (milliseconds ceiled)...\\n\", res)" }, { "code": null, "e": 2143, "s": 2106, "text": "This will produce the following code" }, { "code": null, "e": 2242, "s": 2143, "text": "Timedelta...\n2 days 10:45:20.035000055\n\nTimedelta (milliseconds ceiled)...\n2 days 10:45:20.036000\n" } ]
Azure Machine Learning Service — Train a model | by Pankaj Jainani | Towards Data Science
So far in this series of articles, I was able to cover a brief introduction of the Azure Machine Learning Service (AML) and also able to run a simple experiment. In this post, I am going to cover the parameterization of the experiment script, different ways to configure the script environment, framework, and dependencies. Also, how to register the model with AML service after the training is completed. This particular post is extracted from the Kaggle notebook hosted — here. Use the link to setup to execute the experiment. Before I jump into a discussion about data stores and data set pipelines in AML, here I will briefly touch upon some advanced configuration options to run a simple experiment as described earlier. In the post# 2, I discussed implementing a simple ML experiment using the custom Python script, but that script file had one issue, it was plain and static, so how can we improve the script for the experiment so that it can accept a range of values and train a model effectively? Yes, the answer is to parameterized the script — so in the context of AML service the parameter values for any experiment script can be implemented as below: ### .... ###run = Run.get_context()##Adding the parameter: regularization rate parser = argparse.ArgumentParser()parser.add_argument('--reg_rate', type=float, dest='reg', default=0.01)args=parser.parse_args()r = args.regrun.log("model regularization", np.float(r))# load the data from a local filedata = pd.read_csv('IRIS.csv')X = data[['sepal_length', 'sepal_width','petal_length','petal_width']].valuesX=StandardScaler().fit_transform(X)Y= (data['species']).map(lambda x: 0 if x=='Iris-setosa' else (1 if x=='Iris-versicolor' else 2))#Split data into train and test setX_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.25, random_state=1234)# fit the model: with extra parametermodel = LogisticRegression(C=1/r, solver='lbfgs', multi_class='multinomial').fit(X_train,Y_train)Y_pred = model.predict(X_test)accuracy = np.average(Y_test == Y_pred)print("accuracy: " + str(accuracy))run.log("Accuracy", np.float(accuracy))###....### While Run Configuration and Script Run Configuration allows a developer to run a script-based experiment that trains a machine learning model, the AML service also comes with a better abstraction that encapsulates their capabilities into a single object, known as Estimator. The typical use case is when the Run Configuration may become too complex to configure for certain dependencies and framework. It is available for the most commonly used machine learning framework, i.e., Scikit-Learn, PyTorch, and Tensorflow. The code below implements the generic Estimator class’ object to run the training the experiment. The Estimator()constructor parameterizes the references for compute resources for experiment execution, e.g. Container, VM, or local compute by using compute_targetparameter. The generic Estimator does not include the scikit-learn packages, therefore, we require to pass the value for the conda_packagesparameter. Also, see that we can pass the collection of script’s parameters by using the script_paramsparameter of Estimator()the constructor method. from azureml.train.estimator import Estimatorfrom azureml.core import Experimentfrom azureml.widgets import RunDetails# Create an estimatorestimator = Estimator(source_directory=experiment_folder, entry_script='iris_simple_experiment.py', compute_target='local', use_docker=False, script_params = {'--reg_rate': 0.07}, conda_packages=['scikit-learn'] )# COMMENTED - SKLearn as an estimator#estimator = SKLearn(source_directory=experiment_folder, entry_script='iris_simple_experiment.py', compute_target='local', use_docker=False)# Create an experimentexperiment_name = 'iris-estimator-experiment'experiment = Experiment(workspace = ws, name = experiment_name)# Run the experiment based on the estimatorrun = experiment.submit(config=estimator)# Get Run DetailsRunDetails(run).show()# Wait to complete the experiment. In the Azure Portal we will find the experiment state as preparing --> finished.run.wait_for_completion(show_output=True) The AML SDK includes framework-specific estmators Class — it allows developer to easily configure framework dependencies,e.g, for SKLearn or Tensorflow or PyTorch. The code also has a example for SKLearn Estimator (commented). after completing the training of the ML model we have to use it for inference, therefore, with AML service we can register the model and consume it for inference whenever required. Download Model: The run object’s download_file()ordownload_files() methods are used to download output files to the local file system. # List the files generated by the experimentfor file in run.get_file_names(): print(file)# Download a named filerun.download_file(name='outputs/model.pkl', output_file_path='model.pkl') To register the model and the associated meta-data — name, version, tags we can write the following: from azureml.core import Modelrun.register_model(model_path='outputs/iris_simple_model.pkl', model_name='iris_estimator_model', tags={"Training Context":"Estimator", "Script Context":"Parameters"}, properties={"Accuracy":run.get_metrics()["Accuracy"]}) Finally, to view the models registered with the AML service, one can use the following:- for model in Model.list(ws): print(model.name, ":", model.version) print("\nTag List") for tag_name in model.tags: tag = model.tags[tag_name] print(tag_name, tag) print("\nProperties List") for prop_name in model.properties: prop = model.properties[prop_name] print(prop_name,prop)Outputiris_estimator_model : 4Tag ListTraining Context EstimatorScript Context ParametersProperties ListAccuracy 0.9736842105263158IRIS_model : 1Tag ListTraining context Pipeline With the end of this post, so far we are able to cover the most basic aspects of AML service. We are able to run a simple experiment and train an ML model. Also, using APIs like Run Configuration, Script Run Configuration, and Estimators allows us to create an environment with associated dependencies to dynamically run the experiments irrespective of the computing environment. This is a series of blog posts encompassing a detailed overview of various Azure Machine Learning capabilities, the URLs for other posts are as follows: Post 1: Azure Machine Learning Service: Part 1 — An Introduction Post 2: Azure Machine Learning Service — Run a Simple Experiment Post 3 (this): Azure Machine Learning Service — Train a model Post 4: Azure Machine Learning Service — Where is My Data? Post 5: Azure Machine Learning Service — What is the Target Environment? Connect with me on LinkedIn to discuss further [1] Notebook & Code — Azure Machine Learning — Model Training, Kaggle.[2] Azure Machine Learning — Estimator API, URL[3] Azure Machine Learning Service Official Documentation, Microsoft Azure.
[ { "code": null, "e": 578, "s": 172, "text": "So far in this series of articles, I was able to cover a brief introduction of the Azure Machine Learning Service (AML) and also able to run a simple experiment. In this post, I am going to cover the parameterization of the experiment script, different ways to configure the script environment, framework, and dependencies. Also, how to register the model with AML service after the training is completed." }, { "code": null, "e": 701, "s": 578, "text": "This particular post is extracted from the Kaggle notebook hosted — here. Use the link to setup to execute the experiment." }, { "code": null, "e": 898, "s": 701, "text": "Before I jump into a discussion about data stores and data set pipelines in AML, here I will briefly touch upon some advanced configuration options to run a simple experiment as described earlier." }, { "code": null, "e": 1336, "s": 898, "text": "In the post# 2, I discussed implementing a simple ML experiment using the custom Python script, but that script file had one issue, it was plain and static, so how can we improve the script for the experiment so that it can accept a range of values and train a model effectively? Yes, the answer is to parameterized the script — so in the context of AML service the parameter values for any experiment script can be implemented as below:" }, { "code": null, "e": 2286, "s": 1336, "text": "### .... ###run = Run.get_context()##Adding the parameter: regularization rate parser = argparse.ArgumentParser()parser.add_argument('--reg_rate', type=float, dest='reg', default=0.01)args=parser.parse_args()r = args.regrun.log(\"model regularization\", np.float(r))# load the data from a local filedata = pd.read_csv('IRIS.csv')X = data[['sepal_length', 'sepal_width','petal_length','petal_width']].valuesX=StandardScaler().fit_transform(X)Y= (data['species']).map(lambda x: 0 if x=='Iris-setosa' else (1 if x=='Iris-versicolor' else 2))#Split data into train and test setX_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=0.25, random_state=1234)# fit the model: with extra parametermodel = LogisticRegression(C=1/r, solver='lbfgs', multi_class='multinomial').fit(X_train,Y_train)Y_pred = model.predict(X_test)accuracy = np.average(Y_test == Y_pred)print(\"accuracy: \" + str(accuracy))run.log(\"Accuracy\", np.float(accuracy))###....###" }, { "code": null, "e": 2804, "s": 2286, "text": "While Run Configuration and Script Run Configuration allows a developer to run a script-based experiment that trains a machine learning model, the AML service also comes with a better abstraction that encapsulates their capabilities into a single object, known as Estimator. The typical use case is when the Run Configuration may become too complex to configure for certain dependencies and framework. It is available for the most commonly used machine learning framework, i.e., Scikit-Learn, PyTorch, and Tensorflow." }, { "code": null, "e": 3355, "s": 2804, "text": "The code below implements the generic Estimator class’ object to run the training the experiment. The Estimator()constructor parameterizes the references for compute resources for experiment execution, e.g. Container, VM, or local compute by using compute_targetparameter. The generic Estimator does not include the scikit-learn packages, therefore, we require to pass the value for the conda_packagesparameter. Also, see that we can pass the collection of script’s parameters by using the script_paramsparameter of Estimator()the constructor method." }, { "code": null, "e": 4420, "s": 3355, "text": "from azureml.train.estimator import Estimatorfrom azureml.core import Experimentfrom azureml.widgets import RunDetails# Create an estimatorestimator = Estimator(source_directory=experiment_folder, entry_script='iris_simple_experiment.py', compute_target='local', use_docker=False, script_params = {'--reg_rate': 0.07}, conda_packages=['scikit-learn'] )# COMMENTED - SKLearn as an estimator#estimator = SKLearn(source_directory=experiment_folder, entry_script='iris_simple_experiment.py', compute_target='local', use_docker=False)# Create an experimentexperiment_name = 'iris-estimator-experiment'experiment = Experiment(workspace = ws, name = experiment_name)# Run the experiment based on the estimatorrun = experiment.submit(config=estimator)# Get Run DetailsRunDetails(run).show()# Wait to complete the experiment. In the Azure Portal we will find the experiment state as preparing --> finished.run.wait_for_completion(show_output=True)" }, { "code": null, "e": 4647, "s": 4420, "text": "The AML SDK includes framework-specific estmators Class — it allows developer to easily configure framework dependencies,e.g, for SKLearn or Tensorflow or PyTorch. The code also has a example for SKLearn Estimator (commented)." }, { "code": null, "e": 4828, "s": 4647, "text": "after completing the training of the ML model we have to use it for inference, therefore, with AML service we can register the model and consume it for inference whenever required." }, { "code": null, "e": 4963, "s": 4828, "text": "Download Model: The run object’s download_file()ordownload_files() methods are used to download output files to the local file system." }, { "code": null, "e": 5153, "s": 4963, "text": "# List the files generated by the experimentfor file in run.get_file_names(): print(file)# Download a named filerun.download_file(name='outputs/model.pkl', output_file_path='model.pkl')" }, { "code": null, "e": 5254, "s": 5153, "text": "To register the model and the associated meta-data — name, version, tags we can write the following:" }, { "code": null, "e": 5524, "s": 5254, "text": "from azureml.core import Modelrun.register_model(model_path='outputs/iris_simple_model.pkl', model_name='iris_estimator_model', tags={\"Training Context\":\"Estimator\", \"Script Context\":\"Parameters\"}, properties={\"Accuracy\":run.get_metrics()[\"Accuracy\"]})" }, { "code": null, "e": 5613, "s": 5524, "text": "Finally, to view the models registered with the AML service, one can use the following:-" }, { "code": null, "e": 6116, "s": 5613, "text": "for model in Model.list(ws): print(model.name, \":\", model.version) print(\"\\nTag List\") for tag_name in model.tags: tag = model.tags[tag_name] print(tag_name, tag) print(\"\\nProperties List\") for prop_name in model.properties: prop = model.properties[prop_name] print(prop_name,prop)Outputiris_estimator_model : 4Tag ListTraining Context EstimatorScript Context ParametersProperties ListAccuracy 0.9736842105263158IRIS_model : 1Tag ListTraining context Pipeline" }, { "code": null, "e": 6496, "s": 6116, "text": "With the end of this post, so far we are able to cover the most basic aspects of AML service. We are able to run a simple experiment and train an ML model. Also, using APIs like Run Configuration, Script Run Configuration, and Estimators allows us to create an environment with associated dependencies to dynamically run the experiments irrespective of the computing environment." }, { "code": null, "e": 6649, "s": 6496, "text": "This is a series of blog posts encompassing a detailed overview of various Azure Machine Learning capabilities, the URLs for other posts are as follows:" }, { "code": null, "e": 6714, "s": 6649, "text": "Post 1: Azure Machine Learning Service: Part 1 — An Introduction" }, { "code": null, "e": 6779, "s": 6714, "text": "Post 2: Azure Machine Learning Service — Run a Simple Experiment" }, { "code": null, "e": 6841, "s": 6779, "text": "Post 3 (this): Azure Machine Learning Service — Train a model" }, { "code": null, "e": 6900, "s": 6841, "text": "Post 4: Azure Machine Learning Service — Where is My Data?" }, { "code": null, "e": 6973, "s": 6900, "text": "Post 5: Azure Machine Learning Service — What is the Target Environment?" }, { "code": null, "e": 7020, "s": 6973, "text": "Connect with me on LinkedIn to discuss further" } ]
Check if given Sudoku board configuration is valid or not - GeeksforGeeks
11 May, 2021 Given a Sudoku Board configuration, check whether it is valid or not. Examples: Input: [5 3 - - 7 - - - -] [6 - - 1 9 5 - - -] [- 9 8 - - - - 6 -] [8 - - - 6 - - - 3] [4 - - 8 - 3 - - 1] [7 - - - 2 - - - 6] [- 6 - - - - 2 8 -] [- - - 4 1 9 - - 5] [- - - - 8 - - 7 9] Output: True The basic idea is to check whether each row, column, and 3×3 box is valid or not on the basis of the following points: The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’. An empty Sudoku board is also valid. A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to check whether given sudoku// board is valid or not#include <bits/stdc++.h>using namespace std; // Checks whether there is any duplicate// in current row or notbool notInRow(char arr[][9], int row){ // Set to store characters seen so far. set<char> st; for (int i = 0; i < 9; i++) { // If already encountered before, return false if (st.find(arr[row][i]) != st.end()) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.insert(arr[row][i]); } return true;} // Checks whether there is any duplicate// in current column or not.bool notInCol(char arr[][9], int col){ set<char> st; for (int i = 0; i < 9; i++) { // If already encountered before, return false if (st.find(arr[i][col]) != st.end()) return false; // If it is not an empty cell, // insert value at the current cell in the set if (arr[i][col] != '.') st.insert(arr[i][col]); } return true;} // Checks whether there is any duplicate// in current 3x3 box or not.bool notInBox(char arr[][9], int startRow, int startCol){ set<char> st; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { char curr = arr[row + startRow][col + startCol]; // If already encountered before, return false if (st.find(curr) != st.end()) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.insert(curr); } } return true;} // Checks whether current row and current column and// current 3x3 box is valid or notbool isValid(char arr[][9], int row, int col){ return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3);} bool isValidConfig(char arr[][9], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return false if (!isValid(arr, i, j)) return false; } } return true;} // Drivers codeint main(){ char board[9][9] = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; cout << (isValidConfig(board, 9) ? "YES\n" : "NO\n"); return 0;} // Java Program to check whether given sudoku// board is valid or notimport java.io.*;import java.util.*; class GFG{ // Checks whether there is any duplicate// in current row or notpublic static boolean notInRow(char arr[][], int row){ // Set to store characters seen so far. HashSet<Character> st = new HashSet<>(); for(int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.contains(arr[row][i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.add(arr[row][i]); } return true;} // Checks whether there is any duplicate// in current column or not.public static boolean notInCol(char arr[][], int col){ HashSet<Character> st = new HashSet<>(); for(int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.contains(arr[i][col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i][col] != '.') st.add(arr[i][col]); } return true;} // Checks whether there is any duplicate// in current 3x3 box or not.public static boolean notInBox(char arr[][], int startRow, int startCol){ HashSet<Character> st = new HashSet<>(); for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { char curr = arr[row + startRow][col + startCol]; // If already encountered before, return // false if (st.contains(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.add(curr); } } return true;} // Checks whether current row and current column and// current 3x3 box is valid or notpublic static boolean isValid(char arr[][], int row, int col){ return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3);} public static boolean isValidConfig(char arr[][], int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true;} // Driver codepublic static void main(String[] args){ char[][] board = new char[][] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; System.out.println((isValidConfig(board, 9) ? "YES" : "NO"));}} // This code is contributed by Rohit OBeroi # Python3 program to check whether# given sudoku board is valid or not # Checks whether there is any# duplicate in current row or notdef notInRow(arr, row): # Set to store characters seen so far. st = set() for i in range(0, 9): # If already encountered before, # return false if arr[row][i] in st: return False # If it is not an empty cell, insert value # at the current cell in the set if arr[row][i] != '.': st.add(arr[row][i]) return True # Checks whether there is any# duplicate in current column or not.def notInCol(arr, col): st = set() for i in range(0, 9): # If already encountered before, # return false if arr[i][col] in st: return False # If it is not an empty cell, insert # value at the current cell in the set if arr[i][col] != '.': st.add(arr[i][col]) return True # Checks whether there is any duplicate# in current 3x3 box or not.def notInBox(arr, startRow, startCol): st = set() for row in range(0, 3): for col in range(0, 3): curr = arr[row + startRow][col + startCol] # If already encountered before, # return false if curr in st: return False # If it is not an empty cell, # insert value at current cell in set if curr != '.': st.add(curr) return True # Checks whether current row and current# column and current 3x3 box is valid or notdef isValid(arr, row, col): return (notInRow(arr, row) and notInCol(arr, col) and notInBox(arr, row - row % 3, col - col % 3)) def isValidConfig(arr, n): for i in range(0, n): for j in range(0, n): # If current row or current column or # current 3x3 box is not valid, return false if not isValid(arr, i, j): return False return True # Drivers codeif __name__ == "__main__": board = [[ '5', '3', '.', '.', '7', '.', '.', '.', '.' ], [ '6', '.', '.', '1', '9', '5', '.', '.', '.' ], [ '.', '9', '8', '.', '.', '.', '.', '6', '.' ], [ '8', '.', '.', '.', '6', '.', '.', '.', '3' ], [ '4', '.', '.', '8', '.', '3', '.', '.', '1' ], [ '7', '.', '.', '.', '2', '.', '.', '.', '6' ], [ '.', '6', '.', '.', '.', '.', '2', '8', '.' ], [ '.', '.', '.', '4', '1', '9', '.', '.', '5' ], [ '.', '.', '.', '.', '8', '.', '.', '7', '9' ]] if isValidConfig(board, 9): print("YES") else: print("NO") # This code is contributed by Rituraj Jain // C# Program to check whether given sudoku// board is valid or notusing System;using System.Collections.Generic;class GFG { // Checks whether there is any duplicate // in current row or not public static bool notInRow(char[, ] arr, int row) { // Set to store characters seen so far. HashSet<char> st = new HashSet<char>(); for (int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.Contains(arr[row, i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row, i] != '.') st.Add(arr[row, i]); } return true; } // Checks whether there is any duplicate // in current column or not. public static bool notInCol(char[, ] arr, int col) { HashSet<char> st = new HashSet<char>(); for (int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.Contains(arr[i, col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i, col] != '.') st.Add(arr[i, col]); } return true; } // Checks whether there is any duplicate // in current 3x3 box or not. public static bool notInBox(char[, ] arr, int startRow, int startCol) { HashSet<char> st = new HashSet<char>(); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { char curr = arr[row + startRow, col + startCol]; // If already encountered before, return // false if (st.Contains(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.Add(curr); } } return true; } // Checks whether current row and current column and // current 3x3 box is valid or not public static bool isValid(char[, ] arr, int row, int col) { return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3); } public static bool isValidConfig(char[, ] arr, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true; } // Driver code public static void Main(string[] args) { char[, ] board = new char[, ] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; Console.WriteLine( (isValidConfig(board, 9) ? "YES" : "NO")); }} // This code is contributed by ukasp. <script>// Javascript Program to check whether given sudoku// board is valid or not // Checks whether there is any duplicate// in current row or not function notInRow(arr,row) { // Set to store characters seen so far. let st = new Set(); for(let i = 0; i < 9; i++) { // If already encountered before, // return false if (st.has(arr[row][i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.add(arr[row][i]); } return true; } // Checks whether there is any duplicate// in current column or not. function notInCol(arr,col) { let st = new Set(); for(let i = 0; i < 9; i++) { // If already encountered before, // return false if (st.has(arr[i][col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i][col] != '.') st.add(arr[i][col]); } return true; } // Checks whether there is any duplicate// in current 3x3 box or not. function notInBox(arr,startRow,startCol) { let st = new Set(); for(let row = 0; row < 3; row++) { for(let col = 0; col < 3; col++) { let curr = arr[row + startRow][col + startCol]; // If already encountered before, return // false if (st.has(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.add(curr); } } return true; } // Checks whether current row and current column and// current 3x3 box is valid or not function isValid(arr,row,col) { return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3); } function isValidConfig(arr,n) { for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true; } // Driver code let board = [[ '5', '3', '.', '.', '7', '.', '.', '.', '.' ], [ '6', '.', '.', '1', '9', '5', '.', '.', '.' ], [ '.', '9', '8', '.', '.', '.', '.', '6', '.' ], [ '8', '.', '.', '.', '6', '.', '.', '.', '3' ], [ '4', '.', '.', '8', '.', '3', '.', '.', '1' ], [ '7', '.', '.', '.', '2', '.', '.', '.', '6' ], [ '.', '6', '.', '.', '.', '.', '2', '8', '.' ], [ '.', '.', '.', '4', '1', '9', '.', '.', '5' ], [ '.', '.', '.', '.', '8', '.', '.', '7', '9' ]]; document.write((isValidConfig(board, 9) ? "YES" : "NO")); // This code is contributed by rag2127</script> YES rituraj_jain RohitOberoi ukasp rag2127 cpp-set STL Matrix Matrix STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 The Celebrity Problem Gold Mine Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Python program to multiply two matrices Multiplication of two Matrices in Single line using Numpy in Python Program to find transpose of a matrix
[ { "code": null, "e": 24849, "s": 24821, "text": "\n11 May, 2021" }, { "code": null, "e": 24919, "s": 24849, "text": "Given a Sudoku Board configuration, check whether it is valid or not." }, { "code": null, "e": 24930, "s": 24919, "text": "Examples: " }, { "code": null, "e": 25168, "s": 24930, "text": "Input: \n [5 3 - - 7 - - - -]\n [6 - - 1 9 5 - - -]\n [- 9 8 - - - - 6 -]\n [8 - - - 6 - - - 3]\n [4 - - 8 - 3 - - 1]\n [7 - - - 2 - - - 6]\n [- 6 - - - - 2 8 -]\n [- - - 4 1 9 - - 5]\n [- - - - 8 - - 7 9]\n\nOutput: True" }, { "code": null, "e": 25288, "s": 25168, "text": "The basic idea is to check whether each row, column, and 3×3 box is valid or not on the basis of the following points: " }, { "code": null, "e": 25385, "s": 25288, "text": "The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’." }, { "code": null, "e": 25422, "s": 25385, "text": "An empty Sudoku board is also valid." }, { "code": null, "e": 25535, "s": 25422, "text": "A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated." }, { "code": null, "e": 25586, "s": 25535, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25590, "s": 25586, "text": "C++" }, { "code": null, "e": 25595, "s": 25590, "text": "Java" }, { "code": null, "e": 25603, "s": 25595, "text": "Python3" }, { "code": null, "e": 25606, "s": 25603, "text": "C#" }, { "code": null, "e": 25617, "s": 25606, "text": "Javascript" }, { "code": "// C++ Program to check whether given sudoku// board is valid or not#include <bits/stdc++.h>using namespace std; // Checks whether there is any duplicate// in current row or notbool notInRow(char arr[][9], int row){ // Set to store characters seen so far. set<char> st; for (int i = 0; i < 9; i++) { // If already encountered before, return false if (st.find(arr[row][i]) != st.end()) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.insert(arr[row][i]); } return true;} // Checks whether there is any duplicate// in current column or not.bool notInCol(char arr[][9], int col){ set<char> st; for (int i = 0; i < 9; i++) { // If already encountered before, return false if (st.find(arr[i][col]) != st.end()) return false; // If it is not an empty cell, // insert value at the current cell in the set if (arr[i][col] != '.') st.insert(arr[i][col]); } return true;} // Checks whether there is any duplicate// in current 3x3 box or not.bool notInBox(char arr[][9], int startRow, int startCol){ set<char> st; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { char curr = arr[row + startRow][col + startCol]; // If already encountered before, return false if (st.find(curr) != st.end()) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.insert(curr); } } return true;} // Checks whether current row and current column and// current 3x3 box is valid or notbool isValid(char arr[][9], int row, int col){ return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3);} bool isValidConfig(char arr[][9], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return false if (!isValid(arr, i, j)) return false; } } return true;} // Drivers codeint main(){ char board[9][9] = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; cout << (isValidConfig(board, 9) ? \"YES\\n\" : \"NO\\n\"); return 0;}", "e": 28615, "s": 25617, "text": null }, { "code": "// Java Program to check whether given sudoku// board is valid or notimport java.io.*;import java.util.*; class GFG{ // Checks whether there is any duplicate// in current row or notpublic static boolean notInRow(char arr[][], int row){ // Set to store characters seen so far. HashSet<Character> st = new HashSet<>(); for(int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.contains(arr[row][i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.add(arr[row][i]); } return true;} // Checks whether there is any duplicate// in current column or not.public static boolean notInCol(char arr[][], int col){ HashSet<Character> st = new HashSet<>(); for(int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.contains(arr[i][col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i][col] != '.') st.add(arr[i][col]); } return true;} // Checks whether there is any duplicate// in current 3x3 box or not.public static boolean notInBox(char arr[][], int startRow, int startCol){ HashSet<Character> st = new HashSet<>(); for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { char curr = arr[row + startRow][col + startCol]; // If already encountered before, return // false if (st.contains(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.add(curr); } } return true;} // Checks whether current row and current column and// current 3x3 box is valid or notpublic static boolean isValid(char arr[][], int row, int col){ return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3);} public static boolean isValidConfig(char arr[][], int n){ for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true;} // Driver codepublic static void main(String[] args){ char[][] board = new char[][] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; System.out.println((isValidConfig(board, 9) ? \"YES\" : \"NO\"));}} // This code is contributed by Rohit OBeroi", "e": 31919, "s": 28615, "text": null }, { "code": "# Python3 program to check whether# given sudoku board is valid or not # Checks whether there is any# duplicate in current row or notdef notInRow(arr, row): # Set to store characters seen so far. st = set() for i in range(0, 9): # If already encountered before, # return false if arr[row][i] in st: return False # If it is not an empty cell, insert value # at the current cell in the set if arr[row][i] != '.': st.add(arr[row][i]) return True # Checks whether there is any# duplicate in current column or not.def notInCol(arr, col): st = set() for i in range(0, 9): # If already encountered before, # return false if arr[i][col] in st: return False # If it is not an empty cell, insert # value at the current cell in the set if arr[i][col] != '.': st.add(arr[i][col]) return True # Checks whether there is any duplicate# in current 3x3 box or not.def notInBox(arr, startRow, startCol): st = set() for row in range(0, 3): for col in range(0, 3): curr = arr[row + startRow][col + startCol] # If already encountered before, # return false if curr in st: return False # If it is not an empty cell, # insert value at current cell in set if curr != '.': st.add(curr) return True # Checks whether current row and current# column and current 3x3 box is valid or notdef isValid(arr, row, col): return (notInRow(arr, row) and notInCol(arr, col) and notInBox(arr, row - row % 3, col - col % 3)) def isValidConfig(arr, n): for i in range(0, n): for j in range(0, n): # If current row or current column or # current 3x3 box is not valid, return false if not isValid(arr, i, j): return False return True # Drivers codeif __name__ == \"__main__\": board = [[ '5', '3', '.', '.', '7', '.', '.', '.', '.' ], [ '6', '.', '.', '1', '9', '5', '.', '.', '.' ], [ '.', '9', '8', '.', '.', '.', '.', '6', '.' ], [ '8', '.', '.', '.', '6', '.', '.', '.', '3' ], [ '4', '.', '.', '8', '.', '3', '.', '.', '1' ], [ '7', '.', '.', '.', '2', '.', '.', '.', '6' ], [ '.', '6', '.', '.', '.', '.', '2', '8', '.' ], [ '.', '.', '.', '4', '1', '9', '.', '.', '5' ], [ '.', '.', '.', '.', '8', '.', '.', '7', '9' ]] if isValidConfig(board, 9): print(\"YES\") else: print(\"NO\") # This code is contributed by Rituraj Jain", "e": 34621, "s": 31919, "text": null }, { "code": "// C# Program to check whether given sudoku// board is valid or notusing System;using System.Collections.Generic;class GFG { // Checks whether there is any duplicate // in current row or not public static bool notInRow(char[, ] arr, int row) { // Set to store characters seen so far. HashSet<char> st = new HashSet<char>(); for (int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.Contains(arr[row, i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row, i] != '.') st.Add(arr[row, i]); } return true; } // Checks whether there is any duplicate // in current column or not. public static bool notInCol(char[, ] arr, int col) { HashSet<char> st = new HashSet<char>(); for (int i = 0; i < 9; i++) { // If already encountered before, // return false if (st.Contains(arr[i, col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i, col] != '.') st.Add(arr[i, col]); } return true; } // Checks whether there is any duplicate // in current 3x3 box or not. public static bool notInBox(char[, ] arr, int startRow, int startCol) { HashSet<char> st = new HashSet<char>(); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { char curr = arr[row + startRow, col + startCol]; // If already encountered before, return // false if (st.Contains(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.Add(curr); } } return true; } // Checks whether current row and current column and // current 3x3 box is valid or not public static bool isValid(char[, ] arr, int row, int col) { return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3); } public static bool isValidConfig(char[, ] arr, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true; } // Driver code public static void Main(string[] args) { char[, ] board = new char[, ] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; Console.WriteLine( (isValidConfig(board, 9) ? \"YES\" : \"NO\")); }} // This code is contributed by ukasp.", "e": 38202, "s": 34621, "text": null }, { "code": "<script>// Javascript Program to check whether given sudoku// board is valid or not // Checks whether there is any duplicate// in current row or not function notInRow(arr,row) { // Set to store characters seen so far. let st = new Set(); for(let i = 0; i < 9; i++) { // If already encountered before, // return false if (st.has(arr[row][i])) return false; // If it is not an empty cell, insert value // at the current cell in the set if (arr[row][i] != '.') st.add(arr[row][i]); } return true; } // Checks whether there is any duplicate// in current column or not. function notInCol(arr,col) { let st = new Set(); for(let i = 0; i < 9; i++) { // If already encountered before, // return false if (st.has(arr[i][col])) return false; // If it is not an empty cell, // insert value at the current // cell in the set if (arr[i][col] != '.') st.add(arr[i][col]); } return true; } // Checks whether there is any duplicate// in current 3x3 box or not. function notInBox(arr,startRow,startCol) { let st = new Set(); for(let row = 0; row < 3; row++) { for(let col = 0; col < 3; col++) { let curr = arr[row + startRow][col + startCol]; // If already encountered before, return // false if (st.has(curr)) return false; // If it is not an empty cell, // insert value at current cell in set if (curr != '.') st.add(curr); } } return true; } // Checks whether current row and current column and// current 3x3 box is valid or not function isValid(arr,row,col) { return notInRow(arr, row) && notInCol(arr, col) && notInBox(arr, row - row % 3, col - col % 3); } function isValidConfig(arr,n) { for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // If current row or current column or // current 3x3 box is not valid, return // false if (!isValid(arr, i, j)) return false; } } return true; } // Driver code let board = [[ '5', '3', '.', '.', '7', '.', '.', '.', '.' ], [ '6', '.', '.', '1', '9', '5', '.', '.', '.' ], [ '.', '9', '8', '.', '.', '.', '.', '6', '.' ], [ '8', '.', '.', '.', '6', '.', '.', '.', '3' ], [ '4', '.', '.', '8', '.', '3', '.', '.', '1' ], [ '7', '.', '.', '.', '2', '.', '.', '.', '6' ], [ '.', '6', '.', '.', '.', '.', '2', '8', '.' ], [ '.', '.', '.', '4', '1', '9', '.', '.', '5' ], [ '.', '.', '.', '.', '8', '.', '.', '7', '9' ]]; document.write((isValidConfig(board, 9) ? \"YES\" : \"NO\")); // This code is contributed by rag2127</script>", "e": 41287, "s": 38202, "text": null }, { "code": null, "e": 41291, "s": 41287, "text": "YES" }, { "code": null, "e": 41306, "s": 41293, "text": "rituraj_jain" }, { "code": null, "e": 41318, "s": 41306, "text": "RohitOberoi" }, { "code": null, "e": 41324, "s": 41318, "text": "ukasp" }, { "code": null, "e": 41332, "s": 41324, "text": "rag2127" }, { "code": null, "e": 41340, "s": 41332, "text": "cpp-set" }, { "code": null, "e": 41344, "s": 41340, "text": "STL" }, { "code": null, "e": 41351, "s": 41344, "text": "Matrix" }, { "code": null, "e": 41358, "s": 41351, "text": "Matrix" }, { "code": null, "e": 41362, "s": 41358, "text": "STL" }, { "code": null, "e": 41460, "s": 41362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41469, "s": 41460, "text": "Comments" }, { "code": null, "e": 41482, "s": 41469, "text": "Old Comments" }, { "code": null, "e": 41544, "s": 41482, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 41577, "s": 41544, "text": "Program to multiply two matrices" }, { "code": null, "e": 41628, "s": 41577, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 41649, "s": 41628, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 41671, "s": 41649, "text": "The Celebrity Problem" }, { "code": null, "e": 41689, "s": 41671, "text": "Gold Mine Problem" }, { "code": null, "e": 41771, "s": 41689, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 41811, "s": 41771, "text": "Python program to multiply two matrices" }, { "code": null, "e": 41879, "s": 41811, "text": "Multiplication of two Matrices in Single line using Numpy in Python" } ]
What Is A Cumulative Distribution Function? | by Emmett Boudreau | Towards Data Science
Back in May, I took a look at a distribution function that belongs to most statistical distributions called the Probability Density Function, or PDF. The PDF is a very important part of statistical inference, likewise, so is its function brother, the Cumulative Distribution Function, or CDF. If you would like to learn more about PDFs before CDFs, you may read the article I wrote about them here: towardsdatascience.com I would highly suggest having a decent understanding of the PDF and what it is used for before every even attempting the CDF. This is because CDFs are often far more complicated then your typical PDF. They are also usually used on PDF-distributed data. That in mind, let us start with that. What on Earth is PDF-distributed data? This means that the data has been distributed using a function. In statistics, these functions typically utilize certain metrics from within the data. A formula is then applied to the entire feature. This distributes the data into a distribution. For example, the normal distribution’s PDF is simply subtracted mu (the mean) from xbar (current sample) divided by sigma (the standard deviation.) The CDF of a variable X, or just distribution function of X, is essentially just a representation of the probability that X will take a value less than or equal to X. Of course, this is a function of continuous statistical features. The unique thing about a CDF is that it is monotonic. More specifically, monotonic increasing. This means that overtime, the probability will always increase. This means that CDFs are typically used as a scalar of a continuous distribution. A continuous probability distribution, or CPD, is a probability distribution whose elements are an uncountable set. This means that they are all unique and characterized by a cumulative distribution function. This can then be used to calculate the probability for each subset of support. A great example of this sort of distribution that you might be familiar with is the normal distribution. Furthermore, the uniform distribution is also a continuous probability distribution. This mathematically equates to Fx(x) = P(X <= x) Where the right side of this equation is representative of the probability that X takes to be a value less than or equal to X. The probability that X lies in the interval (a, b) where a < b. In simpler terms, we are checking the probability of X being less than or equal to x. If this is the case, then our line will continue going straight. Otherwise, we will go up. This is precisely what gives a CDF its hill-like shape. And this is also precisely what makes it monotonic non-decreasing. Another thing to note about CDFs is that they are always right-continuous. This means that the values are continuous going left-to-right. So if we were to plot them, they would increase from left to right. As briefly touched on before, CDFs are monotonic increasing. This means that there are of course some stark differences between this function and a PDF. The PDF is shaped as a parabola, whereas the CDF is a non-decreasing slope. If you have ever ready my articles about isotonic regression, technically the formula for that function is a CDF. Finally, let us compare the basic function methodology between both the CDF and the PDF, in order to provide a more complete mathematical understanding of these two functions and the differences between them. We will start with the CDF: Fx(x) = P(X <= x) Followed by the PDF: f = dX.P / dmu Because of the non-decreasing nature of CDFs, they are also typically A LOT more complicated than a typical PDF. As a result, we will not be working through solving any of the functions. However, I will be the first to admit that this is because I have only ever written two into code. They were both a lot of work, and the reality is there is never going to be a scenario where one is going to need to do that. CDFs are a back-end component already programmed into many programming languages. While certainly there are more CDFs to find, I think it is also important to realize that having a broad understanding of the function or concept is important as well. Anyway, this was my quick introduction to CDFs, Hopefully this article was helpful for those who are looking to learn a bit more about the methodologies in statistics, and not too much of a sensory overload, as this is what I am trying to avoid by refraining from going into a 20-minute read today on Medium. I digress, thank you very much for reading!
[ { "code": null, "e": 445, "s": 46, "text": "Back in May, I took a look at a distribution function that belongs to most statistical distributions called the Probability Density Function, or PDF. The PDF is a very important part of statistical inference, likewise, so is its function brother, the Cumulative Distribution Function, or CDF. If you would like to learn more about PDFs before CDFs, you may read the article I wrote about them here:" }, { "code": null, "e": 468, "s": 445, "text": "towardsdatascience.com" }, { "code": null, "e": 1193, "s": 468, "text": "I would highly suggest having a decent understanding of the PDF and what it is used for before every even attempting the CDF. This is because CDFs are often far more complicated then your typical PDF. They are also usually used on PDF-distributed data. That in mind, let us start with that. What on Earth is PDF-distributed data? This means that the data has been distributed using a function. In statistics, these functions typically utilize certain metrics from within the data. A formula is then applied to the entire feature. This distributes the data into a distribution. For example, the normal distribution’s PDF is simply subtracted mu (the mean) from xbar (current sample) divided by sigma (the standard deviation.)" }, { "code": null, "e": 1585, "s": 1193, "text": "The CDF of a variable X, or just distribution function of X, is essentially just a representation of the probability that X will take a value less than or equal to X. Of course, this is a function of continuous statistical features. The unique thing about a CDF is that it is monotonic. More specifically, monotonic increasing. This means that overtime, the probability will always increase." }, { "code": null, "e": 2176, "s": 1585, "text": "This means that CDFs are typically used as a scalar of a continuous distribution. A continuous probability distribution, or CPD, is a probability distribution whose elements are an uncountable set. This means that they are all unique and characterized by a cumulative distribution function. This can then be used to calculate the probability for each subset of support. A great example of this sort of distribution that you might be familiar with is the normal distribution. Furthermore, the uniform distribution is also a continuous probability distribution. This mathematically equates to" }, { "code": null, "e": 2194, "s": 2176, "text": "Fx(x) = P(X <= x)" }, { "code": null, "e": 2891, "s": 2194, "text": "Where the right side of this equation is representative of the probability that X takes to be a value less than or equal to X. The probability that X lies in the interval (a, b) where a < b. In simpler terms, we are checking the probability of X being less than or equal to x. If this is the case, then our line will continue going straight. Otherwise, we will go up. This is precisely what gives a CDF its hill-like shape. And this is also precisely what makes it monotonic non-decreasing. Another thing to note about CDFs is that they are always right-continuous. This means that the values are continuous going left-to-right. So if we were to plot them, they would increase from left to right." }, { "code": null, "e": 3471, "s": 2891, "text": "As briefly touched on before, CDFs are monotonic increasing. This means that there are of course some stark differences between this function and a PDF. The PDF is shaped as a parabola, whereas the CDF is a non-decreasing slope. If you have ever ready my articles about isotonic regression, technically the formula for that function is a CDF. Finally, let us compare the basic function methodology between both the CDF and the PDF, in order to provide a more complete mathematical understanding of these two functions and the differences between them. We will start with the CDF:" }, { "code": null, "e": 3489, "s": 3471, "text": "Fx(x) = P(X <= x)" }, { "code": null, "e": 3510, "s": 3489, "text": "Followed by the PDF:" }, { "code": null, "e": 3525, "s": 3510, "text": "f = dX.P / dmu" }, { "code": null, "e": 3937, "s": 3525, "text": "Because of the non-decreasing nature of CDFs, they are also typically A LOT more complicated than a typical PDF. As a result, we will not be working through solving any of the functions. However, I will be the first to admit that this is because I have only ever written two into code. They were both a lot of work, and the reality is there is never going to be a scenario where one is going to need to do that." } ]